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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bad0fd5b2e6de9bae33a2e73d19ce2d4f065118e | 84864f862dec9171e958920f2c8e7c920fcef056 | /LeetCode/650. 2 Keys Keyboard.cpp | 3095cf4294fa72c753255da480d42abba178d53b | [] | no_license | Orcuslc/Learning | 7704950f8c09232dadbbde81ed82ddc0ca65172d | ffa856febd85235d17358178f1e288ffae7856cb | refs/heads/master | 2020-03-26T11:59:54.093395 | 2018-05-29T04:19:36 | 2018-05-29T04:19:36 | 47,269,920 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 295 | cpp | 650. 2 Keys Keyboard.cpp | class Solution {
public:
int minSteps(int n) {
int s[n+1] = {1};
for(int i = 2; i <= n; i++) {
s[i] = i;
for(int j = i/2; j > 1; j--) {
if(i%j == 0) s[i] = min(s[j]+i/j, s[i]);
}
}
return s[n];
}
}; |
9c3b0ac6a4ac4a6d12e101ce7b30b9970480e33a | c9d714d4c88b2f289216e857a70f00b3480823a5 | /code/client/Other/MapGUI.hpp | c00d1e899367aad34a3df459095881c7aba2941e | [] | no_license | Jepsiko/WhiteHouseDefense | 6c1fc4a5836d5bbeca555aa26d30e185a2db3181 | 025fd066ffa89af16e0f315ca58d025b479cb32d | refs/heads/master | 2020-04-21T12:24:18.471582 | 2017-12-12T17:23:15 | 2017-12-12T17:23:15 | 169,560,852 | 1 | 0 | null | 2019-02-07T11:25:32 | 2019-02-07T11:25:32 | null | UTF-8 | C++ | false | false | 2,144 | hpp | MapGUI.hpp |
#ifndef PROJET_MAPGUI_HPP
#define PROJET_MAPGUI_HPP
static const short GUN_TOWER = 0;
static const short SHOCK_TOWER = 1;
static const short SNIPER_TOWER = 2;
static const short MISSILE_TOWER = 3;
static const short MEXICAN = 0;
static const short MUSLIM = 1;
static const short COMMUNIST = 2;
static const short FROZEN_MEXICAN = 4;
static const short FROZEN_MUSLIM = 5;
static const short FROZEN_COMMUNIST = 3;
#include <QtGui/QPainter>
#include "../../common/Other/Map.hpp"
#include "../Abstract/AbstractGUI.hpp"
#include <QtGui/QMouseEvent>
#include <QtWidgets/QHBoxLayout>
class GameGUI;
class MapGUI : public QWidget, public Map {
private:
GameState gameState;
int quadrant;
Position highlighted;
GameGUI *gameGUI;
std::vector<QImage> tower_images = {QImage("../../qt_ui/resources/tiles/guntower.png"),
QImage("../../qt_ui/resources/tiles/shocktower.png"),
QImage("../../qt_ui/resources/tiles/snipertower.png"),
QImage("../../qt_ui/resources/tiles/missiletower.png")};
std::vector<QImage> NPC_images = {QImage("../../qt_ui/resources/tiles/mexican.png"),
QImage("../../qt_ui/resources/tiles/muslim.png"),
QImage("../../qt_ui/resources/tiles/communist.png"),
QImage("../../qt_ui/resources/tiles/frozenCommunist.png"),
QImage("../../qt_ui/resources/tiles/frozenMexican.png"),
QImage("../../qt_ui/resources/tiles/frozenMuslim.png")};
protected:
void paintEvent(QPaintEvent *event) override;
public:
MapGUI(unsigned int seed, GameGUI *gameGUI, QVBoxLayout *layout);
void display();
void display(GameState &gameState, int quadrant) override;
void mousePressEvent(QMouseEvent *event) override;
Position getHighlightedPosition() const override { return highlighted; }
bool isEnemyBaseInHighlightedPosition(int quadrant) override;
};
#endif //PROJET_MAPGUI_HPP
|
ef3beaa7d7a64ba3ea926a8a79ed328a0e44d5ed | f7d2f9fb264a123b38e3b240a35b9abbaf38d4ff | /src/movegen.cpp | 535d10a785c3e96ccfc20ee39d4a5f20ea11757a | [] | no_license | kz04px/swizzles-old | dfe89a7714bce914c36d2d25cc87e4aec64b865e | 5c7d944eaef3c767c9f752975802ac0edf140390 | refs/heads/master | 2022-09-11T10:05:37.401241 | 2019-08-04T22:39:26 | 2019-08-04T22:39:26 | 138,445,444 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | movegen.cpp | #include "movegen.hpp"
#include "assert.hpp"
#include "move.hpp"
#include "position.hpp"
int movegen(const Position &pos, Move *movelist) {
UCI_ASSERT(movelist);
int num_moves = 0;
num_moves += movegen_captures(pos, &movelist[0]);
num_moves += movegen_noncaptures(pos, &movelist[num_moves]);
UCI_ASSERT(num_moves >= 0);
UCI_ASSERT(num_moves < MAX_MOVES);
return num_moves;
}
|
ff6c9a1cd993a3f5f153ad2b756f61bc17570b6c | 28f5b2d9911367fc843b4badfeae293327a4779d | /include/ApproximationCore/ObjectApprox.h | e80269f73c8d56043a4cb293c78404d55817edf7 | [] | no_license | Makerdolck/ObjectsApproximation | 657b9b9500c0f6dfcc363a4e5ac12f30632c123f | f7e2b3e824e4a67bc5aa9991c1b097b86e07acb6 | refs/heads/master | 2020-04-15T18:58:34.758038 | 2019-06-17T17:23:43 | 2019-06-17T17:23:43 | 164,932,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 628 | h | ObjectApprox.h | #pragma once
#ifndef __OBJECT_APPROX_C3D_H__
#define __OBJECT_APPROX_C3D_H__
#include "GeomObjectApprox.h"
#include "CompensationOptionNamesEnum.h"
#include <iostream>
class ObjectApprox
{
// --- --- --- --- --- --- --- --- --- // Properties
public:
GeomObjectApprox *objMath;
std::wstring Name;
bool flagReady,
flagSelected;
long unsigned int objID;
CompensationOptionNamesEnum CompensationOption;
// --- --- --- --- --- --- --- --- --- // Methods
public:
ObjectApprox();
~ObjectApprox();
void UpdateCompensationOption(wchar_t* option, float value);
};
#endif /* __OBJECT_APPROX_C3D_H__ */ |
1f8487932803d785c8daf06b76a4dfa0ccc3d49d | 1ffc14885a6c0c84b947530dd0ccf184b068b256 | /libservice/include/akvsoptmanager.h | 98ae4fc778ceeb5ce0865308bd5ad7dc0b96239f | [] | no_license | EchelonTeam/akvs_main | 2623e7274c75be17b7e67032aafe29fb200831fa | c9b578a0a4ece75ba0b36d90d6fbbab9c7664cdd | refs/heads/master | 2021-01-02T08:56:25.188076 | 2012-11-13T10:08:53 | 2012-11-13T10:08:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | h | akvsoptmanager.h | #ifndef AKVSOPTMANAGER_H
#define AKVSOPTMANAGER_H
#include "optManager.h"
class AKVSOptManager
{
public:
QString strDescription;
struct main_options
{
int verboseLevel;
AKVS_OPTMANAGER::eObject inputSource;
AKVS_OPTMANAGER::eObject outputSource;
QString input,output,log;
} sOptions;
static AKVSOptManager* _instancePtr;
public:
OptManager* pManager;
/*! This class is a singleton class and so the constructor is private, because of that an object
cannot be created via new instead it will be returned by this method.
The first time that this method is called the \em appFullName needs to be provided
for all subsequent calls it is not needed because the instance will just be returned.
*/
public:
static OptManager * getOptMgr(QString appFullName="");
static AKVSOptManager * getAKVSOptMgr(QString appFullName="");
QString parse(int argc, char *argv[], bool quiet=false);
private:
AKVSOptManager(QString appFullName="");
};
#endif // AKVSOPTMANAGER_H
|
4c45b7ee4bd3d207954e5c45e851dbfbf8278558 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /Simulation/G4Utilities/MCTruthSimAlgs/src/MergeMcEventCollTool.h | 038b9aefa9285373060744f0e1c14690d6d6a6cc | [
"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 | 8,326 | h | MergeMcEventCollTool.h | /*
Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
*/
#ifndef MCTRUTHSIMALGS_MERGEMCEVENTCOLLTOOL_H
#define MCTRUTHSIMALGS_MERGEMCEVENTCOLLTOOL_H
#include "PileUpTools/PileUpToolBase.h"
#include "Gaudi/Property.h"
#include "GaudiKernel/ServiceHandle.h"
#include "GaudiKernel/PhysicalConstants.h"
#include <utility> /* pair */
class McEventCollection;
#include "AtlasHepMC/GenParticle_fwd.h"
#include "AtlasHepMC/GenVertex_fwd.h"
/** @class MergeMcEventCollTool
* @brief a PileUpTool to merge MC truth collection in the overlay store
*
* $Id:
* @author jchapman@cern.ch
*
*/
class MergeMcEventCollTool : public PileUpToolBase {
public:
MergeMcEventCollTool(const std::string& type,
const std::string& name,
const IInterface* parent);
virtual StatusCode initialize() override final;
///called before the subevts loop. Not (necessarily) able to access
///SubEvents
virtual StatusCode prepareEvent(const EventContext& ctx, unsigned int nInputEvents) override final;
///called at the end of the subevts loop. Not (necessarily) able to access
///SubEvents
virtual StatusCode mergeEvent(const EventContext& ctx) override final;
///called for each active bunch-crossing to process current SubEvents
/// bunchXing is in ns
virtual StatusCode processBunchXing(int bunchXing,
SubEventIterator bSubEvents,
SubEventIterator eSubEvents) override final;
/// return false if not interested in certain xing times (in ns)
/// implemented by default in PileUpToolBase as FirstXing<=bunchXing<=LastXing
// virtual bool toProcess(int bunchXing) const;
virtual StatusCode processAllSubEvents(const EventContext& ctx) override final;
private:
//** The types used to classify the events. NOPUTYPE is used both as the number of types, and to flag a reject (no type)
typedef enum puType { INTIME, OUTOFTIME, RESTOFMB, CAVERN, NOPUTYPE } puType;
//** Add the required information from the current GenEvent to the output McEventCollection
StatusCode processEvent(const McEventCollection *pMcEvtColl, const double currentEventTime, const int currentBkgEventIndex);
//** Special case of processEvent for the first (signal) GenEvent
StatusCode processFirstSubEvent(const McEventCollection *pMcEvtColl);
//** Add the required sub-set of the information from the current GenEvent to the output McEventCollection
StatusCode processUnfilteredEvent(const McEventCollection *pMcEvtColl, const double currentEventTime, const int currentBkgEventIndex);
//** This is for events which have already been truth-filtered. Add the whole GenEvent to the output McEventCollection
StatusCode processTruthFilteredEvent(const McEventCollection *pMcEvtColl, const double currentEventTime, const int currentBkgEventIndex);
//** Remove any empty background GenEvents from the output McEventCollection
StatusCode compressOutputMcEventCollection();
//** Print out detailed debug info if required.
void printDetailsOfMergedMcEventCollection() const;
//** Ensure that any GenEvent::HeavyIon info is stored in the signal GenEvent.
StatusCode saveHeavyIonInfo(const McEventCollection *pMcEvtColl);
//** Classify the current GenParticle according to the MC Truth Taskforce requirements
MergeMcEventCollTool::puType classifyVertex(const HepMC::GenParticle *pCurrentVertexParticle, const HepMC::GenVertex *pCurrentParticleProductionVertex, double currentEventTime);
//** Check if the current GenVertex contains beam particles
bool isInitialCollisionVertex(const HepMC::GenVertex *pCurrentVertex) const;
//** Check whether the current McEventCollection has already been truth-filtered
bool isTruthFiltertedMcEventCollection(const McEventCollection *pMcEvtColl) const;
//** Map from GenEvent to puType FIXME: Simpler to key the map on GenEvent* ?
typedef std::map<std::pair<int,int>, int> PileUpBackgroundMap;
PileUpBackgroundMap m_backgroundClassificationMap;
//** Update the map of GenEvent->puType
void updateClassificationMap(int signal_process_id, int event_number, int hack, int classification, bool firstUpdateForThisEvent);
ServiceHandle<PileUpMergeSvc> m_pMergeSvc{this, "PileUpMergeSvc", "PileUpMergeSvc", "Handle for the PileUpMergeSvc (provides input McEventCollections)"};
//** New McEventCollection to be written out to file
McEventCollection* m_pOvrlMcEvColl{};
StringProperty m_truthCollInputKey{this, "TruthCollInputKey", "TruthEvent", "Name of input McEventCollection"};
StringProperty m_truthCollOutputKey{this, "TruthCollOutputKey", "TruthEvent", "Name of output McEventCollection"};
BooleanProperty m_keepUnstable{this, "KeepUnstable", false, "Do not cut unstable particles"};
DoubleProperty m_absEtaMax{this, "AbsEtaMax", 5.0, "Eta cut-off for INTIME GenParticles"};
DoubleProperty m_absEtaMax_outOfTime{this,"OutOfTimeAbsEtaMax", 3.0, "Eta cut-off for OUTOFTIME GenParticles"};
DoubleProperty m_lowTimeToKeep{this, "LowTimeToKeep", -51.0, "leading edge in ns of the time window to keep if SaveOutOfTimePileUp is true"};
DoubleProperty m_highTimeToKeep{this, "HighTimeToKeep", 51.0, "trailing edge in ns of the time window to keep if SaveOutOfTimePileUp is true"};
//** Radius acceptance cut on production vertex of all stable particles (in mm)
DoubleProperty m_rRange{this, "rRange", 20.0*Gaudi::Units::mm, "rRange of production vertex in mm"};
//** Radius acceptance squared to speed up cut
double m_r2Range{400.0};
//** Cut on Z coordinate of production vertex in mm, to distinguish between minbias and cavern background categories
DoubleProperty m_zRange{this, "zRange", 200.0*Gaudi::Units::mm, "z range of production vertex in mm"};
DoubleProperty m_ptMin{this, "ptMin", 0.4*Gaudi::Units::GeV, "Minimum threshold for pT for selected pileup particles in MeV"};
DoubleProperty m_minKinE{this, "EKinMin", 1.0*Gaudi::Units::MeV, "Minimum threshold for Kinetic Energy of selected cavern events in MeV"};
//** save minimum bias events in the t0 bunch xing
BooleanProperty m_saveInTimePileup{this, "SaveInTimeMinBias", true, "save min bias particles in the t0 xing"};
//** save minbias events which are "close" by (within [ m_lowTimeToKeep, m_highTimeToKeep ])
BooleanProperty m_saveOutOfTimePileup{this, "SaveOutOfTimeMinBias", true, "save out of time min bias particles in the [LowTimeToKeep:HighTimeToKeep] range"};
//** save as well the rest of minbias
BooleanProperty m_saveRestOfPileup{this, "SaveRestOfMinBias", false, "save the rest of out of time min bias particles as well"};
//** save as well the cavern background
BooleanProperty m_saveCavernBackground{this, "SaveCavernBackground", true, "save the cavern background as well"};
//** do the slimming - flag to do slimming or not
BooleanProperty m_doSlimming{this, "DoSlimming", true, "flag to do the slimming or save everything"};
//** Should any details of GenEvents corresponding to each puType be saved?
bool m_saveType[NOPUTYPE];
//** The index (before sorting) within the McEventCollection where the background events start
unsigned int m_startingIndexForBackground{0};
//** Bool to indicate that the next GenEvent is a new signal event
bool m_newevent{true};
//** The total number of GenEvents that will be passed for the current signal event
unsigned int m_nInputMcEventColls{0};
//** How many background events have been read so far for this signal event
unsigned int m_nBkgEventsReadSoFar{0};
//** Ensure that the collision GenVertex objects of minbias background events are saved.
BooleanProperty m_addBackgroundCollisionVertices{this, "AddBackgroundCollisionVertices", true, "ensure that the collision GenVertex objects of minbias background events are saved."};
//** Should empty GenEvents be removed from the output McEventCollection?
BooleanProperty m_compressOutputCollection{this, "CompressOutputCollection", false, "Remove all empty GenEvents from the output McEventCollection"};
//** Just save the Signal GenEvent
BooleanProperty m_onlySaveSignalTruth{this, "OnlySaveSignalTruth", false, "Just save the Signal GenEvent"};
//** Temporary store for the true signal event number
int m_signal_event_number{0};
};
#endif //MCTRUTHSIMALGS_MERGEMCEVENTCOLLTOOL_H
|
43c245c9b1d2d9e3f486c6b52dee4486f4312983 | 8c80b2b34ebeb45071a6f62776f73119f2bb2ba1 | /KMPDinoEthernet/src/KMPDinoEthernet/src/MqttTopicHelper.cpp | 4706ef3e270c30718c01d73fae9c02545f60c1bf | [] | no_license | kmpelectronics/Arduino | 815962c6e79d8d53ceb7b1d33ea9a6388853f647 | e8a2908ed095dff93221eae5d3553991b7505aea | refs/heads/master | 2022-09-12T21:39:41.469718 | 2022-08-24T19:21:36 | 2022-08-24T19:21:36 | 28,829,416 | 11 | 18 | null | 2022-11-12T10:57:04 | 2015-01-05T20:07:38 | C++ | UTF-8 | C++ | false | false | 4,666 | cpp | MqttTopicHelper.cpp | //
//
//
#include "MqttTopicHelper.h"
#include "KMPCommon.h"
#include <stdarg.h>
const char* _baseTopic;
const char* _deviceTopic;
char _mainTopic[MAIN_TOPIC_MAXLEN];
size_t _mainTopicLen;
char _isReadyTopic[MAIN_TOPIC_MAXLEN];
size_t _setTopicLen;
Print* _debugPort;
void MqttTopicHelperClass::init(const char* baseTopic, const char* deviceTopic, Print* debugPort)
{
_baseTopic = baseTopic;
_deviceTopic = deviceTopic;
_debugPort = debugPort;
// Building main topic.
strcpy(_mainTopic, baseTopic);
addCharToStr(_mainTopic, TOPIC_SEPARATOR);
strcat(_mainTopic, deviceTopic);
_mainTopicLen = strlen(_mainTopic);
// Building is ready topic.
strcpy(_isReadyTopic, _mainTopic);
addCharToStr(_isReadyTopic, TOPIC_SEPARATOR);
strcat(_isReadyTopic, ISREADY_TOPIC);
_setTopicLen = strlen(SET_TOPIC);
}
void MqttTopicHelperClass::printTopicAndPayload(const char * topic, const byte * payload, unsigned int length)
{
if (_debugPort == NULL)
{
return;
}
_debugPort->print(F("Topic ["));
_debugPort->print(topic);
_debugPort->println(F("]"));
_debugPort->print(F("Payload ["));
for (unsigned int i = 0; i < length; i++)
{
_debugPort->print((char)payload[i]);
}
_debugPort->println(F("]"));
}
void MqttTopicHelperClass::printTopicAndPayload(const char * topic, const char * payload)
{
printTopicAndPayload(topic, (const byte *) payload, strlen(payload));
}
void MqttTopicHelperClass::addCharToStr(char * str, const char chr)
{
size_t len = strlen(str);
str[len++] = chr;
str[len] = CH_NONE;
}
void MqttTopicHelperClass::addTopicSeparator(char * str)
{
addCharToStr(str, TOPIC_SEPARATOR);
}
void MqttTopicHelperClass::appendTopic(char * topic, const char * nextTopic)
{
if (topic[0] == CH_NONE)
{
strcpy(topic, nextTopic);
}
else
{
addTopicSeparator(topic);
strcat(topic, nextTopic);
}
}
const char * MqttTopicHelperClass::getMainTopic()
{
return _mainTopic;
}
const char * MqttTopicHelperClass::getIsReadyTopic()
{
return _isReadyTopic;
}
bool MqttTopicHelperClass::startsWithMainTopic(const char * str)
{
return startsWith(str, _mainTopic);
}
void MqttTopicHelperClass::buildTopic(char * str, int num, ...)
{
str[0] = CH_NONE;
va_list valist;
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++) {
appendTopic(str, va_arg(valist, char*));
}
/* clean memory reserved for valist */
va_end(valist);
}
bool MqttTopicHelperClass::isBaseTopic(char * topic)
{
return isOnlyThisTopic(topic, _baseTopic);
}
bool MqttTopicHelperClass::isMainTopic(char * topic)
{
return isOnlyThisTopic(topic, _mainTopic);
}
bool MqttTopicHelperClass::isReadyTopic(char * topic)
{
return isOnlyThisTopic(topic, _isReadyTopic);
}
bool MqttTopicHelperClass::getNextTopic(const char * topics, char * nextTopic, char ** otherTopics, bool skipMainTopic)
{
if (!topics || !nextTopic)
return false;
size_t topicLen = strlen(topics);
if (topicLen == 0)
return false;
nextTopic[0] = CH_NONE;
char * otherTopicResult;
if (skipMainTopic)
{
if (topicLen <= _mainTopicLen ||
// starts with MT
strncmp(_mainTopic, topics, _mainTopicLen) != 0 ||
// MT ends with topic separator
topics[_mainTopicLen] != TOPIC_SEPARATOR)
{
return false;
}
// Skip MT + separator.
otherTopicResult = (char *)topics + _mainTopicLen + 1;
}
else
{
if (topics[0] == TOPIC_SEPARATOR)
{
// includes only separator
if (topicLen == 1)
return false;
// Skip separator
otherTopicResult = (char*)topics + 1;
}
else
{
otherTopicResult = (char*)topics;
}
}
char * findPos = otherTopicResult;
size_t length = 0;
while (*findPos != CH_NONE && *findPos != TOPIC_SEPARATOR)
{
findPos++;
length++;
}
if (length == 0)
return false;
strNCopy(nextTopic, otherTopicResult, length);
*otherTopics = otherTopicResult + length;
return true;
}
bool MqttTopicHelperClass::isTopicSet(const char* topics)
{
return endsWith(topics, SET_TOPIC);
}
bool MqttTopicHelperClass::isOnlyThisTopic(const char * topic1, const char * topic2)
{
if (!topic1 || !topic2)
{
return false;
}
return isEqual(topic1, topic2);
}
void MqttTopicHelperClass::buildTopicWithMT(char * str, int num, ...)
{
str[0] = CH_NONE;
appendTopic(str, _mainTopic);
va_list valist;
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++) {
appendTopic(str, va_arg(valist, char*));
}
/* clean memory reserved for valist */
va_end(valist);
}
MqttTopicHelperClass MqttTopicHelper; |
b9a3300016378bf220616c04b0c4712c60e02e62 | 945805861f885bd18e943c43659c01aa1f132414 | /fuzz-tests/strings/Zfunc.cpp | 6d0ffacbb51aac35cb3cae37c71e71c22f5c95ac | [] | no_license | aryanc403/kactl | 217385a791d220b7656ab69e07f08aa34951f81b | c3be3a8cf3908f17149c61a1fe2b3df2ca40105e | refs/heads/aryanc403 | 2022-11-10T03:41:47.321909 | 2019-12-30T08:32:16 | 2019-12-30T08:32:16 | 210,900,578 | 3 | 3 | null | 2022-11-01T18:20:45 | 2019-09-25T17:18:32 | C++ | UTF-8 | C++ | false | false | 1,138 | cpp | Zfunc.cpp | // Thanks to Ludo Pulles
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(it, v) for(auto& it : v)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#include "../../content/strings/Zfunc.h"
template <class F> void gen(string &s, int at, int alpha, F f) {
if (at == sz(s))
f();
else {
rep(i, 0, alpha) {
s[at] = (char)('a' + i);
gen(s, at + 1, alpha, f);
}
}
}
void test(const string &s) {
int n = sz(s);
vi found = Z(s);
vi expected(n, 0);
rep(i, 1, n) { // exclude index 0 (!)
int j = 0;
while (i + j < n && s[i + j] == s[j])
j++;
expected[i] = j;
}
assert(found == expected);
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
rep(n, 0, 13) {
string s(n, 'x');
gen(s, 0, 3, [&]() { test(s); });
}
rep(n, 0, 11) {
string s(n, 'x');
gen(s, 0, 4, [&]() { test(s); });
}
cout<<"Tests passed!"<<endl;
}
|
2e7036b457bbdf0263d8e61d9faa897edce937fb | 1960a29ed846efb82af26ee4fc9512dde73b47c3 | /Include/Indicators/Volumes.h | fbd94e8c03b83f1f1279a07befe3b2c8b65c78cc | [] | no_license | BestSean2016/mmqqll44 | fbb4c14e4ed88b658e4940211565fcb180a93d39 | f2b1b933e827e3b813fce177616d7cf06ad03c14 | refs/heads/master | 2016-09-13T15:31:04.642935 | 2016-04-21T23:30:52 | 2016-04-21T23:30:52 | 56,772,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,774 | h | Volumes.h | //+------------------------------------------------------------------+
//| Volumes.h |
//| Copyright 2009-2013, MetaQuotes Software Corp. |
//| http://www.mql4.com |
//+------------------------------------------------------------------+
#include "Indicator.h"
//+------------------------------------------------------------------+
//| Class CiAD. |
//| Purpose: Class of the "Accumulation/Distribution" indicator. |
//| Derives from class CIndicator. |
//+------------------------------------------------------------------+
class CiAD : public CIndicator
{
protected:
ENUM_APPLIED_VOLUME m_applied; // applied volume
public:
CiAD(void);
~CiAD(void);
//--- methods of access to protected data
ENUM_APPLIED_VOLUME Applied(void) const { return(m_applied); }
//--- method of creation
bool Create(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_VOLUME applied);
//--- methods of access to indicator data
virtual double GetData(const int buffer_num,const int index) const;
double Main(const int index) const;
//--- method of identifying
virtual int Type(void) const { return(IND_AD); }
protected:
//--- methods of tuning
virtual bool Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int num_params,const MqlParam ¶ms[]);
bool Initialize(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_VOLUME applied);
};
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CiAD::CiAD(void) : m_applied(-1)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CiAD::~CiAD(void)
{
}
//+------------------------------------------------------------------+
//| Create the "Accumulation/Distribution" indicator |
//+------------------------------------------------------------------+
bool CiAD::Create(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_VOLUME applied)
{
SetSymbolPeriod(symbol,period);
//--- result of initialization
return(Initialize(symbol,period,applied));
}
//+------------------------------------------------------------------+
//| Initialize the indicator with universal parameters |
//+------------------------------------------------------------------+
bool CiAD::Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int num_params,const MqlParam ¶ms[])
{
return(Initialize(symbol,period,(ENUM_APPLIED_VOLUME)params[0].integer_value));
}
//+------------------------------------------------------------------+
//| Initialize the indicator with special parameters |
//+------------------------------------------------------------------+
bool CiAD::Initialize(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_VOLUME applied)
{
m_name="AD";
//--- save settings
m_applied=applied;
//--- ok
return(true);
}
//+------------------------------------------------------------------+
//| Access to buffer of "Accumulation/Distribution" |
//+------------------------------------------------------------------+
double CiAD::GetData(const int buffer_num,const int index) const
{
return(iAD(m_symbol,m_period,index));
}
//+------------------------------------------------------------------+
//| Access to buffer of "Accumulation/Distribution" |
//+------------------------------------------------------------------+
double CiAD::Main(const int index) const
{
return(GetData(0,index));
}
//+------------------------------------------------------------------+
//| Class CiMFI. |
//| Purpose: Class of the "Money Flow Index" indicator. |
//| Derives from class CIndicator. |
//+------------------------------------------------------------------+
class CiMFI : public CIndicator
{
protected:
int m_ma_period;
public:
CiMFI(void);
~CiMFI(void);
//--- methods of access to protected data
int MaPeriod(void) const { return(m_ma_period); }
//--- method of creation
bool Create(const string symbol,const ENUM_TIMEFRAMES period,const int ma_period);
//--- methods of access to indicator data
virtual double GetData(const int buffer_num,const int index) const;
double Main(const int index) const;
//--- method of identifying
virtual int Type(void) const { return(IND_MFI); }
protected:
//--- methods of tuning
virtual bool Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int num_params,const MqlParam ¶ms[]);
bool Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int ma_period);
};
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CiMFI::CiMFI(void) : m_ma_period(-1)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CiMFI::~CiMFI(void)
{
}
//+------------------------------------------------------------------+
//| Create the "Money Flow Index" indicator |
//+------------------------------------------------------------------+
bool CiMFI::Create(const string symbol,const ENUM_TIMEFRAMES period,const int ma_period)
{
SetSymbolPeriod(symbol,period);
//--- result of initialization
return(Initialize(symbol,period,ma_period));
}
//+------------------------------------------------------------------+
//| Initialize the indicator with universal parameters |
//+------------------------------------------------------------------+
bool CiMFI::Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int num_params,const MqlParam ¶ms[])
{
return(Initialize(symbol,period,(int)params[0].integer_value));
}
//+------------------------------------------------------------------+
//| Initialize the indicator with special parameters |
//+------------------------------------------------------------------+
bool CiMFI::Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int ma_period)
{
m_name="MFI";
//--- save settings
m_ma_period=ma_period;
//--- ok
return(true);
}
//+------------------------------------------------------------------+
//| Access to buffer of "Money Flow Index" |
//+------------------------------------------------------------------+
double CiMFI::GetData(const int buffer_num,const int index) const
{
return(iMFI(m_symbol,m_period,m_ma_period,index));
}
//+------------------------------------------------------------------+
//| Access to buffer of "Money Flow Index" |
//+------------------------------------------------------------------+
double CiMFI::Main(const int index) const
{
return(GetData(0,index));
}
//+------------------------------------------------------------------+
//| Class CiOBV. |
//| Purpose: Class of the "On Balance Volume" indicator. |
//| Derives from class CIndicator. |
//+------------------------------------------------------------------+
class CiOBV : public CIndicator
{
protected:
ENUM_APPLIED_PRICE m_applied;
public:
CiOBV(void);
~CiOBV(void);
//--- methods of access to protected data
ENUM_APPLIED_PRICE Applied(void) const { return(m_applied); }
//--- method create
bool Create(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_PRICE applied);
//--- methods of access to indicator data
virtual double GetData(const int buffer_num,const int index) const;
double Main(const int index) const;
//--- method of identifying
virtual int Type(void) const { return(IND_OBV); }
protected:
//--- methods of tuning
virtual bool Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int num_params,const MqlParam ¶ms[]);
bool Initialize(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_PRICE applied);
};
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CiOBV::CiOBV(void) : m_applied(-1)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CiOBV::~CiOBV(void)
{
}
//+------------------------------------------------------------------+
//| Create the "On Balance Volume" indicator |
//+------------------------------------------------------------------+
bool CiOBV::Create(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_PRICE applied)
{
SetSymbolPeriod(symbol,period);
//--- result of initialization
return(Initialize(symbol,period,applied));
}
//+------------------------------------------------------------------+
//| Initialize the indicator with universal parameters |
//+------------------------------------------------------------------+
bool CiOBV::Initialize(const string symbol,const ENUM_TIMEFRAMES period,const int num_params,const MqlParam ¶ms[])
{
return(Initialize(symbol,period,(ENUM_APPLIED_PRICE)params[0].integer_value));
}
//+------------------------------------------------------------------+
//| Initialize the indicator with special parameters |
//+------------------------------------------------------------------+
bool CiOBV::Initialize(const string symbol,const ENUM_TIMEFRAMES period,const ENUM_APPLIED_PRICE applied)
{
m_name="OBV";
//--- save settings
m_applied=applied;
//--- ok
return(true);
}
//+------------------------------------------------------------------+
//| Access to buffer of "On Balance Volume" |
//+------------------------------------------------------------------+
double CiOBV::GetData(const int buffer_num,const int index) const
{
return(iOBV(m_symbol,m_period,m_applied,index));
}
//+------------------------------------------------------------------+
//| Access to buffer of "On Balance Volume" |
//+------------------------------------------------------------------+
double CiOBV::Main(const int index) const
{
return(GetData(0,index));
}
//+------------------------------------------------------------------+
|
18df27705b03e332996a80daed9dea2f72c09907 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/net/irda/irxfer/xfer.cxx | b8c4b423b544b106f6ae06f7818f38b9e82371bc | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 32,292 | cxx | xfer.cxx | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1997 - 1999
//
// File: xfer.cxx
//
//--------------------------------------------------------------------------
#include "precomp.h"
#include <irmonftp.h>
error_status_t
MapWinsockErrorToWin32(
error_status_t status
);
DWORD
MdWork(
WCHAR *arg
);
DWORD
ReportFileError( DWORD mc,
WCHAR * file,
DWORD error
)
{
DWORD dwEventStatus = 0;
EVENT_LOG EventLog(WS_EVENT_SOURCE,&dwEventStatus);
if (!dwEventStatus)
{
TCHAR ErrorDescription[ERROR_DESCRIPTION_LENGTH];
if (!FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM,
0, // ignored
error,
0, // try default language ids
ErrorDescription,
ERROR_DESCRIPTION_LENGTH,
0 // ignored
))
{
//
// could not format the message just use the error value
//
StringCbPrintf(ErrorDescription, sizeof(ErrorDescription), L"0x%x", error);
}
WCHAR * Strings[2];
Strings[0] = file;
Strings[1] = ErrorDescription;
dwEventStatus = EventLog.ReportError(CAT_IRXFER, mc, 2, Strings);
}
return dwEventStatus;
}
FILE_TRANSFER::FILE_TRANSFER( )
{
_refs = 1;
_event = 0;
_socket = INVALID_SOCKET;
_cookie = 0;
m_StopListening=FALSE;
// for sock.c
_fWriteable = FALSE;
// for xfer.c
_dataFileRecv.hFile = INVALID_HANDLE_VALUE;
// for progress.c
_fCancelled = FALSE;
_fInUiReceiveList = FALSE;
_CurrentPercentage = 0;
_files = 0;
_dataXferRecv.dwFileSent = 0;
DbgLog2(SEV_INFO, "[0] %p: refs = %d\n", this, _refs);
}
FILE_TRANSFER::~FILE_TRANSFER()
{
if (_socket != INVALID_SOCKET) {
//
// Drain any remaining receive data to ensure our sent data is sent across the link.
//
closesocket( _socket );
_socket = INVALID_SOCKET;
}
if (_event) {
CloseHandle( _event );
_event = 0;
}
if (_fInUiReceiveList) {
_ReceiveFinished( rpcBinding, _cookie, 0 );
}
delete [] _files;
DeleteCriticalSection(&m_Lock);
}
unsigned long __stdcall
SendFilesWrapper( PVOID arg )
{
PFILE_TRANSFER(arg)->Send();
return 0;
}
void
FILE_TRANSFER::BeginSend(
DWORD DeviceId,
OBEX_DEVICE_TYPE DeviceType,
error_status_t * pStatus,
FAILURE_LOCATION * pLocation
)
{
DWORD status;
DWORD dwFiles = 0L;
DWORD dwFolders = 0L;
__int64 dwTotalSize = 0L;
status = _GetObjListStats( _files, &dwFiles, &dwFolders, &dwTotalSize );
if (status) {
*pLocation = locFileOpen;
goto lExit;
}
if (( 0 == dwFiles) && (0 == dwFolders )) {
goto lExit; // nothing to send
}
status = Sock_EstablishConnection( DeviceId,DeviceType );
if ( status ) {
*pLocation = locConnect;
goto lExit;
}
_dataXferRecv.dwTotalSize = (DWORD) dwTotalSize;
DWORD ThreadId;
HANDLE ThreadHandle;
ThreadHandle = CreateThread( 0,
0,
SendFilesWrapper,
this,
0,
&ThreadId
);
if (!ThreadHandle) {
*pLocation = locStartup;
status = GetLastError();
goto lExit;
}
CloseHandle( ThreadHandle );
lExit:
if (status) {
DecrementRefCount();
}
*pStatus = status;
}
void
FILE_TRANSFER::Send()
{
error_status_t status = 0;
wchar_t * szObj=L"";
ULONG64 dwTotalSize=_dataXferRecv.dwTotalSize;
//
// Avoid idle-time shutdowns. If the call fails, we want to continue anyway.
//
SetThreadExecutionState( ES_SYSTEM_REQUIRED | ES_CONTINUOUS );
status = Obex_Connect( dwTotalSize );
if (status == ERROR_SUCCESS) {
_Send_StartXfer( dwTotalSize, 0 );
//
// send the files one at a time
//
for( szObj = _files; *szObj != 0; szObj += lstrlen(szObj)+1 ) {
DbgLog1( SEV_INFO, "Sending %S", szObj );
_UpdateSendProgress( rpcBinding,
_cookie,
szObj,
_dataXferRecv.dwTotalSize,
_completedFilesSize,
&status
);
if ( DirectoryExists(szObj) ) {
status = _SendFolder( szObj );
} else {
status = _SendFile( szObj );
}
if ((status !=ERROR_SUCCESS) || g_fShutdown) {
break;
}
}
}
//
// Re-enable idle-time shutdowns.
//
SetThreadExecutionState( ES_CONTINUOUS );
//
// Make sure we show 100% for a completed transfer.
//
if (!status) {
_UpdateSendProgress( rpcBinding,
_cookie,
_dataFileRecv.szFileName,
_dataXferRecv.dwTotalSize,
_dataXferRecv.dwTotalSize,
&status
);
}
if (status != ERROR_CANCELLED) {
//
// don't overwrite the error unless there isn't one
//
error_status_t errTemp;
_Send_EndXfer();
errTemp = Obex_Disconnect( status );
if ( !status ) {
status = errTemp;
}
}
if ( status != ERROR_SUCCESS ) {
// status = MapWinsockErrorToWin32( status );
_OneSendFileFailed( rpcBinding, _cookie, szObj, status, locFileSend, &status );
}
_SendComplete( rpcBinding, _cookie, _dataXferRecv.dwTotalSent, &status );
RemoveFromTransferList(this);
DecrementRefCount();
}
error_status_t
MapWinsockErrorToWin32(
error_status_t status
)
{
if (status)
{
DbgLog2(SEV_ERROR, "mapping error 0x%x (%d)", status, status);
}
if (status < WSABASEERR || status > WSABASEERR + 1000)
{
return status;
}
switch (status)
{
case WSAECONNREFUSED:
return ERROR_CONNECTION_REFUSED;
default:
return ERROR_REQUEST_ABORTED;
}
}
error_status_t
_GetObjListStats(
LPWSTR lpszObjList,
LPDWORD lpdwFiles,
LPDWORD lpdwFolders,
__int64 * lpdwTotalSize
)
{
error_status_t status = 0;
LPWSTR szObj;
HANDLE hFile;
// get (a) number of files, (b) total file size
//
for( szObj = lpszObjList; *szObj != 0; szObj += lstrlen(szObj)+1 ) {
hFile = CreateFile(
szObj,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if( INVALID_HANDLE_VALUE == hFile ) {
// if it's a directory, get the total size of its files
if( DirectoryExists(szObj) ) {
*lpdwTotalSize += GetDirectorySize( szObj );
(*lpdwFolders)++;
continue;
} else {
DbgLog2(SEV_ERROR, "open file \'%S\' failed %d", szObj, GetLastError());
ReportFileError( MC_IRXFER_OPEN_FAILED, szObj, GetLastError() );
return GetLastError();
}
}
*lpdwTotalSize += GetFileSize( hFile, NULL );
(*lpdwFiles)++;
CloseHandle( hFile );
}
return 0;
}
BOOL
FILE_TRANSFER::Xfer_Init(
wchar_t * files,
unsigned length,
OBEX_DIALECT dialect,
OBEX_DEVICE_TYPE DeviceType,
BOOL CreateSocket,
SOCKET ListenSocket
)
{
unsigned Timeout = 500;
DWORD status = 0;
m_ListenSocket=ListenSocket;
_dialect = dialect;
InitializeCriticalSection(&m_Lock);
if (length)
{
_xferType = xferSEND;
_files = new wchar_t[ length ];
if (!_files)
{
goto cleanup;
}
memcpy(_files, files, sizeof(wchar_t) * length );
}
else
{
_xferType = xferRECV;
_files = 0;
}
_dataXferRecv.fXferInProgress = FALSE;
m_DeviceType=DeviceType;
if (CreateSocket) {
if (DeviceType == TYPE_IRDA) {
_socket = socket( AF_IRDA, SOCK_STREAM, 0);
} else {
_socket = socket( AF_INET, SOCK_STREAM, 0);
}
if (!_socket) {
goto cleanup;
}
setsockopt( _socket, SOL_SOCKET, SO_RCVTIMEO, (char *) &Timeout, sizeof(Timeout));
} else {
_socket = INVALID_SOCKET;
}
_event = CreateEvent( NULL, // no security
TRUE, // manual-reset
FALSE, // initially not set
NULL // no name
);
if (!_event)
{
goto cleanup;
}
_state = BLANK;
_guard = GUARD_MAGIC;
if ( !Obex_Init())
{
goto cleanup;
}
return TRUE;
cleanup:
if (_files != NULL) {
delete _files;
_files=NULL;
}
if (_socket != INVALID_SOCKET ) {
closesocket( _socket );
_socket=INVALID_SOCKET;
}
if (_event != NULL) {
CloseHandle( _event );
_event=NULL;
}
return FALSE;
}
error_status_t
FILE_TRANSFER::Xfer_ConnStart()
{
_uObjsReceived = 0;
_dataXferRecv.fXferInProgress = TRUE;
_dataXferRecv.dwTotalSize = 0;
_dataXferRecv.dwTotalSent = 0;
return _SetReceiveFolder( NULL );
}
VOID FILE_TRANSFER::Xfer_ConnEnd( VOID )
{
_dataXferRecv.fXferInProgress = FALSE;
}
error_status_t
FILE_TRANSFER::Xfer_SetPath(
LPWSTR szPath
)
{
error_status_t status = 0;
if( !szPath || lstrlen(szPath) == 0 )
{
// set default receive folder
return _SetReceiveFolder( NULL );
}
if( lstrcmp(szPath, szPREVDIR) == 0 )
{
// pop up a level
WCHAR sz[MAX_PATH];
StringCbCopy(sz, sizeof(sz), _szRecvFolder );
// remove trailing backslash
if(bHasTrailingSlash(sz))
sz[lstrlen(sz)-1] = cNIL;
// strip last folder off path
StripFile( sz );
return _SetReceiveFolder( sz );
}
// format szPath and append it to the current receive folder
WCHAR szRFF[MAX_PATH];
LPWSTR lpsz;
// remove preceding backslashes
while( *szPath == cBACKSLASH )
szPath++;
// remove anything after a backslash
lpsz = szPath;
while( *lpsz != cNIL && *lpsz != cBACKSLASH )
lpsz++;
*lpsz = cNIL;
StringCbCopy(szRFF, sizeof(szRFF), _szRecvFolder );
GetUniqueName( szRFF, sizeof(szRFF)/sizeof(WCHAR), szPath, FALSE );
_uObjsReceived++;
return _SetReceiveFolder( szRFF );
}
VOID FILE_TRANSFER::Xfer_FileInit( VOID )
{
_dataXferRecv.dwFileSize = 0;
_dataXferRecv.dwFileSent = 0;
FillMemory( &_dataFileRecv.filetime, sizeof(_dataFileRecv.filetime), (BYTE)-1 );
_dataFileRecv.szFileName[0]= TEXT('\0');
_dataFileRecv.szFileSave[0]= TEXT('\0');
_dataFileRecv.szFileTemp[0]= TEXT('\0');
}
error_status_t
FILE_TRANSFER::Xfer_FileSetName( LPWSTR szName )
{
StringCbCopy(_dataFileRecv.szFileName, sizeof(_dataFileRecv.szFileName), szName );
return _FileStart();
}
BOOL FILE_TRANSFER::Xfer_FileSetSize( BYTE4 b4Size )
{
_dataXferRecv.dwFileSize = b4Size;
return ( IsRoomForFile(_dataXferRecv.dwFileSize, _szRecvFolder) );
}
error_status_t
FILE_TRANSFER::Xfer_FileWriteBody(
LPVOID lpvData,
BYTE2 b2Size,
BOOL fFinal
)
{
error_status_t status = 0;
DWORD dwSize = b2Size;
DWORD dwBytesWritten;
DbgLog1( SEV_FUNCTION, "Xfer_WriteBody: %ld bytes", dwSize );
// has this file been opened yet?
if( INVALID_HANDLE_VALUE == _dataFileRecv.hFile )
{
ASSERT( 0 );
return ERROR_CANTOPEN;
}
// write the data to the file
while( dwSize > 0 )
{
BOOL fRet;
fRet = WriteFile( _dataFileRecv.hFile,
lpvData,
dwSize,
&dwBytesWritten,
NULL
);
if( !fRet )
{
status = GetLastError();
break;
}
lpvData = (LPVOID)( (DWORD_PTR)lpvData + dwBytesWritten );
dwSize -= dwBytesWritten;
_dataXferRecv.dwTotalSent += dwBytesWritten;
_dataXferRecv.dwFileSent += dwBytesWritten;
}
if( fFinal )
{
if (!status)
{
status = _FileEnd( TRUE );
}
else
{
_FileEnd( TRUE );
}
}
return status;
}
VOID FILE_TRANSFER::Xfer_FileAbort( VOID )
{
_FileEnd( FALSE );
}
error_status_t
FILE_TRANSFER::_FileStart()
{
WCHAR szFullPath[MAX_PATH];
WCHAR szBaseFile[MAX_PATH];
//
// get path of file
//
StringCbCopy(szFullPath,sizeof(szFullPath), _szRecvFolder );
//
// strip path to get the base filename
//
StripPath(_dataFileRecv.szFileName ,szBaseFile, sizeof(szBaseFile)/sizeof(WCHAR) );
GetUniqueName( szFullPath, sizeof(szFullPath)/sizeof(WCHAR), szBaseFile, TRUE );
StringCbCopy(_dataFileRecv.szFileSave,sizeof(_dataFileRecv.szFileSave), szFullPath );
DbgLog1( SEV_INFO, "Save file: [%S]", szFullPath );
GetTempPath( sizeof(szBaseFile)/sizeof(WCHAR), szBaseFile );
GetTempFileName( szBaseFile, TEMP_FILE_PREFIX, 0, szFullPath );
StringCbCopy(_dataFileRecv.szFileTemp,sizeof(_dataFileRecv.szFileTemp), szFullPath );
DbgLog1( SEV_INFO, "Temp file: [%S]", szFullPath );
{
wchar_t RFF[1+MAX_PATH];
GetReceivedFilesFolder(RFF, MAX_PATH);
wchar_t * PromptPath = _dataFileRecv.szFileSave + lstrlen(RFF);
DbgLog2( SEV_INFO, "need to ask permission: \n new file = [%S]\n prompt file = [%S]",
_dataFileRecv.szFileSave,
PromptPath );
error_status_t status = _GetPermission( rpcBinding, _cookie, PromptPath, FALSE );
if (status)
{
DbgLog2( SEV_ERROR, "permission check failed, cookie %p error %d", (void *) _cookie, status );
return status;
}
}
//
// Create the temporary file.
//
_dataFileRecv.hFile = CreateFile(
szFullPath,
GENERIC_WRITE,
0L,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if ( INVALID_HANDLE_VALUE == _dataFileRecv.hFile )
{
ReportFileError( MC_IRXFER_OPEN_FAILED, szFullPath, GetLastError() );
return GetLastError();
}
return 0;
}
error_status_t
FILE_TRANSFER::_FileEnd( BOOL fSave )
{
error_status_t status = 0;
// set the date stamp
if( _dataFileRecv.filetime.dwLowDateTime != (DWORD)-1
|| _dataFileRecv.filetime.dwHighDateTime != (DWORD)-1 )
{
if( INVALID_HANDLE_VALUE != _dataFileRecv.hFile )
SetFileTime( _dataFileRecv.hFile, NULL, NULL, &_dataFileRecv.filetime );
}
if( INVALID_HANDLE_VALUE != _dataFileRecv.hFile )
{
CloseHandle( _dataFileRecv.hFile );
_dataFileRecv.hFile = INVALID_HANDLE_VALUE;
}
if( fSave )
{
_uObjsReceived++;
if (!MoveFile( _dataFileRecv.szFileTemp, _dataFileRecv.szFileSave ))
{
status = GetLastError();
ReportFileError( MC_IRXFER_MOVE_FAILED, _dataFileRecv.szFileSave, status );
DbgLog3(SEV_ERROR, "%d moving %S -> %S", status, _dataFileRecv.szFileTemp, _dataFileRecv.szFileSave);
}
else
{
DbgLog2(SEV_INFO, "moved %S -> %S", _dataFileRecv.szFileTemp, _dataFileRecv.szFileSave);
}
}
else
{
DeleteFile( _dataFileRecv.szFileTemp );
}
Xfer_FileInit();
return status;
}
error_status_t
FILE_TRANSFER::_SetReceiveFolder(
LPWSTR szFolder
)
{
error_status_t status = 0;
WCHAR sz[MAX_PATH];
WCHAR szFullPath[MAX_PATH] = { 0 };
WCHAR* pszFilePart;
DbgLog1( SEV_FUNCTION, "_SetReceiveFolder: [%S]", (szFolder?szFolder : L"NULL") );
GetReceivedFilesFolder( sz, sizeof(sz) );
//
// Make sure the requested folder is within the root RFF, for security reasons.
//
if ( szFolder && lstrlen(szFolder) > 0 ) {
DWORD dwLen = GetFullPathName(szFolder, MAX_PATH, szFullPath, &pszFilePart);
//
// normalize the path name first, so that the comparison can be meaningful
//
if (dwLen != 0 && dwLen < MAX_PATH) {
if ( 0 == wcsncmp(sz, szFullPath, lstrlen(sz)) ) {
StringCbCopy(_szRecvFolder,sizeof(_szRecvFolder), szFullPath );
} else {
//
// can't go outside the RFF tree; use the root RFF.
//
StringCbCopy(_szRecvFolder,sizeof(_szRecvFolder),sz );
}
} else {
StringCbCopy(_szRecvFolder,sizeof(_szRecvFolder),sz );
}
} else {
StringCbCopy(_szRecvFolder,sizeof(_szRecvFolder),sz );
}
//
// always end path with a backslash '\'
//
if( bNoTrailingSlash(_szRecvFolder) ) {
StringCbCat(_szRecvFolder, sizeof(_szRecvFolder),szBACKSLASH );
}
//
// Get permission to create this directory, unless we have not yet called ReceiveInProgress.
// This latter will be true only during the connect. This seems harmless: a malicious
// client can only create a couple of empty directories in my desktop w/o authorization.
//
if (_fInUiReceiveList)
{
wchar_t * PromptPath = _szRecvFolder + lstrlen(sz);
DbgLog2( SEV_INFO, "need to ask permission: \n new dir = [%S]\n prompt dir = [%S]",
_szRecvFolder,
PromptPath );
status = _GetPermission( rpcBinding, _cookie, PromptPath, TRUE );
if (status)
{
DbgLog1( SEV_ERROR, "permission check failed %d", status );
return status;
}
}
DbgLog1( SEV_INFO, "Setting Receive Folder: [%S]", _szRecvFolder );
if( !DirectoryExists( _szRecvFolder ) )
{
status = MdWork( _szRecvFolder );
if (status)
{
ReportFileError( MC_IRXFER_CREATE_DIR_FAILED, _szRecvFolder, status );
}
}
DbgLog1( SEV_FUNCTION, "_SetReceiveFolder leave %d", status);
return status;
}
VOID
FILE_TRANSFER::_Send_StartXfer( __int64 dwTotalSize,
LPWSTR szDst
)
{
_dataXferRecv.fXferInProgress = TRUE;
_dataXferRecv.dwTotalSize = dwTotalSize;
_dataXferRecv.dwTotalSent = 0;
_completedFilesSize = 0;
}
VOID FILE_TRANSFER::_Send_EndXfer( VOID )
{
_dataXferRecv.fXferInProgress = FALSE;
}
error_status_t
FILE_TRANSFER::_SendFile(
LPWSTR wszFile
)
{
error_status_t status = 0;
DWORD dwFileTime = (DWORD)-1;
HANDLE hFile=INVALID_HANDLE_VALUE;
FILETIME filetime;
DbgLog1(SEV_FUNCTION, "_SendFile( %S )", wszFile);
StringCbCopy(_dataFileRecv.szFileName,sizeof(_dataFileRecv.szFileName), wszFile );
hFile = CreateFileW(
wszFile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if ( INVALID_HANDLE_VALUE == hFile ) {
status=GetLastError();
goto lExit;
}
if( !GetFileTime(hFile, NULL, NULL, &filetime) ) {
status=GetLastError();
goto lExit;
}
_dataXferRecv.dwFileSize = GetFileSize( hFile, NULL );
_dataXferRecv.dwFileSent = 0;
status = Obex_PutBegin( wszFile, _dataXferRecv.dwFileSize, &filetime );
ExitOnErr( status );
status = _PutFileBody( hFile, wszFile );
ExitOnErr( status );
_completedFilesSize += _dataXferRecv.dwFileSize;
lExit:
DbgLog1( SEV_FUNCTION, "_SendFile leave [%d]", status );
if ( INVALID_HANDLE_VALUE != hFile ) {
CloseHandle( hFile );
}
return status;
}
error_status_t
FILE_TRANSFER::_SendFolder(
LPWSTR wszFolder
)
{
error_status_t status = 0;
BOOL bContinue;
HANDLE hFind = INVALID_HANDLE_VALUE;
WCHAR wszDir[MAX_PATH];
WCHAR wszSpec[MAX_PATH*2];
WIN32_FIND_DATAW findData;
// send this directory so it's created
status = Obex_SetPath( wszFolder );
ExitOnErr( status );
//
// get base directory ending with backslash
//
StringCbCopy(wszDir, sizeof(wszDir), wszFolder );
if ( bNoTrailingSlash(wszDir) ) {
StringCbCat(wszDir,sizeof(wszDir), szBACKSLASH );
}
//
// form search string
//
StringCbCopyW(wszSpec,sizeof(wszSpec), wszDir );
StringCbCatW(wszSpec,sizeof(wszSpec), L"*.*" );
hFind = FindFirstFileW( wszSpec, &findData );
bContinue = ( hFind != INVALID_HANDLE_VALUE );
while( bContinue ) {
WCHAR wszObj[MAX_PATH*2];
StringCbCopy(wszObj, sizeof(wszObj), wszDir );
StringCbCat(wszObj, sizeof(wszObj), findData.cFileName );
if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
// weed out "." and ".."
if (0 != lstrcmp(findData.cFileName, szPERIOD) && 0 != lstrcmp(findData.cFileName, szPREVDIR))
{
status = _SendFolder( wszObj );
}
} else {
status = _SendFile( wszObj );
}
if ( status ) {
break;
}
bContinue = FindNextFileW( hFind, &findData );
}
// pop out of this directory
{
error_status_t errTemp = Obex_SetPath( NULL );
// only set the error if there isn't one already
if( !status )
status = errTemp;
}
ExitOnErr( status );
lExit:
if ( hFind != INVALID_HANDLE_VALUE )
{
FindClose( hFind );
}
return status;
}
// if we have a file size of 0, we still want to write a
// blank body once, hence fPutOnce
error_status_t
FILE_TRANSFER::_PutFileBody( HANDLE hFile, wchar_t FileName[] )
{
error_status_t status = 0;
BOOL fPutOnce = FALSE;
DWORD dwRead;
BYTE1 b1Send[cbSOCK_BUFFER_SIZE];
DWORD Extra = sizeof(b1Send) % (_dataRecv.b2MaxPacket-16);
DbgLog( SEV_FUNCTION, "_PutFileBody" );
while( !status && !g_fShutdown)
{
BOOL fRet = ReadFile(
hFile,
b1Send,
sizeof(b1Send) - Extra,
&dwRead,
NULL
);
if( !fRet )
return GetLastError();
if( dwRead == 0 && fPutOnce )
break;
_dataXferRecv.dwTotalSent += dwRead;
_dataXferRecv.dwFileSent += dwRead;
// NOTE: casting dwRead from 4 bytes to 2 bytes requires
// cbSOCK_BUFFER_SIZE to fit into 2 bytes
status = Obex_PutBody( FileName,
b1Send,
(BYTE2)dwRead,
_dataXferRecv.dwFileSent == _dataXferRecv.dwFileSize
);
fPutOnce = TRUE;
}
DbgLog1( SEV_FUNCTION, "_PutFileBody leave [%d]", status );
return status;
}
VOID FILE_TRANSFER::Xfer_SetSize( BYTE4 b4Size )
{
_dataXferRecv.dwTotalSize = b4Size;
}
void
FILE_TRANSFER::RecordDeviceName(
SOCKADDR_IRDA * s
)
{
char buffer[sizeof(DEVICELIST) + 8*sizeof(IRDA_DEVICE_INFO)];
DEVICELIST * list = (DEVICELIST *) buffer;
int size = sizeof(buffer);
if (SOCKET_ERROR == getsockopt( _socket, SOL_IRLMP, IRLMP_ENUMDEVICES, buffer, &size)) {
StringCbCopy(_DeviceName,sizeof(_DeviceName), g_UnknownDeviceName );
return;
}
for (unsigned i=0; i < list->numDevice; ++i) {
if (0 == memcmp(list->Device[i].irdaDeviceID, s->irdaDeviceID, sizeof(s->irdaDeviceID))) {
UCHAR TempBuffer[sizeof(list->Device[i].irdaDeviceName)+3];
unsigned MaxCharCount;
//
// zero out the whole buffer and then copy the string from the device to make sure it
// is null terminated
//
ZeroMemory(&TempBuffer[0],sizeof(TempBuffer));
CopyMemory(&TempBuffer[0],list->Device[i].irdaDeviceName,sizeof(list->Device[i].irdaDeviceName));
//
// get the character count of unicode destination buffer
//
MaxCharCount = sizeof(_DeviceName)/sizeof(wchar_t);
if (list->Device[i].irdaCharSet != LmCharSetUNICODE) {
MultiByteToWideChar(CP_ACP, 0,
(LPCSTR)&TempBuffer[0],
-1, // NULL terminated string
_DeviceName,
MaxCharCount
);
} else {
//
// the name is in unicode
//
StringCbCopy( _DeviceName,
sizeof(_DeviceName),
(wchar_t *)&TempBuffer[0]
);
}
return;
}
}
StringCbCopy(_DeviceName,sizeof(_DeviceName), g_UnknownDeviceName );
}
//
// Code that I took from CMD.EXE
//
#define COLON ':'
#define NULLC '\0'
#define BSLASH '\\'
BOOL IsValidDrv(TCHAR drv);
/**************** START OF SPECIFICATIONS ***********************/
/* */
/* SUBROUTINE NAME: MdWork */
/* */
/* DESCRIPTIVE NAME: Make a directory */
/* */
/* FUNCTION: MdWork creates a new directory. */
/* */
/* INPUT: arg - a pointer to a NULL terminated string of the */
/* new directory to create. */
/* */
/* EXIT-NORMAL: returns zero if the directory is made */
/* successfully */
/* */
/* EXIT-ERROR: returns an error code otherwise */
/* */
/* EFFECTS: None. */
/* */
/**************** END OF SPECIFICATIONS *************************/
DWORD
MdWork(
WCHAR *arg
)
{
ULONG Status;
WCHAR *lpw;
WCHAR TempBuffer[MAX_PATH];
/* Check if drive is valid because Dosmkdir does not
return invalid drive @@5 */
if ((arg[1] == COLON) && !IsValidDrv(*arg))
{
return ERROR_INVALID_DRIVE;
}
if (!GetFullPathName(arg, MAX_PATH, TempBuffer, &lpw))
{
return GetLastError();
}
if (CreateDirectory( arg, NULL ))
{
return 0;
}
Status = GetLastError();
if (Status == ERROR_ALREADY_EXISTS)
{
return 0;
}
else if (Status != ERROR_PATH_NOT_FOUND)
{
return Status;
}
//
// loop over input path and create any needed intermediary directories.
//
// Find the point in the string to begin the creation. Note, for UNC
// names, we must skip the machine and the share
//
if (TempBuffer[1] == COLON) {
//
// Skip D:\
//
lpw = TempBuffer+3;
} else if (TempBuffer[0] == BSLASH && TempBuffer[1] == BSLASH) {
//
// Skip \\server\share\
//
lpw = TempBuffer+2;
while (*lpw && *lpw != BSLASH) {
lpw++;
}
if (*lpw) {
lpw++;
}
while (*lpw && *lpw != BSLASH) {
lpw++;
}
if (*lpw) {
lpw++;
}
} else {
//
// For some reason, GetFullPath has given us something we can't understand
//
return ERROR_CANNOT_MAKE;
}
//
// Walk through the components creating them
//
while (*lpw) {
//
// Move forward until the next path separator
//
while (*lpw && *lpw != BSLASH) {
lpw++;
}
//
// If we've encountered a path character, then attempt to
// make the given path.
//
if (*lpw == BSLASH) {
*lpw = NULLC;
if (!CreateDirectory( TempBuffer, NULL )) {
Status = GetLastError();
if (Status != ERROR_ALREADY_EXISTS) {
return ERROR_CANNOT_MAKE;
}
}
*lpw++ = BSLASH;
}
}
if (!CreateDirectory( TempBuffer, NULL )) {
Status = GetLastError( );
if (Status != ERROR_ALREADY_EXISTS) {
return Status;
}
}
return 0;
}
/*** IsValidDrv - Check drive validity
*
* Purpose:
* Check validity of passed drive letter.
*
* int IsValidDrv(WCHAR drv)
*
* Args:
* drv - The letter of the drive to check
*
* Returns:
* TRUE if drive is valid
* FALSE if not
*
* Notes:
*
*/
BOOL
IsValidDrv(WCHAR drv)
{
WCHAR temp[4];
temp[ 0 ] = drv;
temp[ 1 ] = COLON;
temp[ 2 ] = BSLASH;
temp[ 3 ] = NULLC;
//
// return of 0 or 1 mean can't determine or root
// does not exists.
//
if (GetDriveType(temp) <= 1)
return( FALSE );
else {
return( TRUE );
}
}
|
b239602cf5d0ee4db8309de2abca824ffd1d31b5 | d344de8e32f82bc2596a01eac6ca1b109884bd06 | /Coyo (competive programming)/assignments/29-09-2019/recusrion.cpp | 88337acb5bbcc1a455a3338bac2a31359036b757 | [] | no_license | vijaygwala/MyCodingStyle- | 214e9149ccbb33b21d2132dd0a7d85272d438f16 | 39d75463ec8af798df7d013efc940de89a447009 | refs/heads/master | 2022-10-06T07:55:46.928080 | 2020-06-05T15:55:31 | 2020-06-05T15:55:31 | 268,440,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | cpp | recusrion.cpp | #include<iostream>
using namespace std;
int sum(int a[],int n)
{if(n==0)
return 0;
else
return a[n-1]+sum(a,n-1);
}
int main()
{
int a[5]={1,2,3,4,5};
int sumn=sum(a,5);
cout<<sumn<<endl;
}
|
eba3ec1713531c68cf8a548721297e1a279e9183 | d499eed2edce0e8557653515e94951ce43504821 | /src/MongoDB/Driver/CursorId.cpp | 59ca3f385e8f0dd52d1c58e7d6f2072208735d3e | [
"Apache-2.0"
] | permissive | mongodb/mongo-hhvm-driver | 67b332f33697298b69c63c96493a6ca3500dd8df | 382df3e6fb5bf3454fd8aadf24617c039afafd08 | refs/heads/master | 2023-08-24T02:54:12.085198 | 2021-12-22T17:05:39 | 2021-12-22T17:05:39 | 27,442,261 | 30 | 16 | Apache-2.0 | 2021-12-22T17:05:40 | 2014-12-02T16:44:52 | PHP | UTF-8 | C++ | false | false | 1,499 | cpp | CursorId.cpp | /**
* Copyright 2014-2015 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/vm/native-data.h"
#include "../../../mongodb.h"
#include "CursorId.h"
namespace HPHP {
const StaticString s_MongoDriverCursorId_className("MongoDB\\Driver\\CursorId");
Class* MongoDBDriverCursorIdData::s_class = nullptr;
const StaticString MongoDBDriverCursorIdData::s_className("MongoDBDriverCursorId");
IMPLEMENT_GET_CLASS(MongoDBDriverCursorIdData);
const StaticString s_MongoDBDriverCursorId_id("id");
String HHVM_METHOD(MongoDBDriverCursorId, __toString)
{
MongoDBDriverCursorIdData* data = Native::data<MongoDBDriverCursorIdData>(this_);
return String(data->id);
}
Array HHVM_METHOD(MongoDBDriverCursorId, __debugInfo)
{
MongoDBDriverCursorIdData* data = Native::data<MongoDBDriverCursorIdData>(this_);
Array retval = Array::Create();
retval.set(s_MongoDBDriverCursorId_id, data->id);
return retval;
}
}
|
e9db44b5e4e27e92697e9711e45e966441a03a41 | e32710c56e37207ba7129f0fcec213b34108cbec | /retroshare-gui/src/gui/People/IdentityWidget.h | 8daebc6c1927bc76ead1014db78db48bc25aaab5 | [] | no_license | sirjenster/RetroShare | 963f56b5662d3c41bf8421124c220c36dc6a38f1 | 47328a4ec9f1b26f84081cd674ced8e5046458cc | refs/heads/master | 2021-01-18T10:33:27.768840 | 2015-11-19T18:11:02 | 2015-11-19T18:11:02 | 42,929,480 | 2 | 0 | null | 2015-09-22T11:24:23 | 2015-09-22T11:24:23 | null | UTF-8 | C++ | false | false | 1,666 | h | IdentityWidget.h | #ifndef IDENTITYWIDGET_H
#define IDENTITYWIDGET_H
#include "gui/common/FlowLayout.h"
#include <QImage>
#include <QGraphicsScene>
#include <QWidget>
#include <retroshare/rsidentity.h>
#include <retroshare/rspeers.h>
namespace Ui {
class IdentityWidget;
}
class IdentityWidget : public FlowLayoutItem
{
Q_OBJECT
public:
explicit IdentityWidget(QString name = QString()
, QWidget *parent = 0);
~IdentityWidget();
void updateData(const RsGxsIdGroup& gxs_group_info);
void updateData(const RsPeerDetails& pgp_details);
void updateData(const RsGxsIdGroup& gxs_group_info
, const RsPeerDetails& pgp_details);
//Start QWidget Properties
QSize sizeHint();
//Start FlowLayoutItem Properties
virtual const QPixmap getImage();
virtual const QPixmap getDragImage();
virtual void setIsSelected(bool value);
virtual void setIsCurrent(bool value);
//End Properties
bool haveGXSId() { return _haveGXSId; }
bool havePGPDetail() { return _havePGPDetail; }
const RsGxsIdGroup& groupInfo() const { return _group_info; }
const RsPeerDetails& details() const { return _details; }
const QString keyId() const { return _keyId; }
const QString idtype() const { return _idtype; }
const QString nickname() const { return _nickname; }
const QString gxsId() const { return _gxsId; }
signals:
void addButtonClicked();
private slots:
void pbAdd_clicked();
private:
bool _haveGXSId;
bool _havePGPDetail;
RsGxsIdGroup _group_info;
RsPeerDetails _details;
QGraphicsScene* _scene;
QImage _avatar;
QString _keyId;
QString _idtype;
QString _nickname;
QString _gxsId;
Ui::IdentityWidget *ui;
};
#endif // IDENTITYWIDGET_H
|
0cca5f39b2ac6e76f0906febb22a03d2a308c278 | f806d792bf22bc8306a0926f7b2306c0b3dd4367 | /Lydsy/P1741 [Usaco2005 nov]Asteroids 穿越小行星群/P1741.cpp | 349023aadef5ec19db779320e29ed6fe33159ef2 | [
"MIT"
] | permissive | Wycers/Codelib | d7665476c810ddefd82dd758a4963f6b0e1b7ac1 | 7d54dce875a69bc998597abb1c2e2c814587c9b8 | refs/heads/master | 2023-03-05T13:57:44.371292 | 2022-09-22T02:23:17 | 2022-09-22T02:23:17 | 143,575,376 | 28 | 4 | MIT | 2023-03-04T22:05:33 | 2018-08-05T01:44:34 | VHDL | UTF-8 | C++ | false | false | 1,002 | cpp | P1741.cpp | #include <cstdio>
#include <cstring>
const int N = 500 + 10;
using namespace std;
struct edge
{
int to,next;
} e[N * N / 2];
int head[N],cnt = 0;
void Insert(int u,int v)
{
e[++cnt] = (edge){v,head[u]};
head[u] = cnt;
}
int n;
void Readin()
{
int m,u,v;
scanf("%d%d",&n,&m);
for (int i=1;i<=m;++i)
{
scanf("%d%d",&u,&v);
Insert(u,v);
}
}
int from[N];bool vis[N];
bool Match(int k)
{
int v;
for (int i=head[k];i;i=e[i].next)
{
v = e[i].to;
if (!vis[v])
{
vis[v] = true;
if (from[v] == -1 || Match(from[v]))
{
from[v] = k;
return true;
}
}
}
return false;
}
void Work()
{
int ans = 0;
memset(from,255,sizeof(from));
for (int i=1;i<=n;++i)
{
memset(vis,false,sizeof(vis));
if (Match(i))
++ans;
}
printf("%d\n",ans);
}
int main()
{
Readin();
Work();
return 0;
}
|
24d449e1e80546675e8dad2eaab026655dba31b0 | 30069e61fbd46926fbfe5d855a2c0ebdbff04225 | /firmware/examples/proximity/wdt_proximity-intensity/wdt_proximity-intensity.ino | 7d0a3689704a94f581af0ddf2c5a51320a3bd87d | [] | no_license | dgngdn/plasma-control | eb3c43605bf06f4caf1c29aa01d409c019b18991 | ad46d395ef86a4f8bd4ad1508aa7086d2693b0f3 | refs/heads/master | 2021-09-25T02:20:40.663698 | 2018-10-15T21:51:55 | 2018-10-15T21:51:55 | 112,388,972 | 0 | 0 | null | 2017-11-28T21:04:30 | 2017-11-28T21:04:29 | null | UTF-8 | C++ | false | false | 2,236 | ino | wdt_proximity-intensity.ino | /* This minimal example shows how to get single-shot range
measurements from the VL6180X.
The range readings are in units of mm. */
#include <Wire.h>
// library: VL6180X proximity sensor
#include <VL6180X.h>
// library: watchdog timer
#include <avr/wdt.h> //#include "lib/avr/wdt.h" // #include <avr/wdt.h>
// GLOBAL CONSTANTS
const long SERIAL_BAUD = 9600; // 4800,9600,14400,19200,38400,57600,115200,0.5M,1.0M,2.0M
const int LOOP_DELAY = 1; // milliseconds
VL6180X sensor;
const int read_num = 512;
//const int read_num = 100;
int read_data[read_num];
float read_average = 0;
int read_index = 0;
int read_total = 0;
void setup_serial() {
// set up serial connection
// initialize serial communication at specified baudrate
Serial.begin(SERIAL_BAUD);
#if DEBUG
Serial.println();
Serial.println();
Serial.println("Serial connection established!");
#endif
}
void setup_watchdog() {
// enable the watchdog timer
// if Arduino stops responding, auto-resets
// Watchdog Timeouts: WDTO_{1,2,4,8}s
// WDTO_{15,30,60,120,250,500}MS
// http://www.megunolink.com/articles/how-to-detect-lockups-using-the-arduino-watchdog/
#if DEBUG
Serial.println("enabling watchdog timer...");
#endif
wdt_enable(WDTO_250MS);
#if DEBUG
Serial.println("watchdog timer enabled!");
#endif
}
void addRead(int value)
{
read_total = read_total - read_data[read_index];
read_data[read_index] = value;
read_total = read_total + read_data[read_index];
read_average = ((float)read_total) / read_num;
read_index++;
if (read_index >= read_num)
{
read_index = 0;
}
}
void setup()
{
setup_serial();
setup_watchdog();
Wire.begin();
sensor.init();
sensor.configureDefault();
sensor.setTimeout(50);
}
void loop()
{
// reset the watchdog timer
//if this doesn't occur within WDTO_X, system resets
wdt_reset();
int sensor_val = sensor.readRangeSingleMillimeters();
addRead(sensor_val);
Serial.print(millis());
Serial.print(',');
Serial.print(sensor_val);
//Serial.print(read_average-61+3);
Serial.print(',');
Serial.print(analogRead(A0));
if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
Serial.println();
delay(LOOP_DELAY);
}
|
b348dcb8d6c72df590a0f881cd7ef7639d142be7 | 45e6664d5a637c616bc8e5b2b6e4368d63ede83c | /examples/MINLP/Power/Microgrid/Microg_main.cpp | 3dc98fde0969e1d3d8f71edd7065a45d68705ee1 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | permissive | guanglei1wang/Gravity | 9c808218fc91b8ec2dd7999ddb8c4eff80390f16 | 30f5afc880f13601107c30484fc6204d36cab53b | refs/heads/master | 2021-01-25T10:28:49.590607 | 2018-02-19T07:05:11 | 2018-02-19T07:05:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,054 | cpp | Microg_main.cpp | //
// Gravity
//
// Created by Hassan Hijazi on Dec 06 2017
//
//
#include <stdio.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
#include <fstream>
#include "../PowerNet.h"
#include <gravity/solver.h>
#include <stdio.h>
#include <stdlib.h>
#include <xlnt/xlnt.hpp>
using namespace std;
using namespace gravity;
int main (int argc, const char * argv[])
{
const char* fname;
if (argc >= 2) {
fname = argv[1];
}
else {
fname = "../../data_sets/Power/Dercam.xlsx";
}
PowerNet grid;
double vlb, vub, kvb, pl, ql;
unsigned index, time, b_type;
string name;
xlnt::workbook wb;
double wall0 = get_wall_time();
double cpu0 = get_cpu_time();
cout << "Reading all excel sheets...\n";
wb.load(fname);
double wall1 = get_wall_time();
double cpu1 = get_cpu_time();
cout << "Done reading.\n";
cout << "Wall clock io time = " << wall1 - wall0 << "\n";
cout << "CPU io time = " << cpu1 - cpu0 << "\n";
auto ws = wb.sheet_by_title("PowerFlowParams");
std::clog << "Processing PowerFlowParams..." << std::endl;
auto row_it = ws.rows().begin();
auto row = *row_it++;
name = row[1].to_string();
DebugOn("Ref Bus name = " << name << endl);
grid.ref_bus = name;
while (row_it!=ws.rows().end())
{
auto row = *row_it++;
name = row[0].to_string();
if (name.compare("Sbase")==0) {
grid.bMVA = row[1].value<double>();
DebugOn("Base MVA = " << to_string(grid.bMVA) << endl);
}
if (name.compare("Vbase")==0) {
grid.bV = row[1].value<double>();
DebugOn("Base V = " << to_string(grid.bV) << endl);
}
if (name.compare("NoOfNodes")==0) {
grid.nb_nodes = row[1].value<double>();
DebugOn("Number of buses = " << to_string(grid.nb_nodes) << endl);
for (size_t i = 0; i<grid.nb_nodes; i++) {
auto bus = new Bus(to_string(i));
grid.add_node(bus);
}
}
}
vector<tuple<double,double,double>> cableparams;
ws = wb.sheet_by_title("CableParams");
std::clog << "Processing CableParams..." << std::endl;
row_it = ws.rows().begin();
row_it++;//SKIP FRIST ROW
while (row_it!=ws.rows().end())
{
auto row = *row_it++;
cableparams.push_back(make_tuple(row[4].value<double>(), row[5].value<double>(), row[7].value<double>()));
}
ws = wb.sheet_by_title("BranchType_Cable");
std::clog << "Processing BranchType_Cable..." << std::endl;
row_it = ws.rows().begin();
row_it++;//SKIP FRIST ROW
index = 0;
for (size_t i = 0; i<grid.nb_nodes-1; i++) {
auto row = *row_it++;
for (size_t j = i+1; j<grid.nb_nodes; j++) {
if (row[j+1].has_value()) {
b_type = row[j+1].value<unsigned>();
DebugOn("(" << i+1 << "," << j+1 << ") = type " << b_type << endl);
auto arc = new Line(to_string(index) + "," + to_string(i+1) + "," + to_string(j+1));
arc->_id = index++;
arc->_src = grid.get_node(to_string(i));
arc->_dest= grid.get_node(to_string(j));
arc->b_type = b_type;
arc->r = get<0>(cableparams[b_type-1]);
arc->x = get<1>(cableparams[b_type-1]);
arc->limit = get<2>(cableparams[b_type-1]);
arc->connect();
grid.add_arc(arc);
arc->print();
}
}
}
// for (auto b: grid.nodes) {
// if (!b->_active) {
// continue;
// }
// ws = wb.sheet_by_title("Pt_"+to_string(b->_id+1));
// std::clog << "Processing Pt_"+to_string(b->_id) << std::endl;
// // for (auto row : ws.rows(false))
// DebugOn("Bus name = " << name << endl);
//
// time = 0;
// auto row_it = ws.rows().begin();
// while (row_it!=ws.rows().end())
// {
// auto row = *(row_it++);
// pl = row[1].value<double>();
// grid.pl.set_val(b->_id, time,pl);
// DebugOn("pl at time" << time << " = " << pl << ", ");
// time++;
// }
// DebugOn(endl);
// }
std::clog << "Processing complete" << std::endl;
return 0;
}
int main_ (int argc, const char * argv[])
{
const char* fname;
if (argc >= 2) {
fname = argv[1];
}
else {
// fname = "../../data_sets/Power/nesta_case3_lmbd.m";
// fname = "/Users/hh/Dropbox/Work/Dev/nesta-0.7.0/opf/nesta_case2383wp_mp.m";
// fname = "../../data_sets/Power/nesta_case3_lmbd.m";
// fname = "../../data_sets/Power/nesta_case2383wp_mp.m";
fname = "../../data_sets/Power/nesta_case5_pjm.m";
//fname = "../../data_sets/Power/nesta_case300_ieee.m";
}
// ACUC
PowerNet* grid = new PowerNet();
grid->readgrid(fname);
// Grid Parameters
auto bus_pairs = grid->get_bus_pairs();
auto nb_bus_pairs = bus_pairs.size();
auto nb_gen = grid->get_nb_active_gens();
auto nb_lines = grid->get_nb_active_arcs();
auto nb_buses = grid->get_nb_active_nodes();
// Schedule
unsigned T = 1;
param<Real> rate_ramp("rate_ramp");
param<Real> rate_switch("rate_switch");
param<Real> min_up("min_up");
param<Real> min_down("min_down");
param<Real> cost_up("cost_up");
param<Real> cost_down("cost_down");
for (auto g: grid->gens) {
rate_ramp(g->_name) = max(grid->pg_min(g->_name).getvalue(), 0.25*grid->pg_max(g->_name).getvalue());
rate_switch(g->_name) = max(grid->pg_min(g->_name).getvalue(), 0.25*grid->pg_max(g->_name).getvalue());
}
min_up = 1;
min_down = 1;
cost_up = 50;
cost_down = 30;
grid->time_expand(T);
rate_ramp.time_expand(T);
rate_switch.time_expand(T);
/** build model */
Model ACUC("ACUC Model");
/** Variables */
// POWER GENERATION
var<Real> Pg("Pg", grid->pg_min.in(grid->gens, T), grid->pg_max.in(grid->gens, T));
var<Real> Qg ("Qg", grid->qg_min.in(grid->gens, T), grid->qg_max.in(grid->gens, T));
ACUC.add_var(Pg^(T*nb_gen));
ACUC.add_var(Qg^(T*nb_gen));
//power flow
var<Real> Pf_from("Pf_from", grid->S_max.in(grid->arcs, T));
var<Real> Qf_from("Qf_from", grid->S_max.in(grid->arcs, T));
var<Real> Pf_to("Pf_to", grid->S_max.in(grid->arcs, T));
var<Real> Qf_to("Qf_to", grid->S_max.in(grid->arcs, T));
ACUC.add_var(Pf_from^(T*nb_lines));
ACUC.add_var(Qf_from^(T*nb_lines));
ACUC.add_var(Pf_to^(T*nb_lines));
ACUC.add_var(Qf_to^(T*nb_lines));
//Lifted variables.
var<Real> R_Wij("R_Wij", grid->wr_min.in(bus_pairs, T), grid->wr_max.in(bus_pairs, T)); // real part of Wij
var<Real> Im_Wij("Im_Wij", grid->wi_min.in(bus_pairs, T), grid->wi_max.in(bus_pairs, T)); // imaginary part of Wij.
var<Real> Wii("Wii", grid->w_min.in(grid->nodes, T), grid->w_max.in(grid->nodes, T));
R_Wij.print(true);
Im_Wij.print(true);
ACUC.add_var(Wii^(T*nb_buses));
ACUC.add_var(R_Wij^(T*nb_bus_pairs));
ACUC.add_var(Im_Wij^(T*nb_bus_pairs));
R_Wij.initialize_all(1.0);
Wii.initialize_all(1.001);
// Commitment variables
var<Real> On_off("On_off");
var<Real> Start_up("Start_up", 0, 1);
var<Real> Shut_down("Shut_down", 0, 1);
ACUC.add_var(On_off^(T*nb_gen));
ACUC.add_var(Start_up^(T*nb_gen));
ACUC.add_var(Shut_down^(T*nb_gen));
/* Construct the objective function*/
func_ obj;
for (auto g:grid->gens) {
if (g->_active) {
obj += grid->c1.in(g,T)*Pg.in(g,T)+ grid->c2.in(g,T)*Pg.in(g,T)*Pg.in(g,T) + grid->c0.in(g,T);
obj += cost_up.getvalue()*Start_up.in(g, T)+ cost_down.getvalue()*Shut_down.in(g, T);
}
}
ACUC.set_objective(min(obj));
/** Define constraints */
/* SOCP constraints */
Constraint SOC("SOC");
SOC = power(R_Wij.in(bus_pairs, T), 2) + power(Im_Wij.in(bus_pairs, T), 2) - Wii.from(bus_pairs, T)*Wii.to(bus_pairs, T) ;
ACUC.add_constraint(SOC <= 0);
//KCL
for (int t = 0; t < T; t++)
for (auto b: grid->nodes) {
if (!b->_active) {
continue;
}
Bus* bus = (Bus*) b;
Constraint KCL_P("KCL_P"+bus->_name+ "time_" + to_string(t));
Constraint KCL_Q("KCL_Q"+bus->_name+ "time_" + to_string(t));
/* Power Conservation */
KCL_P = sum(Pf_from.in_at(b->get_out(), t)) + sum(Pf_to.in_at(b->get_in(), t)) + grid->pl(bus->_name, to_string(t))- sum(Pg.in_at(bus->_gen, t));
KCL_Q = sum(Qf_from.in_at(b->get_out(), t)) + sum(Qf_to.in_at(b->get_in(), t)) + grid->ql(bus->_name, to_string(t))- sum(Qg.in_at(bus->_gen, t));
/* Shunts */
KCL_P += grid->gs(bus->_name, to_string(t))*Wii(bus->_name, to_string(t));
KCL_Q -= grid->bs(bus->_name, to_string(t))*Wii(bus->_name, to_string(t));
ACUC.add_constraint(KCL_P = 0);
ACUC.add_constraint(KCL_Q = 0);
}
////AC Power Flow.
Constraint Flow_P_From("Flow_P_From");
Flow_P_From += Pf_from.in(grid->arcs, T);
Flow_P_From -= grid->g_ff.in(grid->arcs, T)*Wii.from(grid->arcs, T);
Flow_P_From -= grid->g_ft.in(grid->arcs, T)*R_Wij.in_pairs(grid->arcs, T);
Flow_P_From -= grid->b_ft.in(grid->arcs, T)*Im_Wij.in_pairs(grid->arcs, T);
ACUC.add_constraint(Flow_P_From = 0);
Constraint Flow_P_To("Flow_P_To");
Flow_P_To += Pf_to.in(grid->arcs, T);
Flow_P_To -= grid->g_tt.in(grid->arcs, T)*Wii.to(grid->arcs, T);
Flow_P_To -= grid->g_tf.in(grid->arcs, T)*R_Wij.in_pairs(grid->arcs, T);
Flow_P_To += grid->b_tf.in(grid->arcs, T)*Im_Wij.in_pairs(grid->arcs, T);
ACUC.add_constraint(Flow_P_To = 0);
Constraint Flow_Q_From("Flow_Q_From");
Flow_Q_From += Qf_from.in(grid->arcs, T);
Flow_Q_From += grid->b_ff.in(grid->arcs, T)*Wii.from(grid->arcs, T);
Flow_Q_From += grid->b_ft.in(grid->arcs, T)*R_Wij.in_pairs(grid->arcs, T);
Flow_Q_From += grid->g_ft.in(grid->arcs, T)*Im_Wij.in_pairs(grid->arcs, T);
ACUC.add_constraint(Flow_Q_From = 0);
Constraint Flow_Q_To("Flow_Q_To");
Flow_Q_To += Qf_to.in(grid->arcs, T);
Flow_Q_To += grid->b_tt.in(grid->arcs, T)*Wii.to(grid->arcs, T);
Flow_Q_To += grid->b_tf.in(grid->arcs, T)*R_Wij.in_pairs(grid->arcs, T);
Flow_Q_To -= grid->g_tf.in(grid->arcs, T)*Im_Wij.in_pairs(grid->arcs, T);
ACUC.add_constraint(Flow_Q_To = 0);
//
/* Phase Angle Bounds constraints */
Constraint PAD_UB("PAD_UB");
PAD_UB = Im_Wij.in(bus_pairs, T);
PAD_UB -= (grid->tan_th_max).in(bus_pairs, T)*R_Wij.in(bus_pairs, T);
ACUC.add_constraint(PAD_UB <= 0);
Constraint PAD_LB("PAD_LB");
PAD_LB = Im_Wij.in(bus_pairs, T);
PAD_LB -= grid->tan_th_min.in(bus_pairs, T)*R_Wij.in(bus_pairs, T);
ACUC.add_constraint(PAD_LB >= 0);
///* Thermal Limit Constraints */
Constraint Thermal_Limit_from("Thermal_Limit_from");
Thermal_Limit_from += power(Pf_from.in(grid->arcs, T), 2) + power(Qf_from.in(grid->arcs, T), 2);
Thermal_Limit_from -= power(grid->S_max.in(grid->arcs, T), 2);
ACUC.add_constraint(Thermal_Limit_from <= 0);
Constraint Thermal_Limit_to("Thermal_Limit_to");
Thermal_Limit_to += power(Pf_to.in(grid->arcs, T), 2) + power(Qf_to.in(grid->arcs, T), 2);
Thermal_Limit_to -= power(grid->S_max.in(grid->arcs, T),2);
ACUC.add_constraint(Thermal_Limit_to <= 0);
// COMMITMENT CONSTRAINTS
// Inter-temporal constraints
for (int t = 1; t < T; t++) {
Constraint MC1("MC1_"+ to_string(t));
Constraint MC2("MC2_"+ to_string(t));
MC1 = On_off.in_at(grid->gens, t)- On_off.in_at(grid->gens, t-1)- Start_up.in_at(grid->gens, t);
MC2 = On_off.in_at(grid->gens, t-1) - On_off.in_at(grid->gens, t) - Shut_down.in_at(grid->gens, t);
ACUC.add_constraint(MC1 <= 0);
ACUC.add_constraint(MC2 <= 0);
}
//// Min-up constraints
for (int t = 1; t < T; t++) {
Constraint Min_up1("Min_up1_"+ to_string(t));
Min_up1 = On_off.in_at(grid->gens, t) - On_off.in_at(grid->gens, t-1) - Start_up.in_at(grid->gens, t) + Shut_down.in_at(grid->gens, t);
ACUC.add_constraint(Min_up1 = 0);
}
for (int t = min_up.getvalue(); t < T; t++) {
Constraint Min_Up("Min_Up_constraint" + to_string(t));
for (int l = t-min_up.getvalue()+1; l < t+1; l++) {
Min_Up += Start_up.in_at(grid->gens, l);
}
Min_Up -= On_off.in_at(grid->gens, t);
ACUC.add_constraint(Min_Up <= 0);
}
for (int t = min_down.getvalue(); t < T; t++) {
Constraint Min_Down("Min_Down_constraint" + to_string(t));
for (int l = t-min_down.getvalue()+1; l < t +1; l++) {
Min_Down += Shut_down.in_at(grid->gens, l);
}
Min_Down -= 1 - On_off.in_at(grid->gens, t);
ACUC.add_constraint(Min_Down <= 0);
}
////Ramp rate
Constraint Production_P_LB("Production_P_LB");
Constraint Production_P_UB("Production_P_UB");
Constraint Production_Q_LB("Production_Q_LB");
Constraint Production_Q_UB("Production_Q_UB");
Production_P_UB = Pg.in(grid->gens, T) - grid->pg_max.in(grid->gens, T)*On_off.in(grid->gens,T);
Production_P_LB = Pg.in(grid->gens, T) - grid->pg_min.in(grid->gens, T)*On_off.in(grid->gens,T);
ACUC.add_constraint(Production_P_UB <=0);
ACUC.add_constraint(Production_P_LB >= 0);
grid->qg_max.print(true);
grid->qg_min.print(true);
Production_Q_UB = Qg.in(grid->gens, T) - grid->qg_max.in(grid->gens, T)*On_off.in(grid->gens,T);
Production_Q_LB = Qg.in(grid->gens, T) - grid->qg_min.in(grid->gens, T)*On_off.in(grid->gens,T);
ACUC.add_constraint(Production_Q_UB <= 0);
ACUC.add_constraint(Production_Q_LB >= 0);
for (int t = 1; t < T; t++) {
Constraint Ramp_up("Ramp_up_constraint" + to_string(t));
Constraint Ramp_down("Ramp_down_constraint" + to_string(t));
Ramp_up = Pg.in_at(grid->gens, t);
Ramp_up -= Pg.in_at(grid->gens, t-1);
Ramp_up -= rate_ramp*On_off.in_at(grid->gens, t-1);
Ramp_up -= rate_switch*(1 - On_off.in_at(grid->gens, t));
Ramp_down = Pg.in_at(grid->gens, t-1);
Ramp_down -= Pg.in_at(grid->gens, t);
Ramp_down -= rate_ramp*On_off.in_at(grid->gens, t);
Ramp_down -= rate_switch*(1 - On_off.in_at(grid->gens, t-1));
ACUC.add_constraint(Ramp_up <= 0);
ACUC.add_constraint(Ramp_down <= 0);
}
/* Resolve it! */
//solver OPF(ACUC,ipopt);
solver OPF(ACUC, cplex);
OPF.run();
return 0;
}
|
f4ce54e0ffcf5dea0baa58b5cc8e8586e72515bf | d80c3418b842dee26e8b521258c0425a37c0d79a | /Orbit/src/main.cpp | 50232d63e784f0e01d1cbbd6382843f0a1b3a47d | [
"MIT"
] | permissive | JusticesHand/orbit-engine | be355cad9446ce814d434dc3daa9fdd95806a8c9 | fd9bd160f6e54fb49a9e720f0c409ae5deb6e676 | refs/heads/master | 2021-01-22T23:48:17.321418 | 2017-11-11T18:05:38 | 2017-11-11T18:05:38 | 102,429,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | cpp | main.cpp | /*! @file main.cpp */
#include <cstdlib>
#include <iostream>
#include <memory>
#include "Input/WindowLibrary.h"
#include "Input/Window.h"
#include "Render/Renderer.h"
#include "Game/Game.h"
#include "Task/TaskRunner.h"
#if defined(USE_WIN32)
#include "Input/Win32WindowLibrary.h"
#elif defined(USE_XWINDOW)
#error XWindowLibrary is not implemented yet!
#elif defined(USE_WAYLAND)
#error WaylandWindowLibrary is not implemented yet!
#else
#include "Input/GLFWWindowLibrary.h"
#endif
using namespace Orbit;
/*!
@brief Main function of the program. Same signature as all other main functions.
@param argc The amount of arguments.
@param argv The argument strings.
*/
int main(int argc, char* argv[])
{
// TODO: Handle args, etc etc
try
{
std::unique_ptr<WindowLibrary> windowLib = std::make_unique<WINDOWLIB>();
// TODO: Initialization with options.
std::unique_ptr<Window> window = windowLib->createWindow(glm::ivec2{ 1280, 720 }, "Hello World", false);
window->open();
TaskRunner runner;
Game game{ *window, runner };
game.initialize();
// Note that the game's shouldClose() function is directly linked to the window's.
// TODO: Instead of doing rendering on main thread, check if -server is in parameters. Then pipe console commands
// to the game's hypothetical command pipeline.
runner.run(120, [&window]() {
return window->shouldClose();
},
[&window]() {
window->handleMessages();
window->renderer()->renderFrame();
});
runner.joinAll();
}
catch (std::exception& ex)
{
// TODO: Logging.
std::cerr << "Caught exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
catch (...)
{
std::cerr << "Caught unknown exception type!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} |
c99e61de38ccd96ee4d53aeaf9ba5db826064559 | aafa69798f6d0d38830c6d13bbf2fb9fa544d3be | /URI/MATHEMATICS/UOJ_1197 Back to High School Physics.cpp | 1afd49f0b7919f98872309aecb34f0f91b28f66e | [] | no_license | anik-chy/OnlineJudges | 28f4cc6f2ff6206bc81d99955a8e218887d27674 | a057f2a4974d6cfc6fe3e628fd424a8ba928cafa | refs/heads/master | 2023-04-20T23:57:50.522983 | 2021-05-03T19:18:06 | 2021-05-03T19:18:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 162 | cpp | UOJ_1197 Back to High School Physics.cpp | #include<bits/stdc++.h>
using namespace std;
int main(void){
int v,t;
while(scanf("%d%d",&v,&t)!=EOF){
cout<<2*v*t<<"\n";
}
return 0;
}
|
68765dccfc544c50488cde4932dfa45716da9c75 | 55e6599b0c079ec992c082c799eab071631dedb3 | /IPv4_subnetting.h | a37e13befbba415fcec055a809ee2d75db11c129 | [] | no_license | davidxvuong/IPv4-VLSM-Subnet-Practice | 35e0c71da44967ecf7a86b6f6705274bc4ff9dd9 | 2b868e0b7cb38307969704cdf7f4fb5112ae8068 | refs/heads/master | 2021-03-12T23:54:53.832083 | 2015-04-30T04:37:17 | 2015-04-30T04:37:17 | 34,826,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | h | IPv4_subnetting.h | #ifndef IPv4_subnetting
#define IPv4_subnetting
#ifndef nullptr
#define nullptr 0
#endif
#include <iostream>
#include <string>
#include <vector>
class IPv4_subnetting {
private:
int* ip_address_space;
int* subnet_mask_space;
std::vector<int> subnet_users;
public:
IPv4_subnetting(string ip_address, string subnet_mask);
~IPv4_subnetting();
void push_subnet_user_top(int in);
void pop_subnet_user_top();
string get_subnet_mask_space() const;
string get_ip_address_space() const;
std::vector<std::pair<string, string>> compute_subnet() const;
}
IPv4_subnetting::IPv4_subnetting(string ip_address, string subnet_mask):ip_address_space(new int[4]),
subnet_mask_space(new int[4]) {
ip_address_space[0] = ip_address.substr(0, ip_address.find("."));
}
~IPv4_subnetting::IPv4_subnetting() {
delete []ip_address_space;
delete []subnet_mask_space;
}
string IPv4_subnetting::get_subnet_mask_space() {
}
string IPv4_subnetting::get_ip_address_space() {
}
void IPv4_subnetting::push_subnet_user_top(int in) {
}
void IPv4_subnetting::pop_subnet_user_top() {
}
std::vector<std::pair<string, string>> compute_subnet() {
}
#endif
|
8895a140aff1ad60b4b2b0a38e2528e67408cc84 | fffa3b706f8a6611083a5dca098e721da3bbcdda | /March of the Bombs/HQModelData.cpp | 5142943ed6e187e012fe41f1edcd81a762fb04ea | [] | no_license | Jereq/March-of-the-Bombs | bdd882969cf87bfae309935232fb4729b49721a7 | 5f0fb3082939709001614b4a0c80530e50a5c6b4 | refs/heads/master | 2021-01-24T06:13:40.349734 | 2013-05-15T17:08:50 | 2013-05-15T17:08:50 | 3,366,632 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | HQModelData.cpp | #include "HQModelData.h"
HQModelData::ptr HQModelData::instance;
HQModelData::HQModelData()
: Model3DS("Models/base.3ds")
{
if (groups.size() > 0)
{
groups[0].texture = GLTexture::getTexture(L"Models/base.png", true);
}
}
HQModelData::ptr HQModelData::getInstance()
{
if (!instance)
{
instance = HQModelData::ptr(new HQModelData());
}
return instance;
}
|
900a6216ec54f27fe6197c897534ef6cbcc0b696 | 34064621dee506cd3d613e3f23a9826376c32632 | /advanced-cpp/quadtree/include/sim/quad.hpp | 559f21e1621026b4f58b9bf828d0b3b5491dd86e | [] | no_license | Curt-White/school-projects | 9064f7b3125826cd5467769b285014a19af4e81d | cfb56f55fd6b6b2121c8fb81bf913d63eb19fd45 | refs/heads/master | 2023-03-06T16:42:05.123227 | 2021-02-24T19:21:51 | 2021-02-24T19:21:51 | 338,192,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,903 | hpp | quad.hpp | #ifndef QUAD_HPP
#define QUAD_HPP
#include "boost/iterator/iterator_facade.hpp"
#include "sim/shapes.hpp"
#include <new>
#include <iostream>
#include <vector>
namespace sim {
template <class T, int D = 5, int I = 5>
class QuadTree;
template <class T, int D, int I>
std::ostream& operator<<(std::ostream& stream, const QuadTree<T, D, I>& tree);
struct full_tree_error : public std::runtime_error {
using std::runtime_error::runtime_error;
};
/**
* T - the type being held in the tree
* D - is the maximum depth of the tree
* I - is the maximum number of items in a quadrant before splitting
*
* This template should only be instantiated with items that are derivatives of the
* shape class because it is necessary that they have the collision checking functions.
*/
template <class T, int D, int I>
class QuadTree {
private:
std::vector<T> items_;
sim::Rectangle bounds_;
int depth_; // this is the level of the current quadtree (how deeply nested)
QuadTree *parent_;
QuadTree *top_right_child_;
QuadTree *top_left_child_;
QuadTree *bottom_left_child_;
QuadTree *bottom_right_child_;
void subdivide();
public:
enum struct Quadrant : int {
TOP_RIGHT,
TOP_LEFT,
BOTTOM_LEFT,
BOTTOM_RIGHT,
NONE
};
/**
* This is the quad tree iterator which is a relatively complicated piece of code which loops through
* the quad tree recursively visiting the TR, TL, BL, BR quadrants of each subtree. It is only a forward iterator.
*/
template <class L>
class quad_tree_iterator: public boost::iterator_facade<quad_tree_iterator<L>, L, boost::forward_traversal_tag> {
public:
using base = boost::iterator_facade<quad_tree_iterator<L>, L, boost::forward_traversal_tag>;
using typename base::reference;
using typename base::value_type;
template <class OtherT, class = std::enable_if_t<std::is_convertible_v<OtherT*, L*>>>
quad_tree_iterator (const quad_tree_iterator<OtherT>& other): tree_(other.tree_), total_len_(other.total_len_), counter_(other.counter_) {
for (int i = 0; i < D; i++) { iter_index_.quad[i] = other.iter_index_.quad[i]; }
iter_index_.item = other.iter_index_.item;
iter_index_.level = other.iter_index_.level;
}
quad_tree_iterator (QuadTree<T, D, I>* tree): tree_(tree), iter_index_{ { Quadrant::NONE }, 0, 0 }, total_len_(tree->size()), counter_(0) {
std::fill_n(&iter_index_.quad[0], D, Quadrant::NONE);
}
private:
template <class E, int F, int G> friend class QuadTree;
friend class boost::iterator_core_access;
template <class OtherT> friend class quad_tree_iterator;
template <class OtherT> bool equal(const quad_tree_iterator<OtherT>& other) const {
return (other.counter_ == counter_);
}
reference dereference() const {
return tree_->items_[iter_index_.item];
}
void increment() {
// if there is still items in the current tree
++iter_index_.item;
++counter_;
if (iter_index_.item < tree_->size_level()) {
return;
}
iter_index_.item = 0;
do {
// if current level has been iterated
switch (iter_index_.quad[iter_index_.level]) {
case Quadrant::NONE:
if (tree_->get_top_right() == nullptr) {
if (iter_index_.level == 0) {
iter_index_.item = 0;
} else {
--iter_index_.level;
tree_ = tree_->get_parent();
iter_index_.item = tree_->size_level(); // since in BR subtree, must have seen all items already
}
} else {
iter_index_.quad[iter_index_.level] = Quadrant::TOP_RIGHT;
tree_ = tree_->get_top_right();
++iter_index_.level;
iter_index_.item = 0;
}
break;
case Quadrant::TOP_RIGHT:
iter_index_.quad[iter_index_.level] = Quadrant::TOP_LEFT;
tree_ = tree_->get_top_left();
++iter_index_.level;
iter_index_.item = 0;
break;
case Quadrant::TOP_LEFT:
iter_index_.quad[iter_index_.level] = Quadrant::BOTTOM_LEFT;
tree_ = tree_->get_bottom_left();
++iter_index_.level;
iter_index_.item = 0;
break;
case Quadrant::BOTTOM_LEFT:
iter_index_.quad[iter_index_.level] = Quadrant::BOTTOM_RIGHT;
tree_ = tree_->get_bottom_right();
++iter_index_.level;
iter_index_.item = 0;
break;
case Quadrant::BOTTOM_RIGHT:
if (iter_index_.level == 0) {
// uncommenting the below allows the iterator to become circular
// std::fill_n(&iter_index_.quad[0], D, Quadrant::NONE);
// iter_index_.item = 0;
return;
}
--iter_index_.level;
tree_ = tree_->get_parent();
iter_index_.item = tree_->size_level(); // since in BR subtree, must have seen all items already
break;
}
// loop until the tree has atleast a single item in it
} while (tree_->size_level() == 0 || iter_index_.item == tree_->size_level());
}
struct index {
Quadrant quad[D];
int item;
int level;
};
int total_len_, counter_;
index iter_index_;
QuadTree<T, D, I>* tree_;
};
using iterator = quad_tree_iterator<T>;
using const_iterator = quad_tree_iterator<const T>;
QuadTree(const sim::Rectangle& bounds, int depth = 1, QuadTree<T, D, I>* parent = nullptr);
QuadTree(QuadTree<T, D, I>&& tree) = delete; // temporarily delete the move/copy constructors
QuadTree(const QuadTree<T, D, I>& tree) = delete;
~QuadTree();
iterator begin() { return iterator(this); }
const_iterator begin() const { return const_iterator(this); }
iterator end() { auto it = iterator(this); it.counter_ = this->size(); return it; }
const_iterator end() const { auto it = const_iterator(this); it.counter_ = this->size(); return it; }
void search(const T& bound, std::vector<T>& list) const;
int size() const;
int size_level() const { return items_.size(); }
int level() const { return this->top_left_child_ != nullptr ? this->top_left_child_->level() : this->depth_; }
int max_level() const { return D; }
int max_items_per_level() const { return I; }
const sim::Rectangle& bound() const { return bounds_; }
const QuadTree<T, D, I>* get_parent() const { return parent_; }
const QuadTree<T, D, I>* get_bottom_left() const { return bottom_left_child_; }
const QuadTree<T, D, I>* get_bottom_right() const { return bottom_right_child_; }
const QuadTree<T, D, I>* get_top_left() const { return top_left_child_; }
const QuadTree<T, D, I>* get_top_right() const { return top_right_child_; }
QuadTree<T, D, I>* get_parent() { return parent_; }
QuadTree<T, D, I>* get_bottom_left() { return bottom_left_child_; }
QuadTree<T, D, I>* get_bottom_right() { return bottom_right_child_; }
QuadTree<T, D, I>* get_top_left() { return top_left_child_; }
QuadTree<T, D, I>* get_top_right() { return top_right_child_; }
Quadrant find_quadrant(const T s) const;
void insert(const T item);
// draw all of the boxes which are part of the quad tree
void draw() const;
friend std::ostream& operator<< <>(std::ostream& stream, const QuadTree<T, D, I>& tree);
};
/******************************************
* Implementation
******************************************/
template <class T, int D, int I>
QuadTree<T, D, I>::QuadTree(const sim::Rectangle& bounds, int depth, QuadTree<T, D, I>* parent):
top_left_child_(nullptr), top_right_child_(nullptr), bottom_left_child_(nullptr),
bottom_right_child_(nullptr), bounds_(bounds), depth_(depth), parent_(parent) {}
template <class T, int D, int I>
QuadTree<T, D, I>::~QuadTree() {
delete top_left_child_;
delete top_right_child_;
delete bottom_left_child_;
delete bottom_right_child_;
}
template <class T, int D, int I>
std::ostream& operator<<(std::ostream& stream, const QuadTree<T, D, I>& tree) {
auto space = std::string(tree.depth_, ' ');
// print out basic information about this tree
stream << space << "Level: " << tree.depth_ << "\n" << space << "Total Items: " << tree.items_.size() << "\n" << space << "Bounds: " << tree.bounds_ << "\n" << space << "Items: ";
for (int i = 0; i < tree.items_.size(); i++) stream << *tree.items_[i] << (i != tree.items_.size() - 1 ? " | " : "");
if (tree.items_.size() == 0) stream << "None";
stream << std::endl;
// recursively call the function on all of the sub-trees to show all data in the tree
if (tree.top_left_child_ != nullptr) stream << space << "Top Left: " << std::endl << *tree.top_left_child_;
if (tree.top_right_child_ != nullptr) stream << space << "Top Right: " << std::endl << *tree.top_right_child_;
if (tree.bottom_left_child_ != nullptr) stream << space << "Bottom Left: " << std::endl << *tree.bottom_left_child_;
if (tree.bottom_right_child_ != nullptr) stream << space << "Bottom Right: " << std::endl << *tree.bottom_right_child_;
return stream;
}
template <class T, int D, int I>
int sim::QuadTree<T, D, I>::size() const {
int total_size = items_.size();
if (top_left_child_ != nullptr) {
total_size += top_left_child_->size();
total_size += top_right_child_->size();
total_size += bottom_left_child_->size();
total_size += bottom_right_child_->size();
}
return total_size;
}
template <class T, int D, int I>
void QuadTree<T, D, I>::search(const T& bound, std::vector<T>& list) const {
for (auto item : items_) list.push_back(item);
// If there are some sub-tree items
if (top_left_child_ != nullptr) {
auto quad = find_quadrant(bound);
switch (quad) {
case Quadrant::TOP_RIGHT: this->top_right_child_->search(bound, list); break;
case Quadrant::TOP_LEFT: this->top_left_child_->search(bound, list); break;
case Quadrant::BOTTOM_LEFT: this->bottom_left_child_->search(bound, list); break;
case Quadrant::BOTTOM_RIGHT: this->bottom_right_child_->search(bound, list); break;
case Quadrant::NONE: {
this->top_right_child_->search(bound, list);
this->top_left_child_->search(bound, list);
this->bottom_left_child_->search(bound, list);
this->bottom_right_child_->search(bound, list);
} break;
}
}
}
template <class T, int D, int I>
typename QuadTree<T, D, I>::Quadrant QuadTree<T, D, I>::find_quadrant(const T s) const {
if (top_right_child_ == nullptr) return Quadrant::NONE;
bool is = top_right_child_->bound().is_containing(*s);
if (is) return Quadrant::TOP_RIGHT;
is = top_left_child_->bound().is_containing(*s);
if (is) return Quadrant::TOP_LEFT;
is = bottom_left_child_->bound().is_containing(*s);
if (is) return Quadrant::BOTTOM_LEFT;
is = bottom_right_child_->bound().is_containing(*s);
if (is) return Quadrant::BOTTOM_RIGHT;
// this case will return even if the item is inside but its borders are on the containers
return Quadrant::NONE;
}
/**
* subdivide the current quadtree into four more subtrees. Each of the subtrees is assigned thee correct
* sizes. Before this function is called, all of a tree's subtrees are null.
*/
template <class T, int D, int I>
void QuadTree<T, D, I>::subdivide() {
int hw = bounds_.width() / 2;
int hh = bounds_.height() / 2;
top_right_child_ = new QuadTree<T, D, I> (
sim::Rectangle(bounds_.x() + hw, bounds_.y(), (bounds_.width() - hw), hh + 1, bounds_.color()), depth_ + 1, this);
top_left_child_ = new QuadTree<T, D, I> (
sim::Rectangle(bounds_.x(), bounds_.y(), hw + 1, hh + 1, bounds_.color()), depth_ + 1, this);
bottom_right_child_ = new QuadTree<T, D, I> (
sim::Rectangle(bounds_.x() + hw, bounds_.y() + hh, (bounds_.width() - hw), (bounds_.height() - hh), bounds_.color()), depth_ + 1, this);
bottom_left_child_ = new QuadTree<T, D, I> (
sim::Rectangle(bounds_.x(), bounds_.y() + hh, hw + 1, (bounds_.height() - hh), bounds_.color()), depth_ + 1, this);
}
/**
* This is used to insert new items into the quadtree. If a subtree is already at its max depth then
* this function with throw a full_tree_error.
*/
template <class T, int D, int I>
void QuadTree<T, D, I>::insert(const T item) {
if (items_.size() == I && depth_ == D) {
throw full_tree_error("Quad is full");
}
if (top_left_child_ != nullptr) { // If there are subtrees try those first
Quadrant q = find_quadrant(item);
switch (q) {
case Quadrant::TOP_RIGHT: top_right_child_->insert(item); return;
case Quadrant::TOP_LEFT: top_left_child_->insert(item); return;
case Quadrant::BOTTOM_LEFT: bottom_left_child_->insert(item); return;
case Quadrant::BOTTOM_RIGHT: bottom_right_child_->insert(item); return;
case Quadrant::NONE: break; // Item is on or crossing a boundary and must not be placed in sub-tree
}
}
// insert the item into the current tree
items_.push_back(item);
// if the previous item brought the tree to a full state then re-organize the tree
if (items_.size() == I) {
if (depth_ < D) {
subdivide();
}
std::vector<T> keep;
for (auto item : items_) {
Quadrant q = find_quadrant(item);
switch (q) {
case Quadrant::TOP_RIGHT: top_right_child_->insert(item); break;
case Quadrant::TOP_LEFT: top_left_child_->insert(item); break;
case Quadrant::BOTTOM_LEFT: bottom_left_child_->insert(item); break;
case Quadrant::BOTTOM_RIGHT: bottom_right_child_->insert(item); break;
case Quadrant::NONE: keep.push_back(item);
}
}
items_ = keep;
}
}
template <class T, int D, int I>
void QuadTree<T, D, I>::draw() const {
if (top_right_child_ != nullptr) {
top_left_child_->draw();
top_right_child_->draw();
bottom_left_child_->draw();
bottom_right_child_->draw();
}
bounds_.draw_border();
}
}
#endif
|
fcaaa5c2d9d9df763193a0fe5d349d4e56c69039 | c6b649e07a708cb5c6e0932cad662ff9fedea695 | /Singleton/singleton.h | 407b405a8b692763eb3d8c749a31e98c0cf2c8ee | [
"MIT"
] | permissive | UbertoNowak/Head-First_Design-Patterns_cpp | dc496800bc02aa688bf1ea37bf08144def8d0228 | 2dd3ddcc981c2f31f5a4fc087337a501da69a7a1 | refs/heads/master | 2020-05-03T13:56:47.240536 | 2019-06-02T18:40:26 | 2019-06-02T18:40:26 | 178,664,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h | singleton.h | #ifndef SINGLETON_H
#define SINGLETON_H
class ChocolateBoiler
{
public:
void Fill();
void Drain();
void Boil();
bool IsEmpty();
bool IsBoiled();
static void ResetInstance();
// 2. Define a public static accessor function
static ChocolateBoiler* Instance();
private:
// 3. Define private or protected constructor
ChocolateBoiler();
bool m_Empty;
bool m_Boiled;
// 1. Define a private static attribute
static ChocolateBoiler* m_pInstance;
};
#endif // SINGLETON_H
|
91f325d20bf03bda090cd2d89074a9040203015a | 093df6cf938afc1f0af9f7120e2b48112cde7e36 | /libstd_cpp/system_error/error_code/make_error_code_test.cpp | 650f1aee3ebf3c5d6d74a275a92577da3628b47a | [] | no_license | hexu1985/cpp_code | 6487e19563ed2a751f889cb81ad724c40b442097 | 1cdbe297dec47cdd11f9e5d28e6caa2971b469bb | refs/heads/master | 2020-06-25T22:19:55.409303 | 2019-02-19T03:29:49 | 2019-02-19T03:29:49 | 96,992,341 | 3 | 0 | null | 2017-07-12T09:54:11 | 2017-07-12T09:54:11 | null | UTF-8 | C++ | false | false | 1,056 | cpp | make_error_code_test.cpp | #include <iostream>
#include <errno.h>
#include "system_error.h" // std::error_code, std::generic_category
using namespace std;
using namespace Hx;
int main()
{
error_code code;
error_condition cond;
#if __cplusplus >= 201103L
code = make_error_code(errc(EPIPE));
cond = errc(EPIPE);
#else
code = make_error_code(errc::errc_t(EPIPE));
cond = errc::errc_t(EPIPE);
#endif
cout << "code.category: " << code.category().name() << "\n";
cout << "code.message: " << code.message() << "\n";
cout << "cond.category: " << cond.category().name() << "\n";
cout << "cond.message: " << cond.message() << "\n";
if (code == cond) {
cout << " == \n";
} else {
cout << " != \n";
}
code = error_code(EPIPE, system_category());
cout << "code.category: " << code.category().name() << "\n";
cout << "code.message: " << code.message() << "\n";
cout << "cond.category: " << cond.category().name() << "\n";
cout << "cond.message: " << cond.message() << "\n";
if (code == cond) {
cout << " == \n";
} else {
cout << " != \n";
}
return 0;
}
|
157c4e4a78539c7586706c02c3161bb9293f50d2 | a417ee28f754f495eba3c6808acba4bb41eb66fa | /test/test_tmatrix.cpp | f184a592116e7524229aea595601319912624d7f | [] | no_license | MalovaAA/mp2-lab2-matrix | 1f6ec589cc71671bf3b56478b0c1fe17ca0dbf21 | 952505d7b25798ca0fc446e8fd463a0fb9d08f2e | refs/heads/master | 2020-12-28T22:21:58.890360 | 2015-11-04T16:13:17 | 2015-11-04T16:13:17 | 44,588,959 | 0 | 0 | null | 2015-10-20T07:16:50 | 2015-10-20T07:16:48 | C++ | UTF-8 | C++ | false | false | 2,930 | cpp | test_tmatrix.cpp | #include "utmatrix.h"
#include <gtest.h>
TEST(TMatrix, can_create_matrix_with_positive_length)
{
ASSERT_NO_THROW(TMatrix<int> m(5));
}
TEST(TMatrix, cant_create_too_large_matrix)
{
ASSERT_ANY_THROW(TMatrix<int> m(MAX_MATRIX_SIZE + 1));
}
TEST(TMatrix, throws_when_create_matrix_with_negative_length)
{
ASSERT_ANY_THROW(TMatrix<int> m(-5));
}
TEST(TMatrix, can_create_copied_matrix)
{
TMatrix<int> m(5);
ASSERT_NO_THROW(TMatrix<int> m1(m));
}
TEST(TMatrix, copied_matrix_is_equal_to_source_one)
{
TMatrix<int> m(3);
m[1][1] = 1;
TMatrix<int> m1(m);
TMatrix<int> result(3);
result[1][1] = 1;
if (result == m1)
{
result[1][1] = 1;
}
EXPECT_EQ(result, m1);
}
TEST(TMatrix, copied_matrix_has_its_own_memory)
{
TMatrix<int> m(3);
m[1][1] = 1;
TMatrix<int> m1(m);
EXPECT_NE(&m, &m1);
}
TEST(TMatrix, can_get_size)
{
TMatrix<int> m(4);
EXPECT_EQ(4, m.GetSize());
}
TEST(TMatrix, can_set_and_get_element)
{
TMatrix<int> m(4);
m[0][1]=5;
EXPECT_EQ(5, m[0][1]);
}
TEST(TMatrix, throws_when_set_element_with_negative_index)
{
TMatrix<int> m(4);
ASSERT_ANY_THROW(m[0][-1]=1);
}
TEST(TMatrix, throws_when_set_element_with_too_large_index)
{
TMatrix<int> m(4);
ASSERT_ANY_THROW(m[0][5]=1);
}
TEST(TMatrix, can_assign_matrix_to_itself)
{
TMatrix<int> m(4);
m[1][1]=1;
EXPECT_EQ(m, m);
}
TEST(TMatrix, can_assign_matrices_of_equal_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(4);
m2[1][1]=1;
m1=m2;
EXPECT_EQ(m1, m2);
}
TEST(TMatrix, assign_operator_change_matrix_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(6);
m1=m2;
EXPECT_EQ(6, m1.GetSize());
}
TEST(TMatrix, can_assign_matrices_of_different_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(6);
m2[1][1]=1;
m1=m2;
EXPECT_EQ(m1, m2);
}
TEST(TMatrix, compare_equal_matrices_return_true)
{
TMatrix<int> m1(6);
TMatrix<int> m2(6);
m1[0][1]=1;
m1[1][2]=1;
m2[0][1]=1;
m2[1][2]=1;
EXPECT_TRUE(m2==m1);
}
TEST(TMatrix, compare_matrix_with_itself_return_true)
{
TMatrix<int> m1(4);
m1[0][1]=1;
m1[1][2]=1;
EXPECT_TRUE(m1==m1);
}
TEST(TMatrix, matrices_with_different_size_are_not_equal)
{
TMatrix<int> m1(4);
TMatrix<int> m2(6);
EXPECT_FALSE(m2==m1);
}
TEST(TMatrix, can_add_matrices_with_equal_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(4);
TMatrix<int> res(4);
m1[0][1]=2;
m1[1][2]=3;
m2[0][1]=1;
m2[1][2]=1;
res[0][1]=3;
res[1][2]=4;
EXPECT_EQ(res,m1+m2);
}
TEST(TMatrix, cant_add_matrices_with_not_equal_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(6);
ASSERT_ANY_THROW(m1+m2);
}
TEST(TMatrix, can_subtract_matrices_with_equal_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(4);
TMatrix<int> res(4);
m1[0][1]=2;
m1[1][2]=3;
m2[0][1]=1;
m2[1][2]=1;
res[0][1]=1;
res[1][2]=2;
EXPECT_EQ(res,m1-m2);
}
TEST(TMatrix, cant_subtract_matrixes_with_not_equal_size)
{
TMatrix<int> m1(4);
TMatrix<int> m2(6);
ASSERT_ANY_THROW(m1-m2);
}
|
5b77c51d2e02a6fae5c848f2fabbb616c1644cd3 | 130783812cfc97232bdb931c461cabe6a5a25fc6 | /src/test/atomic_value64_offset_unittest.cc | 21293839c4aef2caf130c79fa2e122fa0b231383 | [
"BSD-2-Clause"
] | permissive | altwajre/scal | e07a654906eecff9354d762fae02a39fb4060ed8 | fa2208a97a77d65f4e90f85fef3404c27c1f2ac2 | refs/heads/master | 2020-04-25T15:58:54.783716 | 2018-01-31T08:52:31 | 2018-01-31T08:52:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,356 | cc | atomic_value64_offset_unittest.cc | // Copyright (c) 2012-2013, the Scal Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include <gtest/gtest.h>
#include <stdio.h>
#include <stdlib.h>
#include <numeric>
#include "util/atomic_value64_offset.h"
namespace {
const uint64_t kUint64Max = std::numeric_limits<uint64_t>::max();
const AtomicAba kAbaMax = AtomicValue64Offset<uint64_t>::kAbaMax;
const uint8_t kAbaBits = AtomicValue64Offset<uint64_t>::kAbaBits;
const uint64_t kValueMax = AtomicValue64Offset<uint64_t>::kValueMax;
} // namespace
TEST(AtomicValue64OffsetTest, EmptyConstructor) {
AtomicValue64Offset<uint64_t> a;
EXPECT_EQ(0u, a.value());
EXPECT_EQ(0u, a.aba());
}
TEST(AtomicValue64OffsetTest, ConstructorMax) {
AtomicValue64Offset<uint64_t> a(kValueMax, kAbaMax);
EXPECT_EQ(kValueMax, a.value());
EXPECT_EQ(kAbaMax, a.aba());
}
TEST(AtomicValue64OffsetTest, ConstructorDiff) {
AtomicValue64Offset<uint64_t> a(1234u << 4, 7u);
EXPECT_EQ(1234u << 4, a.value());
EXPECT_EQ(7u, a.aba());
}
TEST(AtomicValue64OffsetTest, Set) {
AtomicValue64Offset<uint64_t> a(1ul, 1ul);
a.set_aba(kAbaMax);
a.set_value(0u);
EXPECT_EQ(a.value(), 0u);
EXPECT_EQ(a.aba(), kAbaMax);
a.set_value(kValueMax);
a.set_aba(0u);
EXPECT_EQ(a.aba(), 0u);
EXPECT_EQ(a.value(), kValueMax);
}
TEST(AtomicValue64OffsetTest, CAS) {
uint64_t val_a = 1u << kAbaBits;
uint64_t val_b = 2u << kAbaBits;
AtomicValue64Offset<uint64_t> a(val_a, 1u);
AtomicValue64Offset<uint64_t> b(val_b, 2u);
EXPECT_EQ(a.value(), val_a);
EXPECT_EQ(b.value(), val_b);
EXPECT_FALSE(a.cas(b, b));
AtomicValue64Offset<uint64_t> c(val_a, 1u);
EXPECT_EQ(b.value(), val_b);
EXPECT_TRUE(a.cas(c, b));
EXPECT_EQ(a.value(), val_b);
EXPECT_EQ(a.aba(), 2u);
}
TEST(AtomicValue64OffsetTest, CopyCtor) {
AtomicValue64Offset<uint64_t> a(1u << 4, 1u);
AtomicValue64Offset<uint64_t> b = a;
}
TEST(AtomicValue64OffsetTest, AssignmentOperator) {
AtomicValue64Offset<uint64_t> a(1u << 4, 1u);
AtomicValue64Offset<uint64_t> b(0u, 0u);
b = a;
EXPECT_EQ(b.aba(), 1u);
EXPECT_EQ(b.value(), 1u << 4);
}
TEST(AtomicValue64OffsetTest, Platform) {
void *a = malloc(sizeof(a));
AtomicValue64Offset<void*> av(a, 0);
EXPECT_EQ(a, av.value());
}
|
6e8c50cb089c10c74e182b943f2c6689980b2b13 | b6fd4d6a75c62a904579341064400b455e97baa7 | /LabWork1/View.h | 5d049ca590a8f3cc319d0e0774b190f17901e126 | [] | no_license | Vokhranov/CourseWorkOOP | 6160e6ba8000c03ed3ce70dc5fb859727db5521b | 235018774f21e8daf055856b707d51bda3f79eaf | refs/heads/master | 2021-04-03T08:59:44.322436 | 2018-03-13T19:47:27 | 2018-03-13T19:47:27 | 125,105,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | h | View.h | #pragma once
#include <string>
#include <vector>
#include "Necklace.h"
#include "PreciousStone.h"
#include "SemipreciousStone.h"
class View {
private:
std::string V_MASS;
std::string V_PRICE;
std::string V_TRANSPARRENCY;
std::string V_CARATES;
std::string V_NECKLACE;
public:
View(int key);
~View();
void View::Print(int value);
void View::Print(double value);
void View::Print(std::string value);
void View::PrintVectorOfStones(std::vector<Stone*> vectorOfStones);
void View::ShowAllNecklaces(std::vector<Necklace*> vectorOfNecklaces);
std::string HELLO;
std::string NACKLACES_ARE_BUILDED;
std::string STONES_IN_NECKLACE;
std::string FINAL_COST;
std::string FINAL_MASS;
std::string STONES_ARE_SORTED;
std::string GIVE_ME_RANGE_OF_TRANSPARECY;
std::string END;
std::string WRONG_INPUT;
std::string CHOOSE_NECKLACE;
std::string NECKLACE_MENU;
std::string JSON_IS_NOT_OPENED;
std::string PARCE_ERROR;
std::string NEW_LINE;
std::string JSON_INVALID;
std::string NO_ELEM_IN_JSON;
std::string NECKLACE_NOT_FOUND;
std::string NO_NECKLACES;
std::string NO_STONES;
}; |
4aa32ee7aae712d6d84cd7874687827df9a1fd92 | bb0d82d18daa788f93f2b6677ef00f22457b258d | /setvolume/Cpp1.cpp | be772862a6e4d2776975973bb10001b3933dc06b | [
"BSD-3-Clause"
] | permissive | No5972/Other_Demos | 8ad1a99ec9e852f643e2e6a7447cdeb97a9de345 | 44d7514f17274a288a7c295718f155de7690eb17 | refs/heads/master | 2021-06-19T08:02:15.294943 | 2021-06-08T14:31:15 | 2021-06-08T14:31:15 | 148,440,171 | 0 | 1 | BSD-3-Clause | 2021-06-08T14:31:05 | 2018-09-12T07:31:18 | C++ | GB18030 | C++ | false | false | 2,223 | cpp | Cpp1.cpp | #include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include <audioclient.h>
//参数:
// -2 恢复静音
// -1 静音
// 0~100:音量比例
bool SetVolumeLevel(int level)
{
HRESULT hr;
IMMDeviceEnumerator* pDeviceEnumerator = 0;
IMMDevice* pDevice = 0;
IAudioEndpointVolume* pAudioEndpointVolume = 0;
IAudioClient* pAudioClient = 0;
try {
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pDeviceEnumerator);
if (FAILED(hr)) throw "CoCreateInstance";
hr = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDevice);
if (FAILED(hr)) throw "GetDefaultAudioEndpoint";
hr = pDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void**)&pAudioEndpointVolume);
if (FAILED(hr)) throw "pDevice->Active";
hr = pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient);
if (FAILED(hr)) throw "pDevice->Active";
if (level == -2) {
hr = pAudioEndpointVolume->SetMute(FALSE, NULL);
if (FAILED(hr)) throw "SetMute";
}
else if (level == -1) {
hr = pAudioEndpointVolume->SetMute(TRUE, NULL);
if (FAILED(hr)) throw "SetMute";
}
else {
if (level<0 || level>100) {
hr = E_INVALIDARG;
throw "Invalid Arg";
}
float fVolume;
fVolume = level / 100.0f;
hr = pAudioEndpointVolume->SetMasterVolumeLevelScalar(fVolume, &GUID_NULL);
if (FAILED(hr)) throw "SetMasterVolumeLevelScalar";
pAudioClient->Release();
pAudioEndpointVolume->Release();
pDevice->Release();
pDeviceEnumerator->Release();
return true;
}
}
catch (...) {
if (pAudioClient) pAudioClient->Release();
if (pAudioEndpointVolume) pAudioEndpointVolume->Release();
if (pDevice) pDevice->Release();
if (pDeviceEnumerator) pDeviceEnumerator->Release();
throw;
}
return false;
}
int main()
{
CoInitialize(0);
try {
//3秒后静音
Sleep(3000);
SetVolumeLevel(-1);
//3秒后恢复静音
Sleep(3000);
SetVolumeLevel(-2);
//调节音量
Sleep(3000);
SetVolumeLevel(10);
Sleep(3000);
SetVolumeLevel(30);
Sleep(3000);
SetVolumeLevel(20);
}
catch (...) {
//错误处理...
}
CoUninitialize();
return 0;
} |
846362efcc7f4455de1763df6a2ce951a1623955 | 98d812e8638a498c626ecbeb05345c9931e7ae7d | /modelo/src/objeto/CintaTransportadora.cpp | 49acce399f2d4b029069d0c19736d35717714bdd | [] | no_license | joelruggieri/tp-taller-de-programacion | c58ba538fb00a8c66627fa2fc95830f794a662db | 3949b704516dc6c1fb6df3781f17af251cd1fe67 | refs/heads/master | 2020-08-27T06:28:06.750370 | 2013-11-27T21:35:52 | 2013-11-27T21:35:52 | 32,125,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,850 | cpp | CintaTransportadora.cpp | /*
* CintaTransportadora.cpp
*
* Created on: 05/10/2013
* Author: javier
*/
#include "CintaTransportadora.h"
#include "../Constantes.h"
#include <Box2D/Box2D.h>
#include "Densidades.h"
#define DEGTORAD 0.0174532925199432957f
#define RADTODEG 57.295779513082320876f
CintaTransportadora::CintaTransportadora(): Engranaje () {
this->ancho = 0;
this->alto = 0;
this->anchoBack = this->ancho;
this->rotacionEje = 0;
}
CintaTransportadora::~CintaTransportadora() {
}
void CintaTransportadora::crearFisica() {
float x = this->getX();
float y = this->getY();
//CREO EL CUERPO QUE VA A HACER CONTACTO CON EL RESTO
b2Vec2 centro(x, y);
b2PolygonShape * polygon = new b2PolygonShape();
b2MassData masa;
polygon->SetAsBox(this->ancho / 2, this->alto / 2);
b2FixtureDef fixture;
fixture.density = DENSIDAD_CINTA_TRANSP;
fixture.shape = polygon;
fixture.friction = 0.01f;
fixture.restitution = 0.00f;
fixture.filter.categoryBits = CATEGORIA_FIGURAS;
fixture.filter.maskBits = CATEGORIA_FIGURAS;
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(x, y);
bodyDef.fixedRotation = true;
double rotacionRad = this->getRotacion() * -1 *DEGTORAD;
bodyDef.angle = rotacionRad;
b2Body* body = myWorld->CreateBody(&bodyDef);
body->CreateFixture(&fixture)->SetUserData(this);
body->SetUserData(this);
this->setBody(body);
// CREO EL DISCO QUE VA A GIRAR
b2CircleShape shapeEngranaje;
shapeEngranaje.m_radius = this->radio;
b2FixtureDef fixtureEngranaje;
fixtureEngranaje.density = 1.00f;
fixtureEngranaje.shape = &shapeEngranaje;
fixtureEngranaje.friction = 0.8f;
fixtureEngranaje.restitution = 0.00f;
fixtureEngranaje.filter.categoryBits = CATEGORIA_CENTRO_CINTA;
fixtureEngranaje.filter.maskBits = CATEGORIA_CENTRO_CINTA;
b2BodyDef bodyDefEngranaje;
bodyDefEngranaje.type = b2_dynamicBody;
bodyDefEngranaje.position = centro;
bodyEngranaje = myWorld->CreateBody(&bodyDefEngranaje);
bodyEngranaje->CreateFixture(&fixtureEngranaje);
bodyEngranaje->SetUserData(this);
//joint engranaje con la tierra;
b2RevoluteJointDef jointEngranajeTierraDef;
jointEngranajeTierraDef.Initialize(ground, bodyEngranaje, centro);
jointEngranajeTierraDef.collideConnected = false;
jointCuerpoTierra = (b2RevoluteJoint*) myWorld->CreateJoint(&jointEngranajeTierraDef);
//radio de accion muy chico
b2CircleShape shapeAccion;
shapeAccion.m_radius = 0.1;
b2FixtureDef fixtureAccion;
fixtureAccion.filter.categoryBits = CATEGORIA_RANGO_ENGRANAJE;
fixtureAccion.filter.maskBits = CATEGORIA_RANGO_ENGRANAJE;
fixtureAccion.density = 1.00f;
fixtureAccion.shape = &shapeAccion;
fixtureAccion.friction = 0.01f;
fixtureAccion.restitution = 0.00f;
b2BodyDef bodyDefAccion;
bodyDefAccion.type = b2_dynamicBody;
bodyDefAccion.position = centro;
radioAccion = myWorld->CreateBody(&bodyDefAccion);
radioAccion->CreateFixture(&fixtureAccion);
radioAccion->SetUserData(this);
//joint radio de accion con la tierra;
b2RevoluteJointDef rjd2;
rjd2.Initialize(ground, radioAccion, centro);
rjd2.collideConnected = false;
myWorld->CreateJoint(&rjd2);
}
void CintaTransportadora::acept(VisitorFigura* visitor) {
visitor->visit(this);
}
CintaTransportadora::CintaTransportadora(float x, float y, float ancho, float alto) : Engranaje(x,y,alto/2) {
this->ancho = ancho;
this->alto = alto;
this->anchoBack = ancho;
this->rotacionEje = 0;
}
CintaTransportadora::CintaTransportadora(const CintaTransportadora& figura):Engranaje(figura) {
this->ancho = figura.ancho;
this->anchoBack = ancho;
this->alto = figura.alto;
this->reg = figura.reg;
this->rotacionEje = 0;
}
void CintaTransportadora::updateModelo() {
Figura::updateModelo();
this->rotacionEje = -1*radianesAGrados(bodyEngranaje->GetAngle());
}
void CintaTransportadora::setAncho(float ancho) {
this->ancho = ancho;
}
float CintaTransportadora::getAncho() const{
return this->ancho;
}
void CintaTransportadora::removerFisica() {
super::removerFisica();
if(bodyEngranaje){
myWorld->DestroyBody(this->bodyEngranaje);
this->bodyEngranaje = NULL;
}
}
float CintaTransportadora::getAlto() const {
return alto;
}
double CintaTransportadora::getRotacionEje() const {
return this->rotacionEje;
}
void CintaTransportadora::estirar(float delta){
this->ancho = ancho + delta;
if (ancho < 15) {
ancho = 15;
}
if (ancho > 50) {
ancho = 50;
}
}
void CintaTransportadora::setRotacion(double rot) {
}
void CintaTransportadora::makeBackUp() {
super::makeBackUp();
anchoBack = this->getAncho();
}
void CintaTransportadora::restoreBackUp() {
super::restoreBackUp();
ancho = anchoBack;
rotacionEje = 0;
}
float CintaTransportadora::getVelocidadCinta() {
if(this->bodyEngranaje != NULL){
return bodyEngranaje->GetAngularVelocity() == 0 ? 0 : bodyEngranaje->GetAngularVelocity() * getRadio() * -1;
}
return 0;
}
|
96dec31d6bc6c8c8e7b24fb81d3455f82def52a5 | e96ee2dfb356902cb618286025aa907b0931f71c | /Matricula.h | a40022c4cc78a9a859eb0dfcfd5b406566e68095 | [] | no_license | Rafa0407/proyectoEstructuras | 82b572b6d8911954fac660057168be1644b60e8f | ee36ff02aee890fe3a18a6082609681d1c10a741 | refs/heads/master | 2021-09-03T09:13:58.853606 | 2018-01-08T00:29:05 | 2018-01-08T00:29:05 | 109,077,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | h | Matricula.h | #pragma once
#include <cstring>
#include <iomanip>
#include <string>
#include <iostream>
using namespace std;
class Matricula {
public:
int cedula; // #0###0###
short int ciclo; // ciclo 1 o 2
char fecha[11]; // dd/mm/aaaa
short int codigoCurso; // ###
string nombreCurso;
short int grupo;
short int creditos;
short int estado; //0 para activo y 1 para error
Matricula(int cedula = 0, short int ciclo = 0, string fecha = " ", short int codigoCurso = 0, string nombreCurso = " ",
short int grupo = 0, short int creditos = 0, short int estado = 0) {
setCedula(cedula);
setCiclo(ciclo);
setFecha(fecha);
setCodigoCurso(codigoCurso);
setNombreCurso(nombreCurso);
setGrupo(grupo);
setCreditos(creditos);
setEstado(estado);
}
~Matricula() {
}
//METODOS SET
void setCedula(int cedula) {
this->cedula = cedula;
}
void setCiclo(short int ciclo) {
this->ciclo = ciclo;
}
void setFecha(string fecha) {
const char *pNombreCurso = fecha.data();
int tam = fecha.size();
strncpy_s(this->fecha, pNombreCurso, 11); // 8 por el formato de dd/mm/yy
//this->nombreCurso[8] = '\0';
}
void setCodigoCurso(short int codigoCurso) {
this->codigoCurso = codigoCurso;
}
void setNombreCurso(string nombreCurso) {
this->nombreCurso = nombreCurso;
}
void setGrupo(short int grupo) {
this->grupo = grupo;
}
void setCreditos(short int creditos) {
this->creditos = creditos;
}
void setEstado(short int estado) {
this->estado = estado;
}
};
|
a68c6d49cdaebecae0009d592df8bcda77b6ce29 | 2a35885833380c51048e54fbdc7d120fd6034f39 | /Competitions/Romário's Trello/706BInterestingDrink.cpp | 6979acaee0601959baedb792ddf090f6fe884d16 | [] | no_license | NelsonGomesNeto/Competitive-Programming | 8152ab8aa6a40b311e0704b932fe37a8f770148b | 4d427ae6a06453d36cbf370a7ec3d33e68fdeb1d | refs/heads/master | 2022-05-24T07:06:25.540182 | 2022-04-07T01:35:08 | 2022-04-07T01:35:08 | 201,100,734 | 8 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 714 | cpp | 706BInterestingDrink.cpp | #include <bits/stdc++.h>
using namespace std;
int binSearch(int array[], int lo, int hi, int target)
{
int mid = lo + (hi - lo) / 2;
if (lo >= hi)
{
if (array[mid] <= target)
return(mid + 1);
return(mid);
}
if (array[mid] <= target)
return(binSearch(array, mid + 1, hi, target));
return(binSearch(array, lo, mid, target));
}
int main()
{
int numShops; scanf("%d", &numShops);
int shops[numShops];
for (int i = 0; i < numShops; i ++)
scanf("%d", &shops[i]);
sort(shops, shops + numShops);
int days, money; scanf("%d", &days);
for (int i = 0; i < days; i ++)
{
scanf("%d", &money);
printf("%d\n", binSearch(shops, 0, numShops - 1, money));
}
return(0);
} |
0b00b185dd7be471dfa9ef30d1a08770f3bb1ff1 | 332e0c3c2189c73c51a9422ab4f9e07ed7d5134e | /10181.cpp | 5f679e63259809dce79e793e8cb4cca44bda6982 | [] | no_license | ksaveljev/UVa-online-judge | 352a05c9d12440337c2a0ba5a5f1c8aa1dc72357 | 006961a966004f744f5780a6a81108c0b79c3c18 | refs/heads/master | 2023-05-24T23:08:48.502908 | 2023-05-16T10:37:37 | 2023-05-16T10:37:37 | 1,566,701 | 112 | 80 | null | 2017-01-10T14:55:46 | 2011-04-04T11:43:53 | C++ | UTF-8 | C++ | false | false | 4,712 | cpp | 10181.cpp | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
int field[4][4];
bool solution_found;
vector<char> steps;
vector<char> solution_steps;
pair<int,int> find_pos(int field[4][4], int c) {
rep (i, 4)
rep (j, 4)
if (field[i][j] == c)
return make_pair(i,j);
}
int nr_of_inversions(int f[16]) {
int result = 0;
rep (i, 16) {
REP (j, i+1, 16) {
if (f[i] == 0 || f[j] == 0)
continue;
if (f[i] > f[j])
result++;
}
}
return result;
}
bool is_solvable() {
int f[16];
rep (i, 4)
rep (j, 4)
f[i*4+j] = field[i][j];
pair<int,int> blank = find_pos(field, 0);
int count = nr_of_inversions(f);
if ((4 - blank.first) % 2 == 0) {
return count % 2 == 1;
} else {
return count % 2 == 0;
}
}
int heuristic(int field[4][4]) {
static int f[4][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,0}};
int result = 0;
REP (i, 1, 16) {
pair<int,int> pos1 = find_pos(field, i);
pair<int,int> pos2 = find_pos(f, i);
result += abs(pos1.first - pos2.first);
result += abs(pos1.second - pos2.second);
}
return result;
}
bool is_goal_reached() {
static int f[4][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,0}};
rep (i, 4)
rep (j, 4)
if (field[i][j] != f[i][j])
return false;
return true;
}
void find_solution(int limit, char prev_move) {
if (solution_found || is_goal_reached()) {
solution_found = true;
solution_steps = steps;
return;
}
pair<int,int> blank = find_pos(field, 0);
/*
cout << "Current field:" << endl;
rep (i, 4) {
rep (j, 4) {
cout << field[i][j] << " ";
}
cout << endl;
}
cout << "Steps taken to reach this field: ";
rep (i, steps.size())
cout << steps[i];
cout << endl;
cout << "f(s) = h(s) + g(s) = " << heuristic(field) + steps.size() << endl;
cout << "current limit = " << limit << endl;
*/
// up
if (blank.first > 0 && prev_move != 'D') {
swap(field[blank.first][blank.second], field[blank.first-1][blank.second]);
int h = heuristic(field);
if (h + steps.size() + 1 <= limit && !solution_found) {
steps.push_back('U');
find_solution(limit, 'U');
steps.pop_back();
}
swap(field[blank.first][blank.second], field[blank.first-1][blank.second]);
}
// down
if (blank.first < 3 && prev_move != 'U') {
swap(field[blank.first][blank.second], field[blank.first+1][blank.second]);
int h = heuristic(field);
if (h + steps.size() + 1 <= limit && !solution_found) {
steps.push_back('D');
find_solution(limit, 'D');
steps.pop_back();
}
swap(field[blank.first][blank.second], field[blank.first+1][blank.second]);
}
// left
if (blank.second > 0 && prev_move != 'R') {
swap(field[blank.first][blank.second], field[blank.first][blank.second-1]);
int h = heuristic(field);
if (h + steps.size() + 1 <= limit && !solution_found) {
steps.push_back('L');
find_solution(limit, 'L');
steps.pop_back();
}
swap(field[blank.first][blank.second], field[blank.first][blank.second-1]);
}
// right
if (blank.second < 3 && prev_move != 'L') {
swap(field[blank.first][blank.second], field[blank.first][blank.second+1]);
int h = heuristic(field);
if (h + steps.size() + 1 <= limit && !solution_found) {
steps.push_back('R');
find_solution(limit, 'R');
steps.pop_back();
}
swap(field[blank.first][blank.second], field[blank.first][blank.second+1]);
}
}
int main(void) {
int n;
cin >> n;
while (n--) {
rep (i, 4)
rep (j, 4)
cin >> field[i][j];
if (!is_solvable()) {
cout << "This puzzle is not solvable." << endl;
continue;
}
int h = heuristic(field);
solution_found = false;
steps.clear();
while (true) {
find_solution(h, ' ');
if (solution_found) {
rep (i, solution_steps.size())
cout << solution_steps[i];
cout << endl;
break;
} else {
h += 5;
}
}
}
return 0;
}
|
21c850f47c7bda481a0351274f6ea8687e9aba30 | 9262559bb3d9e1817457cd5de7608fbca2bb6328 | /xCSGOx/Cheats/NoFlash.cpp | 46cfd5616a2f76fc878736b1fcdc4f024203e31f | [] | no_license | xselectx/xCSGOx | 767b64a2f919b2f0fda18e406aeaa0b76241b12d | 3cf61a306c64bf716df3e85aaf7ef65c8413df07 | refs/heads/master | 2020-09-07T04:03:45.933311 | 2019-11-09T14:05:03 | 2019-11-09T14:05:03 | 220,650,120 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | NoFlash.cpp | #include "NoFlash.h"
CheatNoFlashBang CheatNoFlash;
void CheatNoFlashBang::NoFlash()
{
if (Settings.Visuals.NoFlash.Type == 1) {
int flashDuration = rpm<float>(LocalPlayer::getLocalPlayer() + netvars::m_flFlashDuration);
if (flashDuration > 0) {
wpm<int>(0, LocalPlayer::getLocalPlayer() + netvars::m_flFlashDuration);
}
}
} |
f78ce5272e0a1c51ce32d1c448e359035c5edb67 | 72843da20942b6075f83d31d737957f86191b01e | /Source/Sieve/LOJ6235.cpp | 8f816826aa918df6222d51efe9962ea72dfc954b | [] | no_license | dtcxzyw/OI-Source | cb641f2c7e203a32073f4cae98e690f1cad3dc22 | aa041e2af7e1546e8c7ac5a960a27a3489cfcff8 | refs/heads/master | 2021-12-17T17:52:05.043490 | 2021-12-17T12:52:52 | 2021-12-17T12:52:52 | 140,553,277 | 43 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | cpp | LOJ6235.cpp | #include <cmath>
#include <cstdio>
typedef long long Int64;
const int sqsiz = 320005;
int p[sqsiz], psiz = 0;
bool flag[sqsiz];
void pre(int n) {
for(int i = 2; i <= n; ++i) {
if(!flag[i])
p[++psiz] = i;
for(int j = 1; j <= psiz && i * p[j] <= n;
++j) {
int val = i * p[j];
flag[val] = true;
if(i % p[j] == 0)
break;
}
}
}
Int64 G[2][sqsiz], sqr, n;
Int64& getG(Int64 x) {
if(x <= sqr)
return G[0][x];
return G[1][n / x];
}
Int64 q[sqsiz * 2];
int main() {
scanf("%lld", &n);
sqr = sqrt(n);
pre(sqr);
int m = 0;
Int64 dv = 1;
while(dv <= n) {
Int64 val = n / dv;
getG(val) = val - 1;
q[++m] = val;
dv = n / val + 1;
}
for(int i = 1; i <= psiz; ++i) {
Int64 cp = p[i], cp2 = cp * cp;
for(int j = 1; j <= m && cp2 <= q[j]; ++j) {
Int64 x = q[j], &val = getG(x);
val -= getG(x / cp) - (i - 1);
}
}
printf("%lld\n", getG(n));
return 0;
}
|
f00656d112e586daf68331e026ac01f454c0ccc1 | 555a489ad64783d83ccaa881b19d761310c77835 | /Source/Engine/Mesh/StaticMesh.h | 113c14808c9f785baee1bee1fcf1eb2cd64083f2 | [] | no_license | zapolnov/tiny3d | eb4dd85229293f73813a48923eda5234d05c8cb7 | d6d6746da011c6cb7e11216b962e137171e7d344 | refs/heads/master | 2021-02-04T03:43:51.581200 | 2020-03-03T18:23:01 | 2020-03-03T18:23:01 | 243,613,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | h | StaticMesh.h | #pragma once
#include <vector>
#include <memory>
struct MeshData;
class Engine;
class Material;
class IRenderBuffer;
class StaticMesh
{
public:
StaticMesh(Engine* engine, const MeshData* data);
virtual ~StaticMesh();
virtual void render() const;
protected:
struct Element
{
unsigned firstIndex;
unsigned indexCount;
std::shared_ptr<Material> material;
};
Engine* mEngine;
std::vector<Element> mElements;
std::unique_ptr<IRenderBuffer> mVertexBuffer;
std::unique_ptr<IRenderBuffer> mIndexBuffer;
};
|
10f3ba4ffb1e72f8a8d54398569ad8263f6bce6e | 4241b6d17e9b5c3cf32fdaf07328f143f3396712 | /libcef/browser/browser_host_impl_aura.cc | 594b12657334997af489293a07cf57d9cb48f7f9 | [] | no_license | fmarrabal/chromiumembedded | 00de87f15c6a4d8adab5750bc62511814f1cdfb5 | eaceb1a1ba7b85882460d366da99a9109e7e9b65 | refs/heads/master | 2021-01-21T12:20:52.317187 | 2014-09-29T12:16:27 | 2014-09-29T14:59:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,284 | cc | browser_host_impl_aura.cc | // Copyright (c) 2014 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 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 "libcef/browser/browser_host_impl.h"
#include <sys/sysinfo.h>
#include "libcef/browser/context.h"
#include "libcef/browser/window_delegate_view.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/cef_platform_data_aura.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "base/bind.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/common/file_chooser_params.h"
#include "content/public/common/renderer_preferences.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "content/public/browser/web_contents.h"
#include "ui/aura/test/test_screen.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/ozone/public/cursor_factory_ozone.h"
namespace {
// Returns the number of seconds since system boot.
long GetSystemUptime() {
struct sysinfo info;
if (sysinfo(&info) == 0)
return info.uptime;
return 0;
}
} // namespace
ui::PlatformCursor CefBrowserHostImpl::GetPlatformCursor(
blink::WebCursorInfo::Type type){
return ui::CursorFactoryOzone::GetInstance()->GetDefaultCursor(type);
}
bool CefBrowserHostImpl::PlatformCreateWindow() {
CHECK(!platform_);
gfx::Size default_window_size(640, 480);
aura::TestScreen* screen = aura::TestScreen::Create(gfx::Size());
gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);
platform_ = new cef::PlatformDataAura(default_window_size);
window_ = web_contents_->GetNativeView();
aura::Window* parent = platform_->host()->window();
if (!parent->Contains(window_))
parent->AddChild(window_);
window_->Show();
return true;
}
void CefBrowserHostImpl::PlatformCloseWindow() {
//Fixme: need to implement this
}
void CefBrowserHostImpl::PlatformSizeTo(int width, int height) {
}
void CefBrowserHostImpl::PlatformSetFocus(bool focus) {
if (!focus)
return;
if (web_contents_) {
// Give logical focus to the RenderWidgetHostViewAura in the views
// hierarchy. This does not change the native keyboard focus.
web_contents_->Focus();
}
}
CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() {
return window_info_.window;
}
bool CefBrowserHostImpl::PlatformViewText(const std::string& text) {
CEF_REQUIRE_UIT();
char buff[] = "/tmp/CEFSourceXXXXXX";
int fd = mkstemp(buff);
if (fd == -1)
return false;
FILE* srcOutput = fdopen(fd, "w+");
if (!srcOutput)
return false;
if (fputs(text.c_str(), srcOutput) < 0) {
fclose(srcOutput);
return false;
}
fclose(srcOutput);
std::string newName(buff);
newName.append(".txt");
if (rename(buff, newName.c_str()) != 0)
return false;
std::string openCommand("xdg-open ");
openCommand += newName;
if (system(openCommand.c_str()) != 0)
return false;
return true;
}
void CefBrowserHostImpl::PlatformHandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
// TODO(cef): Is something required here to handle shortcut keys?
}
void CefBrowserHostImpl::PlatformRunFileChooser(
const content::FileChooserParams& params,
RunFileChooserCallback callback) {
NOTIMPLEMENTED();
std::vector<base::FilePath> files;
callback.Run(files);
}
void CefBrowserHostImpl::PlatformHandleExternalProtocol(const GURL& url) {
}
void CefBrowserHostImpl::PlatformTranslateKeyEvent(
content::NativeWebKeyboardEvent& result,
const CefKeyEvent& key_event) {
NOTIMPLEMENTED();
}
void CefBrowserHostImpl::PlatformTranslateClickEvent(
blink::WebMouseEvent& result,
const CefMouseEvent& mouse_event,
MouseButtonType type,
bool mouseUp, int clickCount) {
PlatformTranslateMouseEvent(result, mouse_event);
switch (type) {
case MBT_LEFT:
result.type = mouseUp ? blink::WebInputEvent::MouseUp :
blink::WebInputEvent::MouseDown;
result.button = blink::WebMouseEvent::ButtonLeft;
break;
case MBT_MIDDLE:
result.type = mouseUp ? blink::WebInputEvent::MouseUp :
blink::WebInputEvent::MouseDown;
result.button = blink::WebMouseEvent::ButtonMiddle;
break;
case MBT_RIGHT:
result.type = mouseUp ? blink::WebInputEvent::MouseUp :
blink::WebInputEvent::MouseDown;
result.button = blink::WebMouseEvent::ButtonRight;
break;
default:
NOTREACHED();
}
result.clickCount = clickCount;
}
void CefBrowserHostImpl::PlatformTranslateMoveEvent(
blink::WebMouseEvent& result,
const CefMouseEvent& mouse_event,
bool mouseLeave) {
PlatformTranslateMouseEvent(result, mouse_event);
if (!mouseLeave) {
result.type = blink::WebInputEvent::MouseMove;
if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON)
result.button = blink::WebMouseEvent::ButtonLeft;
else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON)
result.button = blink::WebMouseEvent::ButtonMiddle;
else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON)
result.button = blink::WebMouseEvent::ButtonRight;
else
result.button = blink::WebMouseEvent::ButtonNone;
} else {
result.type = blink::WebInputEvent::MouseLeave;
result.button = blink::WebMouseEvent::ButtonNone;
}
result.clickCount = 0;
}
void CefBrowserHostImpl::PlatformTranslateWheelEvent(
blink::WebMouseWheelEvent& result,
const CefMouseEvent& mouse_event,
int deltaX, int deltaY) {
result = blink::WebMouseWheelEvent();
PlatformTranslateMouseEvent(result, mouse_event);
result.type = blink::WebInputEvent::MouseWheel;
static const double scrollbarPixelsPerGtkTick = 40.0;
result.deltaX = deltaX;
result.deltaY = deltaY;
result.wheelTicksX = result.deltaX / scrollbarPixelsPerGtkTick;
result.wheelTicksY = result.deltaY / scrollbarPixelsPerGtkTick;
result.hasPreciseScrollingDeltas = true;
// Unless the phase and momentumPhase are passed in as parameters to this
// function, there is no way to know them
result.phase = blink::WebMouseWheelEvent::PhaseNone;
result.momentumPhase = blink::WebMouseWheelEvent::PhaseNone;
if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON)
result.button = blink::WebMouseEvent::ButtonLeft;
else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON)
result.button = blink::WebMouseEvent::ButtonMiddle;
else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON)
result.button = blink::WebMouseEvent::ButtonRight;
else
result.button = blink::WebMouseEvent::ButtonNone;
}
void CefBrowserHostImpl::PlatformTranslateMouseEvent(
blink::WebMouseEvent& result,
const CefMouseEvent& mouse_event) {
// position
result.x = mouse_event.x;
result.y = mouse_event.y;
result.windowX = result.x;
result.windowY = result.y;
result.globalX = result.x;
result.globalY = result.y;
// TODO(linux): Convert global{X,Y} to screen coordinates.
// modifiers
result.modifiers |= TranslateModifiers(mouse_event.modifiers);
// timestamp
result.timeStampSeconds = GetSystemUptime();
}
|
70634a4835db2134480976ef82490d22b7453b4e | 7148bd245c4e7cdb60c4ac6cccdfa3d1323fa621 | /1312 - Cricket Field.cpp | f5a27448ae1947eea3b57b24e1809959bcb65426 | [] | no_license | JoeLi12345/UVa-solutions | 612cf15aa30b81a67a66358ae3921d6e2f46430d | 7e0878e868443ffed09b5cd6ebe6cc061625e942 | refs/heads/master | 2021-01-02T10:09:02.162700 | 2018-08-22T08:16:47 | 2018-08-22T08:16:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,155 | cpp | 1312 - Cricket Field.cpp | #include <bits/stdc++.h>
using namespace std;
struct point {
int x;
int y;
};
bool cmp(point &a, point &b) {
return a.x == b.x ? a.y < b.y : a.x < b.x;
}
bool cmp1(point &a, point &b) {
return a.y == b.y ? a.x < b.x : a.y < b.y;
}
vector <point> v;
int N, W, H;
int main() {
int T; scanf("%d", &T); bool shit = false;
while(T--) {
v.clear();
scanf("%d %d %d", &N, &W, &H);
for (int i = 0, a, b; i < N; i++) {
scanf("%d %d", &a, &b);
v.push_back((point){a, b});
}
N += 4;
v.push_back((point){0, 0});
v.push_back((point){0, H});
v.push_back((point){W, 0});
v.push_back((point){W, H});
sort(v.begin(), v.end(), cmp);
int P = 0, Q = 0, L = 0;
for (int i = 0; i < N; i++) {
int miny = 0, maxy = H;
for (int j = i + 1; j < N; j++) {
int nl = min(v[j].x - v[i].x, maxy - miny);
if (nl > L) {
P = v[i].x;
Q = miny;
L = nl;
}
if (v[j].x == v[i].x) continue;
if (v[j].y > v[i].y)
maxy = min(maxy, v[j].y);
else
miny = max(miny, v[j].y);
}
}
sort(v.begin(), v.end(), cmp1);
for (int i = 0; i < N; i++) {
int minx = 0, maxx = W;
// cout<<i<<":"<<v[i].x<<" "<<v[i].y<<"\n";
for (int j = i + 1; j < N; j++) {
// cout<<j<<"->\n";
int nl = min(v[j].y - v[i].y, maxx - minx);
// cout<<v[j].y - v[i].y<<" "<<maxx - minx<<"\n";
if (nl > L) {
P = minx;
Q = v[i].y;
L = nl;
}
if (v[j].y == v[i].y) continue;
if (v[j].x > v[i].x)
maxx = min(maxx, v[j].x);
else
minx = max(minx, v[j].x);
}
}
if (shit) printf("\n");
else shit = true;
printf("%d %d %d\n", P, Q, L);
}
}
|
c6e48f5509f9159b39b7e24084c04631ea091270 | acb390c9feee3af3e57e0b36810fb434e76a691d | /src/engine_systems/config_file.hpp | 67ac0ec42fb7ff8382760fd4e9754fcac08a0c29 | [] | no_license | Baboon9/realms_shattered | 43f8d188a1ded5a4a308dd19fa5d89d2edcbde4c | e97fa4ce2734c38903c2ccdba214484fb7498c41 | refs/heads/master | 2023-01-28T08:58:11.962391 | 2020-10-03T15:52:46 | 2020-10-03T15:52:46 | 311,085,149 | 0 | 0 | null | 2020-11-12T09:18:26 | 2020-11-08T14:50:09 | null | UTF-8 | C++ | false | false | 393 | hpp | config_file.hpp |
#ifndef _CONFIG_FILE_HPP_
#define _CONFIG_FILE_HPP_
struct ConfigFile {
ConfigFile():
m_language( "INVALID" ),
m_game_width( 0 ),
m_game_height( 0 ),
m_game_offset_x( 0 ),
m_game_offset_y( 0 )
{
}
std::string m_language;
int m_game_width;
int m_game_height;
int m_game_offset_x;
int m_game_offset_y;
};
#endif // _CONFIG_FILE_HPP_
|
e094f9417d3b15187e2a28cc54496aa27e0605bf | 58a0ba5ee99ec7a0bba36748ba96a557eb798023 | /GeeksForGeeks/Algorithms/6. Mathematical/6.square-root-of-a-perfect-square.cpp | 0e1941a6f589d2ef1ca8505521e07e4aef0f097a | [
"MIT"
] | permissive | adityanjr/code-DS-ALGO | 5bdd503fb5f70d459c8e9b8e58690f9da159dd53 | 1c104c33d2f56fe671d586b702528a559925f875 | refs/heads/master | 2022-10-22T21:22:09.640237 | 2022-10-18T15:38:46 | 2022-10-18T15:38:46 | 217,567,198 | 40 | 54 | MIT | 2022-10-18T15:38:47 | 2019-10-25T15:50:28 | C++ | UTF-8 | C++ | false | false | 337 | cpp | 6.square-root-of-a-perfect-square.cpp | // http://www.geeksforgeeks.org/square-root-of-a-perfect-square
#include <iostream>
using namespace std;
float squareRoot(int n){
float x = n;
float y = 1;
float e = 0.000001;
while(x-y > e){
x = (x+y)/2;
y = n/x;
}
return x;
}
int main(){
int n = 50;
printf ("Square root of %d is %f", n, squareRoot(n));
return 0;
}
|
5b93cf03033f1e5b3edc844cd68a8958ab1dae8e | 3870889315e3a6327de3723aefc03458783d8b06 | /tool/RPGTool/��Ʒ�༭��/DIB.cpp | 48c212bdd3a4b538fd253ccc5ed7e3c0d9090c50 | [] | no_license | jingjing54007/lge | 7beb9a9afb49e089acdcbcb2e53fd01177bfe13c | e3d1174456e2b3c53926f255bcd728d371f1f4b4 | refs/heads/master | 2021-05-11T02:07:05.931356 | 2013-01-03T14:02:40 | 2013-01-03T14:02:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,183 | cpp | DIB.cpp | // DIB.cpp: implementation of the DIB class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MyEditor.h"
#include "DIB.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
DIB::DIB()
{
m_pBMI=NULL;
m_pDIBData=NULL;
}
DIB::~DIB()
{
//释放内存
if(m_pBMI!=NULL)
delete m_pBMI;
if(m_pDIBData!=NULL)
delete m_pDIBData;
}
BOOL DIB::LoadFromFile(LPCTSTR lpszFileName)
{
CFile file;
BITMAPINFO* pBMI=NULL;
BYTE* pDIBData=NULL;
// 打开指定文件
if(!file.Open(lpszFileName,CFile::modeRead|CFile::typeBinary))
{
AfxMessageBox("打不开文件");
return FALSE;
}
BITMAPFILEHEADER bfh;
if(file.Read(&bfh,sizeof(bfh))!=sizeof(bfh))
{
AfxMessageBox("读文件出错!");
return FALSE;
}
//若不是位图案,不予处理
if(bfh.bfType!=0x4d42)
{
AfxMessageBox("不是BMP文件");
return FALSE;
}
//读入位图信息头
BITMAPINFOHEADER bih;
if(file.Read(&bih,sizeof(bih))!=sizeof(bih))
{
AfxMessageBox("读文件出错!");
return FALSE;
}
//若不是24位真彩色位图,则不予处理
if(bih.biBitCount!=24)
{
AfxMessageBox("不是24位真彩色位图!");
return FALSE;
}
// 为BITMAPINFO结构指针申请内存因为真彩色位图没有颜色表,所以其
// BITMAPINFO=BITMAPINFOHEADER
pBMI=(BITMAPINFO*)new char[sizeof(BITMAPINFOHEADER)];
if(!pBMI)
{
AfxMessageBox("分配内存出错!");
return FALSE;
}
//由于前面已将BITMAPINFOHEADER读入内存,所以这里只需要拷贝一下
memcpy(pBMI,&bih,sizeof(BITMAPINFOHEADER));
//为BMP图像数据指针申请内存;
DWORD dataBytes=bfh.bfSize-bfh.bfOffBits;//图像数据的字节数;
pDIBData=(BYTE*)new char[dataBytes];
if(!pDIBData)
{
AfxMessageBox("分配内存出错!");
delete pBMI;
return FALSE;
}
//读入位图的图像数据
if(file.Read(pDIBData,dataBytes)!=dataBytes)
{
AfxMessageBox("读文件出错!");
delete pBMI;
delete pDIBData;
return FALSE;
}
file.Close();
if(m_pBMI!=NULL)
delete pBMI;
m_pBMI=pBMI;
if(m_pDIBData!=NULL)
delete m_pDIBData;
m_pDIBData=pDIBData;
return TRUE;
}
void DIB::ShowDIB(CDC* pDC,int nLeft,int nTop,int nWidth,int nHeight)
{
pDC->SetStretchBltMode(COLORONCOLOR); //设置伸缩拷贝模式
StretchDIBits(pDC->GetSafeHdc(), //DC句柄
nLeft, //目标矩形左上角的X坐标
nTop, //目标矩形左上角的Y坐标
nWidth, //目标矩形的宽度
nHeight, //目标矩形的高度
0, //源矩形的左上积角的X坐标
0, //源矩形的左上积角的Y坐标
GetDIBWidth(), //源矩形的宽度
GetDIBHeight(), //源矩形的高度
m_pDIBData, //位图图像数据的地址
m_pBMI, //位图信息结构地址
DIB_RGB_COLORS, //标志选项
SRCCOPY); //光栅操作码
}
|
ff944a53f7dfb4c08dd3ec6b6a11af6ae6d599eb | f3acd4152dbed79e8e90fc3a766a93a2a64d70b7 | /hhoard.h | fbba6e5ed8db6ca2cae7bed8e172dd1ec71ad8e5 | [] | no_license | w329li/cc3k | 0bf3f821f617eddaa1061da8e57b50fa0692a62c | 87bda10368b90babec1f7adac252826c202dae77 | refs/heads/master | 2021-07-05T16:42:34.024185 | 2017-09-24T22:48:22 | 2017-09-24T22:48:22 | 104,681,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | h | hhoard.h | #ifndef HHOARD_H
#define HHOARD_H
#include "gold.h"
#include <string>
class Hhoard: public Gold {
public:
Hhoard(); // default ctor
~Hhoard(); // dtor
};
#endif
|
71473ef876ab9607a517bbce6779a00ef07753ac | 45192468a55b9e471a6b49ea6ed2666aca5418d0 | /Core/src/maths/mat4.cpp | d0b6faa15df22d090d9338ca7f783f45ae3953ee | [] | no_license | Jonek52/Game-Engine | 9be8cb992b16f052730b5b0ee0db873ceef4556c | 30bf2f95fff4adf8517530e8e6faa5f4fce01bbe | refs/heads/master | 2020-04-21T08:04:37.174354 | 2019-04-03T14:47:39 | 2019-04-03T14:47:39 | 169,409,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,454 | cpp | mat4.cpp | #include "mat4.h"
#include "maths.h"
namespace sparky {
namespace maths {
mat4::mat4 () {
for (int i = 0; i < 4 * 4; ++i)
elements[i] = 0.0f;
}
mat4::mat4 (float diagonal) {
for (int i = 0; i < 4 * 4; ++i)
elements[i] = 0.0f;
elements[0 + 0 * 4] = diagonal;
elements[1 + 1 * 4] = diagonal;
elements[2 + 2 * 4] = diagonal;
elements[3 + 3 * 4] = diagonal;
}
mat4 mat4::identity () {
return mat4 (1.0f);
}
mat4 mat4::multiply (const mat4 & other) {
mat4 result;
float sum = 0.0f;
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
sum = 0.0;
for (int k = 0; k < 4; ++k) {
sum += elements[k * 4 + x] * other.elements[y * 4 + k];
}
result.elements[y * 4 + x] = sum;
}
}
return result;
}
mat4 operator*(mat4 left, const mat4& right) {
return (left.multiply (right));
}
mat4 mat4::operator*=(const mat4& other) {
return multiply (other);
}
mat4 mat4::orthographic (float left, float right, float bottom, float top, float near, float far) {
mat4 result (1.0f);
result.elements[0 * 4 + 0] = 2.0f / (right - left);
result.elements[1 * 4 + 1] = 2.0f / (top - bottom);
result.elements[2 * 4 + 2] = 2.0f / (near - far);
result.elements[3 * 4 + 0] = (right + left) / (left - right);
result.elements[3 * 4 + 1] = (top + bottom) / (bottom - top);
result.elements[3 * 4 + 2] = (far + near) / (far - near);
return result;
}
mat4 mat4::perspective (float fov, float aspectratio, float near, float far) {
mat4 result (1.0f);
float q = 1 / (tan (toRadians (fov / 2)));
float a = q / aspectratio;
float b = (near + far) / (near - far);
float c = (2.0f * near * far) / (near - far);
result.elements[0 * 4 + 0] = a;
result.elements[1 * 4 + 1] = q;
result.elements[2 * 4 + 2] = b;
result.elements[2 * 4 + 3] = -1.0f;
result.elements[3 * 4 + 2] = c;
return result;
}
mat4 mat4::translation (const vec3& translation) {
mat4 result (1.0f);
result.elements[3 * 4 + 0] = translation.x;
result.elements[3 * 4 + 1] = translation.y;
result.elements[3 * 4 + 2] = translation.z;
return result;
}
mat4 mat4::rotation (float angle, const vec3& axis) {
mat4 result (1.0f);
float radians = toRadians (angle);
float c = cos (radians);
float s = sin (radians);
float omc = 1 - c;
float x = axis.x;
float y = axis.y;
float z = axis.z;
result.elements[0 * 4 + 0] = c + x * x * omc;
result.elements[0 * 4 + 1] = y * x * omc + z * s;
result.elements[0 * 4 + 2] = z * x * omc - y * s;
result.elements[1 * 4 + 0] = x * y * omc - z * s;
result.elements[1 * 4 + 1] = c + y * y * omc;
result.elements[1 * 4 + 2] = z * y * omc + x * s;
result.elements[2 * 4 + 0] = x * z * omc + y * s;
result.elements[2 * 4 + 1] = y * z * omc - x * s;
result.elements[2 * 4 + 2] = c + z * z * omc;
return result;
}
mat4 mat4::scale (const vec3& scale) {
mat4 result (1.0f);
result.elements[0 * 4 + 0] = scale.x;
result.elements[1 * 4 + 1] = scale.y;
result.elements[2 * 4 + 2] = scale.z;
return result;
}
std::ostream & operator<<(std::ostream & os, const mat4 & matrix) {
std::cout << "Matrix" << std::endl;
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
std::cout << matrix.elements[x * 4 + y] << "\t";
}
std::cout << std::endl;
}
return os;
}
}
} |
234a5434d6705c97d8aeaa9eea0a77ef27ba1fd2 | 5cb369854f0cb24c351d0fc096fcb7d51642f4bb | /UVA/443 - Humble Numbers.cpp | 31e297eb22466bfac25bf4edcf6fd8e9f5041fb5 | [] | no_license | sebas095/Competitive-Programming | 3b0710bf76c04f274a67527888fc81dd6ddb9c6f | 0631caca5b10019f44212588ea16dbfc59c42f53 | refs/heads/master | 2021-05-24T00:56:51.945526 | 2020-07-07T06:46:42 | 2020-07-07T06:46:42 | 45,226,584 | 0 | 2 | null | 2016-10-28T16:26:50 | 2015-10-30T03:19:53 | C++ | UTF-8 | C++ | false | false | 1,046 | cpp | 443 - Humble Numbers.cpp | #include <bits/stdc++.h>
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
#define endl '\n'
using namespace std;
vector<int> humble(5844,0);
string toStr(int &n) {
stringstream ss;
ss << n;
return ss.str();
}
void gen() {
int p1, p2, p3, p4;
long h1, h2, h3, h4;
p1 = p2 = p3 = p4 = humble[1] = 1;
for (int i = 2; i < humble.size(); i++) {
h1 = 2 * humble[p1];
h2 = 3 * humble[p2];
h3 = 5 * humble[p3];
h4 = 7 * humble[p4];
humble[i] = min(min(h1, h2), min(h3, h4));
if (humble[i] == h1) p1++;
if (humble[i] == h2) p2++;
if (humble[i] == h3) p3++;
if (humble[i] == h4) p4++;
}
}
int main() {
fast;
gen();
int n;
while (cin >> n and n) {
string ans = "The " + toStr(n);
if ((n % 10) == 1 and (n / 10 ) % 10 != 1) ans += "st";
else if ((n % 10) == 2 and (n / 10) % 10 !=1) ans += "nd";
else if ((n % 10) == 3 and (n / 10) % 10 !=1) ans += "rd";
else ans += "th";
cout << ans << " humble number is " << humble[n] << "." << endl;
}
return 0;
}
|
d6a2d16309e8a6dda54fd0cc6befb016227de324 | bacb0dd13e7e6fd578095a8948e3831d4f47e805 | /Untitled2.cpp | cc8d42056d0be01970ca4dabf45251588d072ba2 | [] | no_license | guluuu3/spoj | 95645bca27ec4163803cea99636f9877f79f930a | af273783470f7ac42c781e43949640026b455b69 | refs/heads/master | 2021-01-18T15:14:28.234260 | 2015-07-18T05:39:35 | 2015-07-18T05:39:35 | 39,065,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | Untitled2.cpp | #include <iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
long long int arr[100000];
arr[0]=0;
for(int i=1;i<=n;i++)
{
cin>>arr[i];
}
int x;
cin>>x;
while(x--)
{
int q,x,y;
int even=0;
int odd=0;
cin>>q>>x>>y;
int ve[100000]=1;;
int vo[100000]=1;
if(q==0)
{
arr[x]=arr[y];
if(arr[y]%2==0)
ve[arr[y]]++;
else
vo[arr[y]]++;
}
if(q==1)
{
if(y%2==0)
even=(y-x)/2;
else
even=1+(y-x)/2;
for(int i=1;i<=n;i++)
{
if(ve[i]>0 && i==y)
even=even+ve[i];
}
cout<<even<<endl;
}
if(q==2)
{
if(y%2==0)
even=(y-x+1)/2;
else
even=1+(y-x+1)/2;
for(int i=1;i<=n;i++)
{
if(vo[i]>0 && i==y)
odd=odd+vo[i];
}
cout<<odd<<endl;
}
}
//for(int i=0;i<=n;i++)cout<<arr[i];
//cout << "Hello World!" << endl;
return 0;
}
|
1a1175c6a538f32baa5ca2aa71c43eb84d62e18e | 747ea3ed98073d66d69cf7fb647fb2b71c1db713 | /Assignment_2_6/StudentMenu.cpp | 704143052bb147a64dc20ad39cc17e835a95491a | [] | no_license | dongho-jung/KW_OOP | 9ec05b91423f95c1566929e43d1574b9b119e088 | 6543b9bdd7bdc61648d8b9e99eb23c769f1d662a | refs/heads/master | 2023-06-09T03:03:57.757595 | 2017-06-06T15:15:13 | 2017-06-06T15:15:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,417 | cpp | StudentMenu.cpp | #include "StudentMenu.h"
#include "myString.h"
using namespace std;
// Add submenu.
void BaseMenuList::pushBack(BaseMenu* insertItem) {
if (head == NULL) {
head = insertItem;
} else {
BaseMenu* currentPtr;
for (currentPtr = head; currentPtr->next != NULL; currentPtr = currentPtr->next);
currentPtr->next = insertItem;
}
}
// Returns number of submenus.
int BaseMenuList::size() {
int size = 0;
for (BaseMenu* currentPtr = head;
currentPtr != NULL;
currentPtr = currentPtr->next, size++);
return size;
}
// Delete dynamically allocated submenu objects.
void BaseMenuList::clear() {
BaseMenu* pDel = head;
while (pDel != NULL) {
head = head->next;
delete pDel;
pDel = head;
}
head = NULL;
}
// Functions for accessing specific submenus.
BaseMenu* BaseMenuList::at(int idx) {
BaseMenu* currentPtr = head;
int i;
for (i = 0; i < idx; i++) {
currentPtr = currentPtr->next;
if (currentPtr == NULL)
throw invalid_argument("[!] Error. invalid idx in BaseMenuList::at()");
}
return currentPtr;
}
// If it is a middle-layer menu, it list submenus.
// Then get the number.
void PopupMenu::command() {
while (true) {
int size = v.size();
// List submenus.
for (int i = 0; i < size; i++)
cout << i + 1 << ". " << v.at(i)->getTitle() << " ";
cout << size + 1 << ". Cancel" << endl;
// Enter the appropriate menu number.
int menuNumber;
do {
cout << "> Input number : ";
} while (safeNumInput(cin, menuNumber, 0, size + 1));
cout << endl;
// Cancel Processing part.
if (menuNumber == size + 1)
break;
// Enter the selected menu.
v.at(menuNumber - 1)->command();
}
}
void PopupMenu::addMenu(BaseMenu* newBaseMenu) {
v.pushBack(newBaseMenu);
}
void MenuPrintDays::command() {
mStudentManager->printItem(mDay, mSortKey);
cout << endl;
}
StudentMenu::StudentMenu(char* fileName) : mStudentManager(fileName){
// Construct menu layers..
mMenu_main = new PopupMenu("Menu"); // Root of menus.
PopupMenu* menu_printSortedByName = new PopupMenu("Print sorted by name"); // Add a submenu named "Print sorted by name" to the root.
mMenu_main->addMenu(menu_printSortedByName);
PopupMenu* menu_printSortedByScore = new PopupMenu("Print sorted by score"); // Add a submenu named "Print sorted by score" to the root.
mMenu_main->addMenu(menu_printSortedByScore);
// Add proper action menu to the each submenu.
menu_printSortedByName->addMenu(new MenuPrintDays(mStudentManager, "Wednesday", Student::Days::WED, OOP::SortKeys::NAME));
menu_printSortedByName->addMenu(new MenuPrintDays(mStudentManager, "Thursday", Student::Days::THU, OOP::SortKeys::NAME));
menu_printSortedByName->addMenu(new MenuPrintDays(mStudentManager, "Friday", Student::Days::FRI, OOP::SortKeys::NAME));
menu_printSortedByName->addMenu(new MenuPrintDays(mStudentManager, "Non-attendance classes", Student::Days::NON, OOP::SortKeys::NAME));
menu_printSortedByScore->addMenu(new MenuPrintDays(mStudentManager, "Wednesday", Student::Days::WED, OOP::SortKeys::SCORE));
menu_printSortedByScore->addMenu(new MenuPrintDays(mStudentManager, "Thursday", Student::Days::THU, OOP::SortKeys::SCORE));
menu_printSortedByScore->addMenu(new MenuPrintDays(mStudentManager, "Friday", Student::Days::FRI, OOP::SortKeys::SCORE));
menu_printSortedByScore->addMenu(new MenuPrintDays(mStudentManager, "Non-attendance classes", Student::Days::NON, OOP::SortKeys::SCORE));
}
|
36c5eaa8ab5f01b5c9041846a4335e2a59cc0b33 | 0adbb853d6de1d7de6336aea7ffd2e404313a5bd | /I2C.ino | 0015fa4ec00be0e174c38208c6bce56ca1e0427b | [] | no_license | Os-Roma/arduino | 79c7ad5f06b54cee2c7892f6bb29bf5cf7c0b01a | 5d47b86283b437aed06d59cded409d07dc746a81 | refs/heads/master | 2023-03-23T02:03:06.951046 | 2021-03-16T01:56:51 | 2021-03-16T01:56:51 | 348,181,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | ino | I2C.ino | #include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Establece las dimenciones del display
#include <RTClib.h>
RTC_DS3231 rtc;
DateTime f;
void setup() {
Serial.begin(9600);
if(!rtc.begin()){
Serial.println("Módulo RTC no encontrado !");
while(1);
}
// Activar linea cuando conecta el módulo RTC por primera vez
// rtc.adjust(DateTime(__DATE__, __TIME__));
lcd.init();
lcd.backlight();
lcd.setCursor(0, 1);
lcd.print("Creative!");
delay(4000);
lcd.clear();
}
void loop() {
f = rtc.now(); // Fecha y hora
// Marca la hora
lcd.setCursor(11, 1);
if (f.hour() <= 9) {
lcd.print("0");
lcd.setCursor(12, 1);
}
lcd.print(f.hour());
lcd.setCursor(13, 1);
if (f.second() % 2 == 0 ) {
lcd.print(" ");
} else {
lcd.print(":");
}
lcd.setCursor(14, 1);
if (f.minute() <= 9) {
lcd.print("0");
lcd.setCursor(15, 1);
}
lcd.print(f.minute());
}
|
fc7f36dcf7124f970c81ac13d592a6fc09b73f2f | 5431502adf171a94aa16f742428bab8ad8340c75 | /esp8266-doorkeeper/src/json.cpp | fe7dc9d00e2d751c07e14290fc2886ee2aead73a | [] | no_license | mxyue/platformIO-demo | 4dcf1c89c7c06886ea763f870d68077a2164672f | 8dd4cf3f49a07487a2f7915ce42953378d3ee673 | refs/heads/master | 2022-11-19T11:31:19.386069 | 2020-07-15T06:36:27 | 2020-07-15T06:36:27 | 279,757,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | json.cpp | #include "json.h"
typedef StaticJsonDocument<200> SJSON;
typedef DynamicJsonDocument DJSON;
// json object to string
String JSON::ObjToStr(DJSON obj){
String resStr;
serializeJson(obj, resStr);
return resStr;
}
//需要clear
DJSON JSON::StrToObj(String str){
DJSON doc(512);
DeserializationError error = deserializeJson(doc, str);
if (error) {
Serial.print("strToObj deserializeJson() failed: ");
Serial.println(error.c_str());
}
return doc;
}
|
1a3d7ac204130a70fbec4610a34d15220c14fefa | 30221016cf6f96959e627b0269553c76cc480e45 | /FaceRecognitionInterfaceApp/source/modele/cachephotos.cpp | df9fc32a4b60e48a6daa57219ea62cfab30f5dbb | [] | no_license | rom1504/FaceRecognitionInterface | 09cdf3d8d624db688ded4448c16f78e8ac46883a | 915d89a3f3f5a916cfd5cce93a5ad55e03cea3f7 | refs/heads/master | 2021-01-19T14:34:08.718625 | 2013-10-17T18:28:10 | 2013-10-17T18:28:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | cachephotos.cpp | #include <QPixmapCache>
#include <QDebug>
#include "cachephotos.h"
void CachePhotos::getPhoto(QString chemin, QPixmap &pm)
{
if (!QPixmapCache::find(chemin,pm))
{
if(chemin.section("_",-1)=="thumb")
{
QPixmap photo;
getPhoto(chemin.section("_",0,-2),photo);
if(!photo.isNull())
{
pm=photo.scaled(200,150,Qt::KeepAspectRatio);
QPixmapCache::insert(chemin,pm);
}
}
else if(chemin.section("_",-1)=="decent")
{
QPixmap photo;
getPhoto(chemin.section("_",0,-2),photo);
if(!photo.isNull())
{
pm=photo.scaled(1200,900,Qt::KeepAspectRatio);
QPixmapCache::insert(chemin,pm);
}
}
else if(chemin.section("_",-1)=="thumb2")
{
QPixmap photo;
getPhoto(chemin.section("_",0,-2),photo);
if(!photo.isNull())
{
pm=photo.scaled(160,120,Qt::KeepAspectRatio);
QPixmapCache::insert(chemin,pm);
}
}
else
{
pm.load(chemin);
QPixmapCache::insert(chemin, pm);
}
}
}
|
926902c049fdf6a7c9646fe86b6da20cc010d843 | 6d1daf69c4df028bb75dc13f38a6b9ee3f7b3f01 | /project2D/BehaviourApp.cpp | 86692e3bff0e0dd441c2494d91989abc21fc6a46 | [] | no_license | Sloth113/AIProject | 641e5fb1e427d8aba0a9d419cabdffca0c1507f7 | f61cbc50a8787aa3e9fb5c3cdfdbe594a6e6a1bf | refs/heads/master | 2021-01-01T17:41:09.100397 | 2017-08-20T02:16:47 | 2017-08-20T02:16:47 | 98,133,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,963 | cpp | BehaviourApp.cpp | #include "BehaviourApp.h"
#include "Texture.h"
#include "Font.h"
#include "Input.h"
BehaviourApp::BehaviourApp()
{
}
BehaviourApp::~BehaviourApp()
{
}
bool BehaviourApp::startup()
{
m_agent = Agent(MathDLL::Vector2(getWindowWidth() / 2, getWindowHeight() / 2));
m_ai = Agent(MathDLL::Vector2(100, 100));
//m_agent.AddBehaviour(new KeyboardController());
m_agent.addBehaviour(new MouseController());
//m_agent.AddBehaviour(new DrunkModifier());
//m_agent.AddBehaviour(new SteeringBehaviour(new WanderForce()));
m_font = new aie::Font("./font/consolas.ttf", 32);
m_2dRenderer = new aie::Renderer2D();
//Behaviour tree
//Wander but avoid sequence
Sequence * closeFlee = new Sequence();
closeFlee->children.push_back(new CloseToCondition(100, &m_agent));
closeFlee->children.push_back(new SteeringBehaviour(new FleeForce(&m_agent)));
Selector * wanderFlee = new Selector();
wanderFlee->children.push_back(closeFlee);
wanderFlee->children.push_back(new SteeringBehaviour(new WanderForce(1.0f)));
m_ai.addBehaviour(wanderFlee);
//m_ai.AddBehaviour(new SteeringBehaviour(new SeekForce(&m_agent)));
//m_ai.AddBehaviour(new SteeringBehaviour(new FleeForce(&m_agent)));
//m_ai.AddBehaviour(new SteeringBehaviour(new WanderForce()));
//m_ai.AddBehaviour(new SteeringBehaviour(new ArrivalForce(&m_agent)));
//m_ai.AddBehaviour(new SteeringBehaviour(new SeekForce(MathDLL::Vector2((*(map.m_verts.begin()))->data.x, (*(map.m_verts.begin()))->data.y))));
//Flock
flockSize = 10;
float flockDist = 100;
m_flock = new Agent[flockSize];
for (int i = 0; i < flockSize-1; i++)
{
m_flock[i] = Agent(MathDLL::Vector2(rand() % 1280, rand() % 720));
m_flock[i].addBehaviour(new SteeringBehaviour(new SeparationForce(m_flock, flockSize, flockDist)));
m_flock[i].addBehaviour(new SteeringBehaviour(new CohesionForce(m_flock, flockSize, flockDist)));
m_flock[i].addBehaviour(new SteeringBehaviour(new AlignmentForce(m_flock, flockSize, flockDist)));
}
m_flock[9] = m_ai;
selected = nullptr;
addEdge = false;
return true;
}
void BehaviourApp::shutdown()
{
delete[] m_flock;
}
void BehaviourApp::update(float deltaTime)
{
// input example
aie::Input* input = aie::Input::getInstance();
m_agent.update(deltaTime);
// m_ai.Update(deltaTime);
for (int i = 0; i < flockSize; i++)
{
m_flock[i].update(deltaTime);
}
// exit the application
if (input->isKeyDown(aie::INPUT_KEY_ESCAPE))
quit();
}
void BehaviourApp::draw()
{
// wipe the screen to the background colour
clearScreen();
// set the camera position before we begin rendering
m_2dRenderer->setCameraPos(0, 0);
// begin drawing sprites
m_2dRenderer->begin();
char fps[32];
sprintf_s(fps, 32, "SPEED: %F", m_ai.getVel().magnitude());
m_2dRenderer->drawText(m_font, fps, 0, 720 - 32);
m_agent.draw(m_2dRenderer);
// m_ai.Draw(m_2dRenderer);
for (int i = 0; i < flockSize; i++)
{
m_flock[i].draw(m_2dRenderer);
}
// done drawing sprites
m_2dRenderer->end();
}
void BehaviourApp::DijkstraThing(Graph<MathDLL::Vector2> & graph)
{
//Set defaults
for (auto i = graph.m_verts.begin(); i != graph.m_verts.end(); i++)
{
(*i)->gScore = 9999999999; (*i)->parent = nullptr; (*i)->traversed = false;
}
auto cmp = [](Vertex<MathDLL::Vector2> * left, Vertex<MathDLL::Vector2> * right)
{
return left->gScore > right->gScore;
};
std::priority_queue<Vertex<MathDLL::Vector2> *, std::vector<Vertex<MathDLL::Vector2>*>, decltype(cmp)> pQueue(cmp);
pQueue.push(*(graph.m_verts.begin()));
pQueue.top()->gScore = 0;
pQueue.top()->parent = pQueue.top();
while (!pQueue.empty())
{
Vertex<MathDLL::Vector2> * node = pQueue.top();
pQueue.pop();
node->traversed = true;
for (auto i = node->edges.begin(); i != node->edges.end(); i++)
{
if (!(*i)->target->traversed)
{
float gScore = node->gScore + (*i)->weight;
if ((*i)->target->gScore > gScore)
{
(*i)->target->gScore = gScore;
(*i)->target->parent = node;
}
//ADD TO LIST IF NOT ALREADY THERE
pQueue.push((*i)->target);
}
}
}
}
void BehaviourApp::AStarOne(Graph<MathDLL::Vector2> & graph, Vertex<MathDLL::Vector2> * start, Vertex<MathDLL::Vector2> * end)
{
//
int count = 0;
int edges = 0;
//Set defaults
for (auto i = graph.m_verts.begin(); i != graph.m_verts.end(); i++)
{
(*i)->gScore = 9999999999; (*i)->hScore = 9999999999; (*i)->fScore = 9999999999; (*i)->parent = nullptr; (*i)->traversed = false;
}
auto cmp = [](Vertex<MathDLL::Vector2> * left, Vertex<MathDLL::Vector2> * right)
{
return left->fScore > right->fScore;
};
std::priority_queue<Vertex<MathDLL::Vector2> *, std::vector<Vertex<MathDLL::Vector2>*>, decltype(cmp)> pQueue(cmp);
std::vector<Vertex<MathDLL::Vector2>*> closedList;
start->gScore = 0;
MathDLL::Vector2 h = end->data - start->data;
start->hScore = h.getMagSquare();
start->fScore = start->hScore;
start->parent = start;
pQueue.push(start);
while (!pQueue.empty())
{
Vertex<MathDLL::Vector2> * node = pQueue.top();
pQueue.pop();
node->traversed = true;
closedList.push_back(node);
if (node == end)
{
break;
//Make path
}
for (auto i = node->edges.begin(); i != node->edges.end(); i++)
{
edges++;
if (!(*i)->target->traversed)
{
MathDLL::Vector2 dis = end->data - (*i)->target->data;
float nextHScore = (dis.getMagSquare());
std::cout << "H:" << nextHScore << std::endl;
float nextGScore = node->gScore + (*i)->weight;
float newScore = node->gScore + (*i)->weight + nextHScore;
if (newScore < (*i)->target->fScore)
{
(*i)->target->parent = node;
(*i)->target->fScore = newScore;
(*i)->target->gScore = nextGScore;
(*i)->target->hScore = nextHScore;
}
//ADD TO LIST IF NOT ALREADY THERE
if (!(std::find(closedList.begin(), closedList.end(), (*i)->target) != closedList.end()))
{
pQueue.push((*i)->target);
}
}
}
std::cout << ":END:" << std::endl;
}
}
|
6777467166606963ad3d80cc6617643d09714d55 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/multimedia/directx/dmusic/dmscript/autperformance.cpp | 2eefda116eb06f574f6eb405ceffefe7d0863057 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | WINDOWS-1252 | C++ | false | false | 11,240 | cpp | autperformance.cpp | // Copyright (c) 1999 Microsoft Corporation. All rights reserved.
//
// Implementation of CAutDirectMusicPerformance.
//
#include "stdinc.h"
#include "autperformance.h"
#include <limits>
#include "dmusicf.h"
const WCHAR CAutDirectMusicPerformance::ms_wszClassName[] = L"Performance";
//////////////////////////////////////////////////////////////////////
// Method Names/DispIDs
const DISPID DMPDISP_SetMasterTempo = 1;
const DISPID DMPDISP_GetMasterTempo = 2;
const DISPID DMPDISP_SetMasterVolume = 3;
const DISPID DMPDISP_GetMasterVolume = 4;
const DISPID DMPDISP_SetMasterGrooveLevel = 5;
const DISPID DMPDISP_GetMasterGrooveLevel = 6;
const DISPID DMPDISP_SetMasterTranspose = 7;
const DISPID DMPDISP_GetMasterTranspose = 8;
const DISPID DMPDISP_Trace = 9;
const DISPID DMPDISP_Rand = 10;
const AutDispatchMethod CAutDirectMusicPerformance::ms_Methods[] =
{
// dispid, name,
// return: type, (opt), (iid),
// parm 1: type, opt, iid,
// parm 2: type, opt, iid,
// ...
// ADT_None
{ DMPDISP_SetMasterTempo, L"SetMasterTempo",
ADPARAM_NORETURN,
ADT_Long, false, &IID_NULL, // tempo!New value for master tempo scaling factor as a percentage. For example, 50 would halve the tempo and 200 would double it.
ADT_None },
/// Calls IDirectMusicPerformance::SetGlobalParam(GUID_PerfMasterTempo, tempo / 100, sizeof(float)).
{ DMPDISP_GetMasterTempo, L"GetMasterTempo",
ADT_Long, true, &IID_NULL, // Current master tempo scaling factor as a percentage.
ADT_None },
/// Calls IDirectMusicPerformance::GetGlobalParam(GUID_PerfMasterTempo, X, sizeof(float)) and returns X * 100.
{ DMPDISP_SetMasterVolume, L"SetMasterVolume",
ADPARAM_NORETURN,
ADT_Long, false, &IID_NULL, // volume!New value for master volume attenuation.
ADT_Long, true, &IID_NULL, // duration
ADT_None },
/// Calls IDirectMusicPerformance::SetGlobalParam(GUID_PerfMasterVolume, volume, sizeof(long)).
/// Range is 100th of a dB. 0 is full volume.
{ DMPDISP_GetMasterVolume, L"GetMasterVolume",
ADT_Long, true, &IID_NULL, // Current value of master volume attenuation.
ADT_None },
/// Calls IDirectMusicPerformance::GetGlobalParam(GUID_PerfMasterVolume, X, sizeof(long)) and returns X.
{ DMPDISP_SetMasterGrooveLevel, L"SetMasterGrooveLevel",
ADPARAM_NORETURN,
ADT_Long, false, &IID_NULL, // groove level!New value for the global groove level, which is added to the level in the command track.
ADT_None },
{ DMPDISP_GetMasterGrooveLevel, L"GetMasterGrooveLevel",
ADT_Long, true, &IID_NULL, // Current value of the global groove level, which is added to the level in the command track.
ADT_None },
{ DMPDISP_SetMasterTranspose, L"SetMasterTranspose",
ADPARAM_NORETURN,
ADT_Long, false, &IID_NULL, // transpose!Number of semitones to transpose everything.
ADT_None },
{ DMPDISP_GetMasterTranspose, L"GetMasterTranspose",
ADT_Long, true, &IID_NULL, // Current global transposition (number of semitones).
ADT_None },
{ DMPDISP_Trace, L"Trace",
ADPARAM_NORETURN,
ADT_Bstr, false, &IID_NULL, // string!text to output to testing log
ADT_None },
/// This allocates, stamps, and sends a DMUS_LYRIC_PMSG with the following fields:
/// <ul>
/// <li> dwPChannel = channel
/// <li> dwVirtualTrackID = 0
/// <li> dwGroupID = -1
/// <li> mtTime = GetTime(X, 0) is called and X * 10000 is used
/// <li> dwFlags = DMUS_PMSGF_REFTIME | DMUS_PMSGF_LOCKTOREFTIME
/// <li> dwType = DMUS_PMSGT_SCRIPTLYRIC
/// <li> wszString = string
/// </ul>
/// This is used to send text to a trace log for debugging purposes. Less commonly, a script could be
/// running in an application that listens and reacts to the script's trace output.
{ DMPDISP_Rand, L"Rand",
ADT_Long, true, &IID_NULL, // Returns a randomly-generated number
ADT_Long, false, &IID_NULL, // Max value--returned number will be between 1 and this max. Cannot be zero or negative.
ADT_None },
{ DISPID_UNKNOWN }
};
const DispatchHandlerEntry<CAutDirectMusicPerformance> CAutDirectMusicPerformance::ms_Handlers[] =
{
{ DMPDISP_SetMasterTempo, SetMasterTempo },
{ DMPDISP_GetMasterTempo, GetMasterTempo },
{ DMPDISP_SetMasterVolume, SetMasterVolume },
{ DMPDISP_GetMasterVolume, GetMasterVolume },
{ DMPDISP_SetMasterGrooveLevel, SetMasterGrooveLevel },
{ DMPDISP_GetMasterGrooveLevel, GetMasterGrooveLevel },
{ DMPDISP_SetMasterTranspose, SetMasterTranspose },
{ DMPDISP_GetMasterTranspose, GetMasterTranspose },
{ DMPDISP_Trace, _Trace },
{ DMPDISP_Rand, Rand },
{ DISPID_UNKNOWN }
};
//////////////////////////////////////////////////////////////////////
// Creation
CAutDirectMusicPerformance::CAutDirectMusicPerformance(
IUnknown* pUnknownOuter,
const IID& iid,
void** ppv,
HRESULT *phr)
: BaseImpPerf(pUnknownOuter, iid, ppv, phr),
m_nTranspose(0),
m_nVolume(0)
{
// set the random seed used by the Rand method
m_lRand = GetTickCount();
*phr = m_pITarget->QueryInterface(IID_IDirectMusicGraph, reinterpret_cast<void**>(&m_scomGraph));
if (SUCCEEDED(*phr))
{
// Due to the aggregation contract, our object is wholely contained in the lifetime of
// the outer object and we shouldn't hold any references to it.
ULONG ulCheck = m_pITarget->Release();
assert(ulCheck);
}
}
HRESULT
CAutDirectMusicPerformance::CreateInstance(
IUnknown* pUnknownOuter,
const IID& iid,
void** ppv)
{
HRESULT hr = S_OK;
CAutDirectMusicPerformance *pInst = new CAutDirectMusicPerformance(pUnknownOuter, iid, ppv, &hr);
if (FAILED(hr))
{
delete pInst;
return hr;
}
if (pInst == NULL)
return E_OUTOFMEMORY;
return hr;
}
//////////////////////////////////////////////////////////////////////
// Automation methods
HRESULT
CAutDirectMusicPerformance::SetMasterTempo(AutDispatchDecodedParams *paddp)
{
LONG lTempo = paddp->params[0].lVal;
float fltTempo = ConvertToTempo(lTempo);
if (fltTempo < DMUS_MASTERTEMPO_MIN)
fltTempo = DMUS_MASTERTEMPO_MIN;
else if (fltTempo > DMUS_MASTERTEMPO_MAX)
fltTempo = DMUS_MASTERTEMPO_MAX;
return m_pITarget->SetGlobalParam(GUID_PerfMasterTempo, &fltTempo, sizeof(float));
}
HRESULT
CAutDirectMusicPerformance::GetMasterTempo(AutDispatchDecodedParams *paddp)
{
LONG *plRet = reinterpret_cast<LONG*>(paddp->pvReturn);
if (!plRet)
return S_OK;
float fltTempo = 1; // default value is 1 (multiplicative identity)
HRESULT hr = this->GetMasterParam(GUID_PerfMasterTempo, &fltTempo, sizeof(float));
if (SUCCEEDED(hr))
*plRet = ConvertFromTempo(fltTempo);
return hr;
}
HRESULT
CAutDirectMusicPerformance::SetMasterVolume(AutDispatchDecodedParams *paddp)
{
if (!m_scomGraph)
{
assert(false);
return E_FAIL;
}
LONG lVol = paddp->params[0].lVal;
LONG lDuration = paddp->params[1].lVal;
return SendVolumePMsg(lVol, lDuration, DMUS_PCHANNEL_BROADCAST_PERFORMANCE, m_scomGraph, m_pITarget, &m_nVolume);
}
HRESULT
CAutDirectMusicPerformance::GetMasterVolume(AutDispatchDecodedParams *paddp)
{
LONG *plRet = reinterpret_cast<LONG*>(paddp->pvReturn);
if (plRet)
*plRet = m_nVolume;
return S_OK;
}
HRESULT
CAutDirectMusicPerformance::SetMasterGrooveLevel(AutDispatchDecodedParams *paddp)
{
LONG lGroove = paddp->params[0].lVal;
char chGroove = ClipLongRangeToType<char>(lGroove, char());
return m_pITarget->SetGlobalParam(GUID_PerfMasterGrooveLevel, reinterpret_cast<void*>(&chGroove), sizeof(char));
}
HRESULT
CAutDirectMusicPerformance::GetMasterGrooveLevel(AutDispatchDecodedParams *paddp)
{
LONG *plRet = reinterpret_cast<LONG*>(paddp->pvReturn);
if (!plRet)
return S_OK;
char chGroove = 0; // default value is 0 (additive identity)
HRESULT hr = this->GetMasterParam(GUID_PerfMasterGrooveLevel, reinterpret_cast<void*>(&chGroove), sizeof(char));
if (SUCCEEDED(hr))
*plRet = chGroove;
return hr;
}
HRESULT
CAutDirectMusicPerformance::SetMasterTranspose(AutDispatchDecodedParams *paddp)
{
LONG lTranspose = paddp->params[0].lVal;
short nTranspose = ClipLongRangeToType<short>(lTranspose, short());
SmartRef::PMsg<DMUS_TRANSPOSE_PMSG> pmsg(m_pITarget);
HRESULT hr = pmsg.hr();
if FAILED(hr)
return hr;
// Generic PMSG stuff
hr = m_pITarget->GetTime(&pmsg.p->rtTime, NULL);
if (FAILED(hr))
return hr;
pmsg.p->dwFlags = DMUS_PMSGF_REFTIME | DMUS_PMSGF_LOCKTOREFTIME | DMUS_PMSGF_DX8;
pmsg.p->dwType = DMUS_PMSGT_TRANSPOSE;
pmsg.p->dwPChannel = DMUS_PCHANNEL_BROADCAST_PERFORMANCE;
pmsg.p->dwVirtualTrackID = 0;
pmsg.p->dwGroupID = -1;
// Transpose PMSG stuff
pmsg.p->nTranspose = nTranspose;
pmsg.p->wMergeIndex = 0xFFFF; // §§ special merge index so this won't get stepped on. is a big number OK? define a constant for this value?
pmsg.StampAndSend(m_scomGraph);
hr = pmsg.hr();
if (SUCCEEDED(hr))
m_nTranspose = nTranspose;
return hr;
}
HRESULT
CAutDirectMusicPerformance::GetMasterTranspose(AutDispatchDecodedParams *paddp)
{
LONG *plRet = reinterpret_cast<LONG*>(paddp->pvReturn);
if (plRet)
*plRet = m_nTranspose;
return S_OK;
}
HRESULT
CAutDirectMusicPerformance::_Trace(AutDispatchDecodedParams *paddp)
{
BSTR bstr = paddp->params[0].bstrVal;
int cwch = wcslen(bstr);
SmartRef::PMsg<DMUS_LYRIC_PMSG> pmsg(m_pITarget, cwch * sizeof(WCHAR));
HRESULT hr = pmsg.hr();
if (FAILED(hr))
return hr;
// Generic PMSG stuff
hr = m_pITarget->GetTime(&pmsg.p->rtTime, NULL);
if (FAILED(hr))
return hr;
pmsg.p->dwFlags = DMUS_PMSGF_REFTIME | DMUS_PMSGF_LOCKTOREFTIME;
pmsg.p->dwType = DMUS_PMSGT_SCRIPTLYRIC;
pmsg.p->dwPChannel = 0;
pmsg.p->dwVirtualTrackID = 0;
pmsg.p->dwGroupID = -1;
// Lyric PMSG stuff
wcscpy(pmsg.p->wszString, bstr);
pmsg.StampAndSend(m_scomGraph);
return pmsg.hr();
}
HRESULT
CAutDirectMusicPerformance::Rand(AutDispatchDecodedParams *paddp)
{
LONG *plRet = reinterpret_cast<LONG*>(paddp->pvReturn);
LONG lMax = paddp->params[0].lVal;
if (lMax < 1 || lMax > 0x7fff)
return E_INVALIDARG;
// Use random number generation lifted from the standard library's rand.c. We don't just
// use the rand function because the multithreaded library has a per-thread random chain,
// but this function is called from various threads and it would be difficult to manage
// getting them seeded. Generates pseudo-random numbers 0 through 32767.
long lRand = ((m_lRand = m_lRand * 214013L + 2531011L) >> 16) & 0x7fff;
if (plRet)
*plRet = lRand % lMax + 1; // trim to the requested range [1,lMax]
return S_OK;
}
HRESULT
CAutDirectMusicPerformance::GetMasterParam(const GUID &guid, void *pParam, DWORD dwSize)
{
HRESULT hr = m_pITarget->GetGlobalParam(guid, pParam, dwSize);
if (SUCCEEDED(hr) || hr == E_INVALIDARG) // E_INVALIDARG is the performance's polite way of telling us the param hasn't been set yet
return S_OK;
return hr;
}
|
3bf0f516175fb572ab4ad80245a0f3ad262fc043 | 9b5b43cf86cca6abb0ed3415ca988001cb3860b7 | /OpenTESArena/src/Game/Game.cpp | d911b4fcec81fea1c844a18f81a150e5deff5489 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Digital-Monk/OpenTESArena | 1591a156cb328b03b7e014cc0990a9bd0603f634 | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | refs/heads/master | 2022-07-12T21:31:13.407764 | 2020-05-14T04:08:00 | 2020-05-14T04:08:00 | 262,842,652 | 0 | 0 | MIT | 2020-05-10T17:44:42 | 2020-05-10T17:44:42 | null | UTF-8 | C++ | false | false | 16,907 | cpp | Game.cpp | #include <chrono>
#include <cmath>
#include <cstdint>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include "SDL.h"
#include "Game.h"
#include "Options.h"
#include "PlayerInterface.h"
#include "../Assets/CityDataFile.h"
#include "../Interface/Panel.h"
#include "../Media/FontManager.h"
#include "../Media/MusicFile.h"
#include "../Media/MusicName.h"
#include "../Media/TextureManager.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Utilities/Platform.h"
#include "components/debug/Debug.h"
#include "components/utilities/File.h"
#include "components/utilities/String.h"
#include "components/vfs/manager.hpp"
namespace
{
// Size of scratch buffer in bytes, reset each frame.
constexpr int SCRATCH_BUFFER_SIZE = 65536;
}
Game::Game()
{
DebugLog("Initializing (Platform: " + Platform::getPlatform() + ").");
// Get the current working directory. This is most relevant for platforms
// like macOS, where the base path might be in the app's own "Resources" folder.
this->basePath = Platform::getBasePath();
// Get the path to the options folder. This is platform-dependent and points inside
// the "preferences directory" so it's always writable.
this->optionsPath = Platform::getOptionsPath();
// Parse options-default.txt and options-changes.txt (if it exists). Always prefer the
// default file before the "changes" file.
this->initOptions(this->basePath, this->optionsPath);
// Initialize virtual file system using the Arena path in the options file.
const bool arenaPathIsRelative = File::pathIsRelative(this->options.getMisc_ArenaPath().c_str());
VFS::Manager::get().initialize(std::string(
(arenaPathIsRelative ? this->basePath : "") + this->options.getMisc_ArenaPath()));
// Initialize the OpenAL Soft audio manager.
const bool midiPathIsRelative = File::pathIsRelative(this->options.getAudio_MidiConfig().c_str());
const std::string midiPath = (midiPathIsRelative ? this->basePath : "") +
this->options.getAudio_MidiConfig();
this->audioManager.init(this->options.getAudio_MusicVolume(),
this->options.getAudio_SoundVolume(), this->options.getAudio_SoundChannels(),
this->options.getAudio_SoundResampling(), this->options.getAudio_Is3DAudio(), midiPath);
// Initialize the SDL renderer and window with the given settings.
this->renderer.init(this->options.getGraphics_ScreenWidth(),
this->options.getGraphics_ScreenHeight(),
static_cast<Renderer::WindowMode>(this->options.getGraphics_WindowMode()),
this->options.getGraphics_LetterboxMode());
// Initialize the texture manager.
this->textureManager.init();
// Determine which version of the game the Arena path is pointing to.
const bool isFloppyVersion = [this, arenaPathIsRelative]()
{
// Path to the Arena folder.
const std::string fullArenaPath = [this, arenaPathIsRelative]()
{
// Include the base path if the ArenaPath is relative.
const std::string path = (arenaPathIsRelative ? this->basePath : "") +
this->options.getMisc_ArenaPath();
return String::addTrailingSlashIfMissing(path);
}();
// Check for the CD version first.
const std::string &acdExeName = ExeData::CD_VERSION_EXE_FILENAME;
const std::string acdExePath = fullArenaPath + acdExeName;
if (File::exists(acdExePath.c_str()))
{
DebugLog("CD version.");
return false;
}
// If that's not there, check for the floppy disk version.
const std::string &aExeName = ExeData::FLOPPY_VERSION_EXE_FILENAME;
const std::string aExePath = fullArenaPath + aExeName;
if (File::exists(aExePath.c_str()))
{
DebugLog("Floppy disk version.");
return true;
}
// If neither exist, it's not a valid Arena directory.
throw DebugException("\"" + fullArenaPath + "\" does not have an Arena executable.");
}();
// Load various miscellaneous assets.
this->miscAssets.init(isFloppyVersion);
// Load and set window icon.
const Surface icon = [this]()
{
const std::string iconPath = this->basePath + "data/icon.bmp";
Surface surface = Surface::loadBMP(iconPath.c_str(), Renderer::DEFAULT_PIXELFORMAT);
// Treat black as transparent.
const uint32_t black = surface.mapRGBA(0, 0, 0, 255);
SDL_SetColorKey(surface.get(), SDL_TRUE, black);
return surface;
}();
this->renderer.setWindowIcon(icon);
this->scratchAllocator.init(SCRATCH_BUFFER_SIZE);
// Initialize panel and music to default.
this->panel = Panel::defaultPanel(*this);
this->setMusic(MusicName::PercIntro);
// Use a texture as the cursor instead.
SDL_ShowCursor(SDL_FALSE);
// Leave some members null for now. The game data is initialized when the player
// enters the game world, and the "next panel" is a temporary used by the game
// to avoid corruption between panel events which change the panel.
this->gameData = nullptr;
this->nextPanel = nullptr;
this->nextSubPanel = nullptr;
// This keeps the programmer from deleting a sub-panel the same frame it's in use.
// The pop is delayed until the beginning of the next frame.
this->requestedSubPanelPop = false;
}
Panel *Game::getActivePanel() const
{
return (this->subPanels.size() > 0) ?
this->subPanels.back().get() : this->panel.get();
}
AudioManager &Game::getAudioManager()
{
return this->audioManager;
}
InputManager &Game::getInputManager()
{
return this->inputManager;
}
FontManager &Game::getFontManager()
{
return this->fontManager;
}
bool Game::gameDataIsActive() const
{
return this->gameData.get() != nullptr;
}
GameData &Game::getGameData() const
{
// The caller should not request the game data when there is no active session.
DebugAssert(this->gameDataIsActive());
return *this->gameData.get();
}
Options &Game::getOptions()
{
return this->options;
}
Renderer &Game::getRenderer()
{
return this->renderer;
}
TextureManager &Game::getTextureManager()
{
return this->textureManager;
}
MiscAssets &Game::getMiscAssets()
{
return this->miscAssets;
}
ScratchAllocator &Game::getScratchAllocator()
{
return this->scratchAllocator;
}
Profiler &Game::getProfiler()
{
return this->profiler;
}
const FPSCounter &Game::getFPSCounter() const
{
return this->fpsCounter;
}
void Game::setPanel(std::unique_ptr<Panel> nextPanel)
{
this->nextPanel = std::move(nextPanel);
}
void Game::pushSubPanel(std::unique_ptr<Panel> nextSubPanel)
{
this->nextSubPanel = std::move(nextSubPanel);
}
void Game::popSubPanel()
{
// The active sub-panel must not pop more than one sub-panel, because it may
// have unintended side effects for other panels below it.
DebugAssertMsg(!this->requestedSubPanelPop, "Already scheduled to pop sub-panel.");
// If there are no sub-panels, then there is only the main panel, and panels
// should never have any sub-panels to pop.
DebugAssertMsg(this->subPanels.size() > 0, "No sub-panels to pop.");
this->requestedSubPanelPop = true;
}
void Game::setMusic(MusicName musicName, const std::optional<MusicName> &jingleMusicName)
{
if (jingleMusicName.has_value())
{
// Play jingle first and set the main music as the next music.
const std::string &jingleFilename = MusicFile::fromName(*jingleMusicName);
const bool loop = false;
this->audioManager.playMusic(jingleFilename, loop);
std::string nextFilename = MusicFile::fromName(musicName);
this->audioManager.setNextMusic(std::move(nextFilename));
}
else
{
// Play main music immediately.
const std::string &filename = MusicFile::fromName(musicName);
const bool loop = true;
this->audioManager.playMusic(filename, loop);
}
}
void Game::setGameData(std::unique_ptr<GameData> gameData)
{
this->gameData = std::move(gameData);
}
void Game::initOptions(const std::string &basePath, const std::string &optionsPath)
{
// Load the default options first.
const std::string defaultOptionsPath(basePath + "options/" + Options::DEFAULT_FILENAME);
this->options.loadDefaults(defaultOptionsPath);
// Check if the changes options file exists.
const std::string changesOptionsPath(optionsPath + Options::CHANGES_FILENAME);
if (!File::exists(changesOptionsPath.c_str()))
{
// Make one. Since the default options object has no changes, the new file will have
// no key-value pairs.
DebugLog("Creating options file at \"" + changesOptionsPath + "\".");
this->options.saveChanges();
}
else
{
// Read in any key-value pairs in the "changes" options file.
this->options.loadChanges(changesOptionsPath);
}
}
void Game::resizeWindow(int width, int height)
{
// Resize the window, and the 3D renderer if initialized.
const bool fullGameWindow = this->options.getGraphics_ModernInterface();
this->renderer.resize(width, height,
this->options.getGraphics_ResolutionScale(), fullGameWindow);
}
void Game::saveScreenshot(const Surface &surface)
{
// Get the path + filename to use for the new screenshot.
const std::string screenshotPath = []()
{
const std::string screenshotFolder = Platform::getScreenshotPath();
const std::string screenshotPrefix("screenshot");
int imageIndex = 0;
auto getNextAvailablePath = [&screenshotFolder, &screenshotPrefix, &imageIndex]()
{
std::stringstream ss;
ss << std::setw(3) << std::setfill('0') << imageIndex;
imageIndex++;
return screenshotFolder + screenshotPrefix + ss.str() + ".bmp";
};
std::string path = getNextAvailablePath();
while (File::exists(path.c_str()))
{
path = getNextAvailablePath();
}
return path;
}();
const int status = SDL_SaveBMP(surface.get(), screenshotPath.c_str());
if (status == 0)
{
DebugLog("Screenshot saved to \"" + screenshotPath + "\".");
}
else
{
DebugCrash("Failed to save screenshot to \"" + screenshotPath + "\": " +
std::string(SDL_GetError()));
}
}
void Game::handlePanelChanges()
{
// If a sub-panel pop was requested, then pop the top of the sub-panel stack.
if (this->requestedSubPanelPop)
{
this->subPanels.pop_back();
this->requestedSubPanelPop = false;
// Unpause the panel that is now the top-most one.
const bool paused = false;
this->getActivePanel()->onPauseChanged(paused);
}
// If a new sub-panel was requested, then add it to the stack.
if (this->nextSubPanel.get() != nullptr)
{
// Pause the top-most panel.
const bool paused = true;
this->getActivePanel()->onPauseChanged(paused);
this->subPanels.push_back(std::move(this->nextSubPanel));
}
// If a new panel was requested, switch to it. If it will be the active panel
// (i.e., there are no sub-panels), then subsequent events will be sent to it.
if (this->nextPanel.get() != nullptr)
{
this->panel = std::move(this->nextPanel);
}
}
void Game::handleEvents(bool &running)
{
// Handle events for the current game state.
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
// Application events and window resizes are handled here.
bool applicationExit = this->inputManager.applicationExit(e);
bool resized = this->inputManager.windowResized(e);
bool takeScreenshot = this->inputManager.keyPressed(e, SDLK_PRINTSCREEN);
if (applicationExit)
{
running = false;
}
if (resized)
{
int width = e.window.data1;
int height = e.window.data2;
this->resizeWindow(width, height);
// Call each panel's resize method. The panels should not be listening for
// resize events themselves because it's more of an "application event" than
// a panel event.
this->panel->resize(width, height);
for (auto &subPanel : this->subPanels)
{
subPanel->resize(width, height);
}
}
if (takeScreenshot)
{
// Save a screenshot to the local folder.
const auto &renderer = this->getRenderer();
const Surface screenshot = renderer.getScreenshot();
this->saveScreenshot(screenshot);
}
// Panel-specific events are handled by the active panel.
this->getActivePanel()->handleEvent(e);
// See if the event requested any changes in active panels.
this->handlePanelChanges();
}
}
void Game::tick(double dt)
{
// Tick the active panel.
this->getActivePanel()->tick(dt);
// See if the panel tick requested any changes in active panels.
this->handlePanelChanges();
}
void Game::render()
{
// Draw the panel's main content.
this->panel->render(this->renderer);
// Draw any sub-panels back to front.
for (auto &subPanel : this->subPanels)
{
subPanel->render(this->renderer);
}
// Call the active panel's secondary render method. Secondary render items are those
// that are hidden on panels below the active one.
Panel *activePanel = this->getActivePanel();
activePanel->renderSecondary(this->renderer);
// Get the active panel's cursor texture and alignment.
const Panel::CursorData cursor = activePanel->getCurrentCursor();
// Draw cursor if not null. Some panels do not define a cursor (like cinematics),
// so their cursor is always null.
if (cursor.getTexture() != nullptr)
{
// The panel should not be drawing the cursor themselves. It's done here
// just to make sure that the cursor is drawn only once and is always drawn last.
this->renderer.drawCursor(*cursor.getTexture(), cursor.getAlignment(),
this->inputManager.getMousePosition(), this->options.getGraphics_CursorScale());
}
this->renderer.present();
}
void Game::loop()
{
// Nanoseconds per second. Only using this much precision because it's what
// high_resolution_clock gives back. Microseconds would be fine too.
constexpr int64_t timeUnits = 1000000000;
// Longest allowed frame time.
const std::chrono::duration<int64_t, std::nano> maxFrameTime(timeUnits / Options::MIN_FPS);
// On some platforms, thread sleeping takes longer than it should, so include a value to
// help compensate.
std::chrono::nanoseconds sleepBias(0);
auto thisTime = std::chrono::high_resolution_clock::now();
// Primary game loop.
bool running = true;
while (running)
{
const auto lastTime = thisTime;
thisTime = std::chrono::high_resolution_clock::now();
// Shortest allowed frame time.
const std::chrono::duration<int64_t, std::nano> minFrameTime(
timeUnits / this->options.getGraphics_TargetFPS());
// Time since the last frame started.
const auto frameTime = [minFrameTime, &sleepBias, &thisTime, lastTime]()
{
// Delay the current frame if the previous one was too fast.
auto diff = thisTime - lastTime;
if (diff < minFrameTime)
{
const auto sleepTime = minFrameTime - diff + sleepBias;
std::this_thread::sleep_for(sleepTime);
// Compensate for sleeping too long. Thread sleeping has questionable accuracy.
const auto tempTime = std::chrono::high_resolution_clock::now();
const auto unnecessarySleepTime = [thisTime, sleepTime, tempTime]()
{
const auto tempFrameTime = tempTime - thisTime;
return tempFrameTime - sleepTime;
}();
sleepBias = -unnecessarySleepTime;
thisTime = tempTime;
diff = thisTime - lastTime;
}
return diff;
}();
// Two delta times: actual and clamped. Use the clamped delta time for game calculations
// so things don't break at low frame rates.
constexpr double timeUnitsReal = static_cast<double>(timeUnits);
const double dt = static_cast<double>(frameTime.count()) / timeUnitsReal;
const double clampedDt = std::fmin(frameTime.count(), maxFrameTime.count()) / timeUnitsReal;
// Reset scratch allocator for use with this frame.
this->scratchAllocator.clear();
// Update the input manager's state.
this->inputManager.update();
// Update the audio manager listener (if any) and check for finished sounds.
if (this->gameDataIsActive())
{
const AudioManager::ListenerData listenerData = [this]()
{
const Player &player = this->getGameData().getPlayer();
const Double3 &position = player.getPosition();
const Double3 &direction = player.getDirection();
return AudioManager::ListenerData(position, direction);
}();
this->audioManager.update(dt, &listenerData);
}
else
{
this->audioManager.update(dt, nullptr);
}
// Update FPS counter.
this->fpsCounter.updateFrameTime(dt);
// Listen for input events.
try
{
this->handleEvents(running);
}
catch (const std::exception &e)
{
DebugCrash("handleEvents() exception! " + std::string(e.what()));
}
// Animate the current game state by delta time.
try
{
// Multiply delta time by the time scale. I settled on having the effects of this
// be application-wide rather than just in the game world since it's intended to
// simulate lower DOSBox cycles.
const double timeScaledDt = clampedDt * this->options.getMisc_TimeScale();
this->tick(timeScaledDt);
}
catch (const std::exception &e)
{
DebugCrash("tick() exception! " + std::string(e.what()));
}
// Draw to the screen.
try
{
this->render();
}
catch (const std::exception &e)
{
DebugCrash("render() exception! " + std::string(e.what()));
}
}
// At this point, the program has received an exit signal, and is now
// quitting peacefully.
this->options.saveChanges();
}
|
abc4192900339edbb6a14ecdafe93e445ad07770 | 269f7b4d8c22993099e6d490be8345080e5fa09b | /src/QuasiModeSelectorCanvas.h | 041a60d08759e2ea1250b056271d0bf2cdcc395a | [] | no_license | ericrosenbaum/melodymorph | a9512cbef4f747b8eb31fe154b14dd7428afdf87 | 5eb33abbc7e2f89f6bebacc5bd9d655e96b67b26 | refs/heads/master | 2020-04-10T16:53:37.751865 | 2015-06-24T19:57:23 | 2015-06-24T19:57:23 | 8,367,830 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,062 | h | QuasiModeSelectorCanvas.h |
//
// QuasiModeSelectorCanvas.h
// MelodyMorph
//
// Created by Eric Rosenbaum on 3/3/13.
//
//
#ifndef MelodyMorph_QuasiModeSelectorCanvas_h
#define MelodyMorph_QuasiModeSelectorCanvas_h
#define NUM_MODES 6
// quasi modes
#define NONE 0
#define DRAW_MODE 1
#define ERASE_MODE 2
#define SELECT_MODE 3
#define PATH_MODE 4
#define MUTE_MODE 5
#define SLIDE_MODE 6
// selection mode states
#define SELECT_DRAWING 0
#define SELECT_DONE_DRAWING 1
class QuasiModeSelectorCanvas : public ofxUICanvas {
public:
// quasi modes
// they are mutually exclusive modes, only active while you're holding one down
int currentMode;
int selectionState;
// icon image file names
string names[NUM_MODES] = {"pencil_button", "eraser_button", "select_button", "path_button", "mute_button", "slide_button"};
QuasiModeSelectorCanvas(int x,int y,int w,int h) : ofxUICanvas(x,y,w,h)
{
currentMode = NONE;
setWidgetSpacing(0);
for (int i=0; i<NUM_MODES; i++) {
ofxUIImageButton *b = new ofxUIImageButton(100, 100, false, "GUI/" + names[i] + ".png", names[i]);
b->setColorFillHighlight(127); // down
b->setColorBack(255); // false
addWidgetDown(b);
// add a spacer between edit-modes and play modes
if (i==4) {
ofxUISpacer *spacer = new ofxUISpacer(100,30);
spacer->setVisible(false);
addWidgetDown(spacer);
}
}
setDrawBack(false);
ofAddListener(newGUIEvent, this, &QuasiModeSelectorCanvas::guiEvent);
autoSizeToFitWidgets();
}
void resetMode() {
currentMode = NONE;
}
int getCurrentMode() {
return currentMode;
}
int getSelectionState() {
return selectionState;
}
void setSelectionState(int s) {
selectionState = s;
}
void setVisibilityOfEditModesOnly(bool visible) {
vector<ofxUIWidget *> w = getWidgets();
for (int i=0; i<5; i++) {
w[i]->setVisible(visible);
}
}
bool isHit(float x, float y, bool allModes) {
vector<ofxUIWidget *> w = getWidgets();
if (allModes) {
for (int i=0; i<NUM_MODES; i++) {
if (w[i]->isHit(x, y)) {
return true;
}
}
} else {
if (w[NUM_MODES-1]->isHit(x, y)) {
return true;
}
// if (w[NUM_MODES-2]->isHit(x, y)) {
// return true;
// }
}
return false;
}
void guiEvent(ofxUIEventArgs &e) {
string name = e.widget->getName();
ofxUIButton *btn = (ofxUIButton *) e.widget;
for (int i=0; i<NUM_MODES; i++) {
// set currentMode to the corresponding #defined int value (above)
if (name == names[i]) {
if (btn->getValue()) { // touch down
currentMode = i+1;
} else {
resetMode();
}
}
}
// when we first enter selection mode, we are about to draw a selection
if (name == "select_button") {
if (btn->getValue()) { // touch down
selectionState = SELECT_DRAWING;
autoSizeToFitWidgets();
ofSendMessage("select_button_pressed");
}
}
// if we just released the select button, send a message to testApp
// so that we can deselect everything
if (name == "select_button") {
if (!btn->getValue()) { // touch up
autoSizeToFitWidgets();
ofSendMessage("select_button_released");
}
}
}
};
#endif
|
8bc221fc05699919a5e99fb11619f89968fdcb92 | 4719ec4d48cb60c1f10ef43b925c4c21f391dee2 | /rw/tools/stdcstring.h | 22cf4d33708162e6c23866747decfeb854a64160 | [] | no_license | damian123/rw | e83278747c56801aa5324589c425c492d3ba5356 | 36ae6048538da719d948c0e1fac780f988410d3d | refs/heads/master | 2021-09-10T06:15:26.318942 | 2018-03-21T10:09:15 | 2018-03-21T10:09:15 | 118,772,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209,341 | h | stdcstring.h | #ifndef RW_TOOLS_STDCSTRING_H
#define RW_TOOLS_STDCSTRING_H
/**********************************************************************
*
* Header file describing class RWStandardCString using basic_string
*
**********************************************************************
*
* $Id: //tools/13/rw/tools/stdcstring.h#1 $
*
**********************************************************************
*
* Copyright (c) 1989-2015 Rogue Wave Software, Inc. All Rights Reserved.
*
* This computer software is owned by Rogue Wave Software, Inc. and is
* protected by U.S. copyright laws and other laws and by international
* treaties. This computer software is furnished by Rogue Wave Software, Inc.
* pursuant to a written license agreement and may be used, copied, transmitted,
* and stored only in accordance with the terms of such license agreement and
* with the inclusion of the above copyright notice. This computer software or
* any other copies thereof may not be provided or otherwise made available to
* any other person.
*
* U.S. Government Restricted Rights. This computer software: (a) was
* developed at private expense and is in all respects the proprietary
* information of Rogue Wave Software, Inc.; (b) was not developed with
* government funds; (c) is a trade secret of Rogue Wave Software, Inc. for all
* purposes of the Freedom of Information Act; and (d) is a commercial item and
* thus, pursuant to Section 12.212 of the Federal Acquisition Regulations (FAR)
* and DFAR Supplement Section 227.7202, Government's use, duplication or
* disclosure of the computer software is subject to the restrictions set forth
* by Rogue Wave Software, Inc.
*
**********************************************************************/
#include <rw/defs.h>
#if !defined(RW_COPY_ON_WRITE_STRING)
# define RWStandardCString RWCString
# define RWStandardCSubString RWCSubString
# define RWStandardCConstSubString RWCConstSubString
#endif
class RW_TOOLS_GLOBAL RWStandardCString;
class RW_TOOLS_SYMBOLIC RWStandardCSubString;
class RW_TOOLS_SYMBOLIC RWStandardCConstSubString;
#include <rw/rwfile.h>
#include <rw/ref.h> // for backwards source compatibility
#include <rw/tools/hash.h>
#include <rw/tools/cstrutil.h>
#include <string>
#include <string.h>
template<class charT> class RWTRegularExpression;
/**
* @ingroup string_processing_classes
* @deprecated As of SourcePro 4, use \link RWTRegex RWTRegex<char>\endlink instead.
*
* @brief Deprecated. This class is a typedef for
* \link RWTRegularExpression RWTRegularExpression<char>\endlink.
*/
typedef RWTRegularExpression<char> RWCRExpr;
class RWCRegexp;
class RWCTokenizer;
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
// Document RWStandardCString and related classes.
/**
* @class RWStandardCSubString rw/tools/stdcstring.h
* @ingroup string_processing_classes
* @brief Alternate implementation of RWCSubString when
* \c RW_COPY_ON_WRITE_STRING is not defined.
*
* RWStandardCSubString should be directly used only with instances
* of class RWStandardCString. RWCSubString should be used with instances
* of class RWCString.
*
* @see RWCSubString for additional documentation.
*/
/**
* @class RWStandardCConstSubString rw/tools/stdcstring.h
* @ingroup string_processing_classes
* @brief Alternate implementation of RWCConstSubString when
* \c RW_COPY_ON_WRITE_STRING is not defined.
*
* RWStandardCConstSubString should be directly used only with instances
* of class RWStandardCString. RWCConstSubString should be used with instances
* of class RWCString.
*
* @see RWCConstSubString for additional documentation.
*/
/**
* @class RWStandardCString rw/tools/stdcstring.h
* @ingroup string_processing_classes
* @brief Alternate implementation of RWCString when
* \c RW_COPY_ON_WRITE_STRING is not defined.
*
* Unless the specific performance characteristics of RWStandardCString
* are required, applications should use RWCString instead. See the
* <em>Essential Tools Module User's Guide</em> for additional information.
*
* @see RWCString for additional documentation.
*/
/**
* @class RWCSubString rw/cstring.h
* @ingroup string_processing_classes
*
* @brief Allows some subsection of an RWCString
* to be addressed by defining a <i>starting position</i> and an
* \e extent
*
* The class RWCSubString allows some subsection of an RWCString
* to be addressed by defining a <i>starting position</i> and an
* \e extent. For example the 7<sup>th</sup> through the
* 11<sup>th</sup> elements, inclusive, would have a starting position of 7
* and an extent of 5. The specification of a starting position and extent
* can also be done on your behalf by such functions as RWCString::strip()
* or the overloaded function call operator taking a regular expression
* as an argument. There are no public constructors -- RWCSubStrings
* are constructed by various functions of the RWCString class and
* then destroyed immediately.
*
* A <i>zero length</i> substring is one with a defined starting
* position and an extent of zero. It can be thought of as starting
* just before the indicated character, but not including it. It
* can be used as an lvalue. A null substring is also legal and
* is frequently used to indicate that a requested substring, perhaps
* through a search, does not exist. A null substring can be detected
* with member function isNull(). However, it cannot be used as
* an lvalue.
*
* @section synopsis Synopsis
*
* @code
* #include <rw/cstring.h>
* RWCString s("test string");
* s(6,3); // "tri"
* @endcode
*
* @section persistence Persistence
*
* None
*
* @section example Example
*
* @code
* #include <iostream>
* #include <rw/cstring.h>
*
* int main()
* {
* RWCString s ("What I tell you is true.");
*
* std::cout << "Take the string: [" << s << "]\n";
*
* // Create a substring and use it as an lvalue:
* s(16, 0) = "three times ";
*
* std::cout << "After assigning text to a substring, the full string becomes: ["
* << s << "]" << std::endl;
*
* return 0;
* }
* @endcode
*
* Program output:
*
* @code
* Take the string: [What I tell you is true.]
* After assigning text to a substring, the full string becomes: [What I tell you three times is true.]
* @endcode
*/
class RW_TOOLS_SYMBOLIC RWStandardCSubString
{
public:
RWStandardCSubString(const RWStandardCSubString& sp);
/**
* Assignment from an RWCSubString. Example:
*
* @code
* RWCString a(10, 'a');
* RWCString b;
* ...
* b(2, 3) = a(5,5);
* @endcode
*
* Copies 5 characters of <tt>a</tt>'s data into the substring <tt>b(2,3)</tt>.
* The number of elements need not match; if they differ, \c b is resized
* appropriately. If self is the null substring, then the statement has no
* effect. Returns a reference to self.
*/
RWStandardCSubString& operator=(const RWStandardCSubString& str);
/**
* Assignment from an RWCConstSubString. Example:
*
* @code
* const RWCString a(10, 'a');
* RWCString b;
* ...
* b(2, 3) = a(5,5);
* @endcode
*
* Copies 5 characters of <tt>a</tt>'s data into the substring <tt>b(2,3)</tt>.
* The number of elements need not match; if they differ, \c b is resized
* appropriately. If self is the null substring, then the statement has no
* effect. Returns a reference to self.
*/
RWStandardCSubString& operator=(const RWStandardCConstSubString& str);
/**
* Assignment from an RWCString. Example:
*
* @code
* RWCString a;
* RWCString b;
* ...
* b(2, 3) = a;
* @endcode
*
* Copies <tt>a</tt>'s data into the substring <tt>b(2,3)</tt>. The number
* of elements need not match; if they differ, \c b is resized
* appropriately. If self is the null substring, then the statement
* has no effect. Returns a reference to self.
*/
RWStandardCSubString& operator=(const RWStandardCString& str);
/**
* Assignment from an \b std::string. Example:
*
* @code
* std::string a;
* RWCString b;
* ...
* b(2, 3) = a;
* @endcode
*
* Copies <tt>a</tt>'s data into the substring <tt>b(2,3)</tt>. The number
* of elements need not match; if they differ, \c b is resized
* appropriately. If self is the null substring, then the statement
* has no effect. Returns a reference to self.
*/
RWStandardCSubString& operator=(const std::string& str);
/**
* Assignment from a character string. Example:
*
* @code
* RWCString str("Mary had a lamb");
* char dat[] = "Perrier";
* str(11,4) = dat; // "Mary had a Perrier"
* @endcode
*
* The number of characters selected need not match; if they differ,
* \c str is resized appropriately. If self is the null substring,
* then the statement has no effect. Returns a reference to self.
*/
RWStandardCSubString& operator=(const char* str);
/**
* Returns the \a i <sup>th</sup> character of the substring. The
* index \a i must be between zero and the length of the substring
* less one. Bounds checking is enabled by defining the preprocessor
* macro \c RWBOUNDS_CHECK before including \c <rw/cstring.h>.
*
* @throw RWBoundsErr if RWBOUNDS_CHECK is defined and the index is out
* of range.
*/
char& operator()(size_t i);
/**
* Returns the \a i <sup>th</sup> character of the substring. The
* index \a i must be between zero and the length of the substring
* less one. Bounds checking is enabled by defining the preprocessor
* macro \c RWBOUNDS_CHECK before including \c <rw/cstring.h>.
*
* @throw RWBoundsErr if RWBOUNDS_CHECK is defined and the index is out
* of range.
*/
char operator()(size_t i) const;
// Here all integer types are provided with an exact match
// to avoid ambiguities with the built in char[] operator
// All operator[] functions are with bounds checking
/**
* Returns the \a i <sup>th</sup> character of the substring. The
* index \a i must be between zero and the length of the substring
* less one. \a i is converted to a \c size_t and bounds checking
* is performed.
*
* @throw RWBoundsErr if the index is out of range.
*/
char& operator[](char i);
/**
* @copydoc operator[](char)
*/
char operator[](char i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](signed char i);
/**
* @copydoc operator[](char)
*/
char operator[](signed char i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](short i);
/**
* @copydoc operator[](char)
*/
char operator[](short i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](int i);
/**
* @copydoc operator[](char)
*/
char operator[](int i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](long i);
/**
* @copydoc operator[](char)
*/
char operator[](long i) const;
#if !defined(RW_NO_LONG_LONG)
/**
* @copydoc operator[](char)
*/
char& operator[](long long i);
/**
* @copydoc operator[](char)
*/
char operator[](long long i) const;
#endif
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned char i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned char i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned short i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned short i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned int i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned int i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned long i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned long i) const;
#if !defined(RW_NO_LONG_LONG)
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned long long i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned long long i) const;
#endif
/**
* Returns \c true if \c this is a null substring.
*/
int operator!() const;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12, use startData() instead.
*/
RW_DEPRECATE_FUNC("Use startData() instead")
const char* data() const;
#endif
/**
* Returns \c true if \c this is a null substring.
*/
bool isNull() const;
/**
* Returns the extent (i.e., length) of the substring.
*/
size_t length() const;
/**
* Returns the index of the starting element of the substring.
*/
size_t start() const;
/**
* @internal
* Returns a pointer to the start of the substring.
*
* @note
* Unlike RWCString::data(), the <tt>const char*</tt> returned by
* this function is not null-terminated at its extent.
*/
const char* startData() const;
/**
* Changes all upper-case letters in self to lower-case. Uses the
* Standard C Library function \c tolower().
*/
void toLower();
/**
* Changes all lower-case letters in self to upper-case. Uses the
* Standard C Library function \c toupper().
*/
void toUpper();
protected:
/**
* @internal
* Verifies that the index \a i is within the bounds of the substring.
*
* @throw RWBoundsErr if the index is out of range.
*/
void assertElement(size_t i) const;
/**
* @internal
* Throws an RWBoundsErr exception indicating the position \a pos or
* extent \a len is outside the string length \a strLen.
*/
void subStringError(size_t strLen, size_t pos, size_t len) const;
private:
/**
* @internal
* Constructs a substring instance from the string \a str with starting
* position \a start and extent \a len.
*/
RWStandardCSubString(const RWStandardCString& str, size_t start, size_t len);
/**
* @internal
* Throws an exception indicating the position \a i is outside the
* substring extent \a len.
*
* @throw RWBoundsErr
*/
void throwBoundsErr(size_t i, size_t len) const;
RWStandardCString* str_;
size_t begin_;
size_t extent_;
friend class RWStandardCConstSubString;
friend class RWStandardCString;
};
/**
* @class RWCConstSubString rw/cstring.h
* @ingroup string_processing_classes
*
* @brief Allows some subsection of an RWCString
* to be addressed by defining a <i>starting position</i> and an
* \e extent
*
* The class RWCConstSubString allows some subsection of an RWCString
* to be addressed by defining a <i>starting position</i> and an
* \e extent. For example, the 7<sup>th</sup> through the 11<sup>th</sup>
* elements, inclusive, would have a starting position of 7 and an extent
* of 5. The specification of a starting position and extent is
* also done on your behalf by such functions as RWCString::strip().
* There are no public constructors other than one that creates
* an RWCConstSubString from an existing RWCSubString. In general,
* RWCConstSubStrings are constructed by various functions of the
* RWCString class and then destroyed immediately.
*
* A <i>zero length</i> substring is one with a defined starting
* position and an extent of zero. It can be thought of as starting
* just before the indicated character, but not including it. It
* can be used as an lvalue. A null substring is also legal and
* is frequently used to indicate that a requested substring, perhaps
* through a search, does not exist. A null substring can be detected
* with member function isNull(). However, it cannot be used
* as an lvalue.
*
* @section synopsis Synopsis
*
* @code
* #include <rw/cstring.h>
* const RWCString s("test string");
* s(6,3); // "tri"
* @endcode
*
* @section persistence Persistence
*
* None
*
* @section example Example
*
* @code
* #include <iostream>
* #include <rw/cstring.h>
*
* int main()
* {
* const RWCString s ("What I tell you is true.");
*
* std::cout << "Take the string: [" << s << "]\n";
*
* // Create a string from substrings:
* const RWCString s2 (s(0, 16) + "three times " + s(16, 8));
*
* std::cout << "After creating a string from substrings, you have: ["
* << s2 << "]" << std::endl;
*
* return 0;
* }
* @endcode
*
* Program output:
*
* @code
* Take the string: [What I tell you is true.]
* After creating a string from substrings, you have: [What I tell you three times is true.]
* @endcode
*
*/
class RW_TOOLS_SYMBOLIC RWStandardCConstSubString
{
public:
/**
* Copy constructor. The resulting substring references the same start
* and extent of the RWCString associated with \a str.
*
* @note
* The resulting substring instance should not be used if the
* RWCString associated with \a str is modified after the substring
* is instantiated.
*/
RWStandardCConstSubString(const RWStandardCConstSubString& str);
/**
* Constructs an RWCConstSubString from an existing RWCSubString. The
* resulting substring references the same start and extent of the
* RWCString associated with \a str.
*
* @note
* The resulting substring instance should not be used if the
* RWCString associated with \a str is modified after the substring
* is instantiated.
*/
RWStandardCConstSubString(const RWStandardCSubString& str);
/**
* Returns the \a i <sup>th</sup> character of the substring. The
* index \a i must be between zero and the length of the substring
* less one. Bounds checking is enabled by defining the preprocessor
* macro \c RWBOUNDS_CHECK before including \c <rw/cstring.h>.
*
* @throw RWBoundsErr if RWBOUNDS_CHECK is defined and the index is out
* of range.
*/
char operator()(size_t i) const;
/**
* @copydoc RWCSubString::operator[](char)const
*/
char operator[](char i) const;
/**
* @copydoc RWCSubString::operator[](signed char)const
*/
char operator[](signed char i) const;
/**
* @copydoc RWCSubString::operator[](short)const
*/
char operator[](short i) const;
/**
* @copydoc RWCSubString::operator[](int)const
*/
char operator[](int i) const;
/**
* @copydoc RWCSubString::operator[](long)const
*/
char operator[](long i) const;
#if !defined(RW_NO_LONG_LONG)
/**
* @copydoc RWCSubString::operator[](long long)const
*/
char operator[](long long i) const;
#endif
/**
* @copydoc RWCSubString::operator[](unsigned char)const
*/
char operator[](unsigned char i) const;
/**
* @copydoc RWCSubString::operator[](unsigned short)const
*/
char operator[](unsigned short i) const;
/**
* @copydoc RWCSubString::operator[](unsigned int)const
*/
char operator[](unsigned int i) const;
/**
* @copydoc RWCSubString::operator[](unsigned long)const
*/
char operator[](unsigned long i) const;
#if !defined(RW_NO_LONG_LONG)
/**
* @copydoc RWCSubString::operator[](unsigned long long)const
*/
char operator[](unsigned long long i) const;
#endif
/**
* @copydoc RWCSubString::operator!()const
*/
int operator!() const;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12, use startData() instead.
*/
RW_DEPRECATE_FUNC("Use startData() instead")
const char* data() const;
#endif
/**
* @copydoc RWCSubString::isNull()const
*/
bool isNull() const;
/**
* @copydoc RWCSubString::length()const
*/
size_t length() const;
/**
* Returns the index of the starting element of the substring.
*/
size_t start() const;
/**
* @internal
* Returns a pointer to the start of the substring.
*
* @note
* Unlike RWCString::data(), the returned <tt>const char*</tt>
* returned by this function is not null-terminated at its
* extent.
*/
const char* startData() const;
protected:
/**
* @internal
* Verifies that the index \a i is within the bounds of the substring.
*
* @throw RWBoundsErr if the index is out of range.
*/
void assertElement(size_t i) const;
/**
* @internal
* Throws an RWBoundsErr exception indicating the position \a pos or
* extent \a len is outside the string length \a strLen.
*/
void subStringError(size_t strLen, size_t pos, size_t len) const;
private:
/**
* @internal
* Constructs a substring instance from the string \a str with starting
* position \a start and extent \a len.
*/
RWStandardCConstSubString(const RWStandardCString& str, size_t start, size_t len);
/**
* @internal
* Throws an exception indicating the position \a i is outside the
* substring extent \a len.
*
* @throw RWBoundsErr
*/
void throwBoundsErr(size_t i, size_t len) const;
const RWStandardCString* str_; // Referenced string
size_t begin_; // Index of starting character
size_t extent_; // Length of RWStandardCConstSubString
friend class RWStandardCString;
friend class RWStandardCSubString;
};
/**
* @class RWCString rw/cstring.h
* @ingroup string_processing_classes
*
* @brief Offers powerful and convenient facilities for
* manipulating strings.
*
* Class RWCString offers powerful and convenient facilities for
* manipulating strings.
*
* @note
* RWCString is designed for use with single or multibyte character
* sequences. To manipulate wide character strings, use RWWString.
*
* Although the class is primarily intended to be used to handle
* single-byte character sets (SBCS; such as US-ASCII or ISO Latin-1),
* with care it can be used to handle multibyte character sets (MBCS).
* There are two things that must be kept in mind when working with
* MBCS:
*
* - Because characters can be more than one byte long, the number
* of bytes in a string can, in general, be greater than the number
* of characters in the string. Use function RWCString::length()
* to get the number of bytes in a string, and function
* RWCString::mbLength() to get the number of characters. Note that the
* latter is much slower because it must determine the number of bytes
* in every character. Hence, if the string is known to use a SBCS,
* then RWCString::length() is preferred.
* - One or more bytes of a multibyte character can be zero. Hence,
* MBCS cannot be counted on being null-terminated. In practice,
* it is a rare MBCS that uses embedded nulls. Nevertheless, you
* should be aware of this and program defensively. In any case,
* class RWCString can handle embedded nulls.
*
* Parameters of type <tt>const char*</tt> must not be passed a value
* of zero. This is detected in the debug version of the library.
*
* A separate class RWCSubString supports substring extraction and
* modification operations. RWCConstSubString supports substring
* extractions on \c const RWCString instances.
*
* @section synopsis Synopsis
*
* @code
* #include <rw/cstring.h>
* RWCString a;
* @endcode
*
* @section persistence Persistence
*
* Simple
*
* @section example Example
*
* @code
* #include <iostream>
* #include <rw/cstring.h>
*
* int main()
* {
* RWCString a("There is no joy in Beantown.");
*
* std::cout << "\"" << a << "\"" << " becomes ";
*
* a.subString("Beantown") = "Redmond";
*
* std::cout << "\"" << a << "\"" << std::endl;
*
* return 0;
* }
* @endcode
*
* Program output:
*
* @code
* "There is no joy in Beantown" becomes "There is no joy in Redmond."
* @endcode
*/
class RW_TOOLS_GLOBAL RWStandardCString
{
public:
/**
* The mutable substring class associated with RWCString.
*/
typedef RWStandardCSubString SubString;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12, use SubString instead.
*
* Retained for backward compatibility with SourcePro 11.1
*/
typedef RW_DEPRECATE_TYPE("Use RWStandardCString::SubString instead") SubString SubStringType;
#endif
/**
* The immutable substring class associated with RWCString.
*/
typedef RWStandardCConstSubString ConstSubString;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12, use ConstSubString instead.
*
* Retained for backward compatibility with SourcePro 11.1
*/
typedef RW_DEPRECATE_TYPE("Use RWStandardCString::ConstSubString instead") ConstSubString ConstSubStringType;
#endif
/**
* Specifies semantics used by comparisons, searches, and hashing
* functions
*/
enum caseCompare {
/**
* Use exact case sensitive semantics
*/
exact,
/**
* Ignore case sensitive semantics
*/
ignoreCase,
/**
* Case-insensitive for alpha characters only. #ignoreCaseStrict
* only differs from #ignoreCase in comparison operations,
* where changing case can affect the order of the strings.
*/
ignoreCaseStrict
};
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @deprecated As of SourcePro 12, provided for compatibility with code that
* relies on the enumeration RWStandardCString::scopeType.
*
* Specifies whether regular expression functions replace the first
* #one substring matched by the regular expression or replaces #all
* substrings matched by the regular expression.
*/
enum RW_DEPRECATE_TYPE("") scopeType {
/**
* replaces first substring matched.
*/
one,
/**
* replaces all substrings matched.
*/
all
};
#endif // RW_DISABLE_DEPRECATED
/**
* Specifies whether characters are stripped from the beginning
* of the string, the end, or both.
*/
enum stripType {
/**
* Remove characters at beginning
*/
leading = 0x1,
/**
* Remove characters at end
*/
trailing = 0x2,
/**
* Remove characters at both ends
*/
both = 0x3
};
enum CharType {
builtin
};
public:
/**
* Creates a string of length zero (the null string).
*/
RWStandardCString();
/**
* Copy constructor. The created string copies the data from \a str.
*/
RWStandardCString(const RWStandardCString& str);
#if !defined(RW_NO_RVALUE_REFERENCES)
/**
* Move constructor. The created string takes ownership of the
* data owned by \a str.
*
* @conditional
* This method is only available on platforms with rvalue reference support.
*/
RWStandardCString(RWStandardCString && str);
#endif // !RW_NO_RVALUE_REFERENCES
/**
* Converts from a substring. The created string copies
* the substring represented by \a str.
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString(const SubString& str);
/**
* Converts from a const substring. The created string copies
* the substring represented by \a str.
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString(const ConstSubString& str);
/**
* Constructs a string with data copied from \a str.
*/
#ifdef RW_DISABLE_IMPLICIT_CONVERSION
explicit
#endif
RWStandardCString(const std::string& str);
/**
* Converts from the null-terminated character string \a str. The
* created string copies the data pointed to by \a str,
* up to the first terminating null.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
#ifdef RW_DISABLE_IMPLICIT_CONVERSION
explicit
#endif
RWStandardCString(const char* str);
/**
* Constructs a string from the character string \a str. The created
* string copies the data pointed to by \a str. Exactly
* \a len bytes are copied, <i>including any embedded nulls</i>. Hence,
* the buffer pointed to by \a str must be at least \a len bytes long.
*/
RWStandardCString(const char* str, size_t len);
/**
* Constructs a string containing the single character \a c.
*/
#ifdef RW_DISABLE_IMPLICIT_CONVERSION
explicit
#endif
RWStandardCString(char c);
/**
* Constructs a string containing the single signed character \a c.
*/
#ifdef RW_DISABLE_IMPLICIT_CONVERSION
explicit
#endif
RWStandardCString(signed char c);
/**
* Constructs a string containing the single unsigned character \a c.
*/
#ifdef RW_DISABLE_IMPLICIT_CONVERSION
explicit
#endif
RWStandardCString(unsigned char c);
/**
* Constructs a string containing the character \a c repeated
* \a count times.
*/
RWStandardCString(char c, size_t count);
/**
* Creates a string of length zero (the null string). The string's
* \e capacity (that is, the size it can grow to without resizing)
* is given by the parameter \a cap. We recommend creating an RWSize_T
* value from a numerical constant to pass into this constructor.
* While RWSize_T knows how to convert \c size_t values to itself,
* conforming compilers choose the conversion to \c char instead.
*/
RWStandardCString(RWSize_T cap);
~RWStandardCString();
/**
* The equivalent of calling RWCString::data() on self.
*/
#ifndef RW_DISABLE_IMPLICIT_CONVERSION
operator const char* () const;
#endif
/**
* Assignment operator. The string copies the data from \a str.
* Returns a reference to self.
*/
RWStandardCString& operator=(const RWStandardCString& str);
#if !defined(RW_NO_RVALUE_REFERENCES)
/**
* Move assignment. Self takes ownership of the data owned by \a str.
*
* @conditional
* This method is only available on platforms with rvalue reference support.
*/
RWStandardCString& operator=(RWStandardCString && str);
#endif // !RW_NO_RVALUE_REFERENCES
/**
* @copydoc operator=(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& operator=(const SubString& str);
/**
* @copydoc operator=(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& operator=(const ConstSubString& str);
/**
* @copydoc operator=(const RWCString&)
*/
RWStandardCString& operator=(const std::string& str);
/**
* Assignment operator. Copies the null-terminated character string
* pointed to by \a str into self. Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with
* embedded nulls.
*/
RWStandardCString& operator=(const char* str);
/**
* Assignment operator. Copies the character \a c into self.
*/
RWStandardCString& operator=(char c);
/**
* Appends the string \a str to self. Returns a reference to self.
*/
RWStandardCString& operator+=(const RWStandardCString& str);
/**
* @copydoc operator+=(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& operator+=(const SubString& str);
/**
* @copydoc operator+=(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& operator+=(const ConstSubString& str);
/**
* @copydoc operator+=(const RWCString&)
*/
RWStandardCString& operator+=(const std::string& str);
/**
* Appends the null-terminated character string pointed to by \a
* str to self. Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with
* embedded nulls.
*/
RWStandardCString& operator+=(const char* str);
/**
* Appends the character \a c to self. Returns a reference to self.
*/
RWStandardCString& operator+=(char c);
/**
* Returns the \a i <sup>th</sup> byte in self. The index \a i must be
* between 0 and the length of the string less one. Bounds checking
* is performed if the preprocessor macro \c RWBOUNDS_CHECK has
* been defined before including \c <rw/cstring.h>.
*
* @throw RWBoundsErr if RWBOUNDS_CHECK is defined and the index is out
* of range.
*/
char& operator()(size_t i);
/**
* Returns the \a i <sup>th</sup> byte in self. The index \a i must be
* between 0 and the length of the string less one. Bounds checking
* is performed if the preprocessor macro \c RWBOUNDS_CHECK has
* been defined before including \c <rw/cstring.h>.
*
* @throw RWBoundsErr if RWBOUNDS_CHECK is defined and the index is out
* of range.
*/
char operator()(size_t i) const;
// Here all integer types are provided with an exact match
// to avoid ambiguities with the built in char[] operator
// All operator[] functions are with bounds checking
/**
* Returns the \a i <sup>th</sup> byte in self. The index \a i must be
* between 0 and the length of the string less one. \a i is converted
* to a \c size_t and bounds checking is performed.
*
* @throw RWBoundsErr if the index is out of range.
*/
char& operator[](char i);
/**
* @copydoc operator[](char)
*/
char operator[](char i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](signed char i);
/**
* @copydoc operator[](char)
*/
char operator[](signed char i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](short i);
/**
* @copydoc operator[](char)
*/
char operator[](short i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](int i);
/**
* @copydoc operator[](char)
*/
char operator[](int i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](long i);
/**
* @copydoc operator[](char)
*/
char operator[](long i) const;
#if !defined(RW_NO_LONG_LONG)
/**
* @copydoc operator[](char)
*/
char& operator[](long long i);
/**
* @copydoc operator[](char)
*/
char operator[](long long i) const;
#endif
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned char i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned char i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned short i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned short i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned int i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned int i) const;
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned long i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned long i) const;
#if !defined(RW_NO_LONG_LONG)
/**
* @copydoc operator[](char)
*/
char& operator[](unsigned long long i);
/**
* @copydoc operator[](char)
*/
char operator[](unsigned long long i) const;
#endif
/**
* Substring operator. Returns a substring of self with length
* \a len, starting at index \a start. The sum of \a start plus
* \a len must be less than or equal to the string length.
*
* @throws RWBoundsErr if the library was built using the
* \c RW_DEBUG flag, and \a start or \a len are out of range.
*/
SubString operator()(size_t start, size_t len);
/**
* Substring operator. Returns a substring of self with length
* \a len, starting at index \a start. The sum of \a start plus
* \a len must be less than or equal to the string length.
*
* @throws RWBoundsErr if the library was built using the
* \c RW_DEBUG flag, and \a start or \a len are out of range.
*/
ConstSubString operator()(size_t start, size_t len) const;
#if !defined(RW_DISABLE_DEPRECATED)
RW_SUPPRESS_DEPRECATED_WARNINGS
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
SubString operator()(const RWCRegexp& re);
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
ConstSubString operator()(const RWCRegexp& re) const;
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
SubString operator()(const RWCRegexp& re, size_t start);
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
ConstSubString operator()(const RWCRegexp& re, size_t start) const;
RW_RESTORE_DEPRECATED_WARNINGS
#endif
/**
* Appends a copy of the string \a str to self. Returns a reference
* to self.
*/
RWStandardCString& append(const RWStandardCString& str);
/**
* @copydoc append(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& append(const SubString& str);
/**
* @copydoc append(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& append(const ConstSubString& str);
/**
* Appends the first \a len bytes of \a str to self. If \a len is
* greater than the length of \a str, the entire string is appended.
* Returns a reference to self.
*/
RWStandardCString& append(const RWStandardCString& str, size_t len);
/**
* @copydoc append(const RWCString&)
*/
RWStandardCString& append(const std::string& str);
/**
* @copydoc append(const RWCString&,size_t)
*/
RWStandardCString& append(const std::string& str, size_t len);
/**
* Appends a copy of the null-terminated character string pointed
* to by \a str to self. Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
RWStandardCString& append(const char* str);
/**
* Appends a copy of the character string \a str to self. Exactly
* \a len bytes are copied, <i>including any embedded nulls</i>. Hence,
* the buffer pointed to by \a str must be at least \a len bytes long.
* Returns a reference to self.
*/
RWStandardCString& append(const char* str, size_t len);
/**
* Appends \a count copies of the character \a c to self. Returns a
* reference to self.
*/
RWStandardCString& append(char c, size_t count = 1);
/**
* Assigns a copy of the string \a str to self, replacing existing
* content. Returns a reference to self.
*/
RWStandardCString& assign(const RWStandardCString& str);
/**
* @copydoc assign(const RWCString&)
*/
RWStandardCString& assign(const std::string& str);
/**
* @copydoc assign(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& assign(const SubString& str);
/**
* @copydoc assign(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& assign(const ConstSubString& str);
/**
* Assigns the null-terminated string pointed to by \a str to self,
* replacing existing content. Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
RWStandardCString& assign(const char* str);
/**
* Assigns a copy of the character string \a str to self, replacing
* existing content. Exactly \a len bytes are copied, <i>including
* any embedded nulls</i>. Hence, the buffer pointed to by \a str must
* be at least \a len bytes long. Returns a reference to self.
*/
RWStandardCString& assign(const char* str, size_t len);
/**
* Assigns \a count copies of the character \a c to self, replacing
* existing content. Returns a reference to self.
*/
RWStandardCString& assign(char c, size_t count = 1);
/**
* Returns the number of bytes necessary to store the object using
* the global functions:
*
* @code
* RWFile& operator<<(RWFile&, const RWCString&);
* RWvostream& operator<<(RWvostream&, const RWCString&);
* @endcode
*/
RWspace binaryStoreSize() const;
/**
* Given a multibyte sequence, \a str, and a number of multibyte
* characters to consider, \a nChars, this method calculates the
* number of bytes required to store the sequence. If \a nChars
* is #RW_NPOS, then the method counts characters up to, but not
* including, the first \c NULL character in the sequence. The method
* returns the number of bytes required to represent the string.
* If an error occurs during the operation, #RW_NPOS is returned.
*/
static size_t byteCount(const char* str, size_t nChars = RW_NPOS);
/**
* Returns the current capacity of self. This is the number of bytes
* the string can hold without resizing.
*/
size_t capacity() const;
/**
* A non-binding request to alter the capacity of self to \c cap.
* The capacity is never reduced below the current number of bytes.
* Returns the actual capacity.
*/
size_t capacity(size_t cap);
/**
* Returns an \c int less than, greater than, or equal to zero,
* according to the result of calling the Standard C Library function
* \c strcoll() on self and the argument \a str. This supports
* locale-dependent collation.
*
* @note
* This function is incompatible with strings with embedded nulls.
*/
int collate(const RWStandardCString& str) const;
/**
* @copydoc collate(const RWCString&)const
*/
int collate(const std::string& str) const;
/**
* @copydoc collate(const RWCString&)const
*/
int collate(const char* str) const;
/**
* Lexicographically compares self to \a str. Returns the following values
* based on the results of the comparison:
*
* <table>
* <tr><td align="right"><0</td><td>self precedes \a str.</td></tr>
* <tr><td align="right">0</td><td>self is equal to \a str.</td></tr>
* <tr><td align="right">>0</td><td>self follows \a str.</td></tr>
* </table>
*
* If \a cmp is either RWCString::ignoreCase or
* RWCString::ignoreCaseStrict, the strings are normalized before they are
* compared.
*
* @note
* If \a cmp is not RWCString::exact, this function is incompatible with
* MBCS strings.
*/
int compareTo(const RWStandardCString& str, caseCompare cmp = exact) const;
/**
* @copydoc compareTo(const RWCString&,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
int compareTo(const SubString& str, caseCompare cmp = exact) const;
/**
* @copydoc compareTo(const RWCString&,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
int compareTo(const ConstSubString& str, caseCompare cmp = exact) const;
/**
* This function is the equivalent of calling:
*
* @code
* RWCString::compareTo(*str, cmp);
* @endcode
*/
int compareTo(const RWStandardCString* str, caseCompare cmp = exact) const;
/**
* @copydoc compareTo(const RWCString&,caseCompare)const
*/
int compareTo(const std::string& str, caseCompare cmp = exact) const;
/**
* @copydoc compareTo(const RWCString*,caseCompare)const
*/
int compareTo(const std::string* str, caseCompare cmp = exact) const;
/**
* @copydoc compareTo(const RWCString&,caseCompare)const
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
int compareTo(const char* str, caseCompare cmp = exact) const;
/**
* Lexicographically compares self to \a str. Returns the following values
* based on the results of the comparison:
*
* <table>
* <tr><td align="right"><0</td><td>self precedes \a str.</td></tr>
* <tr><td align="right">0</td><td>self is equal to \a str.</td></tr>
* <tr><td align="right">>0</td><td>self follows \a str.</td></tr>
* </table>
*
* If \a cmp is either RWCString::ignoreCase or
* RWCString::ignoreCaseStrict, the strings are normalized before they are
* compared.
*
* @note
* If \a cmp is not RWCString::exact, this function is incompatible with
* MBCS strings.
*/
int compareTo(const char* str, size_t len, caseCompare cmp = exact) const;
/**
* Returns \c false if RWCString::index(\a str, \a cmp) returns
* #RW_NPOS, otherwise returns \c true.
*/
bool contains(const RWStandardCString& str, caseCompare cmp = exact) const;
/**
* @copydoc contains(const RWCString&,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
bool contains(const SubString& str, caseCompare cmp = exact) const;
/**
* @copydoc contains(const RWCString&,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
bool contains(const ConstSubString& str, caseCompare cmp = exact) const;
/**
* @copydoc contains(const RWCString&,caseCompare)const
*/
bool contains(const std::string& str, caseCompare cmp = exact) const;
/**
* @copydoc contains(const RWCString&,caseCompare)const
*/
bool contains(const char* str, caseCompare cmp = exact) const;
/**
* Returns \c false if RWCString::index(\a str, \a len, \a cmp) returns
* #RW_NPOS, otherwise returns \c true.
*/
bool contains(const char* str, size_t len, caseCompare cmp = exact) const;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12, use operator=(const RWStandardCString&)
* and modify the copy instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::operator= instead")
RWStandardCString copy() const;
#endif
/**
* Provides access to the RWCString instances's data as a null-terminated
* string. This datum is owned by the RWCString and may not be deleted or
* changed. If the RWCString object itself changes or goes out of scope,
* the pointer value previously returned becomes invalid. While
* the string is null-terminated, its \e length is still given by the member
* function length(). That is, it may contain embedded nulls.
*/
const char* data() const;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @deprecated As of SourcePro 12, use RWCString::firstOf(char, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWCStandardCString::firstOf(...) instead")
size_t first(char c) const;
/**
* @deprecated As of SourcePro 12, use RWCString::firstOf(char, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWCStandardCString::firstOf(...) instead")
size_t first(char c, size_t) const;
/**
* @deprecated As of SourcePro 12, use RWCString::firstOf(const char*, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWCStandardCString::firstOf(...) instead")
size_t first(const char* str) const;
/**
* @deprecated As of SourcePro 12, use RWCString::firstOf(const char*, size_t, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWCStandardCString::firstOf(...) instead")
size_t first(const char* str, size_t len) const;
#endif
/**
* Returns the index of the first occurrence of a character in self
* that is not \a c, starting at position \a pos. Returns #RW_NPOS
* if there is no match.
*/
size_t firstNotOf(char c, size_t pos = 0) const;
/**
* Returns the index of the first occurrence in self, starting at
* position \a pos, of any character not in the null-terminated string
* \a str. Returns #RW_NPOS if there is no match.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
size_t firstNotOf(const char* str, size_t pos = 0) const;
/**
* Returns the index of the first occurrence in self, starting at
* position \a pos, of any character not in the first \a len bytes of
* \a str. Returns #RW_NPOS if there is no match.
*/
size_t firstNotOf(const char* str, size_t pos, size_t len) const;
/**
* Returns the index of the first occurrence in self, starting at position
* \a pos, of any character not in \a str. Returns #RW_NPOS if there is
* no match.
*/
size_t firstNotOf(const RWStandardCString& str, size_t pos = 0) const;
/**
* @copydoc firstNotOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t firstNotOf(const SubString& str, size_t pos = 0) const;
/**
* @copydoc firstNotOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t firstNotOf(const ConstSubString& str, size_t pos = 0) const;
/**
* @copydoc firstNotOf(const RWCString&, size_t) const
*/
size_t firstNotOf(const std::string& str, size_t pos = 0) const;
/**
* Returns the index of the first occurrence of the character \a c
* in self, starting at position \a pos. Returns #RW_NPOS if there is
* no match.
*/
size_t firstOf(char c, size_t pos = 0) const;
/**
* Returns the index of the first occurrence in self, starting at
* position \a pos, of any character in the null-terminated string
* \a str. Returns #RW_NPOS if there is no match.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
size_t firstOf(const char* str, size_t pos = 0) const;
/**
* Returns the index of the first occurrence in self, starting at
* position \a pos, of any character in the first \a len bytes of
* \a str. Returns #RW_NPOS if there is no match.
*/
size_t firstOf(const char* str, size_t pos, size_t len) const;
/**
* Returns the index of the first occurrence in self, starting at position
* \a pos, of any character in \a str. Returns #RW_NPOS if there is no
* match.
*/
size_t firstOf(const RWStandardCString& str, size_t pos = 0) const;
/**
* @copydoc firstOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t firstOf(const SubString& str, size_t pos = 0) const;
/**
* @copydoc firstOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t firstOf(const ConstSubString& str, size_t pos = 0) const;
/**
* @copydoc firstOf(const RWCString&, size_t) const
*/
size_t firstOf(const std::string& str, size_t pos = 0) const;
/**
* Returns the hash value of \a str as returned by
* hash(caseCompare) const, where #caseCompare is RWCString::exact.
*/
static unsigned
hash(const RWStandardCString& str);
/**
* Returns a suitable hash value.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
unsigned hash(caseCompare cmp = exact) const;
/**
* Pattern matching. Starting with index \a start, searches for the
* first occurrence of \a pat in self and returns the index of the
* start of the match. Returns #RW_NPOS if there is no such pattern.
* Case sensitivity is according to \a cmp.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t index(const RWStandardCString& pat, size_t start = 0 , caseCompare cmp = exact) const;
/**
* @copydoc index(const RWCString&,size_t,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t index(const SubString& pat, size_t start = 0, caseCompare cmp = exact) const;
/**
* @copydoc index(const RWCString&,size_t,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t index(const ConstSubString& pat, size_t start = 0, caseCompare cmp = exact) const;
/**
* Pattern matching. Starting with index \a start, searches for the
* first occurrence of the first \a patlen bytes from \a pat in
* self and returns the index of the start of the match. Returns
* #RW_NPOS if there is no such pattern. Case sensitivity is according
* to \a cmp.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t index(const RWStandardCString& pat, size_t patlen, size_t start, caseCompare cmp) const;
/**
* @copydoc index(const RWCString&,size_t,caseCompare)const
*/
size_t index(const std::string& pat, size_t start = 0, caseCompare cmp = exact) const;
/**
* @copydoc index(const RWCString&,size_t,size_t,caseCompare)const
*/
size_t index(const std::string& pat, size_t patlen, size_t start, caseCompare cmp) const;
/**
* Pattern matching. Starting with index \a start, searches for the
* first occurrence of the null-terminated string \a pat in self and
* returns the index of the start of the match. Returns #RW_NPOS if
* there is no such pattern. Case sensitivity is according to \a cmp.
*
* @note
* This function is incompatible with \a pat strings with embedded nulls.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t index(const char* pat, size_t start = 0 , caseCompare cmp = exact) const;
/**
* @copydoc index(const RWCString&,size_t,size_t,caseCompare)const
*/
size_t index(const char* pat, size_t patlen, size_t start, caseCompare cmp) const;
/**
* @copydoc index(const RWCString&,size_t,caseCompare)const
*/
size_t index(const char pat, size_t start = 0 , caseCompare cmp = exact) const;
#if !defined(RW_DISABLE_DEPRECATED)
RW_SUPPRESS_DEPRECATED_WARNINGS
/**
* @deprecated As of SourcePro 12, use RWTRegex::index instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::index instead")
size_t index(const RWCRegexp& re, size_t start = 0) const;
/**
* @deprecated As of SourcePro 12, use RWTRegex::index instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::index instead")
size_t index(const RWCRegexp& re, size_t* ext, size_t start = 0) const;
/**
* @deprecated As of SourcePro 12, use RWTRegex::index instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::index instead")
size_t index(const RWCRExpr& re, size_t start = 0) const;
/**
* @deprecated As of SourcePro 12, use RWTRegex::index instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::index instead")
size_t index(const RWCRExpr& re, size_t* ext, size_t start = 0) const;
/**
* @deprecated As of SourcePro 12, use RWTRegex::index instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::index instead")
size_t index(const char* re, size_t* ext, size_t start = 0) const;
RW_RESTORE_DEPRECATED_WARNINGS
#endif // RW_DISABLE_DEPRECATED
/**
* Inserts a copy of the string \a str into self at index
* \a pos. Returns a reference to self.
*/
RWStandardCString& insert(size_t pos, const RWStandardCString& str);
/**
* @copydoc insert(size_t,const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& insert(size_t pos, const SubString& str);
/**
* @copydoc insert(size_t,const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& insert(size_t pos, const ConstSubString& str);
/**
* Inserts the first \a len bytes of \a str into self at index \a pos.
* If \a len is greater than the length of \a str, the entire string
* is inserted. Returns a reference to self.
*/
RWStandardCString& insert(size_t pos, const RWStandardCString& str , size_t len);
/**
* @copydoc insert(size_t,const RWCString&)
*/
RWStandardCString& insert(size_t pos, const std::string& str);
/**
* @copydoc insert(size_t,const RWCString&,size_t)
*/
RWStandardCString& insert(size_t pos, const std::string& str, size_t len);
/**
* Inserts a copy of the null-terminated string \a str into self at
* index \a pos. Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
RWStandardCString& insert(size_t pos, const char* str);
/**
* Inserts a copy of the first \a len bytes of \a str into self at byte
* position \a pos. Returns a reference to self.
*/
RWStandardCString& insert(size_t pos, const char* str , size_t len);
/**
* Inserts \a count instances of the character \a c into self at byte
* position \a pos. Returns a reference to self.
*/
RWStandardCString& insert(size_t pos, char c, size_t count);
/**
* Returns \c true if all bytes in self are between [0, 127].
*/
bool isAscii() const;
/**
* Returns \c true if \c this is a zero length string (i.e., the null
* string).
*/
bool isNull() const;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @deprecated As of SourcePro 12, use RWCString::lastOf(char, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::lastOf(...) instead")
size_t last(char c) const;
/**
* @deprecated As of SourcePro 12, use RWCString::lastOf(char, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::lastOf(...) instead")
size_t last(char c, size_t) const;
/**
* @deprecated As of SourcePro 12, use RWCString::lastOf(const char*, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::lastOf(...) instead")
size_t last(const char* str) const;
/**
* @deprecated As of SourcePro 12, use RWCString::lastOf(const char*, size_t, size_t) const instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::lastOf(...) instead")
size_t last(const char* str, size_t len) const;
#endif
/**
* Returns the index of the last occurrence of a character in self
* that is not \a c, ending at position \a pos. Returns #RW_NPOS
* if there is no match.
*/
size_t lastNotOf(char c, size_t pos = RW_NPOS) const;
/**
* Returns the index of the last occurrence in self, ending at
* position \a pos, of any character not in the null-terminated string
* \a str. Returns #RW_NPOS if there is no match.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
size_t lastNotOf(const char* str, size_t pos = RW_NPOS) const;
/**
* Returns the index of the last occurrence in self, ending at
* position \a pos, of any character not in the last \a len bytes of
* \a str. Returns #RW_NPOS if there is no match.
*/
size_t lastNotOf(const char* str, size_t pos, size_t len) const;
/**
* Returns the index of the last occurrence in self, ending at position
* \a pos, of any character not in \a str. Returns #RW_NPOS if there is
* no match.
*/
size_t lastNotOf(const RWStandardCString& str, size_t pos = RW_NPOS) const;
/**
* @copydoc lastNotOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t lastNotOf(const SubString& str, size_t pos = RW_NPOS) const;
/**
* @copydoc lastNotOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t lastNotOf(const ConstSubString& str, size_t pos = RW_NPOS) const;
/**
* @copydoc lastNotOf(const RWCString&, size_t) const
*/
size_t lastNotOf(const std::string& str, size_t pos = RW_NPOS) const;
/**
* Returns the index of the last occurrence of the character \a c
* in self, ending at position \a pos. Returns #RW_NPOS if there is
* no match.
*/
size_t lastOf(char c, size_t pos = RW_NPOS) const;
/**
* Returns the index of the last occurrence in self, ending at
* position \a pos, of any character in the null-terminated string
* \a str. Returns #RW_NPOS if there is no match.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
size_t lastOf(const char* str, size_t pos = RW_NPOS) const;
/**
* Returns the index of the last occurrence in self, ending at
* position \a pos, of any character in the last \a len bytes of
* \a str. Returns #RW_NPOS if there is no match.
*/
size_t lastOf(const char* str, size_t pos, size_t len) const;
/**
* Returns the index of the last occurrence in self, ending at position
* \a pos, of any character in \a str. Returns #RW_NPOS if there is
* no match.
*/
size_t lastOf(const RWStandardCString& str, size_t pos = RW_NPOS) const;
/**
* @copydoc lastOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t lastOf(const SubString& str, size_t pos = RW_NPOS) const;
/**
* @copydoc lastOf(const RWCString&, size_t) const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t lastOf(const ConstSubString& str, size_t pos = RW_NPOS) const;
/**
* @copydoc lastOf(const RWCString&, size_t) const
*/
size_t lastOf(const std::string& str, size_t pos = RW_NPOS) const;
/**
* Returns the number of bytes in self.
*
* @note
* If self contains any multibyte characters, RWCString::mbLength()
* should be used to determine the number of characters in self.
*/
size_t length() const;
#if !defined(RW_DISABLE_DEPRECATED)
RW_SUPPRESS_DEPRECATED_WARNINGS
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
SubString match(const RWCRExpr& re);
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
ConstSubString match(const RWCRExpr&) const;
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
SubString match(const RWCRExpr& re, size_t start);
/**
* @deprecated As of SourcePro 12, use RWTRegex::search instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::search instead")
ConstSubString match(const RWCRExpr& re, size_t start) const;
RW_RESTORE_DEPRECATED_WARNINGS
#endif // RW_DISABLE_DEPRECATED
/**
* Returns the number of multibyte characters in self, according
* to the Standard C function \b mblen(). Returns #RW_NPOS if a
* bad character is encountered. If self does not contain any
* multibyte characters, then mbLength() == length().
*/
size_t mbLength() const;
/**
* Given a multibyte character sequence, \a str, and a number of
* bytes to consider, \a nBytes, this method calculates the number
* of multibyte characters in the sequence. If \a nBytes is #RW_NPOS,
* then the method counts the characters up to, but not including,
* the first occurrence of a \c NULL character. The method returns
* the length, in characters, of the input multibyte sequence if
* successful. If an error occurs in the conversion, then #RW_NPOS
* is returned.
*/
static size_t mbLength(const char* str, size_t nBytes = RW_NPOS);
/**
* Prepends a copy of the string \a str to self. Returns a reference
* to self.
*/
RWStandardCString& prepend(const RWStandardCString& str);
/**
* @copydoc prepend(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& prepend(const SubString& str);
/**
* @copydoc prepend(const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& prepend(const ConstSubString& str);
/**
* Prepends the first \a len bytes of \a str to self. If \a len is
* greater than the length of \a str, the entire string is prepended.
* Returns a reference to self.
*/
RWStandardCString& prepend(const RWStandardCString& str , size_t len);
/**
* @copydoc prepend(const RWCString&)
*/
RWStandardCString& prepend(const std::string& str);
/**
* @copydoc prepend(const RWCString&,size_t)
*/
RWStandardCString& prepend(const std::string& str, size_t len);
/**
* Prepends a copy of the null-terminated character string pointed
* to by \a str to self. Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*/
RWStandardCString& prepend(const char* str);
/**
* Prepends a copy of the character string \a str to self. Exactly
* \a len bytes are copied, <i>including any embedded nulls</i>. Hence,
* the buffer pointed to by \a str must be at least \a len bytes long.
* Returns a reference to self.
*/
RWStandardCString& prepend(const char* str , size_t len);
/**
* Prepends \a count copies of character \a c to self. Returns a reference
* to self.
*/
RWStandardCString& prepend(char c, size_t count = 1);
/**
* Reads bytes from the input stream \a strm, replacing the previous
* contents of self, until \c EOF is reached. Null characters are
* treated the same as other characters.
*/
std::istream& readFile(std::istream& strm);
/**
* Reads bytes from the input stream \a strm, replacing the previous
* contents of self, until a newline (or \c EOF) is encountered.
* The newline is removed from the input stream but is not stored.
* Null characters are treated the same as other characters. If
* the \a skipWhite argument is \c true, then leading white space is
* skipped (using the iostream library manipulator \c ws).
*/
std::istream& readLine(std::istream& strm, bool skipWhite = true);
/**
* Reads bytes from the input stream \a strm, replacing the previous
* contents of self, until a null terminator (or \c EOF) is encountered.
*/
std::istream& readString(std::istream& strm);
/**
* Reads bytes from the input stream \a strm, replacing the previous
* contents of self, until the delimiting character \a delim (or \c EOF)
* is encountered. The delimiter is removed from the input
* stream but is not stored.
*/
std::istream& readToDelim(std::istream& strm, char delim = '\n');
/**
* White space is skipped before reading from \a strm. Bytes are
* then read from the input stream \a strm, replacing previous contents
* of self, until trailing white space or \c EOF is encountered.
* The white space is left on the input stream. Null characters
* are treated the same as other characters. White space is identified
* by the Standard C Library function \c isspace().
*
* @note
* This function is incompatible with streams containing MBCS.
*/
std::istream& readToken(std::istream& strm);
/**
* Removes the bytes from index \a pos, which must be
* no greater than length(), to the end of string. Returns a reference
* to self.
*/
RWStandardCString& remove(size_t pos);
/**
* Removes \a len bytes or to the end of string (whichever comes first)
* starting at index \a pos, which must be no greater
* than length(). Returns a reference to self.
*/
RWStandardCString& remove(size_t pos, size_t len);
/**
* Replaces the substring beginning at \a pos and of length \a len
* with the string \a str. If the sum of \a pos and \a len is greater
* than the length of self, the substring replaced is from \a pos to
* end of string.
*
* Returns a reference to self.
*
* @throws RWBoundsErr If \a pos is greater than the length of self.
*/
RWStandardCString& replace(size_t pos, size_t len, const RWStandardCString& str);
/**
* @copydoc replace(size_t,size_t,const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& replace(size_t pos, size_t len, const SubString& str);
/**
* @copydoc replace(size_t,size_t,const RWCString&)
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
RWStandardCString& replace(size_t pos, size_t len, const ConstSubString& str);
/**
* Replaces the substring beginning at \a pos and of length \a len
* with the first \a strLen bytes of string \a str. If the sum of \a pos
* and \a len is greater than the length of self, the substring replaced
* is from \a pos to end of string. If \a strLen is greater than the
* length of \a str, all of \a str is used.
*
* Returns a reference to self.
*
* @throws RWBoundsErr If \a pos is greater than the length of self.
*/
RWStandardCString& replace(size_t pos, size_t len, const RWStandardCString& str, size_t strLen);
/**
* @copydoc replace(size_t,size_t,const RWCString&)
*/
RWStandardCString& replace(size_t pos, size_t len, const std::string& str);
/**
* @copydoc replace(size_t,size_t,const RWCString&,size_t)
*/
RWStandardCString& replace(size_t pos, size_t len, const std::string& str, size_t strLen);
/**
* Replaces the substring beginning at \a pos and of length \a len
* with the null-terminated string \a str. If the sum of \a pos and
* \a len is greater than the length of self, the substring replaced is
* from \a pos to end of string.
*
* Returns a reference to self.
*
* @note
* This function is incompatible with \a str strings with embedded nulls.
*
* @throws RWBoundsErr If \a pos is greater than the length of self.
*/
RWStandardCString& replace(size_t pos, size_t len, const char* str);
/**
* Replaces the substring beginning at \a pos and of length \a len
* with \a strLen bytes from \a str. If the sum of \a pos and \a len is
* greater than the length of self, the substring replaced is from \a pos
* to end of string.
*
* Returns a reference to self.
*
* @throws RWBoundsErr If \a pos is greater than the length of self.
*/
RWStandardCString& replace(size_t pos, size_t len, const char* str, size_t strLen);
#if !defined(RW_DISABLE_DEPRECATED)
RW_SUPPRESS_DEPRECATED_WARNINGS
/**
* @deprecated As of SourcePro 12, use RWTRegex::replace instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::replace instead")
RWStandardCString& replace(const RWCRExpr& re,
const RWStandardCString& str, scopeType scope = one);
/**
* @deprecated As of SourcePro 12, use RWTRegex::replace instead.
*/
RW_DEPRECATE_FUNC("Use RWTRegex::replace instead")
RWStandardCString& replace(const RWCRExpr& re,
const char* str, scopeType scope = one);
RW_RESTORE_DEPRECATED_WARNINGS
#endif // RW_DISABLE_DEPRECATED
/**
* Changes the length of self to \a len bytes, adding blanks
* (i.e., <tt>' '</tt>) or truncating as necessary.
*/
void resize(size_t len);
/**
* @internal
* Restores an instance of RWCString from \a fil into which an instance had
* been persisted using saveOn(RWFile&).
*/
void restoreFrom(RWFile& fil);
/**
* @internal
* Restores an instance of RWCString from \a vis into which an instance had
* been persisted using saveOn(RWvostream&).
*/
void restoreFrom(RWvistream& vis);
/**
* Pattern matching. Searches for the last occurrence of \a pat in self
* that occurs before index \a end and returns the index of the
* start of the match. Returns #RW_NPOS if there is no such pattern.
* Case sensitivity is according to \a cmp.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t rindex(const RWStandardCString& pat, size_t end = RW_NPOS, caseCompare cmp = exact) const;
/**
* @copydoc rindex(const RWCString&,size_t,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t rindex(const SubString& pat,
size_t end = RW_NPOS, caseCompare cmp = exact) const;
/**
* @copydoc rindex(const RWCString&,size_t,caseCompare)const
*
* @note
* Behavior is undefined if \a str is a null substring.
*/
size_t rindex(const ConstSubString& pat,
size_t end = RW_NPOS, caseCompare cmp = exact) const;
/**
* Pattern matching. Searches for the last occurrence of the first
* \a patlen bytes from \a pat in self that occurs before index \a end
* and returns the index of the start of the match. Returns #RW_NPOS
* if there is no such pattern. Case sensitivity is according to \a cmp.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t rindex(const RWStandardCString& pat, size_t patlen, size_t end, caseCompare cmp) const;
/**
* @copydoc rindex(const RWCString&,size_t,caseCompare)const
*/
size_t rindex(const std::string& pat,
size_t end = RW_NPOS, caseCompare cmp = exact) const;
/**
* @copydoc rindex(const RWCString&,size_t,size_t,caseCompare)const
*/
size_t rindex(const std::string& pat, size_t patlen, size_t end, caseCompare cmp) const;
/**
* Pattern matching. Searches for the last occurrence of the
* null-terminated string \a pat in self and returns the index of the
* start of the match. Returns #RW_NPOS if there is no such pattern.
* Case sensitivity is according to \a cmp.
*
* @note
* This function is incompatible with \a pat strings with embedded nulls.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t rindex(const char* pat, caseCompare cmp) const;
/**
* Pattern matching. Searches for the last occurrence of the
* null-terminated string \a pat in self that occurs before index \a end
* and returns the index of the start of the match. Returns #RW_NPOS if
* there is no such pattern. Case sensitivity is according to \a cmp.
*
* @note
* This function is incompatible with \a pat strings with embedded nulls.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
size_t rindex(const char* pat, size_t end = RW_NPOS, caseCompare cmp = exact) const;
/**
* @copydoc rindex(const RWCString&,size_t,size_t,caseCompare)const
*/
size_t rindex(const char* pat, size_t patlen, size_t end, caseCompare cmp) const;
/**
* @copydoc rindex(const RWCString&,size_t,caseCompare)const
*/
size_t rindex(const char pat, size_t end = RW_NPOS, caseCompare cmp = exact) const;
/**
* @internal
* Saves an instance of RWCString to \a fil. The instance can be restored
* using the member function restoreFrom(RWFile&).
*/
void saveOn(RWFile& fil) const;
/**
* @internal
* Saves an instance of RWCString to \a vos. The instance can be restored
* using the member function restoreFrom(RWvistream&).
*/
void saveOn(RWvostream& vos) const;
/**
* Attempts to minimize the memory used by self by reducing the capacity
* to the minimum required to support the current string length. This
* operation is non-binding, and may be ignored by the implementation.
*/
void shrink();
/**
* Returns the underlying \b std::string representation of self.
*
* @note
* - This member function is unavailable on RWCString if
* \c RW_COPY_ON_WRITE_STRING is defined.
* - This member function is unavailable on RWCopyOnWriteCString
*/
std::string& std();
/**
* Returns the underlying \b std::string representation of self.
*
* @note
* - This member function is unavailable on RWCString if
* \c RW_COPY_ON_WRITE_STRING is defined.
* - This member function is unavailable on RWCopyOnWriteCString
*/
const std::string& std() const;
/**
* Swaps the contents of \a str with self.
*/
void swap(RWStandardCString& str);
/**
* Starting at \a start, returns a substring representing the first
* occurrence of the null-terminated string \a pat in self. If \a pat
* is not found, a null substring instance is returned.
*
* @note
* This function is incompatible with \a pat strings with embedded nulls.
*
* @note
* If \a cmp is not RWCString::exact this function is incompatible
* with MBCS strings.
*/
SubString subString(const char* pat, size_t start = 0, caseCompare cmp = exact);
/**
* @copydoc subString(const char*,size_t,caseCompare)
*/
ConstSubString subString(const char* pat, size_t start = 0, caseCompare cmp = exact) const;
/**
* Returns a substring of self where the character \a c has been
* stripped off the beginning, end, or both ends of the string,
* depending on \a st.
*/
SubString strip(stripType st = trailing, char c = ' ');
/**
* @copydoc strip(stripType,char)
*/
ConstSubString strip(stripType st = trailing, char c = ' ') const;
/**
* Changes all upper-case letters in self to lower-case, using the
* Standard C Library facilities declared in \c <ctype.h>.
*
* @note
* This function is incompatible with MBCS strings.
*/
void toLower();
/**
* Changes all lower-case letters in self to upper-case, using the
* Standard C Library facilities declared in \c <ctype.h>.
*
* @note
* This function is incompatible with MBCS strings.
*/
void toUpper();
protected:
/**
* @internal
* Verifies that the index \a i is within the bounds of the substring.
*
* @throw RWBoundsErr if the index is out of range.
*/
void assertElement(size_t i) const;
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12.
* This function is no longer used.
*/
RW_DEPRECATE_FUNC("")
int compareToSpecial(const char*, size_t, caseCompare) const;
/**
* @internal
* @deprecated As of SourcePro 12.
* This function is no longer used.
*/
RW_DEPRECATE_FUNC("")
size_t indexIgnoreCase(const char* pat, size_t patlen, size_t i) const;
/**
* @internal
* @deprecated As of SourcePro 12.
* This function is no longer used.
*/
RW_DEPRECATE_FUNC("")
size_t indexSpecial(const char*, size_t, size_t, caseCompare) const;
/**
* @internal
* @deprecated As of SourcePro 12.
* This function is no longer used.
*/
RW_DEPRECATE_FUNC("")
size_t rindexIgnoreCase(const char* pat, size_t patlen, size_t i) const;
/**
* @internal
* @deprecated As of SourcePro 12.
* This function is no longer used.
*/
RW_DEPRECATE_FUNC("")
size_t rindexSpecial(const char*, size_t, size_t, caseCompare) const;
#endif
/**
* @internal
* Changes all upper-case in the substring beginning at \a pos with
* length \a len in self to lower-case, using the Standard C Library
* facilities declared in \c <ctype.h>.
*
* @note
* This function is incompatible with MBCS strings.
*/
void toLower(size_t pos, size_t len);
/**
* @internal
* Changes all lower-case in the substring beginning at \a pos with
* length \a len in self to upper-case, using the Standard C Library
* facilities declared in \c <ctype.h>.
*
* @note
* This function is incompatible with MBCS strings.
*/
void toUpper(size_t pos, size_t len);
friend class RWStandardCConstSubString;
friend class RWStandardCSubString;
friend class RWCTokenizer;
protected:
std::string data_;
private:
/**
* @internal
* Throws an exception indicating the position \a i is outside the
* substring extent \a len.
*
* @throw RWBoundsErr
*/
void throwBoundsErr(size_t i, size_t len) const;
};
/**
* @relates RWCString
* Returns the result of applying \c strxfrm() to \a str
* to allow quicker collation than RWCString::collate(). Provided
* only on platforms that provide \c strxfrm().
*
* @note
* This function is incompatible with \a str strings with
* embedded nulls.
*/
RW_TOOLS_SYMBOLIC RWStandardCString
strXForm(const RWStandardCString& str);
#if !defined(RW_DISABLE_DEPRECATED)
RW_SUPPRESS_DEPRECATED_WARNINGS
/**
* @relates RWCString
* @deprecated As of SourcePro 12, use strXForm(const RWCString&) instead.
*/
RW_DEPRECATE_FUNC("Use strXForm(const RWCString&) instead")
RW_TOOLS_SYMBOLIC RWStandardCString
strXForm(const std::string& str);
RW_RESTORE_DEPRECATED_WARNINGS
#endif
/**
* @relates RWCString
* Returns a copy of \a str with all upper-case characters replaced
* with lower-case characters. This function is the equivalent of
* calling:
*
* @code
* RWCString tmp(str);
* tmp.toLower();
* @endcode
*/
RWStandardCString
toLower(const RWStandardCString& str);
/**
* @relates RWCString
* Returns a copy of \a str with all lower-case characters replaced
* with upper-case characters. This function is the equivalent of
* calling:
*
* @code
* RWCString tmp(str);
* tmp.toUpper();
* @endcode
*/
RWStandardCString
toUpper(const RWStandardCString& str);
/**
* @relates RWCString
* Concatenates \a lhs and \a rhs and returns the resulting
* string.
*/
RWStandardCString
operator+(const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* Concatenates \a lhs and the null-terminated string \a rhs and returns
* the resulting string.
*
* @note
* This function is incompatible with \a rhs strings with embedded nulls.
*/
RWStandardCString
operator+(const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* Concatenates the null-terminated string \a lhs and \a rhs and returns
* the resulting string.
*
* @note
* This function is incompatible with \a lhs strings with embedded nulls.
*/
RWStandardCString
operator+(const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* Concatenates \a lhs and the null-terminated string \a rhs and returns
* the resulting string.
*
* @note
* This function is incompatible with \a rhs strings with embedded nulls.
*/
RWStandardCString
operator+(const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCString
* Concatenates the null-terminated string \a lhs and \a rhs and returns
* the resulting string.
*
* @note
* This function is incompatible with \a lhs strings with embedded nulls.
*/
RWStandardCString
operator+(const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator+(const RWCString&,const RWCString&)
*/
RWStandardCString
operator+(const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* Concatenates \a lhs and the null-terminated string \a rhs and returns
* the resulting string.
*
* @note
* This function is incompatible with \a rhs strings with embedded nulls.
*/
RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCString
* Concatenates the null-terminated string \a lhs and \a rhs and returns
* the resulting string.
*
* @note
* This function is incompatible with \a lhs strings with embedded nulls.
*/
RWStandardCString
operator+(const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* Restores a string into \a str from an RWFile,
* replacing the previous contents of \a str. If the
* file produces an error on extraction, the operator
* returns the original string contents unmodified. Be sure to
* check the file to determine if an extraction
* error occurred.
*/
RW_TOOLS_SYMBOLIC RWFile&
operator>>(RWFile& file, RWStandardCString& str);
RW_TOOLS_SYMBOLIC RWFile&
operator>>(RWFile& file, RWStandardCString*& cstr);
/**
* @relates RWCString
* Restores a string into \a str from a virtual stream,
* replacing the previous contents of \a str. If the
* virtual stream produces an error on extraction, the operator
* returns the original string contents unmodified. Be sure to
* check the virtual stream to determine if an extraction
* error occurred.
*/
RW_TOOLS_SYMBOLIC RWvistream&
operator>>(RWvistream& vis, RWStandardCString& str);
RW_TOOLS_SYMBOLIC RWvistream&
operator>>(RWvistream& str, RWStandardCString*& cstr);
/**
* @relates RWCString
* Calls RWCString::readToken(std::istream&). That is, a token is read from
* the input stream \a is.
*/
RW_TOOLS_SYMBOLIC std::istream&
operator>>(std::istream& is, RWStandardCString& str);
/**
* @relates RWCString
* Saves string \a str to an RWFile.
*/
RW_TOOLS_SYMBOLIC RWFile&
operator<<(RWFile& file, const RWStandardCString& str);
/**
* @relates RWCString
* Saves string \a str to a virtual stream.
*/
RW_TOOLS_SYMBOLIC RWvostream&
operator<<(RWvostream& vos, const RWStandardCString& str);
/**
* @relates RWCString
* Output an RWCString on \b std::ostream \a os.
*/
RW_TOOLS_SYMBOLIC std::ostream&
operator<<(std::ostream& os, const RWStandardCString& str);
RW_TOOLS_SYMBOLIC std::ostream&
operator<<(std::ostream& os, const RWStandardCSubString& str);
RW_TOOLS_SYMBOLIC std::ostream&
operator<<(std::ostream& os, const RWStandardCConstSubString& str);
RW_TOOLS_SYMBOLIC std::wostream&
operator<<(std::wostream& os, const RWStandardCString& str);
RW_TOOLS_SYMBOLIC std::wostream&
operator<<(std::wostream& os, const RWStandardCSubString& str);
RW_TOOLS_SYMBOLIC std::wostream&
operator<<(std::wostream& os, const RWStandardCConstSubString& str);
/**
* @relates RWCString
* Returns \c true if \a lhs is lexicographically equal to \a rhs.
* Otherwise returns \c false. Use member RWCString::collate()
* or RWCString::strXForm() for locale-sensitive comparisons.
*/
bool
operator==(const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*
* @note
* This function is incompatible with \a rhs strings with
* embedded nulls.
*/
bool
operator==(const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* @copydoc operator==(const RWCString&, const RWCString&)
*
* @note
* This function is incompatible with \a lhs strings with
* embedded nulls.
*/
bool
operator==(const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
*
* Returns \c true if \a lhs has a length of one and the
* first character \a lhs is identical to the char \a rhs.
*/
bool
operator==(const RWStandardCString& lhs, char rhs);
/**
* @relates RWCString
*
* Returns \c true if \a rhs has a length of one and the
* first character \a rhs is identical to the char \a lhs.
*/
bool
operator==(char lhs, const RWStandardCString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, const char*)
*/
bool
operator==(const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const char*, const RWCString&)
*/
bool
operator==(const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(const RWCString&, char)
*/
bool
operator==(const RWStandardCSubString& lhs, char rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator==(char, const RWCString&)
*/
bool
operator==(char lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(const RWCString&, const RWCString&)
*/
bool
operator==(const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(const RWCString&, const char*)
*/
bool
operator==(const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(const char*, const RWCString&)
*/
bool
operator==(const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(const RWCString&, char)
*/
bool
operator==(const RWStandardCConstSubString& lhs, char rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator==(char, const RWCString&)
*/
bool
operator==(char lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* The equivalent of calling:
*
* @code
* !(lhs == rhs)
* @endcode
*/
bool
operator!=(const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCString& lhs, char rhs);
/**
* @relates RWCString
* @copydoc operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(char lhs, const RWStandardCString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCSubString& lhs, char rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(char lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(const RWStandardCConstSubString& lhs, char rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator!=(const RWCString&, const RWCString&)
*/
bool
operator!=(char lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* Returns \c true if \a lhs lexicographically precedes \a rhs.
* Otherwise returns \c false. Use member RWCString::collate() or
* RWCString::strXForm() for locale-sensitive comparisons.
*/
bool
operator< (const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*
* @note
* This function is incompatible with \a rhs strings with
* embedded nulls.
*/
bool
operator< (const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* @copydoc operator<(const RWCString&, const RWCString&)
*
* @note
* This function is incompatible with \a lhs strings with
* embedded nulls.
*/
bool
operator< (const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* Returns \c true if \a lhs is empty or the first character in
* \a lhs is less than \a rhs. Otherwise returns false.
*/
bool
operator< (const RWStandardCString& lhs, char rhs);
/**
* @relates RWCString
* Returns true if the length of \a rhs is at least one and the
* first character of \a rhs is greater than \a lhs.
*/
bool
operator< (char lhs, const RWStandardCString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, const char*)
*/
bool
operator< (const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const char*, const RWCString&)
*/
bool
operator< (const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(const RWCString&, char)
*/
bool
operator< (const RWStandardCSubString& lhs, char rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<(char, const RWCString&)
*/
bool
operator< (char lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(const RWCString&, const RWCString&)
*/
bool
operator< (const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(const RWCString&, const char*)
*/
bool
operator< (const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(const char*, const RWCString&)
*/
bool
operator< (const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(const RWCString&, char)
*/
bool
operator< (const RWStandardCConstSubString& lhs, char rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<(char, const RWCString&)
*/
bool
operator< (char lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* The equivalent of calling:
*
* @code
* !(rhs < lhs)
* @endcode
*/
bool
operator<=(const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCString& lhs, char rhs);
/**
* @relates RWCString
* @copydoc operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(char lhs, const RWStandardCString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCSubString& lhs, char rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(char lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(const RWStandardCConstSubString& lhs, char rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator<=(const RWCString&, const RWCString&)
*/
bool
operator<=(char lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* The equivalent of calling:
*
* @code
* !(lhs < rhs)
* @endcode
*/
bool
operator>=(const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCString& lhs, char rhs);
/**
* @relates RWCString
* @copydoc operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(char lhs, const RWStandardCString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCSubString& lhs, char rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(char lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(const RWStandardCConstSubString& lhs, char rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>=(const RWCString&, const RWCString&)
*/
bool
operator>=(char lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* The equivalent of calling:
*
* @code
* !(rhs < lhs)
* @endcode
*/
bool
operator> (const RWStandardCString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCConstSubString& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCString& lhs, const std::string& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const std::string& lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCString& lhs, const char* rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const char* lhs, const RWStandardCString& rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCString& lhs, char rhs);
/**
* @relates RWCString
* @copydoc operator>(const RWCString&, const RWCString&)
*/
bool
operator> (char lhs, const RWStandardCString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCSubString& lhs, const std::string& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const std::string& lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCSubString& lhs, const char* rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const char* lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCSubString& lhs, char rhs);
/**
* @relates RWCSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (char lhs, const RWStandardCSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCConstSubString& lhs, const std::string& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const std::string& lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCConstSubString& lhs, const char* rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const char* lhs, const RWStandardCConstSubString& rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (const RWStandardCConstSubString& lhs, char rhs);
/**
* @relates RWCConstSubString
* @copydoc RWCString::operator>(const RWCString&, const RWCString&)
*/
bool
operator> (char lhs, const RWStandardCConstSubString& rhs);
//////////////////////////////////////////////////////////////////////////
// //
// Inlines //
// //
//////////////////////////////////////////////////////////////////////////
inline
RWStandardCSubString::RWStandardCSubString(const RWStandardCSubString& sp)
: str_(sp.str_), begin_(sp.begin_), extent_(sp.extent_)
{
}
inline size_t
RWStandardCSubString::length() const
{
return extent_;
}
inline size_t
RWStandardCSubString::start() const
{
return begin_;
}
inline bool
RWStandardCSubString::isNull() const
{
return begin_ == RW_NPOS;
}
inline int
RWStandardCSubString::operator!() const
{
return begin_ == RW_NPOS;
}
inline
RWStandardCConstSubString::RWStandardCConstSubString(const RWStandardCSubString& sp)
: str_(sp.str_), begin_(sp.begin_), extent_(sp.extent_)
{
}
inline
RWStandardCConstSubString::RWStandardCConstSubString(const RWStandardCConstSubString& sp)
: str_(sp.str_), begin_(sp.begin_), extent_(sp.extent_)
{
}
#if !defined(RW_DISABLE_DEPRECATED)
inline const char*
RWStandardCConstSubString::data() const
{
return startData();
}
#endif // RW_DISABLE_DEPRECATED
inline size_t
RWStandardCConstSubString::length() const
{
return extent_;
}
inline size_t
RWStandardCConstSubString::start() const
{
return begin_;
}
inline bool
RWStandardCConstSubString::isNull() const
{
return begin_ == RW_NPOS;
}
inline int
RWStandardCConstSubString::operator!() const
{
return begin_ == RW_NPOS;
}
inline
RWStandardCString::RWStandardCString()
{
}
inline
RWStandardCString::RWStandardCString(const std::string& s)
: data_(s)
{
}
inline RWStandardCString::RWStandardCString(const RWStandardCString& str)
: data_(str.data_)
{
}
#if !defined(RW_NO_RVALUE_REFERENCES)
inline
RWStandardCString::RWStandardCString(RWStandardCString && str)
: data_()
{
str.swap(*this);
}
#endif // !RW_NO_RVALUE_REFERENCES
inline
RWStandardCString::RWStandardCString(char c, size_t N)
: data_(N, c)
{
}
inline
RWStandardCString::RWStandardCString(const char* s)
: data_(s)
{
}
inline
RWStandardCString::RWStandardCString(const char* s, size_t N)
: data_(s, N)
{
}
inline
RWStandardCString::RWStandardCString(char c)
: data_(1, c)
{
}
inline
RWStandardCString::RWStandardCString(signed char c)
: data_(1, RW_STATIC_CAST(char, c))
{
}
inline
RWStandardCString::RWStandardCString(unsigned char c)
: data_(1, RW_STATIC_CAST(char, c))
{
}
inline
RWStandardCString::~RWStandardCString()
{
}
#ifndef RW_DISABLE_IMPLICIT_CONVERSION
inline
RWStandardCString::operator const char* () const
{
return data();
}
#endif
inline RWStandardCString&
RWStandardCString::append(char c, size_t N)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (N) {
data_.append(N, c);
}
#else
data_.append(N, c);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const char* cs)
{
RW_PRECONDITION2(cs != rwnil,
"RWStandardCString::append(const char* cs): null pointer");
data_.append(cs);
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const RWStandardCString& str)
{
data_.append(str.std());
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const RWStandardCString::SubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.append(str.startData(), str.length());
}
#else
data_.append(str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const RWStandardCString::ConstSubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.append(str.startData(), str.length());
}
#else
data_.append(str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const std::string& str)
{
data_.append(str);
return *this;
}
inline RWStandardCString&
RWStandardCString::operator+=(char c)
{
return append(c);
}
inline RWStandardCString&
RWStandardCString::operator+=(const char* cs)
{
return append(cs);
}
inline RWStandardCString&
RWStandardCString::operator+=(const std::string& str)
{
return append(str);
}
inline RWStandardCString&
RWStandardCString::operator+=(const RWStandardCString& str)
{
return append(str);
}
inline RWStandardCString&
RWStandardCString::operator+=(const RWStandardCString::SubString& str)
{
return append(str);
}
inline RWStandardCString&
RWStandardCString::operator+=(const RWStandardCString::ConstSubString& str)
{
return append(str);
}
inline RWspace
RWStandardCString::binaryStoreSize() const
{
return length() + sizeof(size_t);
}
inline size_t
RWStandardCString::capacity(size_t capac)
{
data_.reserve(capac);
return data_.capacity();
}
inline
RWStandardCString::RWStandardCString(RWSize_T ic)
{
capacity(ic.value());
}
inline int
RWStandardCString::compareTo(const std::string& str, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrCompareExact(data(), length(), str.data(), str.length());
}
else if (cmp == ignoreCase) {
return rwCStrCompareIgnoreCase(data(), length(), str.data(), str.length());
}
else {
return rwCStrCompareIgnoreCaseStrict(data(), length(), str.data(), str.length());
}
}
inline int
RWStandardCString::compareTo(const std::string* str, caseCompare cmp) const
{
RW_PRECONDITION2(str != rwnil,
"RWStandardCString::compareTo(const std::string* str, caseCompare cmp) "
"const: null pointer");
return compareTo(*str, cmp);
}
inline int
RWStandardCString::compareTo(const RWStandardCString& str, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrCompareExact(data(), length(), str.data(), str.length());
}
else if (cmp == ignoreCase) {
return rwCStrCompareIgnoreCase(data(), length(), str.data(), str.length());
}
else {
return rwCStrCompareIgnoreCaseStrict(data(), length(), str.data(), str.length());
}
}
inline int
RWStandardCString::compareTo(const RWStandardCString::SubString& str, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrCompareExact(data(), length(), str.startData(), str.length());
}
else if (cmp == ignoreCase) {
return rwCStrCompareIgnoreCase(data(), length(), str.startData(), str.length());
}
else {
return rwCStrCompareIgnoreCaseStrict(data(), length(), str.startData(), str.length());
}
}
inline int
RWStandardCString::compareTo(const RWStandardCString::ConstSubString& str, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrCompareExact(data(), length(), str.startData(), str.length());
}
else if (cmp == ignoreCase) {
return rwCStrCompareIgnoreCase(data(), length(), str.startData(), str.length());
}
else {
return rwCStrCompareIgnoreCaseStrict(data(), length(), str.startData(), str.length());
}
}
inline int
RWStandardCString::compareTo(const RWStandardCString* str, caseCompare cmp) const
{
RW_PRECONDITION2(str != rwnil,
"RWStandardCString::compareTo(const RWStandardCString* str, caseCompare cmp) "
"const: null pointer");
return compareTo(*str, cmp);
}
inline const char*
RWStandardCString::data() const
{
return data_.c_str();
}
inline const std::string&
RWStandardCString::std() const
{
return data_;
}
inline unsigned
RWStandardCString::hash(const RWStandardCString& str)
{
return unsigned(str.hash());
}
inline bool
RWStandardCString::isNull() const
{
return data_.empty();
}
inline size_t
RWStandardCString::length() const
{
return data_.length();
}
inline void
RWStandardCString::toLower()
{
toLower(0, length());
}
inline void
RWStandardCString::toUpper()
{
toUpper(0, length());
}
////
// This RWStandardCSubString ctor appears out of sequence here
// to avoid inlined after called warnings
///
inline
RWStandardCSubString::RWStandardCSubString(const RWStandardCString& str, size_t pos, size_t n)
: str_(const_cast<RWStandardCString*>(&str)),
begin_(pos),
extent_(n)
{
#ifdef RW_DEBUG
size_t len = str.length();
// Allow zero lengthed and null substrings:
if ((pos == RW_NPOS && n != RW_NPOS && n != 0) ||
(pos != RW_NPOS && (pos > len || n > len || pos + n > len))) {
subStringError(len, pos, n);
}
#endif
}
inline RWStandardCString::RWStandardCString(const RWStandardCSubString& s)
{
if (!s.isNull()) {
data_.assign(s.str_->data_, s.begin_, s.extent_);
}
}
inline RWStandardCString::RWStandardCString(const RWStandardCConstSubString& s)
{
if (!s.isNull()) {
data_.assign(s.str_->data_, s.begin_, s.extent_);
}
}
inline size_t
RWStandardCString::mbLength() const
{
return RWStandardCString::mbLength(data(), length());
}
//Assignment
inline RWStandardCString&
RWStandardCString::assign(const RWStandardCString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not attempt to use
// existing capacity when assigning string with assign(),
// however they did with operator=.
data_ = str.std();
#else
data_.assign(str.std());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::assign(const std::string& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not attempt to use
// existing capacity when assigning string with assign(),
// however they did with operator=.
data_ = str;
#else
data_.assign(str);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::assign(const SubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.assign(str.startData(), str.length());
}
else {
remove(0);
}
#else
data_.assign(str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::assign(const ConstSubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.assign(str.startData(), str.length());
}
else {
remove(0);
}
#else
data_.assign(str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::assign(const char* str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not attempt to use
// existing capacity when assigning string with assign(),
// however they did with operator=.
data_ = str;
#else
data_.assign(str);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::assign(const char* str, size_t len)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (len) {
data_.assign(str, len);
}
else {
remove(0);
}
#else
data_.assign(str, len);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::assign(char c, size_t count)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (count) {
data_.assign(count, c);
}
else {
remove(0);
}
#else
data_.assign(count, c);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::operator=(char c)
{
assign(c);
return *this;
}
inline RWStandardCString&
RWStandardCString::operator=(const char* s)
{
assign(s);
return *this;
}
inline RWStandardCString&
RWStandardCString::operator=(const std::string& s)
{
assign(s);
return *this;
}
RW_SUPPRESS_OP_ASSIGN_SELF_CHECK_WARNING
inline RWStandardCString&
RWStandardCString::operator=(const RWStandardCString& s)
{
assign(s);
return *this;
}
RW_RESTORE_OP_ASSIGN_SELF_CHECK_WARNING
#if !defined(RW_NO_RVALUE_REFERENCES)
inline RWStandardCString&
RWStandardCString::operator=(RWStandardCString && s)
{
if (this != &s) {
s.swap(*this);
}
return *this;
}
#endif // !RW_NO_RVALUE_REFERENCES
inline RWStandardCString&
RWStandardCString::operator=(const RWStandardCString::SubString& str)
{
assign(str);
return *this;
}
inline RWStandardCString&
RWStandardCString::operator=(const RWStandardCString::ConstSubString& str)
{
assign(str);
return *this;
}
inline void
RWStandardCString::assertElement(size_t i) const
{
size_t len = length();
if (i >= len) {
throwBoundsErr(i, len);
}
}
//Indexing - non-const
// Note: RWStandardCString::operator() is undefined for i>=length()
// when RWBOUNDS_CHECK is not defined.
inline char&
RWStandardCString::operator()(size_t i)
{
#ifdef RWBOUNDS_CHECK
assertElement(i);
#endif
return data_[i];
}
inline char
RWStandardCString::operator()(size_t i) const
{
#ifdef RWBOUNDS_CHECK
assertElement(i);
#endif
return data()[i];
}
// Here all integer types are provided with an exact match
// to avoid ambiguities with the built in char[] operator
// All operator[] functions are with bounds checking
inline char&
RWStandardCString::operator[](char i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](char i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](signed char i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](signed char i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](short i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](short i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](int i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](int i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](long i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](long i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](unsigned char i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](unsigned char i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](unsigned short i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](unsigned short i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](unsigned int i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](unsigned int i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](unsigned long i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](unsigned long i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
#if !defined(RW_NO_LONG_LONG)
inline char&
RWStandardCString::operator[](unsigned long long i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](unsigned long long i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char&
RWStandardCString::operator[](long long i)
{
assertElement(size_t (i));
return data_[size_t (i)];
}
inline char
RWStandardCString::operator[](long long i) const
{
assertElement(size_t (i));
return data_[size_t (i)];
}
#endif
// Substring operators : non-const
inline RWStandardCSubString
RWStandardCString::operator()(size_t start, size_t len)
{
return RWStandardCSubString(*this, start, len);
}
// Substring operators : const
inline RWStandardCConstSubString
RWStandardCString::operator()(size_t start, size_t len) const
{
return RWStandardCConstSubString(*this, start, len);
}
// Other Non-static member functions
inline RWStandardCString&
RWStandardCString::append(const RWStandardCString& str, size_t N)
{
size_t len = rwmin(N, str.length());
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (len) {
data_.append(str.std(), 0, len);
}
#else
data_.append(str.std(), 0, len);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const char* s, size_t N)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (N) {
data_.append(s, N);
}
#else
data_.append(s, N);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::append(const std::string& str, size_t N)
{
size_t len = rwmin(N, str.length());
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (len) {
data_.append(str, 0, len);
}
#else
data_.append(str, 0, len);
#endif
return *this;
}
inline size_t
RWStandardCString::capacity() const
{
return data_.capacity();
}
inline int
RWStandardCString::compareTo(const char* s, size_t len, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrCompareExact(data(), length(), s, len);
}
else if (cmp == ignoreCase) {
return rwCStrCompareIgnoreCase(data(), length(), s, len);
}
else {
return rwCStrCompareIgnoreCaseStrict(data(), length(), s, len);
}
}
inline int
RWStandardCString::compareTo(const char* s, caseCompare cmp) const
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::compareTo(const char* s, caseCompare cmp) const: "
"null pointer");
return compareTo(s, strlen(s), cmp);
}
#if !defined(RW_DISABLE_DEPRECATED)
inline size_t
RWStandardCString::indexIgnoreCase(const char* pat, size_t patlen, size_t i) const
{
return rwCStrFindIgnoreCase(data(), length(), pat, patlen, i);
}
#endif // RW_DISABLE_DEPRECATED
inline size_t
RWStandardCString::index(const char* pat, size_t patlen, size_t i, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrFindExact(data(), length(), pat, patlen, i);
}
else {
return rwCStrFindIgnoreCase(data(), length(), pat, patlen, i);
}
}
inline size_t
RWStandardCString::index(const std::string& pat, size_t i, caseCompare cmp) const
{
return index(pat.data(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::index(const RWStandardCString& pat, size_t patlen,
size_t i, caseCompare cmp) const
{
RW_ASSERT(patlen <= pat.length());
return index(pat.data(), patlen, i, cmp);
}
inline bool
RWStandardCString::contains(const char* pat, size_t len, caseCompare cmp) const
{
return index(pat, len, size_t(0), cmp) != RW_NPOS;
}
inline bool
RWStandardCString::contains(const char* pat, caseCompare cmp) const
{
RW_PRECONDITION2(pat != rwnil,
"RWStandardCString::contains(const char* pat, caseCompare cmp) const: "
"null pointer");
return index(pat, strlen(pat), size_t(0), cmp) != RW_NPOS;
}
inline bool
RWStandardCString::contains(const std::string& pat, caseCompare cmp) const
{
return index(pat.data(), pat.length(), size_t(0), cmp) != RW_NPOS;
}
inline bool
RWStandardCString::contains(const RWStandardCString& pat, caseCompare cmp) const
{
return index(pat.data(), pat.length(), size_t(0), cmp) != RW_NPOS;
}
inline bool
RWStandardCString::contains(const RWStandardCString::SubString& pat, caseCompare cmp) const
{
return index(pat.startData(), pat.length(), size_t(0), cmp) != RW_NPOS;
}
inline bool
RWStandardCString::contains(const RWStandardCString::ConstSubString& pat, caseCompare cmp) const
{
return index(pat.startData(), pat.length(), size_t(0), cmp) != RW_NPOS;
}
#if !defined(RW_DISABLE_DEPRECATED)
inline RWStandardCString
RWStandardCString::copy() const
{
return RWStandardCString(data_);
}
#endif // RW_DISABLE_DEPRECATED
inline int
RWStandardCString::collate(const char* s) const
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::collate(const char* s) const: null pointer");
return strcoll(data(), s);
}
inline int
RWStandardCString::collate(const std::string& str) const
{
return strcoll(data(), str.c_str());
}
inline int
RWStandardCString::collate(const RWStandardCString& str) const
{
return strcoll(data(), str.data());
}
inline size_t
RWStandardCString::firstNotOf(char c, size_t pos) const
{
return rwCStrFindFirstNotOf(data(), length(), c, pos);
}
inline size_t
RWStandardCString::firstNotOf(const char* str, size_t pos, size_t len) const
{
return rwCStrFindFirstNotOf(data(), length(), str, len, pos);
}
inline size_t
RWStandardCString::firstNotOf(const char* str, size_t pos) const
{
RW_PRECONDITION2(str != rwnil,
"RWStandardCString::firstNotOf(const char* str, size_t pos) const: null pointer");
return firstNotOf(str, pos, strlen(str));
}
inline size_t
RWStandardCString::firstNotOf(const RWStandardCString& str, size_t pos) const
{
return firstNotOf(str.data(), pos, str.length());
}
inline size_t
RWStandardCString::firstNotOf(const RWStandardCString::SubString& str, size_t pos) const
{
return firstNotOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::firstNotOf(const RWStandardCString::ConstSubString& str, size_t pos) const
{
return firstNotOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::firstNotOf(const std::string& str, size_t pos) const
{
return firstNotOf(str.data(), pos, str.length());
}
inline size_t
RWStandardCString::firstOf(char c, size_t pos) const
{
return rwCStrFindFirstOf(data(), length(), c, pos);
}
inline size_t
RWStandardCString::firstOf(const char* str, size_t pos, size_t len) const
{
return rwCStrFindFirstOf(data(), length(), str, len, pos);
}
inline size_t
RWStandardCString::firstOf(const char* str, size_t pos) const
{
RW_PRECONDITION2(str != rwnil,
"RWStandardCString::firstOf(const char* str, size_t pos) const: null pointer");
return firstOf(str, pos, strlen(str));
}
inline size_t
RWStandardCString::firstOf(const RWStandardCString& str, size_t pos) const
{
return firstOf(str.data(), pos, str.length());
}
inline size_t
RWStandardCString::firstOf(const RWStandardCString::SubString& str, size_t pos) const
{
return firstOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::firstOf(const RWStandardCString::ConstSubString& str, size_t pos) const
{
return firstOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::firstOf(const std::string& str, size_t pos) const
{
return firstOf(str.data(), pos, str.length());
}
#if !defined(RW_DISABLE_DEPRECATED)
inline size_t
RWStandardCString::first(char c) const
{
return firstOf(c);
}
inline size_t
RWStandardCString::first(char c, size_t) const
{
return firstOf(c);
}
inline size_t
RWStandardCString::first(const char* s, size_t N) const
{
return firstOf(s, 0, N);
}
inline size_t
RWStandardCString::first(const char* s) const
{
return firstOf(s);
}
#endif // RW_DISABLE_DEPRECATED
inline size_t
RWStandardCString::index(const char* pat, size_t i, caseCompare cmp) const
{
RW_PRECONDITION2(pat != rwnil,
"RWStandardCString::index(const char* pat, size_t i, caseCompare cmp) "
"const: null pointer");
return index(pat, strlen(pat), i, cmp);
}
inline size_t
RWStandardCString::index(const RWStandardCString& pat, size_t i, caseCompare cmp) const
{
return index(pat.data(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::index(const RWStandardCString::SubString& pat, size_t i, caseCompare cmp) const
{
return index(pat.startData(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::index(const RWStandardCString::ConstSubString& pat, size_t i, caseCompare cmp) const
{
return index(pat.startData(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::index(const char pat, size_t i, caseCompare cmp) const
{
return index(&pat, 1, i, cmp);
}
inline size_t
RWStandardCString::index(const std::string& pat,
size_t patlen, size_t i, caseCompare cmp) const
{
RW_ASSERT(patlen <= pat.length());
return index(pat.data(), patlen, i, cmp);
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, char c, size_t extent)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (extent) {
data_.insert(pos, extent, c);
}
#else
data_.insert(pos, extent, c);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const char* s)
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::insert(size_t pos, const char* s): null pointer");
data_.insert(pos, s);
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const std::string& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.empty()) {
data_.insert(pos, str);
}
#else
data_.insert(pos, str);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const RWStandardCString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.insert(pos, str.std());
}
#else
data_.insert(pos, str.std());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const RWStandardCString::SubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.insert(pos, str.startData(), str.length());
}
#else
data_.insert(pos, str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const RWStandardCString::ConstSubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.insert(pos, str.startData(), str.length());
}
#else
data_.insert(pos, str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const char* s, size_t extent)
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::insert(size_t pos, const char* s, size_t extent): "
"null pointer");
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (extent) {
data_.insert(pos, s, extent);
}
#else
data_.insert(pos, s, extent);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const std::string& str, size_t extent)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (extent) {
data_.insert(pos, str, 0, extent);
}
#else
data_.insert(pos, str, 0, extent);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::insert(size_t pos, const RWStandardCString& str, size_t extent)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (extent) {
data_.insert(pos, str.std(), 0, extent);
}
#else
data_.insert(pos, str.std(), 0, extent);
#endif
return *this;
}
inline size_t
RWStandardCString::lastNotOf(char c, size_t pos) const
{
return rwCStrFindLastNotOf(data(), length(), c, pos);
}
inline size_t
RWStandardCString::lastNotOf(const char* str, size_t pos, size_t len) const
{
return rwCStrFindLastNotOf(data(), length(), str, len, pos);
}
inline size_t
RWStandardCString::lastNotOf(const char* str, size_t pos) const
{
RW_PRECONDITION2(str != rwnil,
"RWStandardCString::lastNotOf(const char* str, size_t pos) const: null pointer");
return lastNotOf(str, pos, strlen(str));
}
inline size_t
RWStandardCString::lastNotOf(const RWStandardCString& str, size_t pos) const
{
return lastNotOf(str.data(), pos, str.length());
}
inline size_t
RWStandardCString::lastNotOf(const RWStandardCString::SubString& str, size_t pos) const
{
return lastNotOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::lastNotOf(const RWStandardCString::ConstSubString& str, size_t pos) const
{
return lastNotOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::lastNotOf(const std::string& str, size_t pos) const
{
return lastNotOf(str.data(), pos, str.length());
}
inline size_t
RWStandardCString::lastOf(char c, size_t pos) const
{
return rwCStrFindLastOf(data(), length(), c, pos);
}
inline size_t
RWStandardCString::lastOf(const char* str, size_t pos, size_t len) const
{
return rwCStrFindLastOf(data(), length(), str, len, pos);
}
inline size_t
RWStandardCString::lastOf(const char* str, size_t pos) const
{
RW_PRECONDITION2(str != rwnil,
"RWStandardCString::lastOf(const char* str, size_t pos) const: null pointer");
return lastOf(str, pos, strlen(str));
}
inline size_t
RWStandardCString::lastOf(const RWStandardCString& str, size_t pos) const
{
return lastOf(str.data(), pos, str.length());
}
inline size_t
RWStandardCString::lastOf(const RWStandardCString::SubString& str, size_t pos) const
{
return lastOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::lastOf(const RWStandardCString::ConstSubString& str, size_t pos) const
{
return lastOf(str.startData(), pos, str.length());
}
inline size_t
RWStandardCString::lastOf(const std::string& str, size_t pos) const
{
return lastOf(str.data(), pos, str.length());
}
#if !defined(RW_DISABLE_DEPRECATED)
inline size_t
RWStandardCString::last(char c) const
{
return lastOf(c);
}
inline size_t
RWStandardCString::last(char c, size_t) const
{
return lastOf(c);
}
inline size_t
RWStandardCString::last(const char* s, size_t N) const
{
return lastOf(s, RW_NPOS, N);
}
inline size_t
RWStandardCString::last(const char* s) const
{
return lastOf(s);
}
#endif // RW_DISABLE_DEPRECATED
inline RWStandardCString&
RWStandardCString::prepend(char c, size_t N)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (N) {
data_.insert(size_t(0), N, c);
}
#else
data_.insert(size_t(0), N, c);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const char* s)
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::prepend(const char* s): null pointer");
data_.insert(0, s);
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const std::string& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.empty()) {
data_.insert(0, str);
}
#else
data_.insert(0, str);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const RWStandardCString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.insert(0, str.std());
}
#else
data_.insert(0, str.std());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const RWStandardCString::SubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.insert(0, str.startData(), str.length());
}
#else
data_.insert(0, str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const RWStandardCString::ConstSubString& str)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (!str.isNull()) {
data_.insert(0, str.startData(), str.length());
}
#else
data_.insert(0, str.startData(), str.length());
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const char* s, size_t N)
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::prepend(const char* s, size_t N): null pointer");
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (N) {
data_.insert(0, s, N);
}
#else
data_.insert(0, s, N);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const std::string& str, size_t N)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (N) {
data_.insert(0, str, 0, N);
}
#else
data_.insert(0, str, 0, N);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::prepend(const RWStandardCString& str, size_t N)
{
#if defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (N) {
data_.insert(0, str.std(), 0, N);
}
#else
data_.insert(0, str.std(), 0, N);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::remove(size_t pos)
{
#ifdef RW_MSVC_STDLIB_BUG // see compiler.h
if (data_.size()) {
data_[0];
}
#endif
data_.erase(pos);
return *this;
}
inline RWStandardCString&
RWStandardCString::remove(size_t pos, size_t N)
{
#ifdef RW_MSVC_STDLIB_BUG // see compiler.h
if (data_.size()) {
data_[0];
}
#endif
data_.erase(pos, N);
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const char* s, size_t N)
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::replace(size_t pos, size_t extent, const char* s, "
"size_t N): null pointer");
#if (_STLPORT_VERSION == 0x452)
// STLport 4.5.2 does not properly handle replacement from
// overlapping data regions. we make a copy of the source
// string if the source data overlaps part of the destination.
const char* const beg_dst = data() + pos;
const char* const end_dst = data() + length();
if (!extent || (s + N < beg_dst) || (end_dst < s)) {
data_.replace(pos, extent, s, N);
}
else {
const std::string str(s, N);
data_.replace(pos, extent, str, 0, N);
}
#elif defined(_RWSTD_VER) && (_RWSTD_VER <= 0x02020400)
// Older versions of the RW stdlib did not verify that the
// original string would be modified before allocating a
// new string instance for it. Avoid an unnecessary
// allocation if the string won't be modified.
if (extent || N) {
data_.replace(pos, extent, s, N);
}
#else
data_.replace(pos, extent, s, N);
#endif
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const char* s)
{
RW_PRECONDITION2(s != rwnil,
"RWStandardCString::replace(size_t pos, size_t extent, const char* s): "
"null pointer");
replace(pos, extent, s, strlen(s));
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const std::string& str)
{
replace(pos, extent, str.data(), str.length());
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const RWStandardCString& str)
{
replace(pos, extent, str.data(), str.length());
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const RWStandardCString::SubString& str)
{
replace(pos, extent, str.startData(), str.length());
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const RWStandardCString::ConstSubString& str)
{
replace(pos, extent, str.startData(), str.length());
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent, const RWStandardCString& str, size_t N)
{
replace(pos, extent, str.data(), N);
return *this;
}
inline RWStandardCString&
RWStandardCString::replace(size_t pos, size_t extent,
const std::string& str, size_t N)
{
replace(pos, extent, str.data(), N);
return *this;
}
inline void
RWStandardCString::resize(size_t N)
{
data_.resize(N, ' ');
}
#if !defined(RW_DISABLE_DEPRECATED)
inline size_t
RWStandardCString::rindexIgnoreCase(const char* pat, size_t patlen, size_t i) const
{
return rwCStrRFindIgnoreCase(data(), length(), pat, patlen, i);
}
#endif // RW_DISABLE_DEPRECATED
inline size_t
RWStandardCString::rindex(const char* pat, size_t patlen,
size_t i, caseCompare cmp) const
{
if (cmp == exact) {
return rwCStrRFindExact(data(), length(), pat, patlen, i);
}
else {
return rwCStrRFindIgnoreCase(data(), length(), pat, patlen, i);
}
}
inline size_t
RWStandardCString::rindex(const char* pat, caseCompare cmp) const
{
RW_PRECONDITION2(pat != rwnil,
"RWStandardCString::rindex(const char* pat, caseCompare cmp) const: "
"null pointer");
return rindex(pat, strlen(pat), RW_NPOS, cmp);
}
inline size_t
RWStandardCString::rindex(const RWStandardCString& pat, size_t patlen,
size_t i, caseCompare cmp) const
{
RW_ASSERT(patlen <= pat.length());
return rindex(pat.data(), patlen, i, cmp);
}
inline size_t
RWStandardCString::rindex(const char* pat, size_t i, caseCompare cmp) const
{
RW_PRECONDITION2(pat != rwnil,
"RWStandardCString::rindex(const char* pat, size_t i, "
"caseCompare cmp) const: null pointer");
return rindex(pat, strlen(pat), i, cmp);
}
inline size_t
RWStandardCString::rindex(const char pat, size_t i, caseCompare cmp) const
{
return rindex(&pat, 1, i, cmp);
}
inline size_t
RWStandardCString::rindex(const std::string& pat, size_t i, caseCompare cmp) const
{
return rindex(pat.data(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::rindex(const std::string& pat, size_t patlen,
size_t i, caseCompare cmp) const
{
RW_ASSERT(patlen <= pat.length());
return rindex(pat.data(), patlen, i, cmp);
}
inline size_t
RWStandardCString::rindex(const RWStandardCString& pat, size_t i, caseCompare cmp) const
{
return rindex(pat.data(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::rindex(const RWStandardCString::SubString& pat, size_t i, caseCompare cmp) const
{
return rindex(pat.startData(), pat.length(), i, cmp);
}
inline size_t
RWStandardCString::rindex(const RWStandardCString::ConstSubString& pat, size_t i, caseCompare cmp) const
{
return rindex(pat.startData(), pat.length(), i, cmp);
}
inline void
RWStandardCString::swap(RWStandardCString& str)
{
data_.swap(str.data_);
}
inline void
RWStandardCString::shrink()
{
#ifndef RW_NO_BASIC_STRING_SHRINK_TO_FIT
data_.shrink_to_fit();
#else
data_.reserve(0);
#endif
}
//////////////////////////////////////////////////////////////////////////
// //
// Related global functions //
// //
//////////////////////////////////////////////////////////////////////////
#if !defined(RW_DISABLE_DEPRECATED)
/**
* @internal
* @deprecated As of SourcePro 12, use RWStandardCString::hash(const RWStandardCString&) instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::hash(const RWStandardCString&) instead")
inline unsigned
rwhash(const RWStandardCString& s)
{
return unsigned(s.hash());
}
/**
* @internal
* @deprecated As of SourcePro 12, use RWStandardCString::hash(const RWStandardCString&) instead.
*/
RW_DEPRECATE_FUNC("Use RWStandardCString::hash(const RWStandardCString&) instead")
inline unsigned
rwhash(const RWStandardCString* s)
{
RW_PRECONDITION2(s != rwnil,
"rwhash(const RWStandardCString* s): null pointer");
return unsigned(s->hash());
}
#endif
inline RWStandardCString
toLower(const RWStandardCString& str)
{
RWStandardCString tmp(str);
tmp.toLower();
return tmp;
}
inline RWStandardCString
toUpper(const RWStandardCString& str)
{
RWStandardCString temp(str);
temp.toUpper();
return temp;
}
inline RWStandardCString
operator+(const RWStandardCString& lhs, const RWStandardCString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCString& lhs, const std::string& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return RWStandardCString(rhs);
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const std::string& lhs, const RWStandardCString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return RWStandardCString(lhs);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator+(const RWStandardCString& lhs, const char* rhs): null pointer");
size_t rhsLen = strlen(rhs);
if (!rhsLen) {
return lhs;
}
size_t lhsLen = lhs.length();
if (!lhsLen) {
return RWStandardCString(rhs, rhsLen);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs, rhsLen);
}
inline RWStandardCString
operator+(const char* lhs, const RWStandardCString& rhs)
{
RW_PRECONDITION2(lhs != rwnil,
"operator+(const char* lhs, const RWStandardCString& rhs): null pointer");
size_t lhsLen = strlen(lhs);
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return RWStandardCString(lhs, lhsLen);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs, lhsLen);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCSubString& lhs, const std::string& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return RWStandardCString(rhs);
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const std::string& lhs, const RWStandardCSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return RWStandardCString(lhs);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCSubString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator+(const RWStandardCString& lhs, const char* rhs): null pointer");
size_t rhsLen = strlen(rhs);
if (!rhsLen) {
return lhs;
}
size_t lhsLen = lhs.length();
if (!lhsLen) {
return RWStandardCString(rhs, rhsLen);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs, rhsLen);
}
inline RWStandardCString
operator+(const char* lhs, const RWStandardCSubString& rhs)
{
RW_PRECONDITION2(lhs != rwnil,
"operator+(const char* lhs, const RWStandardCString& rhs): null pointer");
size_t lhsLen = strlen(lhs);
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return RWStandardCString(lhs, lhsLen);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs, lhsLen);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const std::string& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return RWStandardCString(rhs);
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return lhs;
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const std::string& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return RWStandardCString(lhs);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs);
}
inline RWStandardCString
operator+(const RWStandardCConstSubString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator+(const RWStandardCString& lhs, const char* rhs): null pointer");
size_t rhsLen = strlen(rhs);
if (!rhsLen) {
return lhs;
}
size_t lhsLen = lhs.length();
if (!lhsLen) {
return RWStandardCString(rhs, rhsLen);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs);
return ret.append(rhs, rhsLen);
}
inline RWStandardCString
operator+(const char* lhs, const RWStandardCConstSubString& rhs)
{
RW_PRECONDITION2(lhs != rwnil,
"operator+(const char* lhs, const RWStandardCString& rhs): null pointer");
size_t lhsLen = strlen(lhs);
if (!lhsLen) {
return rhs;
}
size_t rhsLen = rhs.length();
if (!rhsLen) {
return RWStandardCString(lhs, lhsLen);
}
RWStandardCString ret(RWSize_T(lhsLen + rhsLen));
ret.append(lhs, lhsLen);
return ret.append(rhs);
}
//////////////////////////////////////////////////////////////////////////
// RWStandardCSubString //
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// RWCSubString::startData()
//
// This member replaces data().
// startData() will remain undocumented.
// Use at your own risk. It may be deprecated in the future.
//
// Since RWCSubString works by referencing the RWStandardCString's data,
// if you attempt to directly use the data() member of the RWStandardCString,
// you will very likely be surprised by the result, which is null
// terminated not at the extent of the substring,
// but at the end of the RWStandardCString.
//
///////////////////////////////////////////////////////////////////////////////
////
// The RWStandardCSubString ctor appears out of sequence at the beginning of the
// RWStandardCString inlines section, in order to avoid inlined after called warnings.
//
inline const char*
RWStandardCSubString::startData() const
{
return str_->data() + begin_;
}
#if !defined(RW_DISABLE_DEPRECATED)
inline const char*
RWStandardCSubString::data() const
{
return startData();
}
#endif
inline RWStandardCSubString&
RWStandardCSubString::operator=(const char* s)
{
if (!isNull()) {
str_->replace(begin_, extent_, s);
}
return *this;
}
inline RWStandardCSubString&
RWStandardCSubString::operator=(const RWStandardCSubString& str)
{
if (this == &str) {
return *this;
}
if (!isNull()) {
str_->replace(begin_, extent_, str.startData(), str.length());
}
return *this;
}
inline RWStandardCSubString&
RWStandardCSubString::operator=(const RWStandardCConstSubString& str)
{
if (!isNull()) {
str_->replace(begin_, extent_, str.startData(), str.length());
}
return *this;
}
inline RWStandardCSubString&
RWStandardCSubString::operator=(const std::string& str)
{
if (!isNull()) {
str_->replace(begin_, extent_, str);
}
return *this;
}
inline RWStandardCSubString&
RWStandardCSubString::operator=(const RWStandardCString& str)
{
if (!isNull()) {
str_->replace(begin_, extent_, str.std());
}
return *this;
}
inline void
RWStandardCSubString::assertElement(size_t i) const
{
size_t len = length();
if (i >= len) {
throwBoundsErr(i, len);
}
}
inline char&
RWStandardCSubString::operator()(size_t i)
{
assertElement(i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator()(size_t i) const
{
assertElement(i);
return (*str_)(begin_ + i);
}
// Here all integer types are provided with an exact match
// to avoid ambiguities with the built in char[] operator
inline char&
RWStandardCSubString::operator[](char i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](char i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](signed char i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](signed char i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](short i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](short i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](int i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](int i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](long i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](unsigned char i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](unsigned char i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](unsigned short i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](unsigned short i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](unsigned int i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](unsigned int i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char&
RWStandardCSubString::operator[](unsigned long i)
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCSubString::operator[](unsigned long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
#if !defined(RW_NO_LONG_LONG)
inline char&
RWStandardCSubString::operator[](unsigned long long i)
{
assertElement((size_t)i);
return (*str_)(begin_ + (size_t)i);
}
inline char
RWStandardCSubString::operator[](unsigned long long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + (size_t)i);
}
inline char&
RWStandardCSubString::operator[](long long i)
{
assertElement((size_t)i);
return (*str_)(begin_ + (size_t)i);
}
inline char
RWStandardCSubString::operator[](long long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + (size_t)i);
}
#endif
// Convert self to lower-case
inline void
RWStandardCSubString::toLower()
{
if (!isNull()) {
str_->toLower(begin_, extent_);
}
}
// Convert self to upper-case
inline void
RWStandardCSubString::toUpper()
{
if (!isNull()) {
str_->toUpper(begin_, extent_);
}
}
//////////////////////////////////////////////////////////////////////////
// RWStandardCConstSubString //
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// RWStandardCConstSubString::startData()
//
// This member replaces data().
// startData() will remain undocumented. Please don't even ask.
// Use at your own risk. It may be deprecated in the future.
//
// Since RWStandardCSubString works by referencing the RWStandardCString's data,
// if you attempt to directly use the data() member of the RWStandardCString,
// you will very likely be surprised by the result, which is null
// terminated not at the extent of the substring,
// but at the end of the RWStandardCString.
//
///////////////////////////////////////////////////////////////////////////////
inline void
RWStandardCConstSubString::assertElement(size_t i) const
{
size_t len = length();
if (i >= len) {
throwBoundsErr(i, len);
}
}
inline char
RWStandardCConstSubString::operator()(size_t i) const
{
assertElement(i);
return (*str_)(begin_ + i);
}
// Here all integer types are provided with an exact match
// to avoid ambiguities with the built in char[] operator
inline char
RWStandardCConstSubString::operator[](char i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](signed char i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](short i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](int i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](unsigned char i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](unsigned short i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](unsigned int i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
inline char
RWStandardCConstSubString::operator[](unsigned long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + i);
}
#if !defined(RW_NO_LONG_LONG)
inline char
RWStandardCConstSubString::operator[](long long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + (size_t)i);
}
inline char
RWStandardCConstSubString::operator[](unsigned long long i) const
{
assertElement((size_t)i);
return (*str_)(begin_ + (size_t)i);
}
#endif
/*
* Returns a substring matching "pattern", or the null substring
* if there is no such match. It would be nice if this could be yet another
* overloaded version of operator(), but this would result in a type
* conversion ambiguity with operator(size_t, size_t).
*/
inline RWStandardCString::SubString
RWStandardCString::subString(const char* pattern, size_t startIndex, caseCompare cmp)
{
RW_PRECONDITION2(pattern != rwnil,
"RWStandardCString::subString(const char* pattern, size_t startIndex, "
"caseCompare cmp): null pointer");
size_t len = strlen(pattern);
size_t i = index(pattern, len, startIndex, cmp);
return RWStandardCString::SubString(*this, i, i == RW_NPOS ? 0 : len);
}
inline RWStandardCConstSubString
RWStandardCString::subString(const char* pattern, size_t startIndex,
caseCompare cmp) const
{
RW_PRECONDITION2(pattern != rwnil,
"RWStandardCString::subString(const char* pattern, size_t startIndex, "
"caseCompare cmp) const: null pointer");
size_t len = strlen(pattern);
size_t i = index(pattern, len, startIndex, cmp);
return RWStandardCConstSubString(*this, i, i == RW_NPOS ? 0 : len);
}
inline std::string&
RWStandardCString::std()
{
return RW_EXPOSE(data_);
}
inline void
RWStandardCString::toLower(size_t pos, size_t extent)
{
size_t n = (pos + extent > length()) ? length() : pos + extent;
for (; pos < n; ++pos) {
char& c = data_[pos];
c = char(tolower(RW_STATIC_CAST(unsigned char, c)));
}
}
inline void
RWStandardCString::toUpper(size_t pos, size_t extent)
{
size_t n = (pos + extent > length()) ? length() : pos + extent;
for (; pos < n; ++pos) {
char& c = data_[pos];
c = char(toupper(RW_STATIC_CAST(unsigned char, c)));
}
}
inline RWStandardCConstSubString::RWStandardCConstSubString
(const RWStandardCString& str, size_t pos, size_t n)
: str_(&str), begin_(pos), extent_(n)
{
#ifdef RW_DEBUG
size_t len = str.length();
// Allow zero lengthed and null substrings:
if ((pos == RW_NPOS && n != 0) || (pos != RW_NPOS && pos + n > len)) {
subStringError(len, pos, n);
}
#endif
}
inline const char*
RWStandardCConstSubString::startData() const
{
return str_->data() + begin_;
}
inline bool
operator==(const RWStandardCString& lhs, const RWStandardCString& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.data(), lhsLen, rhs.data(), rhsLen);
}
inline bool
operator==(const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.data(), lhsLen, rhs.startData(), rhsLen);
}
inline bool
operator==(const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.data(), lhsLen, rhs.startData(), rhsLen);
}
inline bool
operator==(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCString& lhs, const std::string& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.data(), lhsLen, rhs.data(), rhsLen);
}
inline bool
operator==(const std::string& lhs, const RWStandardCString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator==(const RWStandardCString& lhs, const char* rhs): null pointer");
size_t lhsLen = lhs.length();
size_t rhsLen = strlen(rhs);
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.data(), lhsLen, rhs, rhsLen);
}
inline bool
operator==(const char* lhs, const RWStandardCString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCString& lhs, char rhs)
{
return 1 == lhs.length() && lhs(0) == rhs;
}
inline bool
operator==(char lhs, const RWStandardCString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs.startData(), rhsLen);
}
inline bool
operator==(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs.startData(), rhsLen);
}
inline bool
operator==(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCSubString& lhs, const std::string& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs.data(), rhsLen);
}
inline bool
operator==(const std::string& lhs, const RWStandardCSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCSubString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator==(const RWStandardCSubString& lhs, const char* rhs): null pointer");
size_t lhsLen = lhs.length();
size_t rhsLen = strlen(rhs);
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs, rhsLen);
}
inline bool
operator==(const char* lhs, const RWStandardCSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCSubString& lhs, char rhs)
{
return (1 == lhs.length() && lhs(0) == rhs);
}
inline bool
operator==(char lhs, const RWStandardCSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs.startData(), rhsLen);
}
inline bool
operator==(const RWStandardCConstSubString& lhs, const std::string& rhs)
{
size_t lhsLen = lhs.length();
size_t rhsLen = rhs.length();
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs.data(), rhsLen);
}
inline bool
operator==(const std::string& lhs, const RWStandardCConstSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCConstSubString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator==(const RWStandardCConstSubString& lhs, const char* rhs): "
"null pointer");
size_t lhsLen = lhs.length();
size_t rhsLen = strlen(rhs);
if (lhsLen != rhsLen) {
return false;
}
return 0 == rwCStrCompareExact(lhs.startData(), lhsLen, rhs, rhsLen);
}
inline bool
operator==(const char* lhs, const RWStandardCConstSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator==(const RWStandardCConstSubString& lhs, char rhs)
{
return (1 == lhs.length() && lhs(0) == rhs);
}
inline bool
operator==(char lhs, const RWStandardCConstSubString& rhs)
{
return (rhs == lhs);
}
inline bool
operator!=(const RWStandardCString& lhs, const RWStandardCString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCString& lhs, const std::string& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const std::string& lhs, const RWStandardCString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCString& lhs, const char* rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const char* lhs, const RWStandardCString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCString& lhs, char rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(char lhs, const RWStandardCString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCSubString& lhs, const std::string& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const std::string& lhs, const RWStandardCSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCSubString& lhs, const char* rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const char* lhs, const RWStandardCSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCSubString& lhs, char rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(char lhs, const RWStandardCSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCConstSubString& lhs, const std::string& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const std::string& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCConstSubString& lhs, const char* rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const char* lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(const RWStandardCConstSubString& lhs, char rhs)
{
return !(lhs == rhs);
}
inline bool
operator!=(char lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs == rhs);
}
inline bool
operator< (const RWStandardCString& lhs, const RWStandardCString& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const RWStandardCString& lhs, const std::string& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const std::string& lhs, const RWStandardCString& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const RWStandardCString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator< (const RWStandardCString& lhs, const char* rhs): null pointer");
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs, strlen(rhs));
}
inline bool
operator< (const char* lhs, const RWStandardCString& rhs)
{
RW_PRECONDITION2(lhs != rwnil,
"operator< (const char* lhs, const RWStandardCString& rhs): null pointer");
return 0 > rwCStrCompareExact(lhs, strlen(lhs), rhs.data(), rhs.length());
}
inline bool
operator< (const RWStandardCString& lhs, char rhs)
{
return 0 == lhs.length() || lhs(0) < rhs;
}
inline bool
operator< (char lhs, const RWStandardCString& rhs)
{
const size_t len = rhs.length();
return len > 0 && (lhs < rhs(0) || (lhs == rhs(0) && len > 1));
}
inline bool
operator< (const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCSubString& lhs, const std::string& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const std::string& lhs, const RWStandardCSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCSubString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator< (const RWStandardCSubString& lhs, const char* rhs): null pointer");
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs, strlen(rhs));
}
inline bool
operator< (const char* lhs, const RWStandardCSubString& rhs)
{
RW_PRECONDITION2(lhs != rwnil,
"operator< (const char* lhs, const RWStandardCSubString& rhs): null pointer");
return 0 > rwCStrCompareExact(lhs, strlen(lhs), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCSubString& lhs, char rhs)
{
return 0 == lhs.length() || lhs(0) < rhs;
}
inline bool
operator< (char lhs, const RWStandardCSubString& rhs)
{
const size_t len = rhs.length();
return len > 0 && (lhs < rhs(0) || (lhs == rhs(0) && len > 1));
}
inline bool
operator< (const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCConstSubString& lhs, const std::string& rhs)
{
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs.data(), rhs.length());
}
inline bool
operator< (const std::string& lhs, const RWStandardCConstSubString& rhs)
{
return 0 > rwCStrCompareExact(lhs.data(), lhs.length(), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCConstSubString& lhs, const char* rhs)
{
RW_PRECONDITION2(rhs != rwnil,
"operator< (const RWStandardCConstSubString& lhs, const char* rhs): null pointer");
return 0 > rwCStrCompareExact(lhs.startData(), lhs.length(), rhs, strlen(rhs));
}
inline bool
operator< (const char* lhs, const RWStandardCConstSubString& rhs)
{
RW_PRECONDITION2(lhs != rwnil,
"operator< (const char* lhs, const RWStandardCConstSubString& rhs): null pointer");
return 0 > rwCStrCompareExact(lhs, strlen(lhs), rhs.startData(), rhs.length());
}
inline bool
operator< (const RWStandardCConstSubString& lhs, char rhs)
{
return 0 == lhs.length() || lhs(0) < rhs;
}
inline bool
operator< (char lhs, const RWStandardCConstSubString& rhs)
{
const size_t len = rhs.length();
return len > 0 && (lhs < rhs(0) || (lhs == rhs(0) && len > 1));
}
inline bool
operator> (const RWStandardCString& lhs, const RWStandardCString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCString& lhs, const std::string& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const std::string& lhs, const RWStandardCString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCString& lhs, const char* rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const char* lhs, const RWStandardCString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCString& lhs, char rhs)
{
return (rhs < lhs);
}
inline bool
operator> (char lhs, const RWStandardCString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCSubString& lhs, const std::string& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const std::string& lhs, const RWStandardCSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCSubString& lhs, const char* rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const char* lhs, const RWStandardCSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCSubString& lhs, char rhs)
{
return (rhs < lhs);
}
inline bool
operator> (char lhs, const RWStandardCSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCConstSubString& lhs, const std::string& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const std::string& lhs, const RWStandardCConstSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCConstSubString& lhs, const char* rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const char* lhs, const RWStandardCConstSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator> (const RWStandardCConstSubString& lhs, char rhs)
{
return (rhs < lhs);
}
inline bool
operator> (char lhs, const RWStandardCConstSubString& rhs)
{
return (rhs < lhs);
}
inline bool
operator<=(const RWStandardCString& lhs, const RWStandardCString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCString& lhs, const std::string& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const std::string& lhs, const RWStandardCString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCString& lhs, const char* rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const char* lhs, const RWStandardCString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCString& lhs, char rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(char lhs, const RWStandardCString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCSubString& lhs, const std::string& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const std::string& lhs, const RWStandardCSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCSubString& lhs, const char* rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const char* lhs, const RWStandardCSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCSubString& lhs, char rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(char lhs, const RWStandardCSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCConstSubString& lhs, const std::string& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const std::string& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCConstSubString& lhs, const char* rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const char* lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(const RWStandardCConstSubString& lhs, char rhs)
{
return !(lhs > rhs);
}
inline bool
operator<=(char lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs > rhs);
}
inline bool
operator>=(const RWStandardCString& lhs, const RWStandardCString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCSubString& lhs, const RWStandardCString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCConstSubString& lhs, const RWStandardCString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCString& lhs, const std::string& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const std::string& lhs, const RWStandardCString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCString& lhs, const char* rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const char* lhs, const RWStandardCString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCString& lhs, char rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(char lhs, const RWStandardCString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCSubString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCSubString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCConstSubString& lhs, const RWStandardCSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCSubString& lhs, const std::string& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const std::string& lhs, const RWStandardCSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCSubString& lhs, const char* rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const char* lhs, const RWStandardCSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCSubString& lhs, char rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(char lhs, const RWStandardCSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCConstSubString& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCConstSubString& lhs, const std::string& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const std::string& lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCConstSubString& lhs, const char* rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const char* lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(const RWStandardCConstSubString& lhs, char rhs)
{
return !(lhs < rhs);
}
inline bool
operator>=(char lhs, const RWStandardCConstSubString& rhs)
{
return !(lhs < rhs);
}
/**
* @ingroup stl_extension_based_collection_classes
* @brief Function object for hashing an RWCString.
*
* Provides a C++ Standard Library compliant hash function object suitable for
* use with hash or unordered containers.
*/
template <>
struct RWTHash<RWStandardCString> : public std::unary_function<RWStandardCString, size_t> {
/**
* Constructs a hash object instance with the specified comparison
* type.
*/
RWTHash<RWStandardCString>(RWStandardCString::caseCompare cmp = RWStandardCString::exact)
: cmp_(cmp) {}
/**
* Returns a hash of \a obj. This function is the equivalent of calling
*
* @code
* obj.hash(cmp);
* @endcode
*
* Where \a cmp is the comparison type specified at construction.
*/
size_t operator()(const RWStandardCString& obj) const {
return obj.hash(cmp_);
}
private:
RWStandardCString::caseCompare cmp_;
};
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // RW_TOOLS_STDCSTRING_H
|
1f5eeee9f0d13fa8eda8bd807fdd97a0ea919b6b | 9a22fa9d99ad94836e6e27a76509bb9fbd814055 | /src/generator/utils.h | 9ac1c9a0e6772ffa04649c5c77b33ce0cde463fd | [
"MIT"
] | permissive | R0ll1ngSt0ne/qtprotobuf | f5bf4615c6650f4dc22e6486f7df61ed50074939 | ce6f09ffa77fecd35fff84deb798720d870ab3e7 | refs/heads/master | 2020-09-05T11:36:00.769694 | 2019-11-07T19:50:21 | 2019-11-07T19:50:21 | 220,091,876 | 1 | 0 | MIT | 2019-11-06T21:17:32 | 2019-11-06T21:17:31 | null | UTF-8 | C++ | false | false | 2,392 | h | utils.h | /*
* MIT License
*
* Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
*
* This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <list>
#include <algorithm>
namespace google { namespace protobuf {
class FileDescriptor;
}}
namespace QtProtobuf {
namespace generator {
class utils {
public:
static void split(const std::string &str, std::vector<std::string> &container, char delim)
{
container.clear();
std::stringstream stream(str);
std::string token;
while (std::getline(stream, token, delim)) {
container.push_back(token);
}
}
static void replace(std::string &data, const std::string &from, const std::string &to) {
size_t pos = data.find(from);
while (pos != std::string::npos) {
data.replace(pos, from.size(), to);
pos = data.find(from, pos + to.size());
}
}
static void tolower(std::string &str) {
std::transform(std::begin(str), std::end(str), std::begin(str), ::tolower);
}
};
#define UNUSED(expr) do { (void)(expr); } while (0)
using PackagesList = std::unordered_map<std::string/*package*/, std::list<const ::google::protobuf::FileDescriptor *>>;
} //namespace generator
} //namespace QtProtobuf
|
bdd3f297d01eabfcbc72eb5be3555f62d10d98cf | ecbf23209f9a6898f85080702a6b229b60b83444 | /week_8/C++_week8_1108.cpp | 245b56f69ced5e4a80d0edcf199b65ea73bce149 | [] | no_license | jm-zheng/CPP_109-1_class | def8d5e59b1ac969813fe13c179f2e994c2f0f25 | 340f9ae9edebe0bf72f2810447602b112e8384df | refs/heads/master | 2023-03-29T11:40:20.351279 | 2021-03-23T14:15:55 | 2021-03-23T14:15:55 | 315,560,090 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,496 | cpp | C++_week8_1108.cpp | #include<iostream>
#include<cstring>
using namespace std ;
void shifstring(char *str ,int shift);
int checkAnswer( char *sheet ,char *ans);
int checkAnswer( char *sheet ,char *ans);
int power(int , int );
int power2(int *x, int *y);
//--------ex void hello()------------
void hello ()
{
cout << "hello";
return ;
cout << "world";
}
//--------setone-------------
void setone(int *arr ,int len)
{
for (int i=0; i<len ; i++)
{
*(arr+i) = 1;
}
}
int main(){
/* //--------power-------
int a =2,b=10, result=1;
for(int i =0; i<b ;i++)
{
result *=a;
}
cout <<"result" <<result<<endl;
cout<< "power(a,b)"<<power(a,b);*/
//------ex void hello()------------------
//hello();
/* //-----------¶Ç§}----------------------
int a =2,b=5;
cout<< "power2(&a,&b)"<<power2(&a,&b)<<endl;
cout << "a:" << a << " b:" << b;*/
//----------¶Ç°}¦C--------------------------
int a[5];
setone(a,5);
for(int i=0; i<5 ;i++)
{
cout << a[i];
}
/* //-----------hw1----------------
char test[5] , check[5];
cout << "Sheet"<<endl;
for(int i=0 ;i<5; i++)
{
cin >> test[i];
}
cout << "Ans"<<endl;
for(int i=0 ;i<5; i++)
{
cin >> check[i];
}
cout << "point" << checkAnswer(test,check);*/
/* //----------HW2---------------
int arr[100] , brr[100], crr[200] , len =0 ;
cout << "len :";
cin >> len;
for(int i=0 ;i<len; i++)
{
cin >> arr[i];
}
for(int i=0 ;i<len; i++)
{
cin >> brr[i];
}
cout << "crr :";
mix(arr ,brr,crr ,len*2 );
for(int i=0 ;i<len*2; i++)
{
cout<< crr[i]<<" ";
}*/
/* //--------hw3----------------
char arr[100] ;
int sh =0;
cin.get(arr , sizeof(arr));
cout<< "shift : ";
cin>> sh ;
cout << arr <<endl;
shifstring(arr , sh);
cout << arr ;*/
}
int power(int x , int y)
{
int power_result=1 ;
for(int i =0;i<y ;i++)
{
power_result *=x;
}
return power_result;
}
int power2(int *x, int *y)
{
int power_result=1 ;
for(int i =0;i<*y ;i++)
{
power_result *= *x;
}
*x =0;
*y = 0;
return power_result;
}
/*int checkAnswer( char *sheet ,char *ans)
{
int point=0;
for(int i=0 ;i<strlen(sheet); i++)
{
if(*(sheet+i) == *(ans+i))
{
point +=20;
}
}
return point;
}
void mix( int *a, int *b, int *c, int size )
{
int x=0, y=0;
for(int i=0 ;i<size; i++)
{
if( i %2 ==1)
{
*(c+i)= *(a+x);
x+=1;
}
else
{
*(c+i)= *(b+y);
y+=1;
}
}
}
void shifstring(char *str ,int shift)
{
for(int i=0 ;i<strlen(str); i++)
{
*(str+i) = *(str+i) + shift;
}
}*/
|
21ae48ea4a3435d3401bd8deea075659ee4cf557 | 3bb25ad8242c84ca7d5d7927a5f46ac7f15a574b | /BlackJackSimulation/Croupier.cpp | 178f60cbca73d7590ab639762a905e77b8bc2a72 | [] | no_license | KacperBieganek/BlackJackSimulation | 82c2caaae65979891a3fc84cabe3339155164c55 | 37437c2cdf407458d6aa0d7333b855f3598ed1a4 | refs/heads/master | 2021-08-14T20:05:29.013943 | 2017-11-16T13:25:47 | 2017-11-16T13:25:47 | 110,266,584 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 218 | cpp | Croupier.cpp | #include "Croupier.h"
Croupier::Croupier(std::string playerName) : Player(playerName)
{
}
Croupier::~Croupier()
{
}
void Croupier::shouldStand()
{
if (cardsValue >= 17)
stands= true;
else
stands = false;
}
|
8776be8dcf1ba3b5e8ec27e0fdffdc0e031aa70c | f6ad1c5e9736c548ee8d41a7aca36b28888db74a | /luogu/3381-new.cpp | f9e097f67666ff7b40a7860287afb58c1f7930c4 | [] | no_license | cnyali-czy/code | 7fabf17711e1579969442888efe3af6fedf55469 | a86661dce437276979e8c83d8c97fb72579459dd | refs/heads/master | 2021-07-22T18:59:15.270296 | 2021-07-14T08:01:13 | 2021-07-14T08:01:13 | 122,709,732 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,949 | cpp | 3381-new.cpp | #define REP(i, s, e) for (register int i = s; i <= e; i++)
#define DREP(i, s, e) for (register int i = s; i >= e; i--)
#define DEBUG fprintf(stderr, "Passing [%s] in Line %d\n", __FUNCTION__, __LINE__)
#define chkmax(a, b) a = max(a, b)
#define chkmin(a, b) a = min(a, b)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5000 + 10, maxm = 50000 + 10, inf = 1e9;
int bg[maxn], ne[maxm << 1], to[maxm << 1], w[maxm << 1], cost[maxm << 1], e = 1;
inline void add(int x, int y, int z, int c)
{
e++;
to[e] = y;
ne[e] = bg[x];
bg[x] = e;
w[e] = z;
cost[e] = c;
}
template <typename T> T read()
{
T ans = 0, p = 1;
char c = getchar();
while (!isdigit(c))
{
if (c == '-') p = -1;
c = getchar();
}
while (isdigit(c))
{
ans = ans * 10 + c - 48;
c = getchar();
}
return ans * p;
}
int n, m, S, T;
int dis[maxn], pre[maxn], Max[maxn];bool vis[maxn];
queue <int> q;
bool spfa()
{
REP(i, 1, n) vis[i] = 0, dis[i] = inf;
dis[S] = 0;Max[S] = inf;q.push(S);
while (!q.empty())
{
register int x = q.front();vis[x] = 0;q.pop();
for (register int i = bg[x]; i ; i = ne[i])
if (w[i] > 0 && dis[to[i]] > dis[x] + cost[i])
{
dis[to[i]] = dis[x] + cost[i];
Max[to[i]] = min(Max[x], w[i]);
pre[to[i]] = i;
if (!vis[to[i]])
{
vis[to[i]] = 1;
q.push(to[i]);
}
}
}
return dis[T] != inf;
}
int max_flow, min_cost;
void update()
{
max_flow += Max[T];
min_cost += Max[T] * dis[T];
register int x = T;
while (x ^ S)
{
w[pre[x]] -= Max[T];
w[pre[x] ^ 1] += Max[T];
x = to[pre[x] ^ 1];
}
}
int main()
{
#ifdef CraZYali
freopen("3381-new.in", "r", stdin);
freopen("3381-new.out", "w", stdout);
#endif
cin >> n >> m >> S >> T;
while (m --> 0)
{
register int x, y, z, c;
x = read<int>();y = read<int>();z = read<int>();c = read<int>();
add(x, y, z, c);
add(y, x, 0, -c);
}
while (spfa()) update();
cout << max_flow << ' ' << min_cost << endl;
return 0;
}
|
8edb1bc88bd730d89a2fedfa25fa2896ef853092 | 2e65909c4055dbee3ff4b32ac643f1292169296c | /src/ast/function-var.cc | db60b22797010dd110ef716ba0c67a9cfd938c16 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nakrez/RePy | 5bb8ccc1484678a9550dc4a63f9ecf5271ad5608 | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | refs/heads/master | 2021-01-13T01:23:32.478310 | 2013-07-31T12:52:19 | 2013-07-31T12:52:19 | 10,599,366 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,596 | cc | function-var.cc | #include <ast/function-var.hh>
#include <ast/any-list.hh>
namespace ast
{
FunctionVar::FunctionVar(const yy::location& location,
Var* var,
ExprList* params)
: Var(location)
, var_(var)
, params_(params)
, def_(nullptr)
, constructor_(false)
{}
FunctionVar::~FunctionVar()
{
delete var_;
delete params_;
}
const Var* FunctionVar::var_get() const
{
return var_;
}
Var* FunctionVar::var_get()
{
return var_;
}
const ExprList* FunctionVar::params_get() const
{
return params_;
}
ExprList* FunctionVar::params_get()
{
return params_;
}
const FunctionDec* FunctionVar::def_get() const
{
return def_;
}
FunctionDec* FunctionVar::def_get()
{
return def_;
}
bool FunctionVar::constructor_get() const
{
return constructor_;
}
void FunctionVar::constructor_set(bool c)
{
constructor_ = c;
}
void FunctionVar::def_set(FunctionDec* d)
{
def_ = d;
}
void FunctionVar::params_set(ExprList* p)
{
params_ = p;
}
void FunctionVar::add_component(Var* v)
{
if (var_ == nullptr)
{
var_ = v;
return;
}
var_->add_component(v);
}
void FunctionVar::accept(Visitor& v)
{
v(*this);
}
void FunctionVar::accept(ConstVisitor& v) const
{
v(*this);
}
} // namespace ast
|
0394455cf06a4f839eb550d324de83de9e6e1a2c | bb9869148672bd01016830cff0242a3aa8630eab | /Figure.cpp | 37615c473e8ab79c9dfad3365a0b1b1ff74a1288 | [] | no_license | Siegmeyer1/oop_exercise_03 | 90a0e1cc084aaca6fbe032a764571aca07a0ff4b | 7c726c045f48d9ebbfa948b73f9174d445ef133c | refs/heads/master | 2020-08-28T04:56:20.949805 | 2019-10-28T15:04:05 | 2019-10-28T15:04:05 | 217,597,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,540 | cpp | Figure.cpp | #include <iostream>
#include <sstream>
#include <cmath>
#include "Figure.h"
//Методы класса Dot
Dot::Dot() {
x = 0;
y = 0;
}
Dot::Dot(double X, double Y) {
x = X;
y = Y;
}
Dot operator""_dot(const char* str, size_t size) {
std::istringstream is(str);
char tmp;
double x, y;
is >> x >> tmp >> y;
return {x, y};
}
Dot& Dot::operator=(const Dot &A) {
this->x = A.x;
this->y = A.y;
return *this;
}
Dot Dot::operator+(const Dot &A) {
Dot res;
res.x = this->x + A.x;
res.y = this->y + A.y;
return res;
}
Dot Dot::operator-(const Dot &A) {
Dot res;
res.x = this->x - A.x;
res.y = this->y - A.y;
return res;
}
Dot Dot::operator/(const double &A) {
Dot res;
res.x = this->x / A;
res.y = this->y / A;
return res;
}
std::ostream &operator<<(std::ostream &os, const Dot& A) {
os << "(" << A.x << "; " << A.y << ")";
return os;
}
std::istream &operator>>(std::istream &is, Dot& A) {
is >> A.x >> A.y;
return is;
}
double Dot::Length(const Dot &A) {
double res;
res = sqrt(pow(this->x - A.x, 2) + pow(this->y - A.y, 2));
return res;
}
//конец Dot
//Методы класса Octagon
double Octagon::Area() {
double res = 0;
for (size_t i = 0; i < 7; i++) {
res += (coordinates[i].x * coordinates[i+1].y) - (coordinates[i+1].x * coordinates[i].y);
}
/*for (size_t i = 0; i < 7; ++i) {
res += (coordinates[i].y + coordinates[i+1].y) * (coordinates[i+1].x - coordinates[i].x) / 2;
}*/
res = res + (coordinates[7].x * coordinates[0].y) - (coordinates[0].x * coordinates[7].y);
return std::abs(res)/ 2;
}
Dot Octagon::Center() {
Dot res(0, 0);
for (int i = 0; i < 8; ++i) {
res = res + coordinates[i];
}
res = res / 8.0;
return res;
}
void Octagon::PrintOut(std::ostream& os) {
for (int i = 0; i < 8; ++i) {
os << this->coordinates[i];
if (i != 7) {
os << ", ";
}
}
os << '\n';
}
Octagon::Octagon() {
coordinates = new Dot[8];
for (int i = 0; i < 8; ++i) {
coordinates[i] = "0.0 0.0"_dot;
}
}
Octagon::Octagon(std::istream &is) {
coordinates = new Dot[8];
for (size_t i = 0; i < 8; ++i) {
is >> coordinates[i];
}
}
Octagon::~Octagon() {
delete[] this->coordinates;
}
//конец Octagon
//методы класса Triangle
Triangle::Triangle() {
coordinates = new Dot[3];
for (int i = 0; i < 3; ++i) {
coordinates[i] = "0.0 0.0"_dot;
}
}
Triangle::Triangle(std::istream &is) {
coordinates = new Dot[3];
for (size_t i = 0; i < 3; ++i) {
is >> coordinates[i];
}
}
Dot Triangle::Center() {
Dot res(0, 0);
for (int i = 0; i < 3; ++i) {
res = res + coordinates[i];
}
res = res / 3.0;
return res;
}
double Triangle::Area() {
double x1 = this->coordinates[0].x;
double x2 = this->coordinates[1].x;
double x3 = this->coordinates[2].x;
double y1 = this->coordinates[0].y;
double y2 = this->coordinates[1].y;
double y3 = this->coordinates[2].y;
double res = std::abs((x2 - x1)*(y3 - y1) - (x3 - x1)*(y2 - y1)) / 2;
return res;
}
void Triangle::PrintOut(std::ostream& os) {
for (int i = 0; i < 3; ++i) {
os << this->coordinates[i];
if (i != 2) {
os << ", ";
}
}
os << '\n';
}
Triangle::~Triangle() {
delete[] coordinates;
}
//конец Triangle
//методы класса Square
Square::Square() {
coordinates = new Dot[2];
for (int i = 0; i < 2; ++i) {
coordinates[i] = "0.0 0.0"_dot;
}
}
Square::Square(std::istream &is) {
coordinates = new Dot[2];
for (size_t i = 0; i < 2; ++i) {
is >> coordinates[i];
}
}
Dot Square::Center() {
Dot res = (this->coordinates[0] + this->coordinates[1]) / 2;
return res;
}
double Square::Area() {
double res = this->coordinates[0].Length(this->coordinates[1]);
res = pow(res , 2) / 2;
return res;
}
void Square::PrintOut(std::ostream& os) {
Dot C = this->Center();
double tmp;
Dot res[2];
for (int i = 0; i < 2; ++i) {
res[i] = this->coordinates[i];
res[i] = res[i] - C;
tmp = res[i].y;
res[i].y = res[i].x;
res[i].x = -tmp;
res[i] = res[i] + C;
}
os << res[0] << ", " << this->coordinates[0] << ", "
<< res[1] << ", " << this->coordinates[1] << '\n';
}
Square::~Square() {
delete[] coordinates;
} |
c85aedf269c3190ef4984c70f7379cc6fdc98b66 | f77eea859f20b64592890acc5d468d375bd40a5d | /skimmer/scripts/unused/iDM_datacard_maker.cpp | 958dade7eb7bf17a360e05c96193371471a148d1 | [] | no_license | afrankenthal/iDMAnalysis | 9d8e3e9c32b04449f3b02ed8143b98b2e6edd681 | a632c58e0cc630bb2c0d28aa6f9fe136497dcae0 | refs/heads/master | 2023-05-02T21:27:58.734768 | 2021-06-02T21:03:28 | 2021-06-02T21:03:28 | 148,357,937 | 1 | 3 | null | 2021-03-03T05:48:17 | 2018-09-11T17:59:15 | C++ | UTF-8 | C++ | false | false | 1,897 | cpp | iDM_datacard_maker.cpp | #include <string>
#include <iostream>
#include "CombineHarvester/CombineTools/interface/CombineHarvester.h"
#include "CombineHarvester/CombineTools/interface/Systematics.h"
using namespace std;
int main() {
//! [part1]
// Define four categories labelled A, B, C and D, and
// set the observed yields in a map.
ch::Categories cats = {
{0, "A"},
{1, "B"},
{2, "C"},
{3, "D"}
};
std::map<std::string, float> obs_rates = {
{"A", 688.},
{"B", 60.},
{"C", 5.},
{"D", 1.}
};
std::map<std::string, float> sig_rates = {
{"A", 10.61},
{"B", 0.},
{"C", 6.56},
{"D", 0.}
};
//! [part1]
//! [part2]
ch::CombineHarvester cb;
cb.SetVerbosity(3);
cb.AddObservations({"*"}, {""}, {"13TeV"}, {""}, cats);
cb.AddProcesses( {"*"}, {""}, {"13TeV"}, {""}, {"sig"}, cats, true);
cb.AddProcesses( {"*"}, {""}, {"13TeV"}, {""}, {"bkg"}, cats, false);
cb.ForEachObs([&](ch::Observation *x) {
x->set_rate(obs_rates[x->bin()]);
});
cb.cp().backgrounds().ForEachProc([](ch::Process *x) {
x->set_rate(1);
});
cb.cp().signals().ForEachProc([&](ch::Process *x) {
x->set_rate(sig_rates[x->bin()]);
});
//! [part2]
//! [part3]
using ch::syst::SystMap;
using ch::syst::SystMapFunc;
using ch::syst::bin;
// Add a traditional lnN systematic
//cb.cp().bin({"D"}).AddSyst(cb, "DummySys", "lnN", SystMap<>::init(1.0001));
// Create a unqiue floating parameter in each bin
cb.cp().backgrounds().bin({"A", "B", "C", "D"}).AddSyst(cb, "bkgA_norm", "rateParam", SystMap<>::init(688));
cb.cp().backgrounds().bin({"B", "D"}).AddSyst(cb, "c1", "rateParam", SystMap<>::init(0.087));
cb.cp().backgrounds().bin({"C", "D"}).AddSyst(cb, "c2", "rateParam", SystMap<>::init(0.0072));
//! [part3]
//! [part4]
cb.PrintAll();
cb.WriteDatacard("iDM_datacard.txt");
//! [part4]
}
|
ab297be7dae6abf06390b01208684a80f2c77806 | 512e8c94de4c7d4b7f68aa85cc0e026edf9edd69 | /3DManipulator/Types.h | d1c4da19fe3df02dbfb38228b49074a2321fa7d0 | [] | no_license | CapObvios/3D-Manipulator | 3e2d2903e1527309358aaf451d34579360bd435f | ce50c6874adb7e42e1e224458657cc7d4cca1bd3 | refs/heads/master | 2021-03-21T23:55:13.766592 | 2018-03-03T10:09:10 | 2018-03-03T10:09:10 | 110,299,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,520 | h | Types.h | #pragma once
#include <Windows.h>
#include "cube.h"
#include "dodecahedron.h"
#include "icosahedron.h"
#include "octahedron.h"
#include "tetrahedron.h"
#include "sphere.h"
#include "torus.hpp"
namespace Types {
using namespace System::Collections::Generic;
enum coordType
{
X = 0, Y = 1, Z = 2
};
enum permutationType
{
Move,
Rotate,
RotateGlobal,
Resize
};
enum objectType
{
Tet,
Cub,
Dod,
Ico,
Oct,
Sph,
Tor
};
ref class Point3D
{
public:
float X, Y, Z;
Point3D() : X(0), Y(0), Z(0) { }
Point3D(float x, float y, float z) : X(x), Y(y), Z(z) { }
Point3D(array<float,1>^ p) : X(p[0]), Y(p[1]), Z(p[2]) { }
Point3D(Point3D^ p) : X(p->X), Y(p->Y), Z(p->Z) { }
Point3D(Point3D% p) : X(p.X), Y(p.Y), Z(p.Z) { }
Point3D% operator= (Point3D^ right)
{
if (this == right)
return *this;
X = right->X;
Y = right->Y;
Z = right->Z;
return *this;
}
Point3D% operator+(Point3D^ right)
{
return Point3D(right->X + this->X, right->Y + this->Y, right->Z + this->Z);
}
Point3D% operator/(float divisor)
{
return Point3D(this->X / divisor, this->Y / divisor, this->Z / divisor);
}
array<float>^ GetVector()
{
return gcnew array<float>(3) { X, Y, Z };
}
};
ref class Polygon
{
public:
Point3D K, L, M;
Polygon() : K(), L(), M() { }
Polygon(Point3D^ k, Point3D^ l, Point3D^ m)
{
K = k;
L = l;
M = m;
}
array<array<float>^>^ getMatrix()
{
auto res = gcnew array<array<float>^>(3);
res[0] = K.GetVector();
res[1] = L.GetVector();
res[2] = M.GetVector();
return res;
}
};
ref class GeometryObj
{
public:
List<Polygon^>^ Polygons;
List<array<array<float>^>^>^ getMatrices(objectType type)
{
const int SizeFactor = 100;
const vertex* vertices = dod_vertices;
const uint32_t* vertex_indices = dod_indices;
int vertexCount = dod_vcount;
int vertexICount = dod_icount;
switch (type)
{
case Types::Tet:
vertices = tet_vertices;
vertex_indices = tet_indices;
vertexCount = tet_vcount;
vertexICount = tet_icount;
break;
case Types::Cub:
vertices = cub_vertices;
vertex_indices = cub_indices;
vertexCount = cub_vcount;
vertexICount = cub_icount;
break;
case Types::Dod:
vertices = dod_vertices;
vertex_indices = dod_indices;
vertexCount = dod_vcount;
vertexICount = dod_icount;
break;
case Types::Ico:
vertices = ico_vertices;
vertex_indices = ico_indices;
vertexCount = ico_vcount;
vertexICount = ico_icount;
break;
case Types::Oct:
vertices = oct_vertices;
vertex_indices = oct_indices;
vertexCount = oct_vcount;
vertexICount = oct_icount;
break;
case Types::Sph:
vertices = sph_vertices;
vertex_indices = sph_indices;
vertexCount = sph_vcount;
vertexICount = sph_icount;
break;
case Types::Tor:
vertices = tor_vertices;
vertex_indices = tor_indices;
vertexCount = tor_vcount;
vertexICount = tor_icount;
break;
default:
break;
}
auto res = gcnew List<array<array<float>^>^>(vertexCount);
for (size_t i = 0; i < vertexICount; i+=3)
{
array<array<float>^>^ poly = gcnew array<array<float>^>(3);
for (size_t j = 0; j < 3; j++)
{
// numeration of sphere and torus vertex indices starts from 0, meanwhile all the other figures (decompiled from .obj type) start from 1
// ideally later they have to be lead to the same type, but just for now I did this quickfix due to the lack of time.
auto ver = vertices[vertex_indices[i + j] - (type == objectType::Sph || type == objectType::Tor ? 0 : 1) ].coords;
poly[j] = gcnew array<float>(3) { ver[0]*SizeFactor, ver[1]*SizeFactor, ver[2] * SizeFactor };
}
res->Add(poly);
}
/*for each (auto pol in Polygons)
{
res->Add(pol->getMatrix());
}*/
return res;
}
};
ref class PlaneEquation
{
public:
PlaneEquation(Point3D^ A, Point3D^ B, Point3D^ C)
{
X = (B->Y - A->Y)*(C->Z - A->Z) - (B->Z - A->Z)*(C->Y - A->Y);
Y = -(B->X - A->X)*(C->Z - A->Z) + (B->Z - A->Z)*(C->X - A->X);
Z = (B->X - A->X)*(C->Y - A->Y) - (B->Y - A->Y)*(C->X - A->X);
D = -A->X*X - A->Y*Y - A->Z*Z;
/*while ((int)X % 10 == 0 && (int)Y % 10 == 0 && (int)Z % 10 == 0 && (int)D % 10 == 0)
{
X /=10;
Y /=10;
Z /=10;
D /=10;
}*/
};
double X, Y, Z, D;
float GetZCoord(System::Drawing::Point p)
{
return (-D - X*p.X - Y*p.Y) / Z;
}
};
} |
a9c59c579b24822fc0c0bcb299afba08f4396860 | b27918300a880451f67287820082a1756514972a | /check/TestLpSolvers.cpp | 6468dc60b99bbfeca394dd69e8f77767bfb4b089 | [
"MIT"
] | permissive | AnupGoenka/HiGHS | 6c14aa1dc9d65278c7f104e82c87e602d62d3255 | 2c013a8fcd009b7df01e3d6655274e84d234fa2f | refs/heads/master | 2023-05-11T01:45:45.134579 | 2021-05-17T14:54:55 | 2021-05-17T14:54:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,640 | cpp | TestLpSolvers.cpp | #include "Highs.h"
#include "catch.hpp"
const bool dev_run = false;
struct IterationCount {
int simplex;
int ipm;
int crossover;
};
void testSolver(Highs& highs, const std::string solver,
IterationCount& default_iteration_count,
const int int_simplex_strategy = 0) {
double default_time_limit;
int default_simplex_iteration_limit;
int default_ipm_iteration_limit;
HighsModelStatus model_status;
HighsStatus return_status;
const bool perform_timeout_test = false; // true; //
const bool use_simplex = solver == "simplex";
const HighsInfo& info = highs.getHighsInfo();
return_status = highs.setHighsOptionValue("solver", solver);
REQUIRE(return_status == HighsStatus::OK);
if (use_simplex) {
SimplexStrategy simplex_strategy =
static_cast<SimplexStrategy>(int_simplex_strategy);
if (simplex_strategy == SimplexStrategy::SIMPLEX_STRATEGY_DUAL_TASKS)
return;
if (dev_run) printf("Simplex strategy %d\n", int_simplex_strategy);
return_status =
highs.setHighsOptionValue("simplex_strategy", simplex_strategy);
REQUIRE(return_status == HighsStatus::OK);
}
return_status = highs.getHighsOptionValue("time_limit", default_time_limit);
REQUIRE(return_status == HighsStatus::OK);
if (use_simplex) {
return_status = highs.getHighsOptionValue("simplex_iteration_limit",
default_simplex_iteration_limit);
REQUIRE(return_status == HighsStatus::OK);
// Force HiGHS to start from a logical basis - if this is the
// second or subsequent call to testSolver
return_status = highs.setBasis();
REQUIRE(return_status == HighsStatus::OK);
} else {
return_status = highs.getHighsOptionValue("ipm_iteration_limit",
default_ipm_iteration_limit);
REQUIRE(return_status == HighsStatus::OK);
}
// Vanilla solve: get solution time to calibrate time limit test
double run_time = highs.getHighsRunTime();
return_status = highs.run();
REQUIRE(return_status == HighsStatus::OK);
const double single_solve_run_time = highs.getHighsRunTime() - run_time;
if (use_simplex) {
REQUIRE(info.simplex_iteration_count == default_iteration_count.simplex);
} else {
if (dev_run)
printf("IPM: %d; Crossover: %d\n", info.ipm_iteration_count,
info.crossover_iteration_count);
REQUIRE(info.ipm_iteration_count == default_iteration_count.ipm);
REQUIRE(info.crossover_iteration_count ==
default_iteration_count.crossover);
}
// Only perform the time limit test if the solve time is large enough
const double min_run_time_for_test = 0.001;
if (perform_timeout_test && single_solve_run_time > min_run_time_for_test) {
const int ideal_num_solve = 10;
const double local_time_limit = ideal_num_solve * single_solve_run_time;
// Solve with time limit
run_time = highs.getHighsRunTime();
if (dev_run) printf("Current run time is %g\n", run_time);
double use_time_limit = run_time + local_time_limit;
return_status = highs.setHighsOptionValue("time_limit", use_time_limit);
REQUIRE(return_status == HighsStatus::OK);
const int max_num_solve = 10 * ideal_num_solve;
int num_solve;
for (num_solve = 0; num_solve < max_num_solve; num_solve++) {
if (use_simplex) return_status = highs.setBasis();
return_status = highs.run();
if (highs.getModelStatus() == HighsModelStatus::REACHED_TIME_LIMIT) break;
}
REQUIRE(num_solve < max_num_solve);
run_time = highs.getHighsRunTime();
if (dev_run)
printf("Current run time is %g: time limit is %g (difference = %g)\n",
run_time, use_time_limit, run_time - use_time_limit);
if (dev_run)
printf("Required %d solves (ideally %d - max %d)\n", num_solve,
ideal_num_solve, max_num_solve);
} else {
if (dev_run)
printf(
"Not performed the time limit test since solve time is %g <= %g = "
"min_run_time_for_test\n",
single_solve_run_time, min_run_time_for_test);
}
return_status = highs.setHighsOptionValue("time_limit", default_time_limit);
REQUIRE(return_status == HighsStatus::OK);
if (!use_simplex) {
if (dev_run)
printf("IPM: %d; Crossover: %d\n", info.ipm_iteration_count,
info.crossover_iteration_count);
}
// Solve with iteration limit
// First of all check that no iterations are performed if the
// iteration limit is zero
if (use_simplex) {
return_status = highs.setHighsOptionValue("simplex_iteration_limit", 0);
REQUIRE(return_status == HighsStatus::OK);
return_status = highs.setBasis();
REQUIRE(return_status == HighsStatus::OK);
} else {
return_status = highs.setHighsOptionValue("ipm_iteration_limit", 0);
REQUIRE(return_status == HighsStatus::OK);
}
return_status = highs.run();
model_status = highs.getModelStatus();
if (dev_run)
printf("Returns status = %d; model status = %s\n", (int)return_status,
highs.highsModelStatusToString(model_status).c_str());
REQUIRE(return_status == HighsStatus::Warning);
REQUIRE(model_status == HighsModelStatus::REACHED_ITERATION_LIMIT);
if (use_simplex) {
REQUIRE(info.simplex_iteration_count == 0);
} else {
REQUIRE(info.ipm_iteration_count == 0);
}
// Now check that simplex/IPM stops after 10/5 iterations
const int further_simplex_iterations = 10;
const int further_ipm_iterations = 5;
if (use_simplex) {
if (dev_run)
printf("Setting simplex_iteration_limit = %d\n",
further_simplex_iterations);
return_status = highs.setHighsOptionValue("simplex_iteration_limit",
further_simplex_iterations);
REQUIRE(return_status == HighsStatus::OK);
return_status = highs.setBasis();
REQUIRE(return_status == HighsStatus::OK);
} else {
if (dev_run)
printf("Setting ipm_iteration_limit = %d\n", further_ipm_iterations);
return_status = highs.setHighsOptionValue("ipm_iteration_limit",
further_ipm_iterations);
REQUIRE(return_status == HighsStatus::OK);
}
return_status = highs.run();
REQUIRE(return_status == HighsStatus::Warning);
REQUIRE(highs.getModelStatus() == HighsModelStatus::REACHED_ITERATION_LIMIT);
if (use_simplex) {
REQUIRE(info.simplex_iteration_count == further_simplex_iterations);
return_status = highs.setHighsOptionValue("simplex_iteration_limit",
default_simplex_iteration_limit);
REQUIRE(return_status == HighsStatus::OK);
} else {
REQUIRE(info.ipm_iteration_count == further_ipm_iterations);
return_status = highs.setHighsOptionValue("ipm_iteration_limit",
default_ipm_iteration_limit);
REQUIRE(return_status == HighsStatus::OK);
}
}
void testSolversSetup(const std::string model,
IterationCount& model_iteration_count,
vector<int>& simplex_strategy_iteration_count) {
if (model.compare("adlittle") == 0) {
simplex_strategy_iteration_count[(
int)SimplexStrategy::SIMPLEX_STRATEGY_CHOOSE] = 72;
simplex_strategy_iteration_count[(
int)SimplexStrategy::SIMPLEX_STRATEGY_DUAL_PLAIN] = 72;
simplex_strategy_iteration_count[(
int)SimplexStrategy::SIMPLEX_STRATEGY_DUAL_TASKS] = 72;
simplex_strategy_iteration_count[(
int)SimplexStrategy::SIMPLEX_STRATEGY_DUAL_MULTI] = 73;
simplex_strategy_iteration_count[(
int)SimplexStrategy::SIMPLEX_STRATEGY_PRIMAL] = 94;
model_iteration_count.ipm = 18;
model_iteration_count.crossover = 4;
}
}
void testSolvers(Highs& highs, IterationCount& model_iteration_count,
const vector<int>& simplex_strategy_iteration_count) {
bool have_omp = false;
#ifdef OPENMP
have_omp = true;
#endif
/*
int i = (int)SimplexStrategy::SIMPLEX_STRATEGY_PRIMAL;
model_iteration_count.simplex = simplex_strategy_iteration_count[i];
testSolver(highs, "simplex", model_iteration_count, i);
*/
int from_i = (int)SimplexStrategy::SIMPLEX_STRATEGY_MIN;
int to_i = (int)SimplexStrategy::SIMPLEX_STRATEGY_NUM;
for (int i = from_i; i < to_i; i++) {
if (!have_omp) {
if (i == (int)SimplexStrategy::SIMPLEX_STRATEGY_DUAL_TASKS) continue;
if (i == (int)SimplexStrategy::SIMPLEX_STRATEGY_DUAL_MULTI) continue;
}
model_iteration_count.simplex = simplex_strategy_iteration_count[i];
testSolver(highs, "simplex", model_iteration_count, i);
}
testSolver(highs, "ipm", model_iteration_count);
}
// No commas in test case name.
TEST_CASE("LP-solver", "[highs_lp_solver]") {
std::string model;
std::string model_file;
IterationCount model_iteration_count;
vector<int> simplex_strategy_iteration_count;
simplex_strategy_iteration_count.resize(
(int)SimplexStrategy::SIMPLEX_STRATEGY_NUM);
HighsOptions options;
HighsLp lp;
// HighsStatus run_status;
HighsStatus return_status;
HighsStatus read_status;
Highs highs(options);
if (!dev_run) {
highs.setHighsLogfile();
highs.setHighsOutput();
}
// Read mps
model = "adlittle";
model_file = std::string(HIGHS_DIR) + "/check/instances/" + model + ".mps";
testSolversSetup(model, model_iteration_count,
simplex_strategy_iteration_count);
return_status = highs.setHighsOptionValue("model_file", model_file);
REQUIRE(return_status == HighsStatus::OK);
read_status = highs.readModel(model_file);
REQUIRE(read_status == HighsStatus::OK);
return_status = highs.setBasis();
REQUIRE(return_status == HighsStatus::OK);
return_status = highs.run();
REQUIRE(return_status == HighsStatus::OK);
testSolvers(highs, model_iteration_count, simplex_strategy_iteration_count);
// Now check that we can change model within the same Highs instance
// First reset all the options to their default values
return_status = highs.resetHighsOptions();
REQUIRE(return_status == HighsStatus::OK);
model_file = std::string(HIGHS_DIR) + "/check/instances/etamacro.mps";
return_status = highs.setHighsOptionValue("model_file", model_file);
REQUIRE(return_status == HighsStatus::OK);
read_status = highs.readModel(model_file);
REQUIRE(read_status == HighsStatus::OK);
return_status = highs.setBasis();
REQUIRE(return_status == HighsStatus::OK);
return_status = highs.run();
REQUIRE(return_status == HighsStatus::OK);
const HighsInfo& info = highs.getHighsInfo();
REQUIRE(info.num_dual_infeasibilities == 1);
REQUIRE(info.simplex_iteration_count == 370);
HighsModelStatus model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::NOTSET);
model_status = highs.getModelStatus(true);
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
}
TEST_CASE("dual-objective-upper-bound", "[highs_lp_solver]") {
std::string filename;
HighsStatus status;
HighsModelStatus model_status;
bool bool_status;
const double min_objective_function_value = -11.6389290663705;
const double max_objective_function_value = 111.650960689315;
const double smaller_min_dual_objective_value_upper_bound = -110.0;
const double larger_min_dual_objective_value_upper_bound = -45.876;
const double use_max_dual_objective_value_upper_bound = 150.0;
double save_dual_objective_value_upper_bound;
HighsOptions options;
Highs highs(options);
if (!dev_run) {
highs.setHighsLogfile();
highs.setHighsOutput();
}
const HighsInfo& info = highs.getHighsInfo();
// status = highs.setHighsOptionValue("message_level", 7);REQUIRE(status ==
// HighsStatus::OK);
double error;
filename = std::string(HIGHS_DIR) + "/check/instances/e226.mps";
status = highs.setHighsOptionValue("model_file", filename);
REQUIRE(status == HighsStatus::OK);
// Solve vanilla
if (dev_run) printf("\nSolving vanilla LP\n");
status = highs.run();
REQUIRE(status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
error = fabs((info.objective_function_value - min_objective_function_value) /
min_objective_function_value);
if (dev_run) printf("\nOptimal objective value error = %g\n", error);
REQUIRE(error < 1e-14);
// Set dual objective value upper bound after saving the default value
status = highs.getHighsOptionValue("dual_objective_value_upper_bound",
save_dual_objective_value_upper_bound);
REQUIRE(status == HighsStatus::OK);
status =
highs.setHighsOptionValue("dual_objective_value_upper_bound",
larger_min_dual_objective_value_upper_bound);
REQUIRE(status == HighsStatus::OK);
// Solve again
if (dev_run)
printf(
"\nSolving LP with presolve and dual objective value upper bound of "
"%g\n",
larger_min_dual_objective_value_upper_bound);
status = highs.setBasis();
REQUIRE(status == HighsStatus::OK);
status = highs.run();
REQUIRE(status == HighsStatus::OK);
// Switch off presolve
status = highs.setHighsOptionValue("presolve", "off");
REQUIRE(status == HighsStatus::OK);
// Solve again
// This larger dual objective value upper bound is satisfied during phase 2
if (dev_run)
printf(
"\nSolving LP without presolve and larger dual objective value upper "
"bound of %g\n",
larger_min_dual_objective_value_upper_bound);
status = highs.setBasis();
REQUIRE(status == HighsStatus::OK);
status = highs.run();
REQUIRE(status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status ==
HighsModelStatus::REACHED_DUAL_OBJECTIVE_VALUE_UPPER_BOUND);
// Solve again
// This smaller dual objective value upper bound is satisfied at the start of
// phase 2
if (dev_run)
printf(
"\nSolving LP without presolve and smaller dual objective value upper "
"bound of %g\n",
smaller_min_dual_objective_value_upper_bound);
status =
highs.setHighsOptionValue("dual_objective_value_upper_bound",
smaller_min_dual_objective_value_upper_bound);
REQUIRE(status == HighsStatus::OK);
status = highs.setBasis();
REQUIRE(status == HighsStatus::OK);
status = highs.run();
REQUIRE(status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status ==
HighsModelStatus::REACHED_DUAL_OBJECTIVE_VALUE_UPPER_BOUND);
// Solve as maximization and ensure that the dual objective value upper bound
// isn't used
bool_status = highs.changeObjectiveSense(ObjSense::MAXIMIZE);
REQUIRE(bool_status);
status = highs.setHighsOptionValue("dual_objective_value_upper_bound",
use_max_dual_objective_value_upper_bound);
REQUIRE(status == HighsStatus::OK);
// Solve again
if (dev_run)
printf(
"\nSolving LP as maximization without presolve and dual objective "
"value "
"upper bound of %g\n",
use_max_dual_objective_value_upper_bound);
status = highs.setBasis();
REQUIRE(status == HighsStatus::OK);
status = highs.run();
REQUIRE(status == HighsStatus::OK);
model_status = highs.getModelStatus();
REQUIRE(model_status == HighsModelStatus::OPTIMAL);
error = fabs((info.objective_function_value - max_objective_function_value) /
max_objective_function_value);
if (dev_run) printf("\nOptimal objective value error = %g\n", error);
REQUIRE(error < 1e-14);
}
|
c6b1fddccc10f51606bc8dbfcecc67473a1f2c77 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-apigatewaymanagementapi/include/aws/apigatewaymanagementapi/model/GetConnectionResult.h | 0eb468302828f1fb44ac14f3a85761bfc6d03b77 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 4,440 | h | GetConnectionResult.h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/apigatewaymanagementapi/ApiGatewayManagementApi_EXPORTS.h>
#include <aws/core/utils/DateTime.h>
#include <aws/apigatewaymanagementapi/model/Identity.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace ApiGatewayManagementApi
{
namespace Model
{
class GetConnectionResult
{
public:
AWS_APIGATEWAYMANAGEMENTAPI_API GetConnectionResult();
AWS_APIGATEWAYMANAGEMENTAPI_API GetConnectionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_APIGATEWAYMANAGEMENTAPI_API GetConnectionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The time in ISO 8601 format for when the connection was established.</p>
*/
inline const Aws::Utils::DateTime& GetConnectedAt() const{ return m_connectedAt; }
/**
* <p>The time in ISO 8601 format for when the connection was established.</p>
*/
inline void SetConnectedAt(const Aws::Utils::DateTime& value) { m_connectedAt = value; }
/**
* <p>The time in ISO 8601 format for when the connection was established.</p>
*/
inline void SetConnectedAt(Aws::Utils::DateTime&& value) { m_connectedAt = std::move(value); }
/**
* <p>The time in ISO 8601 format for when the connection was established.</p>
*/
inline GetConnectionResult& WithConnectedAt(const Aws::Utils::DateTime& value) { SetConnectedAt(value); return *this;}
/**
* <p>The time in ISO 8601 format for when the connection was established.</p>
*/
inline GetConnectionResult& WithConnectedAt(Aws::Utils::DateTime&& value) { SetConnectedAt(std::move(value)); return *this;}
inline const Identity& GetIdentity() const{ return m_identity; }
inline void SetIdentity(const Identity& value) { m_identity = value; }
inline void SetIdentity(Identity&& value) { m_identity = std::move(value); }
inline GetConnectionResult& WithIdentity(const Identity& value) { SetIdentity(value); return *this;}
inline GetConnectionResult& WithIdentity(Identity&& value) { SetIdentity(std::move(value)); return *this;}
/**
* <p>The time in ISO 8601 format for when the connection was last active.</p>
*/
inline const Aws::Utils::DateTime& GetLastActiveAt() const{ return m_lastActiveAt; }
/**
* <p>The time in ISO 8601 format for when the connection was last active.</p>
*/
inline void SetLastActiveAt(const Aws::Utils::DateTime& value) { m_lastActiveAt = value; }
/**
* <p>The time in ISO 8601 format for when the connection was last active.</p>
*/
inline void SetLastActiveAt(Aws::Utils::DateTime&& value) { m_lastActiveAt = std::move(value); }
/**
* <p>The time in ISO 8601 format for when the connection was last active.</p>
*/
inline GetConnectionResult& WithLastActiveAt(const Aws::Utils::DateTime& value) { SetLastActiveAt(value); return *this;}
/**
* <p>The time in ISO 8601 format for when the connection was last active.</p>
*/
inline GetConnectionResult& WithLastActiveAt(Aws::Utils::DateTime&& value) { SetLastActiveAt(std::move(value)); return *this;}
inline const Aws::String& GetRequestId() const{ return m_requestId; }
inline void SetRequestId(const Aws::String& value) { m_requestId = value; }
inline void SetRequestId(Aws::String&& value) { m_requestId = std::move(value); }
inline void SetRequestId(const char* value) { m_requestId.assign(value); }
inline GetConnectionResult& WithRequestId(const Aws::String& value) { SetRequestId(value); return *this;}
inline GetConnectionResult& WithRequestId(Aws::String&& value) { SetRequestId(std::move(value)); return *this;}
inline GetConnectionResult& WithRequestId(const char* value) { SetRequestId(value); return *this;}
private:
Aws::Utils::DateTime m_connectedAt;
Identity m_identity;
Aws::Utils::DateTime m_lastActiveAt;
Aws::String m_requestId;
};
} // namespace Model
} // namespace ApiGatewayManagementApi
} // namespace Aws
|
f68a5459d52795394d35bdc28dc6c9472e11e87f | 6623b8a5906669a92df0d328b0928e3ea24106a0 | /CachingMessageQueue/mq_efficient.h | bd2157573510d7a770018b2bae96c4907c8dff35 | [
"MIT"
] | permissive | KnowSheet/Sandbox | ae35e63a84dfa3ed3e5511b1c01a82cc855173f7 | 9428a46922893b9e5ea819df272655b6c5a28e67 | refs/heads/master | 2021-01-23T07:03:54.437643 | 2015-02-20T22:00:59 | 2015-02-20T22:00:59 | 27,014,012 | 0 | 1 | null | 2015-02-20T22:00:59 | 2014-11-22T22:03:02 | C++ | UTF-8 | C++ | false | false | 6,850 | h | mq_efficient.h | #ifndef SANDBOX_MQ_EFFICIENT_H
#define SANDBOX_MQ_EFFICIENT_H
// EfficientMQ is an efficient in-memory layer to buffer logged events before exporting them.
// Intent: To buffer events before they get to be send over the network or appended to a log file.
// Objective: To miminize the time during which the thread that emits the message to be logged is blocked.
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
template <typename CONSUMER, typename MESSAGE = std::string, size_t DEFAULT_BUFFER_SIZE = 1024>
class EfficientMQ final {
public:
// Type of entries to store, defaults to `std::string`.
typedef MESSAGE T_MESSAGE;
// Type of the processor of the entries.
// It should expose one method, void OnMessage(const T_MESSAGE&, size_t number_of_dropped_events_if_any);
// This method will be called from one thread, which is spawned and owned by an instance of EfficientMQ.
typedef CONSUMER T_CONSUMER;
// The only constructor requires the refence to the instance of the consumer of entries.
explicit EfficientMQ(T_CONSUMER& consumer, size_t buffer_size = DEFAULT_BUFFER_SIZE)
: consumer_(consumer),
circular_buffer_size_(buffer_size),
circular_buffer_(circular_buffer_size_),
consumer_thread_(&EfficientMQ::ConsumerThread, this) {
}
// Destructor waits for the consumer thread to terminate, which implies committing all the queued events.
~EfficientMQ() {
{
std::unique_lock<std::mutex> lock(mutex_);
destructing_ = true;
}
condition_variable_.notify_all();
consumer_thread_.join();
}
// Adds an message to the buffer.
// Supports both copy and move semantics.
// THREAD SAFE. Blocks the calling thread for as short period of time as possible.
void PushMessage(const T_MESSAGE& message) {
const size_t index = PushEventAllocate();
circular_buffer_[index].message_body = message;
PushEventCommit(index);
}
void PushMessage(T_MESSAGE&& message) {
const size_t index = PushEventAllocate(message);
circular_buffer_[index].message_body = std::move(message);
PushEventCommit(index);
}
private:
EfficientMQ(const EfficientMQ&) = delete;
EfficientMQ(EfficientMQ&&) = delete;
void operator=(const EfficientMQ&) = delete;
void operator=(EfficientMQ&&) = delete;
// Increment the index respecting the circular nature of the buffer.
void Increment(size_t& i) const {
i = (i + 1) % circular_buffer_size_;
}
// The thread which extracts fully populated events from the tail of the buffer and exports them.
void ConsumerThread() {
while (true) {
size_t index;
size_t this_time_dropped_events;
{
// First, get an message to export. Wait until it's finalized and ready to be exported.
// MUTEX-LOCKED, except for the conditional variable part.
index = tail_;
std::unique_lock<std::mutex> lock(mutex_);
if (head_ready_ == tail_) {
if (destructing_) {
return;
}
condition_variable_.wait(lock, [this] { return head_ready_ != tail_ || destructing_; });
if (destructing_) {
return;
}
}
this_time_dropped_events = number_of_dropped_events_;
number_of_dropped_events_ = 0;
}
{
// Then, export the message.
// NO MUTEX REQUIRED.
consumer_.OnMessage(circular_buffer_[index].message_body, this_time_dropped_events);
}
{
// Finally, mark the message as successfully exported.
// MUTEX-LOCKED.
std::lock_guard<std::mutex> lock(mutex_);
Increment(tail_);
}
}
}
size_t PushEventAllocate() {
// First, allocate room in the buffer for this message.
// Overwrite the oldest message if have to.
// MUTEX-LOCKED.
std::lock_guard<std::mutex> lock(mutex_);
const size_t index = head_allocated_;
Increment(head_allocated_);
if (head_allocated_ == tail_) {
// Buffer overflow, must drop the least recent element and keep the count of those.
++number_of_dropped_events_;
if (tail_ == head_ready_) {
Increment(head_ready_);
}
Increment(tail_);
}
// Mark this message as incomplete, not yet ready to be sent over to the consumer.
circular_buffer_[index].finalized = false;
return index;
}
void PushEventCommit(const size_t index) {
// After the message has been copied over, mark it as finalized and advance `head_ready_`.
// MUTEX-LOCKED.
std::lock_guard<std::mutex> lock(mutex_);
circular_buffer_[index].finalized = true;
while (head_ready_ != head_allocated_ && circular_buffer_[head_ready_].finalized) {
Increment(head_ready_);
}
condition_variable_.notify_all();
}
// The instance of the consuming side of the FIFO buffer.
T_CONSUMER& consumer_;
// The capacity of the circular buffer for intermediate events.
// Events beyond it will be dropped.
const size_t circular_buffer_size_;
// The `Entry` struct keeps the entries along with the flag describing whether the message is done being
// populated and thus is ready to be exported. The flag is neccesary, since the message at index `i+1` might
// chronologically get finalized before the message at index `i` does.
struct Entry {
T_MESSAGE message_body;
bool finalized;
};
// The circular buffer, of size `circular_buffer_size_`.
std::vector<Entry> circular_buffer_;
// The number of events that have been overwritten due to buffer overflow.
size_t number_of_dropped_events_ = 0;
// The thread in which the consuming process is running.
std::thread consumer_thread_;
// To minimize the time for which the message emitting thread is blocked for,
// the buffer uses three "pointers":
// 1) `tail_`: The index of the next element to be exported and removed from the buffer.
// 2) `head_ready_`: The successor of the index of the element that is the last finalized element.
// 3) `head_allocated_`: The index of the first unallocated element,
// into which the next message will be written.
// The order of "pointers" is always tail_ <= head_ready_ <= head_allocated_.
// The range [tail_, head_ready_) is what is ready to be extracted and sent over.
// The range [head_ready_, head_allocated_) is the "grey area", where the entries are already
// assigned indexes, but their population, done by respective client threads, is not done yet.
// All three indexes are guarded by one mutex. (This can be improved, but meh. -- D.K.)
size_t tail_ = 0;
size_t head_ready_ = 0;
size_t head_allocated_ = 0;
std::mutex mutex_;
std::condition_variable condition_variable_;
// For safe thread destruction.
bool destructing_ = false;
};
#endif // SANDBOX_MQ_EFFICIENT_H
|
3e54eeba22777f65d30dade85e52c20db2725776 | 928863f83611e4cd3256f58c0c0199b72baefabb | /3rd_party_libs/chai3d_a4/src/display/CCamera.h | eae79d78509c69aec7460e30c139b4946d262034 | [
"BSD-3-Clause"
] | permissive | salisbury-robotics/jks-ros-pkg | b3c2f813885e48b1fcd732d1298027a4ee041a5c | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | refs/heads/master | 2020-03-31T01:20:29.860477 | 2015-09-03T22:13:17 | 2015-09-03T22:13:17 | 41,575,746 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,582 | h | CCamera.h | //===========================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2012, CHAI3D.
(www.chai3d.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\author <http://www.chai3d.org>
\author Francois Conti
\author Dan Morris
\version $MAJOR.$MINOR.$RELEASE $Rev: 403 $
*/
//===========================================================================
//---------------------------------------------------------------------------
#ifndef CCameraH
#define CCameraH
//---------------------------------------------------------------------------
#include "world/CGenericObject.h"
#include "math/CMaths.h"
#include "graphics/CImage.h"
//---------------------------------------------------------------------------
class cWorld;
//---------------------------------------------------------------------------
//===========================================================================
/*!
\file CCamera.h
\brief
<b> Scenegraph </b> \n
Virtual Camera.
*/
//===========================================================================
//===========================================================================
/*!
\class cCamera
\ingroup scenegraph
\brief cCamera describes a virtual Camera located inside the world.
Its job in life is to set up the OpenGL projection matrix
for the current OpenGL rendering context. The default camera
looks down the negative x-axis. OpenGL folks may wonder why
we chose the negative x-axis... it turns out that's a better
representation of the standard conventions used in general
robotics.
*/
//===========================================================================
class cCamera : public cGenericObject
{
friend class cWorld;
public:
//-----------------------------------------------------------------------
// CONSTRUCTOR & DESTRUCTOR:
//-----------------------------------------------------------------------
//! Constructor of cCamera
cCamera(cWorld* iParent);
//! Destructor of cCamera
virtual ~cCamera() {};
//-----------------------------------------------------------------------
// METHODS - MOUSE SELECTION:
//-----------------------------------------------------------------------
//! Get pointer to parent world.
cWorld* getParentWorld() { return (m_parentWorld); }
//! Query whether the specified position is 'pointing at' any objects in the world.
virtual bool select(const int a_windowPosX, const int a_windowPosY,
const int a_windowWidth, const int a_windowHeight,
cCollisionRecorder& a_collisionRecorder,
cCollisionSettings& a_collisionSettings);
//-----------------------------------------------------------------------
// METHODS - POSITION & ORIENTATION:
//-----------------------------------------------------------------------
//! Set the position and orientation of the camera.
virtual bool set(const cVector3d& a_localPosition,
const cVector3d& a_localLookAt,
const cVector3d& a_localUp);
//! Get the camera "look at" position vector for this camera.
cVector3d getLookVector() const { return m_localRot.getCol0(); }
//! Get the "up" vector for this camera.
cVector3d getUpVector() const { return m_localRot.getCol2(); }
//! Get the "right direction" vector for this camera.
cVector3d getRightVector() const { return m_localRot.getCol1(); }
//! Projection matrix of camera.
cTransform m_projectionMatrix;
//! Modelview matrix of camera.
cTransform m_modelviewMatrix;
//-----------------------------------------------------------------------
// METHODS - CLIPPING PLANES:
//-----------------------------------------------------------------------
//! Set near and far clipping planes.
void setClippingPlanes(const double a_distanceNear, const double a_distanceFar);
//! Get near clipping plane.
double getNearClippingPlane() { return (m_distanceNear); }
//! Get far clipping plane.
double getFarClippingPlane() { return (m_distanceFar); }
//! Automatically adjust back and front clipping planes.
void adjustClippingPlanes();
//-----------------------------------------------------------------------
// METHODS - SHADOW CASTING:
//-----------------------------------------------------------------------
//! Enable or disable shadow rendering.
void setUseShadowCasting(bool a_enabled);
//! Read if shadow rendering is enabled.
bool getUseShadowCastring() { return(m_useShadowCasting); }
//-----------------------------------------------------------------------
// METHODS - FIELD OF VIEW & OPTICS:
//-----------------------------------------------------------------------
//! Set camera is orthographic mode
void setOrthographicView(double a_viewWidth);
//! Set field of view angle (in degrees).
void setFieldViewAngle(double a_fieldViewAngle);
//! Read field of view angle (in degrees).
double getFieldViewAngle() { return (m_fieldViewAngle); }
//! Return aspect ratio.
double getAspectRatio();
//! Set stereo focal length.
void setStereoFocalLength(double a_stereoFocalLength);
//! Get stereo focal length.
double getStereoFocalLength() { return (m_stereoFocalLength); }
//! Set stereo eye separation.
void setStereoEyeSeparation(double a_stereoEyeSeparation);
//! Get stereo eye separation.
double getStereoEyeSeparation() { return (m_stereoEyeSeparation); }
//-----------------------------------------------------------------------
// METHODS - RENDERING AND IMAGING:
//-----------------------------------------------------------------------
//! Render the camera in OpenGL (i.e. set up the projection matrix)...
virtual void renderView(const int a_windowWidth, const int a_windowHeight);
//! Copy output image data to image structure.
void copyImageData(cImage* a_image);
//! Enable or disable additional rendering passes for transparency (see full comment).
virtual void setUseMultipassTransparency(bool a_enabled);
//! Read if multipass rendering is enabled.
bool getUseMultipassTransparency() { return (m_useMultipassTransparency); }
//! Enable or disable 3D stereo rendering.
virtual void setUseStereo(bool a_enabled = true);
//! Read if 3D stereo is enabled.
bool getUseStereo() { return (m_useStereo); }
//! Get the width of the current window display in pixels.
int getDisplayWidth() { return (m_lastDisplayWidth); }
//! Get the height of the current window display in pixels.
int getDisplayHeight() { return (m_lastDisplayHeight); }
//! Resets textures and displays for the world associated with this camera.
virtual void onDisplayReset();
//-----------------------------------------------------------------------
// MEMBERS - FRONT AND BACK PLANES:
//-----------------------------------------------------------------------
/*
These are special 'children' of the camera that are rendered independently of
all other objects, intended to contain 2d objects only. The 'back' scene is
rendered before the 3d objects; the 'front' scene is rendered after the
3d object. These are made public variables to allow convenient access to
the scenegraph management functions.
These objects are rendered through an orthographic projection matrix, so the
positive z axis faces the camera. Depth is currently not used. Lighting
is disabled during rendering.
*/
//! Front plane scenegraph which can be used to attach widgets.
cWorld* m_frontLayer;
//! Black plane scenegraph which can be used to attach widgets.
cWorld* m_backLayer;
//-----------------------------------------------------------------------
// MEMBERS:
//-----------------------------------------------------------------------
protected:
//! Parent world.
cWorld *m_parentWorld;
//! Distance to near clipping plane.
double m_distanceNear;
//! Distance to far clipping plane.
double m_distanceFar;
//! Field of view angle in degrees.
double m_fieldViewAngle;
//! Width of orthographic view
double m_orthographicWidth;
//! If \b true, then camera is in perspective mode. If \b false, then camera is of orthographic mode.
bool m_perspectiveMode;
//! If true, three rendering passes are performed to approximate back-front sorting (see long comment)
bool m_useMultipassTransparency;
//! If true, then use shadow casting.
bool m_useShadowCasting;
//! Focal length.
double m_stereoFocalLength;
//! Eye separation.
double m_stereoEyeSeparation;
//! If true, then use stereo display rendering.
bool m_useStereo;
//! last width size of the window.
unsigned int m_lastDisplayWidth;
//! last height size of the window.
unsigned int m_lastDisplayHeight;
//! if \b true then display reset has been requested.
bool m_resetDisplay;
//-----------------------------------------------------------------------
// METHODS:
//-----------------------------------------------------------------------
protected:
//! Render a 2d scene within this camera's view.
void renderLayer(cGenericObject* a_graph, int a_width, int a_height);
//! Verifies if shadow casting is supported on this hardware.
bool isShadowCastingSupported();
};
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
|
f833bb4dbc0c6b5582dbcf4ed79606a33272ea56 | 21b7d8820a0fbf8350d2d195f711c35ce9865a21 | /Alyona and Numbers.cpp | 2948648a97c68808ae612fe8de507dded224183d | [] | no_license | HarshitCd/Codeforces-Solutions | 16e20619971c08e036bb19186473e3c77b9c4634 | d8966129b391875ecf93bc3c03fc7b0832a2a542 | refs/heads/master | 2022-12-25T22:00:17.077890 | 2020-10-12T16:18:20 | 2020-10-12T16:18:20 | 286,409,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | cpp | Alyona and Numbers.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int a, b;
unsigned long long ans=0;
cin>>a>>b;
vector<long long> v(5, a/5), u(5, b/5);
int n = a%5;
while(n>0){
v[n--]++;
}
n=b%5;
while(n>0){
u[n--]++;
}
n=0;
while(n!=5){
ans+=v[n]*u[(5-n)%5];
n++;
}
cout<<ans;
}
|
ec20b3f70321651bf1fce5fbb5430f2b95da0a7a | 212b0bff91cd3e48343e22a162b5d18a9532b7a1 | /evaluations.cpp | 0464eff8d1852e682cad05ff0d3a94a2c1543255 | [] | no_license | suhit09/MIML | f0f8fcf9e7c0f5fe99b42f4d6ac6903b85456912 | 9451ace8fc052016ef57a33f3143f3c5870e0beb | refs/heads/master | 2020-12-25T14:57:35.295857 | 2016-08-25T21:05:04 | 2016-08-25T21:05:04 | 66,592,944 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,430 | cpp | evaluations.cpp | #include"evaluations.h"
#include <algorithm>
using namespace std;
Evaluation::Evaluation()
{
}
double * Evaluation::getMaxCpePerEntityPair(const Data *data,const double *cpeMentions)
{
double *cpeEntityPairs= (double *) malloc(data->entityCount*sizeof(double));
int mentionsIterator=0;
for(int entityPairsIterator=0; entityPairsIterator<data->entityCount ; entityPairsIterator++)
{
int iterator=0;
double maxCpe=0;
while(iterator<data->mentionsPerEntityPairCount[entityPairsIterator])
{
// cout<<data->cpeMentions[mentionsIterator]<<endl;
if(maxCpe<cpeMentions[mentionsIterator])
maxCpe=cpeMentions[mentionsIterator];
mentionsIterator++;
iterator++;
}
cpeEntityPairs[entityPairsIterator]=maxCpe;
//cout<<endl<<endl;
}
return cpeEntityPairs;
}
double Evaluation::findBestMacroThreshold(const double *cpeEntityPairs,const Data *data,int relationNumber)
{
double *thresholdValues= (double * ) malloc((data->entityCount + 1)*sizeof(double)); //+1 coz to include both borders
double *sortedCpeEntityPairs= sortArray(cpeEntityPairs,data->entityCount);
int entityPairsIterator=0;
thresholdValues[entityPairsIterator]=sortedCpeEntityPairs[0]-0.01;
for(entityPairsIterator=1; entityPairsIterator<data->entityCount ; entityPairsIterator++)
{
thresholdValues[entityPairsIterator]= (sortedCpeEntityPairs[entityPairsIterator-1]+sortedCpeEntityPairs[entityPairsIterator])/2;
}
thresholdValues[entityPairsIterator]= sortedCpeEntityPairs[entityPairsIterator -1]+0.01;
double maxFscore=0;
double bestThreshold=0;
for(int iterator=0;iterator<data->entityCount+1;iterator++)
{
double *predictedEntityPairsLabel = findLabelsBasedOnEntity(cpeEntityPairs,thresholdValues[iterator],data->entityCount);
double tempFscore=getFscore(predictedEntityPairsLabel,data->allLabels[relationNumber],data->entityCount);
if(tempFscore>maxFscore)
{
maxFscore=tempFscore;
bestThreshold= thresholdValues[iterator];
}
free(predictedEntityPairsLabel);
}
free(thresholdValues);
free(sortedCpeEntityPairs);
cout<<"Best training Fscore on training data "<<maxFscore<<"\t relationNumber : "<<relationNumber<<endl;
return bestThreshold;
}
double * Evaluation::sortArray(const double *cpeEntityPairs,int SIZE)
{
double *sortedCpeEntityPairs=(double * ) malloc((SIZE)*sizeof(double));
std::copy(cpeEntityPairs,cpeEntityPairs + SIZE, sortedCpeEntityPairs);
sort(sortedCpeEntityPairs, sortedCpeEntityPairs + SIZE);
return sortedCpeEntityPairs;
}
double * Evaluation::findLabelsBasedOnEntity(const double *cpeMentions,double threshold,int entityCount)
{
double *entityPairsLabel = (double * ) malloc(entityCount*sizeof(double));
int mentionsIterator=0;
for(int entityPairsIterator=0; entityPairsIterator<entityCount ; entityPairsIterator++)
{
if(cpeMentions[entityPairsIterator]>threshold)
entityPairsLabel[entityPairsIterator]=1;
else
entityPairsLabel[entityPairsIterator]=0;
}
return entityPairsLabel;
}
double Evaluation::getFscore(const double *predictedEntityLabels,const double *entityLabels, int entityCount)
{
double precision;
double recall;
double beta=0.5;
double betaSquare=beta*beta;
//cout<<"get F scor fundtion"<<endl;
int TP=0;
int FP=0;
int FN=0;
for(int entityPairsIterator=0; entityPairsIterator<entityCount ; entityPairsIterator++)
{
if(predictedEntityLabels[entityPairsIterator]==1 &&entityLabels[entityPairsIterator]==1)
{
TP++;
}else if(predictedEntityLabels[entityPairsIterator]==1 &&entityLabels[entityPairsIterator]==0)
{
FP++;
}else if(predictedEntityLabels[entityPairsIterator]==0 &&entityLabels[entityPairsIterator]==1)
{
FN++;
}
}
double fvalue=0;
if(TP==0)
return fvalue;
precision= (double)TP/(TP+FP);
recall= (double)TP/(TP+FN);
if(precision>0 && recall>0)
fvalue=(precision*recall)/(precision+recall);
return fvalue;
}
double * Evaluation::getKForEntityPairs(const Data *data,double threshold,double *cpeMentions,int relationNumber)
{
//double *cpeMentions= data->cpeMentions;
double *k = (double * ) malloc(data->entityCount*sizeof(double));
int mentionsIterator=0;
double *lables = data->allLabels[relationNumber];
for(int entityPairsIterator=0; entityPairsIterator<data->entityCount ; entityPairsIterator++)
{
int iterator=0;
int ktemp=0;
if(lables[entityPairsIterator]==0)
{
k[entityPairsIterator]=0;
continue;
}
while(iterator<data->mentionsPerEntityPairCount[entityPairsIterator])
{
if(cpeMentions[mentionsIterator]>threshold)
{
ktemp++;
}
iterator++;
mentionsIterator++;
}
//cout<< ktemp<<" "<<data->mentionsPerEntityPairCount[entityPairsIterator]<<endl;
k[entityPairsIterator]=(double)ktemp/data->mentionsPerEntityPairCount[entityPairsIterator];
}
return k;
}
double Evaluation::getFScore(const Data *data,double threshold,double *cpeMentions,int relationNumber)
{
double *entityCpeMentions = getMaxCpePerEntityPair(data,cpeMentions);
//double *predictedEntityLabels = findLabelsBasedOnEntity(entityCpeMentions,threshold,data);
double *predictedEntityPairsLabel = findLabelsBasedOnEntity(entityCpeMentions,threshold,data->entityCount);
double tempFscore=getFscore(predictedEntityPairsLabel,data->allLabels[relationNumber],data->entityCount); ///
free(entityCpeMentions);
free(predictedEntityPairsLabel);
return tempFscore;
///return getFScore(predictedEntityLabels,data->trueEntityLabels,data);
} |
2dcd7bb8e0b7f783850b860a97e7a584b2046c52 | 3adb6f26fdab18a9ad548fc4e5ca8c6171dcf154 | /src/ISDLG.CPP | a4c406d52c3e608ec6c533b7292e61b08ac21ba1 | [] | no_license | gitmesam/3DWorld | 16fd59e2540e980f512e3ac82474df086e2de9d5 | b17d55cdc57c351bfe1102ba644d439fa2a365ca | refs/heads/master | 2023-04-08T10:39:34.485279 | 2018-01-28T20:15:33 | 2018-01-28T20:15:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,978 | cpp | ISDLG.CPP | #include "isdlg.hpp"
#include "noisydlg.hpp"
#include "INC\isdlg.inc"
#include "INC\io_em.inc"
#include "INC\errors.inc"
#ifdef __DLL__
extern PTModule pModule;
#else
static PTModule pModule = NULL;
#endif
extern HINSTANCE hInstRC;
extern PTModule pModuleRc;
TBtnValueTbl TImageOptDialog::bvtTbl[ iNumbBtn ] =
{
{ ID_ISDLG_256_RADIO, 256 },
{ ID_ISDLG_236_RADIO, 236 },
{ ID_ISDLG_16SYS_RADIO, -16 },
{ ID_ISDLG_16ADAPT_RADIO, 16 },
{ ID_ISDLG_TRUECOLOR_RADIO, 0 },
{ ID_ISDLG_WINDOWED_RADIO, IF_Windowed },
{ ID_ISDLG_FULLSCREEN_RADIO, IF_FullScreen },
{ ID_ISDLG_640x480_RADIO, IF_640x480 },
{ ID_ISDLG_800x600_RADIO, IF_800x600 },
{ ID_ISDLG_1024x768_RADIO, IF_1024x768 }
};
int TImageOptDialog::iAlhoBtnTbl[ iNumbBtnAlho ] =
{
ID_RADIO_QUANT,
ID_RADIO_MEDIUMSECT,
ID_RADIO_GEOMETRIC,
ID_RADIO_DISCRET,
ID_CHECK_DIFFUSION,
ID_CHECK_NOISY
};
int TImageOptDialog::Btn( int iValue ) const
{
for( int i = 0; i < iNumbBtn; i++ )
if( TImageOptDialog::bvtTbl[ i ].iValueVariable == iValue )
return TImageOptDialog::bvtTbl[ i ].iIdBtn;
return -1;
}
int TImageOptDialog::Value( int iBtn ) const
{
for( int i = 0; i < iNumbBtn; i++ )
if( TImageOptDialog::bvtTbl[ i ].iIdBtn == iBtn )
return TImageOptDialog::bvtTbl[ i ].iValueVariable;
return -1;
}
static char* cNoisyNames[ 3 ] =
{
"Marginal noisy",
"Uniform noisy",
"No noisy"
};
void TImageOptDialog::CheckNoisy()
{
if( nNoisy > - 1 && nNoisy < 4 )
SetDlgItemText( HWindow, ID_CHECK_NOISY, cNoisyNames[ nNoisy ] );
SendDlgItemMessage( HWindow, ID_CHECK_NOISY, BM_SETCHECK, (WPARAM)TRUE, 0 );
}
void TImageOptDialog::SetupNoisy()
{
TNoisyDta ndDta;
ndDta.nNoisy = nNoisy;
ndDta.iMarginalAmplitude = iMarginalAmplitude;
ndDta.iUniformAmplitude = iUniformAmplitude;
ndDta.iUniformThreshold = iUniformThreshold;
PTNoisyDialog pDlg;
int res;
if( (pDlg = new TNoisyDialog( this, (LPSTR)MAKEINTRESOURCE(DlgNoisy), &ndDta, pModuleRc )) && !pDlg->Status )
res = GetApplication()->ExecDialog( pDlg );
else
{
GetApplication()->Error( pDlg ? pDlg->Status:ER_CREATEOBJECT );
if( pDlg ) pDlg->CloseWindow();
return;
}
if( res == IDOK )
{
nNoisy = ndDta.nNoisy;
iMarginalAmplitude = ndDta.iMarginalAmplitude;
iUniformAmplitude = ndDta.iUniformAmplitude;
iUniformThreshold = ndDta.iUniformThreshold;
CheckNoisy();
}
}
TImageOptDialog::TImageOptDialog( PTWindowsObject AParent, LPSTR AName, int& iPalSize_,
TImageFormat& ifFormat_, TConvertAlho& caAlhoPalette_,
TNoisy& nNoisy_, int& iMarginalAmplitude_,
int& iUniformAmplitude_, int& iUniformThreshold_,
PTModule AModule ):
TCenterDialog( AParent, AName, AModule ),
iPalSize( iPalSize_ ),
ifFormat( ifFormat_ ),
caAlhoPalette( caAlhoPalette_ ),
nNoisy( nNoisy_ ),
iMarginalAmplitude( iMarginalAmplitude_ ),
iUniformAmplitude( iUniformAmplitude_ ),
iUniformThreshold( iUniformThreshold_ )
{
}
void TImageOptDialog::SetupWindow()
{
TCenterDialog::SetupWindow();
SendDlgItemMessage( HWindow, Btn(iPalSize), BM_SETCHECK, (WPARAM)TRUE, 0 );
SendDlgItemMessage( HWindow, Btn( int(ifFormat) ), BM_SETCHECK, (WPARAM)TRUE, 0 );
SendDlgItemMessage( HWindow, (caAlhoPalette & CA_Quantize) ? ID_RADIO_QUANT:ID_RADIO_MEDIUMSECT,
BM_SETCHECK, 1, 0 );
//if( (caAlhoPalette & (CA_MedianCutGeom | CA_MedianCutDiscr)) )
SendDlgItemMessage( HWindow, (caAlhoPalette & CA_MedianCutGeom) ? ID_RADIO_GEOMETRIC:ID_RADIO_DISCRET,
BM_SETCHECK, 1, 0 );
SendDlgItemMessage( HWindow, ID_CHECK_DIFFUSION, BM_SETCHECK,
(caAlhoPalette & CA_Diffuzion) ? 1:0, 0 );
LRESULT lCheckedTrue = SendDlgItemMessage( HWindow, ID_ISDLG_TRUECOLOR_RADIO,
BM_GETCHECK, 0, 0 );
LRESULT lCheckedSys16 = SendDlgItemMessage( HWindow, ID_ISDLG_16SYS_RADIO,
BM_GETCHECK, 0, 0 );
BOOL bFlEnable = (lCheckedTrue || lCheckedSys16) ? FALSE:TRUE;
for( int i = 0; i < iNumbBtnAlho; i++ )
EnableWindow( GetDlgItem(HWindow, TImageOptDialog::iAlhoBtnTbl[i]), bFlEnable );
DetectRadioState();
CheckNoisy();
SetFocus( GetDlgItem(HWindow, IDOK) );
}
void TImageOptDialog::DetectRadioState()
{
if( !IsWindowEnabled(GetDlgItem( HWindow, ID_RADIO_QUANT )) )
return;
int iFl = SendDlgItemMessage( HWindow, ID_RADIO_MEDIUMSECT, BM_GETCHECK, 0, 0 );
EnableWindow( GetDlgItem(HWindow, ID_RADIO_GEOMETRIC), iFl == 1 );
EnableWindow( GetDlgItem(HWindow, ID_RADIO_DISCRET), iFl == 1 );
}
void TImageOptDialog::Ok( RTMessage msg )
{
TConvertAlho alho = 0;
if( !SendDlgItemMessage( HWindow, ID_RADIO_MEDIUMSECT, BM_GETCHECK, 0, 0 ) )
alho = CA_Quantize;
else
alho = SendDlgItemMessage( HWindow, ID_RADIO_GEOMETRIC, BM_GETCHECK, 0, 0 ) ?
CA_MedianCutGeom:CA_MedianCutDiscr;
alho |= (SendDlgItemMessage( HWindow, ID_CHECK_DIFFUSION, BM_GETCHECK, 0, 0 ) ?
CA_Diffuzion:0);
caAlhoPalette = alho;
TCenterDialog::Ok( msg );
}
void TImageOptDialog::WMCommand( RTMessage Msg )
{
if( HIWORD(Msg.LParam) == BN_CLICKED )
{
if( Msg.WParam >= ID_IMG_STA && Msg.WParam <= ID_IMG_END )
{
int iValue = Value( Msg.WParam );
if( iValue != -1 )
{
if( iValue == 0 || iValue == 236 || iValue == 256 ||
iValue == 16 || iValue == -16
)
iPalSize = iValue;
else ifFormat = (TImageFormat)iValue;
if( Msg.WParam >= ID_ISDLG_256_RADIO && Msg.WParam <= ID_ISDLG_TRUECOLOR_RADIO )
{
BOOL bFlEnable = TRUE;
if( Msg.WParam == ID_ISDLG_TRUECOLOR_RADIO ||
Msg.WParam == ID_ISDLG_16SYS_RADIO
)
bFlEnable = FALSE;
for( int i = 0; i < iNumbBtnAlho; i++ )
EnableWindow( GetDlgItem(HWindow, TImageOptDialog::iAlhoBtnTbl[i]), bFlEnable );
DetectRadioState();
}
Msg.Result = 0;
return;
}
}
else if( Msg.WParam >= ID_METHOD_STA && Msg.WParam <= ID_METHOD_END )
{
switch( Msg.WParam )
{
case ID_RADIO_QUANT:
case ID_RADIO_MEDIUMSECT:
TCenterDialog::WMCommand( Msg );
DetectRadioState();
break;
case ID_RADIO_GEOMETRIC:
case ID_RADIO_DISCRET:
int iCh1 = SendDlgItemMessage( HWindow, ID_RADIO_GEOMETRIC, BM_GETCHECK, 0, 0 ),
iCh2 = SendDlgItemMessage( HWindow, ID_RADIO_DISCRET, BM_GETCHECK, 0, 0 );
int iTmp = iCh1; iCh1 = iCh2; iCh2 = iTmp;
TCenterDialog::WMCommand( Msg );
SendDlgItemMessage( HWindow, ID_RADIO_GEOMETRIC, BM_SETCHECK, iCh1, 0 );
SendDlgItemMessage( HWindow, ID_RADIO_DISCRET, BM_SETCHECK, iCh2, 0 );
break;
case ID_CHECK_NOISY:
SetupNoisy();
break;
}
Msg.Result = 0;
return;
}
}
TCenterDialog::WMCommand( Msg );
}
|
ad380c5dd06c30be0518d115e6f129dd6e01ac13 | d61118a487f8a6979eb6c2e5df722429ad12ac9e | /c++/game1/level.cpp | 03f343446be219100484a888e0453cd82c78b07f | [] | no_license | mohamedbabachekh/C_games | 91ac20939420d56117d9d659acb7f3de88d6a7d3 | 09727a81c371fa3e1e64fe934b2dd398c45e9728 | refs/heads/main | 2023-06-09T12:11:06.781522 | 2021-06-30T14:45:30 | 2021-06-30T14:45:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | cpp | level.cpp | #include"level.h"
#include<fstream>
#include<string>
#include<iostream>
#include"player.h"
//#include"player.cpp"
#include<conio.h>
using namespace std;
Level::Level(){
}
void Level::load(string &filename,Player &player){
//loadinggggg
fstream file;
file.open(filename.c_str());
if(file.fail()){
perror(filename.c_str());
system("PAUSE");
exit(1);
}
string line;
while(getline(file,line)){
_levelData.push_back(line);
}
file.close();
//palying
char tile;
for(int i=0;i<_levelData.size();i++)
{
for(int j=0;j<_levelData[i].size();j++)
{
tile=_levelData[i][j];
switch(tile){
case '@':
player.setposition(j,i);
break;
}
}
}
}
void Level::print(){
cout<<string(100,'\n');
for(int i=0;i<_levelData.size();i++)
{
printf("%s\n",_levelData[i].c_str());
}
printf("\n");
}
void Level::moveplayer(char input,Player &player)
{
int playerx;
int playery;
player.getposition(playerx,playery);
char movetile;
switch(input){
//up
case 'W':
case 'w':
//
processplaymove(player,playerx,playery-1);
break;
//right
case 'D':
case 'd':
processplaymove(player,playerx+1,playery);
break;
//left
case 'A':
case 'a':processplaymove(player,playerx-1,playery);
break;
//down
case 'S':
case 's':processplaymove(player,playerx,playery+1);
break;
default:
printf("INVALID MOVE ???\n");
break;
system("PAUSE");
}
}
char Level::getTILE(int x,int y)
{
return _levelData[y][x]; }
void Level::setTILE(int x ,int y,char tile)
{
_levelData[y][x]=tile;
}
void Level::processplaymove(Player &player,int targetx,int targety)
{
int playerx;
int playery;
player.getposition(playerx,playery);
char movetile=getTILE(targetx,targety);
switch(movetile){
// case '#':
// printf("you're ran into a wall");
// system("PAUSE");
// break;
case '.':
player.setposition( targetx,targety);
setTILE(playerx,playery,'.');
setTILE(targetx,targety,'@');
break;
}
}
|
8518fac7950aa9fc43ce8c1aa7ff12849752ef12 | 266a60c1437214751f5bf7995495fa8ba769008e | /键盘交互,计时器与多线程/076接收组合键.cpp | a115993a53cf85bd210e179ca23a727b3ca20160 | [] | no_license | AramakiYui/ReLearn-C- | ec4a268cd2107d4851c5e2219a58f9bb32b1ae61 | 2d17a7cde6bf5ea5bcd6ee26c39baa84906b09a5 | refs/heads/master | 2020-05-03T07:39:47.604283 | 2019-10-14T11:27:25 | 2019-10-14T11:27:25 | 178,504,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,071 | cpp | 076接收组合键.cpp | #include <windows.h>
#include <iostream>
#include <ctime>
#include <conio.h>
#include "basic.cpp"
using namespace std;
class game
{
private:
int x,y;
clock_t t,tt;
bool flag;//初始状态,边界标识
char c1,c2;//接受的键盘码;
public:
game(int x0,int y0,int t0)
{
x=x0;y=y0;
tt=t0;
flag=true;//小球初始化
t=clock();
}
void draw()
{
gotoxy(x,y);
cout<<"●";
}
void del()
{
gotoxy(x,y);
cout<<" ";
}
void background()
{
cout<<"┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┃ ┃"<<endl;
cout<<"┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛"<<endl;
}
void move()
{
if(flag==true)//重新绘制小球
{
draw();
flag = false;
}
if(clock()-t>tt)
{
if(GetAsyncKeyState(VK_ESCAPE))exit(0);
if(GetAsyncKeyState(VK_UP))
{
del();
--y;
if(y<1)
y=1;
draw();
}
if(GetAsyncKeyState(VK_DOWN))
{
del();
++y;
if(y>14)
y=14;
draw();
}
if(GetAsyncKeyState(VK_RIGHT))
{
del();
x=x+2;
if(x>33)
x=33;
draw();
}
if(GetAsyncKeyState(VK_LEFT))
{
del();
x=x-2;
if(x<2)
x=2;
draw();
}
//flag = true;
t = clock();//为计时器变量重新赋值
}
}
};
int main()
{
hide_cursor();
game g(10,10,150);
g.background();
while(true)
{
g.move();
}
show_cursor();
return 0;
}
|
d203444436b97c45e5de555e6a899dcd318f9370 | e30ab85bde0c8887f4fb519337da95ad4393fe8d | /w_BuffStateValueControl.cpp | 6fc38c87d7d6ce9a1e9eaf39374d2f2b07791fe1 | [] | no_license | rodrigolmonteiro/muonline-client-sources | a80a105c2d278cee482b504b167c393d3b05322e | be7f279f0d17bb8ca87455e434edd30b60e5a5fe | refs/heads/master | 2023-06-29T09:45:22.154516 | 2021-08-04T17:10:15 | 2021-08-04T17:10:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,921 | cpp | w_BuffStateValueControl.cpp | // w_BuffStateControl.cpp: implementation of the BuffStateControl class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "UIManager.h"
#include "ItemAddOptioninfo.h"
#include "w_BuffStateValueControl.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BuffStateValueControlPtr BuffStateValueControl::Make()
{
BuffStateValueControlPtr buffstatecontrol( new BuffStateValueControl );
return buffstatecontrol;
}
BuffStateValueControl::BuffStateValueControl()
{
Initialize();
}
BuffStateValueControl::~BuffStateValueControl()
{
Destroy();
}
void BuffStateValueControl::Initialize()
{
for ( int i = eBuff_Attack; i < eBuff_Count; ++i )
{
CheckValue( static_cast<eBuffState>(i) );
}
}
void BuffStateValueControl::Destroy()
{
}
eBuffValueLoadType BuffStateValueControl::CheckValue( eBuffState bufftype )
{
if( bufftype >= eBuff_Attack && bufftype <= eBuff_GMEffect )
{
return eBuffValueLoad_None;
}
else
{
return eBuffValueLoad_ItemAddOption;
}
}
void BuffStateValueControl::SetValue( eBuffState bufftype, BuffStateValueInfo& valueinfo )
{
eBuffValueLoadType loadtype = CheckValue( bufftype );
if( eBuffValueLoad_ItemAddOption == loadtype )
{
const BuffInfo buffinfo = g_BuffInfo( bufftype );
const ITEM_ADD_OPTION& Item_data = g_pItemAddOptioninfo->GetItemAddOtioninfo(ITEMINDEX( buffinfo.s_ItemType, buffinfo.s_ItemIndex));
valueinfo.s_Value1 = Item_data.m_byValue1;
valueinfo.s_Value2 = Item_data.m_byValue2;
valueinfo.s_Value2 = Item_data.m_Time;
}
else
{
valueinfo.s_Value1 = 0;
valueinfo.s_Value2 = 0;
valueinfo.s_Value2 = 0;
}
}
const BuffStateValueControl::BuffStateValueInfo BuffStateValueControl::GetValue( eBuffState bufftype )
{
BuffStateValueInfo tempvalueinfo;
BuffStateValueMap::iterator iter = m_BuffStateValue.find( bufftype );
if( iter == m_BuffStateValue.end() )
{
const BuffInfo buffinfo = g_BuffInfo( bufftype );
if( buffinfo.s_ItemType != 255 )
{
SetValue( bufftype, tempvalueinfo );
}
m_BuffStateValue.insert( make_pair( bufftype, tempvalueinfo ));
}
else
{
tempvalueinfo = (*iter).second;
}
return tempvalueinfo;
}
void BuffStateValueControl::GetBuffInfoString( list<string>& outstr, eBuffState bufftype )
{
BuffStateValueInfo tempvalueinfo;
tempvalueinfo = GetValue( bufftype );
const BuffInfo buffinfo = g_BuffInfo( bufftype );
outstr = buffinfo.s_BuffDescriptlist;
outstr.push_front("\n");
outstr.push_front(buffinfo.s_BuffName);
/*
if( tempvalueinfo.s_Value1 != 0 && tempvalueinfo.s_Value2 != 0 )
{
outstr.push_back(buffinfo.s_BuffName);
outstr.push_back(( format( buffinfo.s_BuffDescript ) % tempvalueinfo.s_Value1 % tempvalueinfo.s_Value2 ).str());
}
else if( tempvalueinfo.s_Value1 != 0 && tempvalueinfo.s_Value2 == 0 )
{
outstr.push_back(buffinfo.s_BuffName);
outstr.push_back(( format( buffinfo.s_BuffDescript ) % tempvalueinfo.s_Value1 ).str());
}
else if( tempvalueinfo.s_Value1 == 0 && tempvalueinfo.s_Value2 != 0 )
{
outstr.push_back(buffinfo.s_BuffName);
outstr.push_back(( format( buffinfo.s_BuffDescript ) % tempvalueinfo.s_Value2 ).str());
}
else if( tempvalueinfo.s_Value1 != 0 && tempvalueinfo.s_Value2 != 0 )
{
outstr.push_back(buffinfo.s_BuffName);
outstr.push_back(( format( buffinfo.s_BuffDescript ) ).str());
}
*/
}
void BuffStateValueControl::GetBuffValueString( string& outstr, eBuffState bufftype )
{
BuffStateValueInfo tempvalueinfo;
tempvalueinfo = GetValue( bufftype );
if( tempvalueinfo.s_Value1 != 0 )
{
outstr = (( format( "+%1%" ) % tempvalueinfo.s_Value1 ).str());
}
else
{
outstr = (( format( "" )).str());
}
} |
90f8fde978fd22eaac70c83dbbaba5cc7fe860ca | 53142bedc8f678ab54f7dbfed66aa3196a58b702 | /PA06/Project/PA06.2/ExpressionTree.h | 4bf5242518f481e2614c859645e53b7128b45c5d | [] | no_license | lkramer37/CS302-Data-Structures | d2ec715491f3f5901145ba9e0b1dc387ca99a880 | 087bf1022f6924f2914b2f227489201351e2f085 | refs/heads/master | 2023-01-22T13:11:13.437124 | 2020-11-18T18:13:14 | 2020-11-18T18:13:14 | 209,921,362 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,073 | h | ExpressionTree.h | //--------------------------------------------------------------------
//
// Laboratory 8 ExpressionTree.h
//
// Class declarations for the linked implementation of the
// Expression Tree ADT -- including the recursive helpers for the
// public member functions
//
// Instructor copy with the recursive helper function declarations.
// The student version does not have those, but has a place to write
// the declarations in the private section.
//
//--------------------------------------------------------------------
#ifndef EXPRESSIONTREE_H
#define EXPRESSIONTREE_H
#include <stdexcept>
#include <iostream>
using namespace std;
template <typename DataType>
class ExprTree {
public:
// Constructor
ExprTree ();
ExprTree(const ExprTree& source);
ExprTree& operator=(const ExprTree& source);
// Destructor
~ExprTree ();
// Expression tree manipulation operations
void build ();
void expression () const;
DataType evaluate() const throw (logic_error);
void clear (); // Clear tree
void commute();
bool isEquivalent(const ExprTree& source) const;
// Output the tree structure -- used in testing/debugging
void showStructure () const;
private:
class ExprTreeNode {
public:
// Constructor
ExprTreeNode ( char elem, ExprTreeNode *leftPtr, ExprTreeNode *rightPtr );
// Data members
char dataItem; // Expression tree data item
ExprTreeNode *left, // Pointer to the left child
*right; // Pointer to the right child
};
// Recursive helper functions for the public member functions -- insert
// prototypes of these functions here.
void showHelper ( ExprTreeNode *p, int level ) const;
void buildHelper(ExprTreeNode*& node);
void evalHelper(ExprTreeNode* nodePtr) const;
void expressionHelper();
bool isEmpty()const;
// Data member
ExprTreeNode *root; // Pointer to the root node
};
#endif // #ifndef EXPRESSIONTREE_H
|
4642d62373d1403be9616362323398d7b4a9b74a | df69cec5702b3d7b5f543b8b3643b3eb19167b9a | /sqlanalyze.h | 5e277a202e7bb0af2628c4ed37f602960997959d | [] | no_license | Jessting/- | 3269089d453ac656613e4ba62112aa12f8439cd9 | ba03e59cb71d2da5beaadaa326e09b8dac0c6047 | refs/heads/master | 2020-03-25T13:50:27.981402 | 2018-08-07T09:14:55 | 2018-08-07T09:14:55 | 143,845,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,786 | h | sqlanalyze.h | #ifndef SQLANALYZE_H
#define SQLANALYZE_H
#include "info.h"
#include <QString>
class SQLAnalyze
{
public:
SQLAnalyze();//构造函数
static DBAdmin selectDBAdminInfo(QString id);
static User selectUserInfo(QString id);//按id查询用户信息
static UserList selectUserInfos(void);//导出所有的用户信息
static UserList selectUserInfosAS(QString type);//导出按要求的所有用户信息
static StudentList selectStudentInfos(void);//导出所有的学生信息
static Student selectStudentInfo(QString id);//查询学生信息,返回学生
static StudentList selectStudentInfos(QString name);//按姓名查询学生信息,返回学生列表
static StudentList selectStudentInfosAsDept(QString deptID);//按系名查询学生信息,返回学生列表
static QStringList selectDeptNames(void);//查询所有的系名
static bool insertStudentInfo(Student student);//插入学生信息
static bool updateStudentInfo(Student student);//修改学生信息
static Student firstStudentInfo(void);//返回到第一条学生信息
static Student lastStudentInfo(void);//返回到最后一条学生信息
static Student nextStudentInfo(void);//返回到下一条学生信息
static Student previousStudentInfo(void);//返回到上一条学生信息
static TeacherList selectTeacherInfos(void);//导出所有的教师信息
static Teacher selectTeacherInfo(QString id);//查询教师信息,返回单个教师
static TeacherList selectTeacherInfos(QString name);//按姓名查询教师信息,返回教师列表
static TeacherList selectTeacherInfosAsDept(QString dept);//按系名查询教师信息,返回教师列表
};
#endif // SQLANALYZE_H
|
ce31f7191a653afd998eb30104d5f1ca19fdbb0c | 9fd8dfaeb822390c80d5b7b708f935b9a682ff43 | /PraxisWissenC++NewStd/PraxisWissenC++NewStd/Kap3Templates.h | 093224b41997d1585bec2f471647b7dfc777c069 | [] | no_license | Oxid2178/PraxisWissenC-NewStd | 7ad4c88e0ff772a40ab3b651ed8675e46fcfa5e5 | 9e8c64724b9208c75bcee4af580988fc8b25e63d | refs/heads/master | 2020-03-25T23:48:39.754325 | 2018-09-11T15:25:33 | 2018-09-11T15:25:33 | 144,294,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | h | Kap3Templates.h | #pragma once
class Kap3Templates
{
public:
Kap3Templates();
virtual ~Kap3Templates();
void kap3_1variablenTemplates();
template<class T>
static T var;
template <typename T>
inline T const& Max(T const& a, T const& b)
{
return a < b ? b : a;
}
template<int digit>
int BinToNumber()
{
return digit;
}
template<int firstDigit, int secondDigit, int... restDigits>
int BinToNumber()
{
return firstDigit + BinToNumber<2 * secondDigit, 2 * restDigits...>();
}
};
|
e3d21e21f70fd5a5435442066c205b5ce1d7b022 | eb0be1f783353ed5eba7db39e4d41cf02d186835 | /Задача №2 10.09.2020/task210092020.cpp | 0113993c762ef747f8194e5996d83df70c511aa8 | [] | no_license | BurundukA/Matcq | 4637d4c41e2dcee9b3575a27e3d3199be83eb308 | bf2f75005908e831351e2d7083cadeb9e38756d9 | refs/heads/master | 2023-03-03T18:50:50.305118 | 2021-02-15T04:37:54 | 2021-02-15T04:37:54 | 257,822,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | cpp | task210092020.cpp | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
fstream text;
text.open("text.txt");
string buk;
getline(text,buk);
int n = buk[0] - '0';
cout << "n = "<< n<< endl;
int m = buk[2] -'0';
cout << "m = "<< m <<endl;
int mas[m][2];
int y=0;
int v = 0;
int r = 0;
while (!text.eof())
{
getline(text,buk);
for (int i=0;i<buk.size()-1; i++)
{
if(buk[i]!=' ')
{
if(buk[i+1]!=' ')
{
mas[v][r] = (buk[i] - '0')*10+(buk[i+1] - '0');
r++;
i++;
}
else
{
mas[v][r] = buk[i] - '0';
r++;
}
}
}
v++;
r=0;
}
for(int i =0 ; i<m;i++)
{
for(int j =0;j<2;j++)
{
cout<<mas[i][j]<<" ";
}
cout<<endl;
}
int st1[m];
int st2[m];
for ( int i=0;i<m;i++)
{
st1[i]= mas [i][0]-1;
}
for ( int i=0;i<m;i++)
{
st2[i]= mas [i][1]-1;
}
cout << "st1"<<endl;
for ( int i=0;i<m;i++)
{
cout<<st1[i]<<" ";
}
cout<<endl;
cout<<"st2"<<endl;
for ( int i=0;i<m;i++)
{
cout<<st2[i]<<" ";
}
int maq [n][n];
for(int i =0 ; i<n;i++)
{
for(int j =0;j<n;j++)
{
maq[i][j]=0;
}
}
for (int i=0 ;i<m;i++)
{
maq [st1[i]][st2[i]]=1;
}
cout<<endl;
for(int i=0;i<n;i++){
{
for(int j =0;j<n;j++)
{
cout<<maq[i][j]<<" ";
}
cout<<endl;
}
}
int l=0;
for(int i=0;i<n;i++){
{ cout<<(i+1)<<" ";
for(int j =0;j<n;j++)
{
if (maq[i][j]==1)
{
cout<<(j+1)<<" ";
l++;
}
}
if (l==0)
{
cout<<l;
}
l=0;
cout<<endl;
}
}
return 0;
}
|
724e70834de7f59be39c42f4c081eae0cfc4e210 | 602f4661e27057e2ae1646cd785c4a1e90228f45 | /src/timer.cc | 3faddce6d9d4dfecb592d897382960f6d4b35355 | [
"MIT"
] | permissive | obs145628/opl | 770194e1bde8f63b4eebb2c3325277d2c477eba7 | aeb8e70f3dbca8b8564cd829c2327df25e00392e | refs/heads/master | 2021-01-10T05:52:32.008468 | 2016-02-18T21:42:27 | 2016-02-18T21:42:27 | 50,236,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | cc | timer.cc | #include "timer.hh"
#include "date.hh"
namespace opl
{
Timer::Timer (bool auto_start)
{
reset ();
if (auto_start)
start ();
}
void
Timer::start ()
{
if (start_ != -1)
return;
start_ = Date::timestamp_ms () - stop_;
stop_ = -1;
}
void
Timer::stop ()
{
if (stop_ != -1)
return;
stop_ = Date::timestamp_ms () - start_;
start_ = -1;
}
void
Timer::reset ()
{
start_ = -1;
stop_ = 0;
}
bool
Timer::is_active () const
{
return stop_ == -1;
}
time_t
Timer::get () const
{
return is_active () ? Date::timestamp_ms () - start_ : stop_;
}
} |
490926991435f3a2da1dbab39fd9fc96a728e178 | c14500adc5ce57e216123138e8ab55c3e9310953 | /contrib/Revoropt/include/Revoropt/RVD/flann_backend.hpp | de31c70caa01308db3f3ae1ad84bf1265ce16da2 | [
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"LicenseRef-scancode-generic-exception",
"GPL-1.0-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-2.0-only",
"GPL-2.0-or-later",
"LicenseRef-scancode-other-copyleft",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ResonanceGroup/GMSH304 | 8c8937ed3839c9c85ab31c7dd2a37568478dc08e | a07a210131ee7db8c0ea5e22386270ceab44a816 | refs/heads/master | 2020-03-14T23:58:48.751856 | 2018-05-02T13:51:09 | 2018-05-02T13:51:09 | 131,857,142 | 0 | 1 | MIT | 2018-05-02T13:51:10 | 2018-05-02T13:47:05 | null | UTF-8 | C++ | false | false | 2,363 | hpp | flann_backend.hpp | // @licstart revoropt
// This file is part of Revoropt, a library for the computation and
// optimization of restricted Voronoi diagrams.
//
// Copyright (C) 2013 Vincent Nivoliers <vincent.nivoliers@univ-lyon1.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// @licend revoropt
#ifndef _REVOROPT_RVD_FLANN_BACKND_HPP_
#define _REVOROPT_RVD_FLANN_BACKND_HPP_
#include <flann/flann.hpp>
#include <vector>
#include <iostream>
namespace Revoropt {
/** Nearest neighbour backend for flann **/
template<int _Dim>
class FLANNBackend {
public :
/* Types and template data */
enum { Dim = _Dim } ;
/* Initialization, destruction */
FLANNBackend() : index_(flann::KDTreeSingleIndexParams(10)),
flann_params_(flann::FLANN_CHECKS_UNLIMITED,0,true) {
}
FLANNBackend( const double* sites,
unsigned int sites_size
) : index_(flann::KDTreeSingleIndexParams(10)),
flann_params_(flann::FLANN_CHECKS_UNLIMITED,0,true) {
set_sites(sites, sites_size) ;
}
/* Nearest neighbours */
void knnSearch( const double* query, unsigned int size,
unsigned int* nnsites, double* nndistances
) {
//convert input to flann matrices
flann::Matrix<double> flann_query(const_cast<double*>(query), 1, Dim) ;
flann::Matrix<int> flann_nnsites((int*) nnsites, 1, size) ;
flann::Matrix<double> flann_nndistances(nndistances, 1, size) ;
//query
index_.knnSearch( flann_query,
flann_nnsites,
flann_nndistances,
size,
flann_params_
) ;
}
/* Overloading site setting in clipper to update nearest neighbours */
void set_sites( const double* sites, unsigned int sites_size ) {
//build flann index
flann_points_ = flann::Matrix<double>(
const_cast<double*>(sites), sites_size, Dim
) ;
index_.buildIndex(flann_points_) ;
}
private :
/* FLANN data */
flann::Matrix<double> flann_points_ ;
flann::Index< flann::L2<double> > index_ ;
/* Parameters */
flann::SearchParams flann_params_ ;
} ;
//}}}
} //end of namespace Revoropt
#endif
|
de2854d45c8835227240893cb146c8b20a425360 | 76d0e84b1efd2249497b26287ad3a301658af852 | /CPP/resq.cpp | 5378a566ab370b4f0026631949f39f1496e0553b | [] | no_license | nickzuck/Codechef | e5409e31343350fb884770a96161d18689f96536 | cfcd7e9aeeec29e1434162e077ca05793eec7184 | refs/heads/master | 2021-05-22T04:18:09.764528 | 2021-04-05T03:32:02 | 2021-04-05T03:32:02 | 38,664,793 | 0 | 2 | null | 2021-04-05T03:32:03 | 2015-07-07T04:49:14 | C++ | UTF-8 | C++ | false | false | 468 | cpp | resq.cpp | /*NICE PROBLEM ....Have to check the editorial for the solution*/
#include<cstdio>
#include<cmath>
using namespace std ;
int main ()
{
long int n , t , x , y , ans ;
scanf ("%ld",&t) ;
while (t--)
{
scanf ("%ld",&n) ;
for (x= sqrt(n) ; x>0 ; x--)
{
//printf ("x = %ld ans = %ld",x , ans ) ;
if (n % x == 0)
{
y = n/x ;
ans = y -x ;
break ;
}
}
printf ("%ld\n",ans) ;
}
return 0 ;
} |
19c9c5cfac7e80d0fbf15924574a6a1518484380 | 06db43b5ca8c0212f950c62c4f8764a15cf5c06a | /CppBrassart/Monster.h | 3c6d7b629c3d3c6205e820362edfe66c925fa2a4 | [] | no_license | bobcastle/CppBrassart | b6013a39c0415f4c0bae3b0017d99f894f48f92a | 1c5b46043dcd48b9960e49655e91598a6b5b0d91 | refs/heads/main | 2023-03-10T09:05:17.751821 | 2021-02-21T22:10:57 | 2021-02-21T22:10:57 | 336,903,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | h | Monster.h | #pragma once
#include "Character.h"
class Monster : public Character
{
public:
Monster(string pName, int pLife, int pDamage);
};
|
0b9dcee8e7bd39b51759ffe42ae62935ea7ab151 | 8e5db4f907ecbf23c0bef72798d7e542d898aae7 | /src/engine/engine.cc | e3076f68bf1b60ff23a3e5fd840d36afd435710f | [] | no_license | GBuella/Kator | 36b187024de8edcb812d7b8dfce8f5ad9f4a6a00 | f0799f190e328f1c4c9e8bf574fc448fb4099a98 | refs/heads/master | 2016-09-06T19:16:39.242030 | 2015-09-01T18:43:03 | 2015-09-01T18:43:03 | 30,843,562 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,692 | cc | engine.cc |
#include <chrono>
#include <mutex>
#include <thread>
#include <vector>
#include "chess/game_state.h"
#include "engine.h"
#include "search.h"
#include "chess/position.h"
using ::std::unique_ptr;
using ::std::make_unique;
using ::std::function;
namespace kator
{
namespace engine
{
namespace
{
class engine_implementation : public engine
{
std::mutex mutex;
unique_ptr<search_factory> factory;
unsigned max_depth;
unsigned max_time;
bool is_search_running;
std::vector<unique_ptr<search> > workers;
function<void(result)> sub_result_callback;
function<void(result)> final_result_callback;
function<void(result)> fixed_result_callback;
unique_ptr<game_state> root;
static constexpr unsigned absolute_max_depth = 128;
public:
engine_implementation(unique_ptr<search_factory> ctor_factory):
max_depth(0),
is_search_running(false)
{
if (ctor_factory == nullptr) {
throw std::exception();
}
factory = std::move(ctor_factory);
}
void set_max_depth(unsigned depth)
{
std::lock_guard<std::mutex> guard(mutex);
if (not is_search_running) {
if (depth > absolute_max_depth) {
depth = absolute_max_depth;
}
max_depth = depth;
if (max_depth > 0) {
max_time = 0;
}
}
}
unsigned get_max_depth() const noexcept
{
return max_depth;
}
bool is_running() const noexcept
{
return is_search_running;
}
void set_sub_result_callback(function<void(result)> callback)
{
sub_result_callback = callback;
}
void set_final_result_callback(function<void(result)> callback)
{
final_result_callback = callback;
}
void set_fixed_result_callback(function<void(result)> callback)
{
fixed_result_callback = callback;
}
void set_max_time(unsigned ms)
{
std::lock_guard<std::mutex> guard(mutex);
if (not is_search_running) {
max_time = ms;
if (ms > 0 ) {
max_depth = 0;
}
}
}
void start(unique_ptr<game_state> search_root)
{
std::lock_guard<std::mutex> guard(mutex);
if (is_search_running) {
throw std::exception();
}
root = std::move(search_root);
is_search_running = true;
}
void shutdown()
{
std::lock_guard<std::mutex> guard(mutex);
if (not is_search_running) {
return;
}
workers.clear();
is_search_running = false;
}
~engine_implementation()
{
workers.clear();
}
}; /* class engine_implementation */
} /* anonymous namespace */
unique_ptr<engine> engine::create(unique_ptr<search_factory> factory)
{
return make_unique<engine_implementation>(std::move(factory));
}
} // namespace kator::engine
} // namespace kator
|
04e26a92b573b1e1c2b0c5ceaee5d7443683f761 | 4d526bede6ab033c9437d4d82c58aa0c047b6df6 | /src/cell.h | 8a80840b760b191336f201b0df33a86395387163 | [] | no_license | teaolivia/zootopia | e81185a3d9b145a78fbc57a9adf0fcfbbfebaef2 | 726a2e8c27d42c07a7145eaffa815ed4e9e02bba | refs/heads/master | 2021-01-19T12:10:13.691339 | 2017-03-16T04:37:13 | 2017-03-16T04:37:13 | 82,290,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | h | cell.h | // Pembuat :
// Thea Olivia - 13511001
// Mahesa Gandakusuma - 13513091
#ifndef CELL_H
#define CELL_H
class Cell {
public:
Cell();
Cell(char _c);
~Cell();
virtual char GetChar();
private:
char c;
};
#endif |
656081567a543b69fa012a340f4aeaf700e95dfa | 9e79b322867bcf881a02ccdbafb82c4a4e2dc140 | /rclcpp/include/rclcpp/detail/rmw_implementation_specific_subscription_payload.hpp | b909a351798f813b8ce557e70f737193b5e3cd8c | [
"Apache-2.0"
] | permissive | ros2/rclcpp | 087aefd7d412b8ac5ad11614bd98978206fa3c9b | 65f0b70d4aa4d1a3b8dc4c08aae26151ca00ca55 | refs/heads/rolling | 2023-08-16T23:02:41.840776 | 2023-08-15T22:21:33 | 2023-08-15T22:21:33 | 22,737,333 | 439 | 443 | Apache-2.0 | 2023-09-14T14:53:05 | 2014-08-07T21:36:38 | C++ | UTF-8 | C++ | false | false | 1,883 | hpp | rmw_implementation_specific_subscription_payload.hpp | // Copyright 2019 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP__DETAIL__RMW_IMPLEMENTATION_SPECIFIC_SUBSCRIPTION_PAYLOAD_HPP_
#define RCLCPP__DETAIL__RMW_IMPLEMENTATION_SPECIFIC_SUBSCRIPTION_PAYLOAD_HPP_
#include "rcl/subscription.h"
#include "rclcpp/detail/rmw_implementation_specific_payload.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace detail
{
/// Subscription payload that may be rmw implementation specific.
class RCLCPP_PUBLIC RMWImplementationSpecificSubscriptionPayload
: public RMWImplementationSpecificPayload
{
public:
~RMWImplementationSpecificSubscriptionPayload() override = default;
/// Opportunity for a derived class to inject information into the rcl options.
/**
* This is called after the rcl_subscription_options_t has been prepared by
* rclcpp, but before rcl_subscription_init() is called.
*
* The passed option is the rmw_subscription_options field of the
* rcl_subscription_options_t that will be passed to rcl_subscription_init().
*
* By default the options are unmodified.
*/
virtual
void
modify_rmw_subscription_options(rmw_subscription_options_t & rmw_subscription_options) const;
};
} // namespace detail
} // namespace rclcpp
#endif // RCLCPP__DETAIL__RMW_IMPLEMENTATION_SPECIFIC_SUBSCRIPTION_PAYLOAD_HPP_
|
a9d1f9fda1646dde767c0544120aa43dff09aca1 | 53f5b15f264a77f64c8e76be72ca9d9f3efb5698 | /jim-and-the-orders/jim-and-the-orders.cpp | 28de8ea77c9e16cef749572475eb52fdf66cafdd | [] | no_license | alepez/hackerrank-solutions | 5bccbc34896e84d040fd7f1e8ccd1b211bd4a3e6 | 94dd6695f969971e4619a46de71d0170cfd97c8a | refs/heads/master | 2023-02-18T03:03:15.817513 | 2023-02-15T06:46:25 | 2023-02-15T06:46:25 | 166,770,512 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | cpp | jim-and-the-orders.cpp | #include <algorithm>
#include <iostream>
#include <vector>
int main() {
struct Customer {
int i;
int orderNumber;
int prepTime;
};
std::vector<Customer> orders;
int n;
std::cin >> n;
for (int i = 1; i <= n; ++i) {
Customer c;
c.i = i;
std::cin >> c.orderNumber;
std::cin >> c.prepTime;
orders.push_back(c);
}
std::sort(orders.begin(), orders.end(), [](Customer l, Customer r) {
const int diff = l.orderNumber - r.orderNumber + l.prepTime - r.prepTime;
return diff == 0 ? l.i < r.i : diff < 0;
});
for (auto c : orders) {
std::cout << c.i << " ";
}
}
|
c79ba723abf95da1baadc81cd809413fcd32b13e | 41b0d768b3d9373b6e0d4e950f24c875a2639793 | /Gems2D/AnimatedElementsLayer.h | 6ae5f8f2e61ef5ecb31af8d73f1f3d9200646a7a | [] | no_license | AmazingTeapot/Gems2D | 3140a90d50fd3ff8aed9d98c148e4d7b6dcdf689 | 2e8198d1df509fd05a7e14b27c92fdfe43d8869d | refs/heads/master | 2016-09-16T11:50:04.235703 | 2013-11-14T23:07:46 | 2013-11-14T23:07:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,407 | h | AnimatedElementsLayer.h | #pragma once
#include "stdafx.h"
#include "Layer.h"
#include "Camera.h"
#include "Sprite.h"
#include "Enemy1.h"
#include "ResourceManager.h"
#include "AnimatedSprite.h"
#include <fstream>
#include <iostream>
/* Class: Animated Elements Layer
Brief: With this kind of layer it is possible to display image resources. This resources can have some animations
defined. They will have animation sheets with all the "steps".
On one layer of this kind we'll draw the player.
If you draw this layer after the player layer is drawn, the objects will cover the player. */
class AnimatedElementsLayer : public Layer {
public:
/* CONSTRUCTORS */
/* Empty constructor */
AnimatedElementsLayer();
/* DESTRUCTORS */
/* Empty destructor */
~AnimatedElementsLayer();
/* SETTERS */
/* Sets the layer presets, located on the file defined by path */
virtual void setLayer(std::string path);
/* Changes the current animation of the element "element" to "animation" */
void changeAnimation(int element, int animation);
/* Changes the position of the element "element" to "x" and "y" */
void changePosition(int element, int x, int y);
/* Returns the actual animation of the element "element" */
int getActualAnimation(int element);
/* GETTERS */
/* Gets the animated elements of the layer */
std::vector<AnimatedSprite> getAnimatedSprites();
/* Gets the animated enemies -> WE NEED A NEW MODULE FOR THIS */
std::vector<Enemy*> getAnimatedEnemies();
void kill(int i);
/* DOMAIN FUNCTIONS */
/* Updates the position of the background image according to the observer */
virtual void update (float deltaTime);
/* Draws the layer on the window. Concretely, draws all the elements of the subrectangle of the image visible by the player on the window.
It would be good to define an offset range to precharge the elements */
virtual void draw(sf::RenderWindow& App);
/* This method is used to write only some of the layers. It is used situationally, but I have to polish it. It was useful during
the Game&Bud development phase. */
virtual void superDraw (sf::RenderWindow& App, int element, float x_pos, float y_pos);
private:
int m_elements;
int m_diff_resources;
std::string m_level_folder;
std::vector<AnimatedSprite> m_layer_elements;
std::vector<Enemy*> m_layer_enemy1;
bool isDrawable(AnimatedSprite anim, std::vector<int> drawableArea);
};
|
98bced353faf1e40bf44dbfca3bd78fed4aacd7f | 751504517113e5ebc6edb0178283b9a0165daa3c | /p2/tests/tests/public_rectangle0.cpp | b6c8401e057b92dab593cabe06cffa83fc148406 | [] | no_license | Rose-Lin/245 | 5146406785f170967f28cdb965f0b66cef1b5ad1 | 8c9b42a9b6697e34fb52cb73d8dd31c2d0fd87d9 | refs/heads/master | 2020-04-30T04:34:00.740204 | 2019-05-04T19:24:41 | 2019-05-04T19:24:41 | 176,613,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cpp | public_rectangle0.cpp | #include <iostream>
#include "../ShapesStructs.h"
int main()
{
void* rect = newRectangle(0,0,50,100);
if (vtable(rect)->getXpos(rect) != 25) return 1;
if (vtable(rect)->getYpos(rect) != 50) return 1;
if (vtable(rect)->getArea(rect) != 5000) return 1;
return 0;
}
|
d053e00bfbdc8718a944053c9eb1dbd20b18c8cf | 378699a7f0f1b3305859d9b0cba6a99d24136ac2 | /navi/bind/TypeList.hh | e8f022a3254b3b35bb1343866b262d4db294a0f9 | [] | no_license | Wotan/WSMS | 84b3549beb76d15bfc0ad047c876e22c8c12eceb | 3d580124d055dbccbe0e640653f79a1a00af1130 | refs/heads/master | 2021-01-10T19:54:59.747919 | 2013-04-22T02:37:48 | 2013-04-22T02:37:48 | 8,824,946 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,208 | hh | TypeList.hh | #ifndef _TYPELISTBIND_H_
#define _TYPELISTBIND_H_
# include "Value.hh"
# include "TypeTraits.hh"
# include "PlaceHolder.hh"
namespace navi {
template <typename T>
struct TypeTraits;
struct TypeList0 : private Storage0
{
TypeList0() : Storage0() {}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List&)
{
return caller();
}
};
template <typename P1>
struct TypeList1 : private Storage1<P1>
{
typedef Storage1<P1> BaseClass;
TypeList1(P1 p1) : BaseClass(p1) {}
P1& operator[](Arg<1>)
{
return BaseClass::_t1;
}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List& list)
{
list[BaseClass::_t1];
return caller(list[BaseClass::_t1]);
}
};
template <typename P1, typename P2>
struct TypeList2 : private Storage2<P1, P2>
{
typedef Storage2<P1, P2> BaseClass;
TypeList2(P1 p1, P2 p2) : BaseClass(p1, p2) {}
P1& operator[](Arg<1>)
{
return BaseClass::_t1;
}
P2& operator[](Arg<2>)
{
return BaseClass::_t2;
}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List& list)
{
return caller(list[BaseClass::_t1], list[BaseClass::_t2]);
}
};
template <typename P1, typename P2, typename P3>
struct TypeList3 : private Storage3<P1, P2, P3>
{
typedef Storage3<P1, P2, P3> BaseClass;
TypeList3(P1 p1, P2 p2, P3 p3) : BaseClass(p1, p2, p3) {}
P1& operator[](Arg<1>)
{
return BaseClass::_t1;
}
P2& operator[](Arg<2>)
{
return BaseClass::_t2;
}
P3& operator[](Arg<3>)
{
return BaseClass::_t3;
}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List& list)
{
return caller(list[BaseClass::_t1], list[BaseClass::_t2], list[BaseClass::_t3]);
}
};
template <typename P1, typename P2, typename P3, typename P4>
struct TypeList4 : private Storage4<P1, P2, P3, P4>
{
typedef Storage4<P1, P2, P3, P4> BaseClass;
TypeList4(P1 p1, P2 p2, P3 p3, P4 p4) : BaseClass(p1, p2, p3, p4) {}
P1& operator[](Arg<1>)
{
return BaseClass::_t1;
}
P2& operator[](Arg<2>)
{
return BaseClass::_t2;
}
P3& operator[](Arg<3>)
{
return BaseClass::_t3;
}
P4& operator[](Arg<4>)
{
return BaseClass::_t4;
}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List& list)
{
return caller(list[BaseClass::_t1], list[BaseClass::_t2], list[BaseClass::_t3],
list[BaseClass::_t4]);
}
};
template <typename P1, typename P2, typename P3, typename P4, typename P5>
struct TypeList5 : private Storage5<P1, P2, P3, P4, P5>
{
typedef Storage5<P1, P2, P3, P4, P5> BaseClass;
TypeList5(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) : BaseClass(p1, p2, p3, p4, p5) {}
P1& operator[](Arg<1>)
{
return BaseClass::_t1;
}
P2& operator[](Arg<2>)
{
return BaseClass::_t2;
}
P3& operator[](Arg<3>)
{
return BaseClass::_t3;
}
P4& operator[](Arg<4>)
{
return BaseClass::_t4;
}
P5& operator[](Arg<5>)
{
return BaseClass::_t5;
}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List& list)
{
return caller(list[BaseClass::_t1], list[BaseClass::_t2], list[BaseClass::_t3],
list[BaseClass::_t4], list[BaseClass::_t5]);
}
};
template <typename P1, typename P2, typename P3, typename P4, typename P5, typename P6>
struct TypeList6 : private Storage6<P1, P2, P3, P4, P5, P6>
{
typedef Storage6<P1, P2, P3, P4, P5, P6> BaseClass;
TypeList6(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) : BaseClass(p1, p2, p3, p4, p5, p6) {}
P1& operator[](Arg<1>)
{
return BaseClass::_t1;
}
P2& operator[](Arg<2>)
{
return BaseClass::_t2;
}
P3& operator[](Arg<3>)
{
return BaseClass::_t3;
}
P4& operator[](Arg<4>)
{
return BaseClass::_t4;
}
P5& operator[](Arg<5>)
{
return BaseClass::_t5;
}
P6& operator[](Arg<6>)
{
return BaseClass::_t6;
}
template <typename T>
T& operator[](Value<T>& value)
{
return value.get();
}
template <typename ReturnType, typename Caller, typename List>
ReturnType operator()(TypeTraits<ReturnType>, Caller& caller, List& list)
{
return caller(list[BaseClass::_t1], list[BaseClass::_t2], list[BaseClass::_t3],
list[BaseClass::_t4], list[BaseClass::_t5], list[BaseClass::_t6]);
}
};
} // !navi
#endif /* !_TYPELISTBIND_H_ */
|
add4f4f1449622442737e21a05b0900b2fe45b9d | eca506dd3af9fefc2715aac97cb39c4410ec8f9e | /4_sem_prac/contests/7/3.cpp | fef1e8132177d9eeebf8adcac156b6dd46ba0a4f | [] | no_license | ArtemVeshkin/cmc_cpp_prac | 4979fd93ff5d798d381cb7a1aec8efa4f3952728 | 072b2d0fa3e696c591d6746e3c6c6ee73850e5f5 | refs/heads/master | 2021-01-01T00:58:16.695083 | 2020-05-18T09:10:52 | 2020-05-18T09:10:52 | 239,108,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | cpp | 3.cpp | #include <iostream>
class S
{
int num_{};
bool read_{};
public:
S()
{
read_ = bool{std::cin >> num_};
}
S(S&& other)
{
read_ = bool{std::cin >> num_};
if (read_ && other.read_) {
other.read_ = false;
num_ += other.num_;
}
}
~S()
{
if (read_) {
std::cout << num_ << std::endl;
}
}
operator bool()
{
return read_;
}
}; |
a459c0b0c7eeebbe38da34b754b66de6b872cbc6 | 98bbc1c7c8513164b9fe498ceee541b425130492 | /Week 1/Question 4/Employee.cpp | 7a2e1f7e944b2747d4bc513d6ef7c9b4fda9e8ff | [] | no_license | kawaijoesch/DSA_Practical | 304daef1eb9b63383144a505900151f8afb356ab | 65985785c2fefd3376f20eec24702369d2bfd25d | refs/heads/master | 2021-09-03T16:55:52.776800 | 2018-01-10T16:05:23 | 2018-01-10T16:05:23 | 116,979,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | cpp | Employee.cpp | //
// Created by Joe Kawai on 9/12/17.
//
#include "Employee.h"
const string &Employee::getFirstName() const {
return firstName;
}
void Employee::setFirstName(const string &firstName) {
Employee::firstName = firstName;
}
const string &Employee::getLastName() const {
return lastName;
}
void Employee::setLastName(const string &lastName) {
Employee::lastName = lastName;
}
Employee::Employee(const string &lastName, const string &firstName, int salary) : lastName(lastName),
firstName(firstName) {
setSalary(salary);
}
int Employee::getSalary() const {
return salary;
}
void Employee::setSalary(int salary) {
if (salary < 0) salary = 0;
Employee::salary = salary;
}
|
fe74735bdc30da27cc9d70a4b872d36747663f72 | af7596e5da7eb50165cf672322f22bb520760045 | /src/app/releasemgr/task/cloudcontroller/rpm/clear.cpp | 9e9d88b041ac89cea90771e7600683fe82adce76 | [] | no_license | cntysoft/releasemgr | f5fd4859235947d0613ca827fdb56ccc49245224 | 40183e515c821550938ebaa684fb9f9f995e8d77 | refs/heads/master | 2021-01-01T04:56:38.110622 | 2016-04-06T03:47:36 | 2016-04-06T03:47:36 | 58,316,444 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | clear.cpp | #include <QFileInfo>
#include "clear.h"
#include "task/abstract_taskmgr.h"
#include "io/filesystem.h"
#include "kernel/errorinfo.h"
namespace releasemgr{
namespace task{
namespace cloudcontroller{
namespace rpmbuild{
using sn::corelib::Filesystem;
using sn::corelib::ErrorInfo;
Clear::Clear(const AbstractTaskMgr& taskmgr, const TaskParamsType& invokeArgs)
:RpmBuildAbstractTask(taskmgr, invokeArgs)
{}
void Clear::exec()
{
writeBeginMsg("开始清除打包目录 ... ");
if(Filesystem::fileExist(m_buildDir)){
if(!Filesystem::isWritable(m_buildDir)){
throw ErrorInfo("build directory is no writable");
}
Filesystem::deleteDirRecusive(m_buildDir);
}
Filesystem::createPath(m_buildDir);
writeDoneMsg();
}
Clear::~Clear()
{}
}//rpmbuild
}//cloudcontroller
}//task
}//releasemgr |
e5c0bf25445e7e7fd8e85254cc6abe29b977bf3f | b6c35382b383b8f9d387f0a08e05c7c30992d0e8 | /projects/engine/src/Simulation/SimManager.h | f228a7d93af9e820211daef72d7d24ca94b23006 | [] | no_license | rpsfonseca/EngineCGJ | d948a7ac77debb60165932771dad9dc04fd1fc36 | e38149ee95e94f3092ed18f873e820df8a0bd2b0 | refs/heads/master | 2021-09-04T09:14:50.476199 | 2018-01-17T16:20:42 | 2018-01-17T16:20:42 | 104,339,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | h | SimManager.h | /*
* A cellular automata approach to simulating clouds
* such as described by Dobashi et al.,
* which extends Nagel's method
*/
#ifndef __SIM_MANAGER_H__
#define __SIM_MANAGER_H__
#include "SimData.h"
#include "Cloud.h"
#include <random>
#include <deque>
class SimManager {
public:
SimManager(const int x, const int y, const int z);
// Asynchronous Step
void stepAsych(SimData* data);
// Part of the simulation step that updates shared data and is protected with a mutex
void stepMutex(SimData* data, const double startTime);
private:
typedef std::deque<Cloud> CV;
const int x;
const int y;
const int z;
// Smaller base gives bigger clouds
const int exponentialBase;
const int minCloudSize;
const int maxCloudSize;
// List of clouds
CV clouds;
// Vapor extinction probability
float pHumExt;
// Phase transition extinction probability
float pActExt;
// Cloud extinction probability
float pCldExt;
std::mt19937 gen;
int randomResolution;
// Simulate a cellular automata step
void simulateCellular(bool *** hum, bool
*** act, bool *** cld, bool *** fAc, float *** distSize);
// Creates a cloud at random position with random size
void createRandomCloud();
// Recalculates dist/size, should be called when clouds are created
void calculateDistSize(float *** distSize);
// Calculate continous cloud density distribution for entire grid
void calculateDensity(bool *** cld, float *** den);
// Calculate continous cloud density distribution for one cell
float singleDensity(int i, int j, int k,
bool *** cld, int S);
// Calculate field function
float fieldFunction(float a);
// Override one array with another
void copyGrid(float*** copyTo, float*** copyFrom);
};
#endif |
8295f93d1562ff36477e53e44f68c37166f61939 | 8a4c24de1230bbb060d96340485cf63824b501e1 | /DeusCore/PacketConnectedUdpAnswer.cpp | ebe287ad16c1800c37f7734d5c2f6f41c04806fb | [
"MIT"
] | permissive | Suliac/ProjectDeusServer | c9b46c3fbb86d14bb0bc36eaaec2c0bdf76b25e5 | b7af922a6bc2596c733665898b6aefd989bf2270 | refs/heads/master | 2020-03-22T15:52:22.600876 | 2018-10-30T00:17:06 | 2018-10-30T00:17:06 | 140,285,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,395 | cpp | PacketConnectedUdpAnswer.cpp | #include "PacketConnectedUdpAnswer.h"
namespace DeusCore
{
PacketConnectedUdpAnswer::PacketConnectedUdpAnswer()
: Packet(Packet::EMessageType::ConnectedUdpAnswer)
{
}
PacketConnectedUdpAnswer::~PacketConnectedUdpAnswer()
{
}
void PacketConnectedUdpAnswer::OnDeserialize(Buffer512 & buffer)
{
// get the size of the string
uint8_t dataSize;
DeserializeData(buffer, dataSize);
// get the string
m_playerNickname.clear();
std::vector<unsigned char> tmp = buffer.Select(dataSize);
m_playerNickname.assign((char *)tmp.data());
}
void PacketConnectedUdpAnswer::OnSerialize(Buffer512 & buffer) const
{
uint8_t dataSize = m_playerNickname.size() + 1; // +1 to add the \0 of string
SerializeData(buffer, dataSize); // SerializeData only for primitive
// then we add the string
const char* myCurrentText = m_playerNickname.c_str();
for (size_t i = 0; i < dataSize; i++)
{
SerializeData(buffer, *myCurrentText);
myCurrentText++;
}
}
uint16_t PacketConnectedUdpAnswer::EstimateCurrentSerializedSize() const
{
// 1 PacketClientConnected uses :
// - 1 byte : to save an unsigned int for the length of the next string
// - m_message.size()+1 bytes : to save the string ip address ('+1' is for the \0)
return uint16_t(sizeof(uint8_t) + (m_playerNickname.size() + 1));
}
}
|
547a95f67e5c71af533e4b10643b658627299488 | 9a2c1b2a59617f5367f14fd494a03c2c64c8a908 | /WordText/score.cpp | 7bf3ecb09d79df63c6e278ec39123f8833795086 | [] | no_license | lizhenjie94/textword | dacf4d26ee4d6fa796fb9970208c5a42df76fa16 | b58d5ff2b5aece050db2b3b60aee12800ddc35c9 | refs/heads/master | 2021-01-10T08:15:54.127601 | 2015-12-23T15:32:32 | 2015-12-23T15:32:32 | 48,487,254 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 458 | cpp | score.cpp | #include "score.h"
#include "ui_score.h"
score::score(QWidget *parent) :
QDialog(parent),
ui(new Ui::score)
{
ui->setupUi(this);
connect(ui->btnBack, SIGNAL(clicked(bool)), this, SLOT(openMain()));
connect(ui->btnExit, SIGNAL(clicked(bool)), qApp, SLOT(quit()));
}
score::~score()
{
delete ui;
}
void score::openMain()
{
MainWindow *w = new MainWindow;
w->setAttribute(Qt::WA_DeleteOnClose);
w->show();
close();
}
|
f7904c9af06725488efbe36ae2c5303e4b6a49c4 | 27534cbbf7f0ae1e2cf0feb260c755660f2fb483 | /External/FEXCore/Source/Interface/HLE/Syscalls/Info.h | df59b5240fddcbad15e9dba2785f541e44fde600 | [
"MIT"
] | permissive | woachk/FEX | 38762407172526ace01cbef841b8cd24d4c5d951 | 66dc5ebc54f3ff9b51eed714eb37bff34a0a82e6 | refs/heads/master | 2022-06-16T18:39:27.918624 | 2020-05-01T23:58:07 | 2020-05-01T23:58:07 | 261,212,978 | 0 | 0 | MIT | 2020-05-04T14:54:47 | 2020-05-04T14:54:46 | null | UTF-8 | C++ | false | false | 571 | h | Info.h | #pragma once
#include <stddef.h>
#include <stdint.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
namespace FEXCore::Core {
struct InternalThreadState;
}
namespace FEXCore::HLE {
uint64_t Uname(FEXCore::Core::InternalThreadState *Thread, struct utsname *buf);
uint64_t Sysinfo(FEXCore::Core::InternalThreadState *Thread, struct sysinfo *info);
uint64_t Syslog(FEXCore::Core::InternalThreadState *Thread, int priority, const char *format, ...);
uint64_t Getrandom(FEXCore::Core::InternalThreadState *Thread, void *buf, size_t buflen, unsigned int flags);
}
|
fc04d1035a8ba0b055b316b242ce5f34e4cea63a | 4573e9e864746724016d3157123fefdaad27c73b | /Partenering parenting codejam 2020.cpp | e94e9df4b5b03eb21e508ca664d4fad9f82102da | [] | no_license | sanchitgoel10/365_of_code | 0389a28d88e947d3a1230016ab74b36319b71f27 | 8e57bb5274c30a7d11359a6e4f9d358524894fbc | refs/heads/master | 2021-01-04T22:24:54.870820 | 2020-10-02T13:36:21 | 2020-10-02T13:36:21 | 240,783,118 | 5 | 2 | null | 2020-07-03T16:24:44 | 2020-02-15T20:26:26 | C++ | UTF-8 | C++ | false | false | 1,743 | cpp | Partenering parenting codejam 2020.cpp | #include<bits/stdc++.h>
using namespace std;
#define FastRead ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//#define int long int
bool comp(pair<int, pair<bool, int> > p1,
pair<int, pair<bool, int> > p2) {
if (p1.first==p2.first) return p1.second.first > p2.second.first;
return p1.first < p2.first;
}
int main(){
FastRead;
int t;
cin>>t;
int tc=1;
while(t--){
int n;
cin>>n;
vector<pair<int, pair<bool, int> > > v;
bool ans[n+1];
bool poss=true;
for(int i=1;i<=n;i++){
int si;int ei;
cin>>si>>ei;
v.push_back(make_pair(si, make_pair(0,i)));
v.push_back(make_pair(ei, make_pair(1,i)));
}
sort(v.begin(),v.end(),comp);
bool c=false,j=false;
for(auto i:v){
if(i.second.first==0){
if(c==1 && j==1){
poss=false;
break;
}
if(c==0){
ans[i.second.second]=1;
c=1;
}else if(j==0){
ans[i.second.second]=0;
j=1;
}
}else{
if(ans[i.second.second]==0){
j=0;
}else{
c=0;
}
}
}
string s="";
if(poss==false){
s="IMPOSSIBLE";
}else{
for(int i=1;i<=n;i++){
if(ans[i]){
s+="C";
}else{
s+="J";
}
}
}
cout<<"Case"<<" "<<"#"<<tc<<": "<<s<<endl;
tc++;
}
} |
672b77d9f0f7ea947c90c1a77c641063aa598d90 | e79e11b98cd6e02d82cbee1d24458a57cb188194 | /Board.cpp | 02c000ff961013d7aad4cb792349090d2cc7edb9 | [] | no_license | FrontRowWithJ/Mabble | 23f0aac099c38693ee6b26822974d6b974df0723 | 6f89054adee7f2e705b3f9e8411e6dac6fe419c4 | refs/heads/master | 2020-05-02T16:50:41.928742 | 2019-06-25T19:52:38 | 2019-06-25T19:52:38 | 178,080,056 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,963 | cpp | Board.cpp | #include "Board.hpp"
Board::Board(float width, int rowLen, float xPos, float yPos, const char *fontName, Color textColor, Color bgColor)
{
//boardWidth must be an odd number
this->width = width;
this->rowLen = rowLen % 2 == 1 ? rowLen : rowLen + 1;
this->xPos = xPos;
this->yPos = yPos;
gen_board(fontName, textColor, bgColor);
}
void Board::place_tile(LinkedList<TileData> *placedTiles, Tile *selectedTile, int i, int j)
{
TileData td;
Vector2f boardCoords;
Tile *t;
switch (table[i][j].get_state())
{
case TILE_FULL_TEMP:
t = table[i][j].get_tile();
t->deselect_tile();
td = (TileData){i, j, t->get_value()};
placedTiles->delete_node(td);
set_radii(i, j);
case TILE_EMPTY:
table[i][j].set_tile(selectedTile);
table[i][j].set_state(TILE_FULL_TEMP);
table[i][j].set_bgColor(selectedTile->get_bgColor());
table[i][j].update_text(selectedTile->get_value(), selectedTile->get_textColor());
selectedTile->set_state(ON_BOARD_TEMP);
selectedTile->set_isSelected(false);
selectedTile->set_boardPos(Vector2i(i, j));
boardCoords = table[i][j].get_position() - (selectedTile->get_width() - table[i][j].get_width()) / 2;
selectedTile->set_position_to_board(boardCoords);
td = (TileData){i, j, selectedTile->get_value()};
placedTiles->insert(td);
set_radii(i, j);
break;
case TILE_FULL_PERM:
selectedTile->deselect_tile();
}
}
void Board::clear_board()
{
for (int i = 0; i < width; i++)
for (int j = 0; j < width; j++)
{
table[i][j].set_tile_to_null();
table[i][j].set_state(TILE_EMPTY);
}
}
void Board::gen_board(const char *fontName, Color textColor, Color bgColor)
{
table = new BoardTile *[rowLen];
for (int i = 0; i < rowLen; i++)
table[i] = new BoardTile[rowLen];
int yOffset = 0;
for (int i = 0; i < rowLen; i++)
{
int xOffset = 0;
for (int j = 0; j < rowLen; j++)
{
table[i][j] = BoardTile(width / rowLen, xPos + xOffset, yPos + yOffset, textColor, bgColor, fontName, i == rowLen / 2 && j == rowLen / 2);
xOffset += width / rowLen;
table[i][j].gen_visuals();
}
yOffset += width / rowLen;
}
}
void Board::draw(RenderWindow *window)
{
for (int i = 0; i < rowLen; i++)
for (int j = 0; j < rowLen; j++)
table[i][j].draw(window);
}
void Board::remove_tile(LinkedList<TileData> *placedTiles, int i, int j)
{
switch (table[i][j].get_state())
{
case TILE_FULL_PERM:
break;
case TILE_EMPTY:
break;
case TILE_FULL_TEMP:
Tile *t = table[i][j].get_tile();
t->deselect_tile();
TileData td = (TileData){i, j, t->get_value()};
placedTiles->delete_node(td);
table[i][j].set_tile(NULL);
table[i][j].set_state(TILE_EMPTY);
table[i][j].update_text(EMPTY, Color::Black);
table[i][j].revert_bgColor();
unset_radii(i, j);
}
}
void Board::print_list(LinkedList<TileData> *list)
{
list->print();
}
BoardTile **Board::get_table()
{
return table;
}
float Board::get_width()
{
return width;
}
Vector2f Board::get_position()
{
return Vector2f(xPos, yPos);
}
int Board::get_rowLen()
{
return rowLen;
}
bool TileData::operator==(TileData rhs)
{
return i == rhs.i && j == rhs.j && value == rhs.value;
}
char *TileData::c_str()
{
return new char[2]{value, '\0'};
}
void Board::set_radii(int i, int j)
{
if (j + 1 < rowLen)
update_tile_radii(&table[i][j], &table[i][j + 1], A, D, B, C);
if (i - 1 >= 0)
update_tile_radii(&table[i][j], &table[i - 1][j], A, B, C, D);
if (j - 1 >= 0)
update_tile_radii(&table[i][j], &table[i][j - 1], B, C, A, D);
if (i + 1 < rowLen)
update_tile_radii(&table[i][j], &table[i + 1][j], C, D, A, B);
}
typedef int __;
#define ___ (
#define ____ )
#define _____ {
#define ______ }
#define _______ return
#define ________ *
#define _________ ;
__ _ ___ __ _ ____
_____
_______ _ ________ _ _________
______ void
Board::update_tile_radii(BoardTile *t0, BoardTile *t1, Quadrant a, Quadrant b, Quadrant c, Quadrant d)
{
BoardTileState bt0 = t0->get_state(), bt1 = t1->get_state();
if (bt0 != TILE_EMPTY && bt1 != TILE_EMPTY)
{
t0->set_quadrant_radius(0, a);
t0->set_quadrant_radius(0, b);
t1->set_quadrant_radius(0, c);
t1->set_quadrant_radius(0, d);
printf("%d\n", _(47));
}
}
void Board::unset_radii(int i, int j)
{
int _i, _j;
table[i][j].set_quadrant_radius(10, A);
table[i][j].set_quadrant_radius(10, B);
table[i][j].set_quadrant_radius(10, C);
table[i][j].set_quadrant_radius(10, D);
_i = i - 1;
_j = j;
if (_j - 1 >= 0 && table[_i][_j - 1].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, C);
if (_j + 1 < rowLen && table[_i][_j + 1].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, D);
_i = i + 1;
_j = j;
if (_j - 1 >= 0 && table[_i][_j - 1].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, B);
if (_j + 1 < rowLen && table[_i][_j + 1].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, D);
_i = i;
_j = j - 1;
if (_i - 1 >= 0 && table[_i - 1][_j].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, A);
if (_i + 1 < rowLen && table[_i + 1][_j].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, D);
_i = i;
_j = j + 1;
if (_i - 1 >= 0 && table[_i - 1][_j].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, B);
if (_i + 1 < rowLen && table[_i + 1][_j].get_state() == TILE_EMPTY)
table[_i][_j].set_quadrant_radius(10, C);
}
|
7caca0e4404bbbe9355fd9298b3b243eddd7d0af | 7439e4c50dc0bc0213bbb8626208d10bc167371a | /SnifferCxx/SnifferCxx/runmode/ExecutorFactory.cpp | 33c9810b7c4b536e3a9b3e677c2b6fb4f7f731ec | [] | no_license | gf4t47/Sniffer2 | d64d8956122ce2255903fb4ad30ad7e5a3c24965 | afc950a74222da2367eec56ff253bab4438b1f6a | refs/heads/master | 2020-05-17T12:18:09.980665 | 2017-11-16T21:52:22 | 2017-11-16T21:52:22 | 21,962,184 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | ExecutorFactory.cpp | #include "ExecutorFactory.h"
#include "../runmode/AsynEvent.h"
#include "../runmode/MultiThread.h"
#include "../runmode/Executor.h"
namespace RunMode
{
using namespace std;
using namespace RunMode;
ExecutorFactory::ExecutorFactory()
{
}
ExecutorFactory::~ExecutorFactory()
{
}
shared_ptr<Executor> ExecutorFactory::createExecutor(execute_mode run_type, const Model::Map3D& map, const Forward::ForwardChecking& forward, const Backward::BackwardChecking& backward)
{
switch (run_type)
{
case single:
return make_shared<Executor>(map, forward, backward);
case asyn_event:
return make_shared<AsynEvent>(map, forward, backward);
case multi_thread:
return make_shared<MultiThread>(map, forward, backward);
default:
return nullptr;
}
}
} |
90e09747b881b0c458fffcd7d664f846bcd186d0 | 9d761c1b289a5d784e786512d30b222eb00fdb8c | /Labs/Lab 1/PayCheck/main.cpp | b4135729cec5ea835f0e321ad5273f9ad3a3003a | [] | no_license | Laaccon/Lee-Norman-CSC5-46091 | 4dbe1901163ffd85637362b3e2af9ef01775be55 | d683c3992b324ae87dd373d83103693921b1b6ac | refs/heads/master | 2021-01-01T19:38:19.488216 | 2015-07-29T22:58:30 | 2015-07-29T22:58:30 | 38,081,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | main.cpp | /*
* File: main.cpp
* Author: Norman Lee
* Created on June 24, 2015, 12:45 AM
* Purpose: First Program to calculate a paycheck
*/
//System Libraries
#include <iostream> //File I/O
using namespace std; //std namespace -> iostream
//User Libraries
//Global constants
//Functions Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
// Declare Variables Here
float hours,rate,pay;
//Input Values Here
hours=40.0f;//Hours Worked Units = hours
rate=1e1f; //Pay Rate Units = $'s /hour
//Process Input Here
pay=hours*rate;//Units = $'s
//Output Unknowns Here
cout<<"Hours worked = "<<hours<<"(hrs)"<<endl;
cout<<"Pay Rate = $"<<rate<<"/(hrs)"<<endl;
cout<<"My Paycheck = $"<<pay<<endl;
//Exit Stage Right!
return 0;
} |
49913f2f56d58b3b7008e9f2fbebfe303e2cacdb | 4166afcb32e220f965bfdcf87abdac2ca9f00803 | /FileReader.cpp | f154edfb8ef85acee3e4356373d6ff4fcfabc952 | [] | no_license | abauer361/Assignment3 | 4ffc541b7111f40951baf8cb98167be763143753 | 710c685089f207fdd5a7ab449f89e6c1c6c8e6ab | refs/heads/master | 2020-04-01T00:38:39.087052 | 2018-10-12T06:49:25 | 2018-10-12T06:49:25 | 152,705,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,667 | cpp | FileReader.cpp | #include <iostream>
#include "Genstack.h"
#include "FileReader.h"
#include <fstream>
using namespace std;
FileReader::FileReader()
{
getFileName();
stack = new Genstack<char>(); //needed <char> because of template class
}
FileReader::FileReader(string name)
{
fileName = name;
stack = new Genstack<char>();
checkDelim();
}
FileReader::~FileReader()
{
delete stack;
}
bool FileReader::checkDelim()
{
string line;
ifstream input(fileName);
if(!input) //there's no file named fileName
{
cout << "No file was available with the name " << fileName << endl;
getFileName();
}
int lineNum = 0;
while(getline(input, line)) //goes through file line by line
{
for(int i = 0; i < line.length(); ++i) //goes through line character by character
{
if(line[i] == '(' || line[i] == '{' || line[i] == '[' || line[i] == ')' || line[i] == '}' || line[i] == ']') //only checks delimiters
{
if(line[i] == '(' || line[i] == '{' || line[i] == '[') //creates stack for open brackets
stack->push(line[i]);
else if(line[i] == ')' || line[i] == '}' || line[i] == ']')
{
if(stack->isEmpty()) //no delimiters overall
{
cout << "There was no other delimiter to match with.";
return false;
}
if(stack->peek() == '(' && line[i] != ')')
{
cout << "You see to be missing a ) at line " << lineNum+1 << endl;
return false;
}
else if(stack->peek() == '{' && line[i] != '}')
{
cout << "You see to be missing a } at line " << lineNum+1 << endl;
return false;
}
else if(stack->peek() == '[' && line[i] != ']')
{
cout << "You see to be missing a ] at line " << lineNum+1 << endl;
return false;
}
stack->pop();
}
}
}
lineNum++; //keeps the line count up
}
if(stack->isEmpty()) //we good
{
cout << "There are no delimiter errors!" << endl;
return true;
}
else //all for end of the file if delimiter is never found
{
if(stack->peek() == '(')
{
cout << "Reached end of file: missing )." << endl;
}
else if(stack->peek() == '{')
{
cout << "Reached end of file: missing }." << endl;
}
else if(stack->peek() == '[')
{
cout << "Reached end of file: missing ]." << endl;
}
return false;
}
input.close();
}
void FileReader::getFileName() //if name was entered wrong or no name entered at all
{
cout << "What is the name of your file?" << endl;
cin >> fileName;
checkDelim();
}
|
68824297d436b116b196929993b33bda288cae6e | cb312724fe7a6d367f5c83312ff65a75bd2a1bab | /Count1 In Bin.cpp | 3d1797ccf0d34d2a6e97e908cd69ec657de61462 | [] | no_license | arthurlz/hairy-coding | 4f475e92b4409c5d5843bd8ba4d73def1ce85246 | e885b5a0c85554a39c82ac1686794f385c9386f4 | refs/heads/master | 2021-09-09T00:29:45.217920 | 2014-11-29T18:04:33 | 2014-11-29T18:04:33 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 876 | cpp | Count1 In Bin.cpp | // Count1 In Bin.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
int countOriginal(int num);
int countByAnd(int num);
int countByAndSubOne(int num);
int _tmain(int argc, _TCHAR* argv[])
{
int num,count = 0;
scanf_s("%d",&num);
count = countByAndSubOne(num);
printf("二进制数%d有%d个1\n",num,count);
int ret = 0;
for(int i = 1;i <= num;i++)
{
int j = i;
while(j % 5 ==0)
ret++,j /= 5;
}
printf("%d的阶乘末尾有%d个0\n",num,ret);
system("pause");
return 0;
}
int countOriginal(int num)
{
int count = 0;
while (num)
{
if(num % 2 == 1)
count++;
num = num/2;
}
return count;
}
int countByAnd(int num)
{
int count = 0;
while(num)
{
count += num & 0x01;
num>>=1;
}
return count;
}
int countByAndSubOne(int num)
{
int count = 0;
while (num)
{
num &= (num-1);
count++;
}
return count;
} |
5a8640b7c61467b2fd31d45993b3229a03afd99b | a8c3b3f836350543cfa5ed486b8c4b725928a427 | /HK.SKINS/src/KitParser.cpp | cc5f5a1aef3f823563f032926dfb993d4ab9013b | [] | no_license | mvasilkov/CaramelbyHattrickHKS | 4eed761eb82cfd64ae7900886e3d78716574c5c0 | 481efd460dc07b23504b32606fd0af4b315b2281 | refs/heads/master | 2021-09-05T12:17:41.183465 | 2018-01-27T13:29:03 | 2018-01-27T13:29:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,819 | cpp | KitParser.cpp |
#include "SDK.hpp"
#include "Platform.hpp"
#include "KitParser.hpp"
#include "nSkinz.hpp"
vector <Kit_t> k_skins;
vector <Kit_t> k_gloves;
vector <Kit_t> k_stickers;
class CCStrike15ItemSchema;
class CCStrike15ItemSystem;
template <typename Key, typename Value> struct Node_t {
int previous_id;
int next_id;
void * _unknown_ptr;
int _unknown;
Key key;
Value value;
};
template <typename Key, typename Value> struct Head_t {
Node_t <Key, Value> * memory;
int allocation_count;
int grow_size;
int start_element;
int next_available;
int _unknown;
int last_element;
};
struct String_t {
char * buffer;
int capacity;
int grow_size;
int length;
};
struct CPaintKit {
int id;
String_t name;
String_t description;
String_t item_name;
String_t material_name;
String_t image_inventory;
char pad_0x0054[0x0000008C];
};
struct CStickerKit {
int id;
int item_rarity;
String_t name;
String_t description;
String_t item_name;
String_t material_name;
String_t image_inventory;
int tournament_event_id;
int tournament_team_id;
int tournament_player_id;
bool is_custom_sticker_material;
float rotate_end;
float rotate_start;
float scale_min;
float scale_max;
float wear_min;
float wear_max;
String_t image_inventory2;
String_t image_inventory_large;
uint32_t pad0[4];
};
CONST VOID CONST InitializeKits(VOID)
{
static INT i = 0, iter = 0;
static wstring_convert < codecvt_utf8_utf16 < WCHAR > > converter;
auto sig_address = FindPattern(XorString("client.dll"), XorString("E8 ?? ?? ?? ?? FF 76 0C 8D 48 04 E8"));
auto item_system_offset = *reinterpret_cast < int32_t * > (sig_address + 1);
auto item_system_fn = reinterpret_cast < CCStrike15ItemSystem * (*) () > (sig_address + 5 + item_system_offset);
auto item_schema = reinterpret_cast < CCStrike15ItemSchema * > (uintptr_t(item_system_fn()) + sizeof(void *));
{
auto get_paint_kit_definition_offset = *reinterpret_cast < int32_t * > (sig_address + 12);
auto get_paint_kit_definition_fn = reinterpret_cast < CPaintKit * (__thiscall *) (CCStrike15ItemSchema *, int) > (sig_address + 16 + get_paint_kit_definition_offset);
auto start_element_offset = *reinterpret_cast <intptr_t * > (uintptr_t(get_paint_kit_definition_fn) + 10);
auto head_offset = start_element_offset - 12;
auto map_head = reinterpret_cast < Head_t < int, CPaintKit * > * > (uintptr_t(item_schema) + head_offset);
for (i = 0; i <= map_head->last_element; i++)
{
auto paint_kit = map_head->memory[i].value;
if (paint_kit->id == 9001) continue;
CONST PWCHAR CONST wide_name = g_localize->Find(paint_kit->item_name.buffer + 1);
auto name = converter.to_bytes(wide_name);
for (iter = 0; iter < name.length(); iter++)
if ((name.at(iter) >= 'a' && name.at(iter) <= 'z') || (name.at(iter) >= 'A' && name.at(iter) <= 'Z'))
name.at(iter) = toupper(name.at(iter));
if (paint_kit->id < 10000) k_skins.push_back({ paint_kit->id, name });
else k_gloves.push_back({ paint_kit->id, name });
}
sort(k_skins.begin(), k_skins.end()), sort(k_gloves.begin(), k_gloves.end());
};
{
auto sticker_sig = FindPattern(XorString("client.dll"), XorString("53 8D 48 04 E8 ? ? ? ? 8B 4D 10")) + 4;
auto get_sticker_kit_definition_offset = *reinterpret_cast < intptr_t * > (sticker_sig + 1);
auto get_sticker_kit_definition_fn = reinterpret_cast < CPaintKit * (__thiscall *) (CCStrike15ItemSchema *, int) > (sticker_sig + 5 + get_sticker_kit_definition_offset);
auto start_element_offset = *reinterpret_cast < intptr_t * > (uintptr_t(get_sticker_kit_definition_fn) + 10);
auto head_offset = start_element_offset - 12;
auto map_head = reinterpret_cast < Head_t < int, CStickerKit * > * > (uintptr_t(item_schema) + head_offset);
for (i = 0; i <= map_head->last_element; i++)
{
auto sticker_kit = map_head->memory[i].value;
char sticker_name_if_valve_fucked_up_their_translations[XS_RANDOM_SIZE / 2] = {};
auto sticker_name_ptr = sticker_kit->item_name.buffer + 1;
if (strstr(sticker_name_ptr, XorString("StickerKit_dhw2014_dignitas")))
{
strcpy(sticker_name_if_valve_fucked_up_their_translations, XorString("StickerKit_dhw2014_teamdignitas"));
strcat(sticker_name_if_valve_fucked_up_their_translations, sticker_name_ptr + 27);
sticker_name_ptr = sticker_name_if_valve_fucked_up_their_translations;
};
CONST PWCHAR CONST wide_name = g_localize->Find(sticker_name_ptr);
auto name = converter.to_bytes(wide_name);
for (iter = 0; iter < name.length(); iter++)
if ((name.at(iter) >= 'a' && name.at(iter) <= 'z') || (name.at(iter) >= 'A' && name.at(iter) <= 'Z'))
name.at(iter) = toupper(name.at(iter));
k_stickers.push_back({ sticker_kit->id, name });
};
sort(k_stickers.begin(), k_stickers.end());
k_stickers.insert(k_stickers.begin(), { 0, XorString("NONE") });
};
};
|
34d3132faa85f4f7c56e0ce2aa812c184ba58623 | 695b15cf7128b974462ede79486da03e21471fd1 | /segrgatevenodd.cpp | 403fab8a040c5dd67772f077f6e64763143cfc1c | [] | no_license | SAGGSOC/CodeChef-Programs | 3613332bef851f61561fe873e2fa24777ce959e2 | 4d06a1a51520412995c6cdd1afa8209583398a4d | refs/heads/master | 2021-08-07T19:52:10.608195 | 2017-11-08T21:17:16 | 2017-11-08T21:17:16 | 110,030,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | segrgatevenodd.cpp | #include<stdio.h>
void segregateevenodd(int arr[],int size)
{
int left=0,right=size-1;
while(left<right)
{
while(arr[left]%2==0&&left<right)
left++;
while(arr[right]%2==1&&left<right)
right--;
if(left<right)
{
swap(&arr[left], &arr[right]);
left++;
right--;
}
}
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = {12, 34, 45, 9, 8, 90, 3};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int i = 0;
segregateevenodd(arr, arr_size);
printf("Array after segregation ");
for (i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.