blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
2479ab4fa42eef0ea9c9cee0897bcd0cb8b02286
3b47446de46d048a2e6e628a0b9dab7b7a5a63ab
/src/qt/transactiontablemodel.cpp
ae13fd88971dad73c8285bdd393caf165d6dbdb6
[ "MIT" ]
permissive
travelpaycoin/travelpay-old
c84741ec99534035279137cb8d6c97084393767e
a017c495951e9df56127d036673d878d65c09bec
refs/heads/master
2020-04-13T14:18:57.738745
2019-01-02T15:08:10
2019-01-02T15:08:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,774
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactiontablemodel.h" #include "addresstablemodel.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "transactiondesc.h" #include "transactionrecord.h" #include "walletmodel.h" #include "main.h" #include "sync.h" #include "uint256.h" #include "util.h" #include "wallet.h" #include <QColor> #include <QDateTime> #include <QDebug> #include <QIcon> #include <QList> // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft | Qt::AlignVCenter, /* status */ Qt::AlignLeft | Qt::AlignVCenter, /* watchonly */ Qt::AlignLeft | Qt::AlignVCenter, /* date */ Qt::AlignLeft | Qt::AlignVCenter, /* type */ Qt::AlignLeft | Qt::AlignVCenter, /* address */ Qt::AlignRight | Qt::AlignVCenter /* amount */ }; // Comparison operator for sort/binary search of model tx list struct TxLessThan { bool operator()(const TransactionRecord& a, const TransactionRecord& b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord& a, const uint256& b) const { return a.hash < b; } bool operator()(const uint256& a, const TransactionRecord& b) const { return a < b.hash; } }; // Private implementation class TransactionTablePriv { public: TransactionTablePriv(CWallet* wallet, TransactionTableModel* parent) : wallet(wallet), parent(parent) { } CWallet* wallet; TransactionTableModel* parent; /* Local cache of wallet. * As it is in the same order as the CWallet, by definition * this is sorted by sha256. */ QList<TransactionRecord> cachedWallet; /* Query entire wallet anew from core. */ void refreshWallet() { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); { LOCK2(cs_main, wallet->cs_wallet); for (std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) { if (TransactionRecord::showTransaction(it->second)) cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second)); } } } /* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256& hash, int status, bool showTransaction) { qDebug() << "TransactionTablePriv::updateWallet : " + QString::fromStdString(hash.ToString()) + " " + QString::number(status); // Find bounds of this transaction in model QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); if (status == CT_UPDATED) { if (showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if (!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } qDebug() << " inModel=" + QString::number(inModel) + " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) + " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status); switch (status) { case CT_NEW: if (inModel) { qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is already in model"; break; } if (showTransaction) { LOCK2(cs_main, wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); if (mi == wallet->mapWallet.end()) { qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is not in wallet"; break; } // Added -- insert at the right position QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wallet, mi->second); if (!toInsert.isEmpty()) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex + toInsert.size() - 1); int insert_idx = lowerIndex; foreach (const TransactionRecord& rec, toInsert) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } parent->endInsertRows(); } } break; case CT_DELETED: if (!inModel) { qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_DELETED, but transaction is not in model"; break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for // visible transactions. break; } } int size() { return cachedWallet.size(); } TransactionRecord* index(int idx) { if (idx >= 0 && idx < cachedWallet.size()) { TransactionRecord* rec = &cachedWallet[idx]; // Get required locks upfront. This avoids the GUI from getting // stuck if the core is holding the locks for a longer time - for // example, during a wallet rescan. // // If a status update is needed (blocks came in since last check), // update the status of this transaction from the wallet. Otherwise, // simply re-use the cached status. TRY_LOCK(cs_main, lockMain); if (lockMain) { TRY_LOCK(wallet->cs_wallet, lockWallet); if (lockWallet && rec->statusUpdateNeeded()) { std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if (mi != wallet->mapWallet.end()) { rec->updateStatus(mi->second); } } } return rec; } return 0; } QString describe(TransactionRecord* rec, int unit) { { LOCK2(cs_main, wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if (mi != wallet->mapWallet.end()) { return TransactionDesc::toHTML(wallet, mi->second, rec, unit); } } return QString(); } }; TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), wallet(wallet), walletModel(parent), priv(new TransactionTablePriv(wallet, this)), fProcessingQueuedTransactions(false) { columns << QString() << QString() << tr("Date") << tr("Type") << tr("Address") << BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); priv->refreshWallet(); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); subscribeToCoreSignals(); } TransactionTableModel::~TransactionTableModel() { unsubscribeFromCoreSignals(); delete priv; } /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void TransactionTableModel::updateAmountColumnTitle() { columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); emit headerDataChanged(Qt::Horizontal, Amount, Amount); } void TransactionTableModel::updateTransaction(const QString& hash, int status, bool showTransaction) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(updated, status, showTransaction); } void TransactionTableModel::updateConfirmations() { // Blocks came in since last poll. // Invalidate status (number of confirmations) and (possibly) description // for all rows. Qt is smart enough to only actually request the data for the // visible rows. emit dataChanged(index(0, Status), index(priv->size() - 1, Status)); emit dataChanged(index(0, ToAddress), index(priv->size() - 1, ToAddress)); } int TransactionTableModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord* wtx) const { QString status; switch (wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)", "", wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Offline: status = tr("Offline"); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed"); break; case TransactionStatus::Confirming: status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations); break; case TransactionStatus::Confirmed: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Conflicted: status = tr("Conflicted"); break; case TransactionStatus::Immature: status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in); break; case TransactionStatus::MaturesWarning: status = tr("This block was not received by any other nodes and will probably not be accepted!"); break; case TransactionStatus::NotAccepted: status = tr("Orphan Block - Generated but not accepted. This does not impact your holdings."); break; } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord* wtx) const { if (wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } return QString(); } /* Look up address in address book, if found return label (address) otherwise just return (address) */ QString TransactionTableModel::lookupAddress(const std::string& address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if (!label.isEmpty()) { description += label; } if (label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord* wtx) const { switch (wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::MNReward: return tr("Masternode Reward"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::RecvWithObfuscation: return tr("Received via Obfuscation"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::StakeMint: return tr("Minted"); case TransactionRecord::Generated: return tr("Mined"); case TransactionRecord::ObfuscationDenominate: return tr("Obfuscation Denominate"); case TransactionRecord::ObfuscationCollateralPayment: return tr("Obfuscation Collateral Payment"); case TransactionRecord::ObfuscationMakeCollaterals: return tr("Obfuscation Make Collateral Inputs"); case TransactionRecord::ObfuscationCreateDenominations: return tr("Obfuscation Create Denominations"); case TransactionRecord::Obfuscated: return tr("Obfuscated"); case TransactionRecord::ZerocoinMint: return tr("Converted Tpc to xTPC"); case TransactionRecord::ZerocoinSpend: return tr("Spent xTPC"); case TransactionRecord::RecvFromZerocoinSpend: return tr("Received Tpc from xTPC"); case TransactionRecord::ZerocoinSpend_Change_xTPC: return tr("Minted Change as xTPC from xTPC Spend"); case TransactionRecord::ZerocoinSpend_FromMe: return tr("Converted xTPC to TPC"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord* wtx) const { switch (wtx->type) { case TransactionRecord::Generated: case TransactionRecord::StakeMint: case TransactionRecord::MNReward: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithObfuscation: case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: case TransactionRecord::RecvFromZerocoinSpend: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: case TransactionRecord::ZerocoinSpend: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } } QString TransactionTableModel::formatTxToAddress(const TransactionRecord* wtx, bool tooltip) const { QString watchAddress; if (tooltip) { // Mark transactions involving watch-only addresses by adding " (watch-only)" watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : ""; } switch (wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::RecvWithAddress: case TransactionRecord::MNReward: case TransactionRecord::RecvWithObfuscation: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: case TransactionRecord::StakeMint: case TransactionRecord::ZerocoinSpend: case TransactionRecord::ZerocoinSpend_FromMe: case TransactionRecord::RecvFromZerocoinSpend: return lookupAddress(wtx->address, tooltip); case TransactionRecord::Obfuscated: return lookupAddress(wtx->address, tooltip) + watchAddress; case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::ZerocoinMint: case TransactionRecord::ZerocoinSpend_Change_xTPC: return tr("xTPC Accumulator"); case TransactionRecord::SendToSelf: default: return tr("(n/a)") + watchAddress; } } QVariant TransactionTableModel::addressColor(const TransactionRecord* wtx) const { switch (wtx->type) { case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; // Show addresses without label in a less visible color case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: case TransactionRecord::MNReward: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if (label.isEmpty()) return COLOR_BAREADDRESS; } default: // To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet, // so we must always return a color here return COLOR_BLACK; } } QString TransactionTableModel::formatTxAmount(const TransactionRecord* wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const { QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators); if (showUnconfirmed) { if (!wtx->status.countsForBalance) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord* wtx) const { switch (wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return COLOR_TX_STATUS_OPENUNTILDATE; case TransactionStatus::Offline: return COLOR_TX_STATUS_OFFLINE; case TransactionStatus::Unconfirmed: return QIcon(":/icons/transaction_0"); case TransactionStatus::Confirming: switch (wtx->status.depth) { case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::Confirmed: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::Conflicted: return QIcon(":/icons/transaction_conflicted"); case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::MaturesWarning: case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); default: return COLOR_BLACK; } } QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord* wtx) const { if (wtx->involvesWatchAddress) return QIcon(":/icons/eye"); else return QVariant(); } QString TransactionTableModel::formatTooltip(const TransactionRecord* rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if (rec->type == TransactionRecord::RecvFromOther || rec->type == TransactionRecord::SendToOther || rec->type == TransactionRecord::SendToAddress || rec->type == TransactionRecord::RecvWithAddress || rec->type == TransactionRecord::MNReward) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); TransactionRecord* rec = static_cast<TransactionRecord*>(index.internalPointer()); switch (role) { case Qt::DecorationRole: switch (index.column()) { case Status: return txStatusDecoration(rec); case Watchonly: return txWatchonlyDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DisplayRole: switch (index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec, true, BitcoinUnits::separatorAlways); } break; case Qt::EditRole: // Edit role is used for sorting, so return the unformatted values switch (index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case Watchonly: return (rec->involvesWatchAddress ? 1 : 0); case ToAddress: return formatTxToAddress(rec, true); case Amount: return qint64(rec->credit + rec->debit); } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: // Conflicted, most probably orphaned if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted) { return COLOR_CONFLICTED; } // Unconfimed or immature if ((rec->status.status == TransactionStatus::Unconfirmed) || (rec->status.status == TransactionStatus::Immature)) { return COLOR_UNCONFIRMED; } if (index.column() == Amount && (rec->credit + rec->debit) < 0) { return COLOR_NEGATIVE; } if (index.column() == ToAddress) { return addressColor(rec); } // To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet, // so we must always return a color here return COLOR_BLACK; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case WatchonlyRole: return rec->involvesWatchAddress; case WatchonlyDecorationRole: return txWatchonlyDecoration(rec); case LongDescriptionRole: return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit()); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return qint64(rec->credit + rec->debit); case TxIDRole: return rec->getTxID(); case TxHashRole: return QString::fromStdString(rec->hash.ToString()); case ConfirmedRole: return rec->status.countsForBalance; case FormattedAmountRole: // Used for copy/export, so don't include separators return formatTxAmount(rec, false, BitcoinUnits::separatorNever); case StatusRole: return rec->status.status; } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch (section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case Watchonly: return tr("Whether or not a watch-only address is involved in this transaction."); case ToAddress: return tr("Destination address of transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); TransactionRecord* data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } return QModelIndex(); } void TransactionTableModel::updateDisplayUnit() { // emit dataChanged to update Amount column with the current unit updateAmountColumnTitle(); emit dataChanged(index(0, Amount), index(priv->size() - 1, Amount)); } // queue notifications to show a non freezing progress dialog e.g. for rescan struct TransactionNotification { public: TransactionNotification() {} TransactionNotification(uint256 hash, ChangeType status, bool showTransaction) : hash(hash), status(status), showTransaction(showTransaction) {} void invoke(QObject* ttm) { QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, strHash), Q_ARG(int, status), Q_ARG(bool, showTransaction)); } private: uint256 hash; ChangeType status; bool showTransaction; }; static bool fQueueNotifications = false; static std::vector<TransactionNotification> vQueueNotifications; static void NotifyTransactionChanged(TransactionTableModel* ttm, CWallet* wallet, const uint256& hash, ChangeType status) { // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); // Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread) bool inWallet = mi != wallet->mapWallet.end(); bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second)); TransactionNotification notification(hash, status, showTransaction); if (fQueueNotifications) { vQueueNotifications.push_back(notification); return; } notification.invoke(ttm); } static void ShowProgress(TransactionTableModel* ttm, const std::string& title, int nProgress) { if (nProgress == 0) fQueueNotifications = true; if (nProgress == 100) { fQueueNotifications = false; if (vQueueNotifications.size() > 10) // prevent balloon spam, show maximum 10 balloons QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true)); for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) { if (vQueueNotifications.size() - i <= 10) QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false)); vQueueNotifications[i].invoke(ttm); } std::vector<TransactionNotification>().swap(vQueueNotifications); // clear } } void TransactionTableModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); } void TransactionTableModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); }
[ "support@travelpaycoin.org" ]
support@travelpaycoin.org
90e7917eda6b39ff214cf4a387a424b9eb2df51f
b766ca07ba6554cf334570b93c5aa8c28a74ab1d
/string.hpp
0d255a1c0bacee3143f53ec06849910db511c4e1
[]
no_license
heckwithu2/custom-string-data-structure
148e199c0a978d2a849433d579a3a5a25581892f
21b34a829ee828585aebc73120f0f9f690d7b887
refs/heads/master
2023-02-24T04:06:42.550554
2021-02-03T16:25:51
2021-02-03T16:25:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,372
hpp
#pragma once //Jeremiah Heck //project 2 milestone 1 //2/17/2020 #ifndef STRING_HPP_ #define STRING_HPP_ #include <iostream> #include <vector> const int STRING_SIZE = 256; //The size of the String. //////////////////////////////////////////////////// // CLASS INV: str[length()] == 0 && // 0 <= length() <= capacity() && // capacity() == STRING_SIZE - // class String { public: String(); //Empty string String(char); //Stirng('x') String(const char[]); //String("abcd") char& operator[] (int); //Accessor/Modifier char operator[] (int) const; //Accessor int capacity() const; //Max chars that can be stored (not including null terminator) int length() const; //Number of char in string String operator+ (const String&) const; //Concatenation bool operator== (const String&) const; bool operator< (const String&) const; String substr(int, int); int findch(int, char); int findstr(int, const String&); void reset(); String operator+ (const char[], const String&); String operator+ (char, const String&); bool operator== (const char[], const String&); bool operator== (char, const String&); bool operator< (const char[], const String&); bool operator< (char, const String&); bool operator<= (const String&, const String&); bool operator!= (const String&, const String&); bool operator>= (const String&, const String&); bool operator> (const String&, const String&); //friend std::istream& operator>>(std::istream&, String&); friend std::ostream& operator<<(std::ostream&, const String&); friend std::vector<String> split(const String&); private: char str[STRING_SIZE]; }; String::String() { str[0] = '\0'; } String::String(char x) { str[0] = x; str[1] = '\0'; } String::String(const char x[]) { for (int i = 0; i < STRING_SIZE; ++i) { if (x[i] != '\0') { str[i] = x[i]; str[i + 1] = '\0'; } else { i = STRING_SIZE; } } } char& String::operator[](int x) { return str[x]; } char String::operator[](int x)const { return str[x]; } int String::capacity() const { int storage = 0; for (int i = 0; i < STRING_SIZE; ++i) { if (str[i] == '\0') { storage++; } } return storage; } int String::length() const { int length = 0; for (int i = 0; i < STRING_SIZE; ++i) { if (str[i] != '\0') { length++; } else { return length; } } return length; } String String::operator+(const String& right) const { //make a copy of the left String Concatenation; int g = length(); for (int i = 0; i < g; ++i) { Concatenation.str[i] = str[i]; Concatenation.str[i + 1] = '\0'; } //find the end of the left string int end = 0; bool done = false; for (int i = 0; i < STRING_SIZE; ++i) { if (str[i] == '\0' && done == false) { end = i; done = true; } } //add the second string to the end of it. g = right.length(); for (int i = 0; i < g; ++i) { Concatenation.str[end + i] = right[i]; Concatenation.str[end + i + 1] = '\0'; } /*for (int i = 0; i < Concatenation.length(); ++i) { std::cout << Concatenation.str[i] << std::endl; }*/ return Concatenation; } bool String::operator==(const String& right)const { for (int i = 0; i < STRING_SIZE; ++i) { if (str[i] != right.str[i]) { return false; } } return true; } bool String::operator<(const String& rightS)const { int left = 0; int right = 0; left = length(); right = rightS.length(); if (left < right) { return true; } else { return false; } } std::istream& operator>>(std::istream& is, String& x) { //this needs work char array[STRING_SIZE] = { '\0' }; for (int i = 0; i > STRING_SIZE; ++i) { is >> array[i]; } String newString(array); return is; } std::ostream& operator<<(std::ostream& os, const String& x) { if (x == ' ' || x == " ") { os << " "; return os; } else { for (int i = 0; i < x.length(); ++i) { os << x.str[i]; } return os; } } String operator+ (const char x[], const String& right) { String left(x), concatenation; concatenation = left + right; return concatenation; } String operator+ (char x, const String& right) { String left(x), concatenation; concatenation = left + right; return concatenation; } bool operator== (const char x[], const String& right) { String left(x); for (int i = 0; i < STRING_SIZE; ++i) { if (left[i] != right[i]) { return false; } } return true; } bool operator== (char x, const String& right) { String left(x); for (int i = 0; i < STRING_SIZE; ++i) { if (left[i] != right[i]) { return false; } } return true; } bool operator< (const char x[], const String& rightS) { String leftS(x); int left = 0; int right = 0; left = leftS.length(); right = rightS.length(); if (left < right) { return true; } else { return false; } } bool operator< (char x, const String& rightS) { String leftS(x); int left = 0; int right = 0; left = leftS.length(); right = rightS.length(); if (left < right) { return true; } else { return false; } } bool operator> (const String& leftS, const String& rightS) { int left = 0; int right = 0; left = leftS.length(); right = rightS.length(); if (left > right) { return true; } else { return false; } } bool operator< (const String& leftS, const String& rightS) { int left = 0; int right = 0; left = leftS.length(); right = rightS.length(); if (left < right) { return true; } else { return false; } } bool operator!= (const String& left, const String& right) { for (int i = 0; i < STRING_SIZE; ++i) { if (left[i] == right[i]) { return false; } } return true; } bool operator<=(const String& left, const String& right) { for (int i = 0; i < STRING_SIZE; ++i) { if (left[i] != right[i] || left[i] < right[i]) { return false; } } return true; } bool operator>=(const String& left, const String& right) { for (int i = 0; i < STRING_SIZE; ++i) { if (left[i] != right[i] || left[i] > right[i]) { return false; } } return true; } String String::substr(int start, int end) { String sub; for (int i = start; i <= end; ++i) { sub.str[i] = str[i]; } return sub; } int String::findch(int pos, char ch) { for (int i = pos; i <= STRING_SIZE; ++i) { if (str[i] == ch) { return i; } } return -1; } int String::findstr(int pos, const String& stringWithin) { int lengthright = stringWithin.length(); int right = 0; bool check = true; for (int i = pos; i <= STRING_SIZE; ++i) { if (str[i] == stringWithin.str[right]) { for (int x = i; x < lengthright + i; ++x) { if (str[x] != stringWithin.str[right]) { check = false; } else { right++; check = true; } } if (check == true) { return i; } right = 0; } } return -1; } void String::reset() { str[0] = '\0'; } std::vector<String> split(const String& bigString) { int count = 0; for (int i = 0; i < bigString.length(); ++i) { //ignore spaces if (bigString[i] != '\0' || ' ') { count++; } } std::vector<String> clean(count); for (int i = 0; i < bigString.length(); ++i) { //ignore spaces if (bigString[i] != '\0' || ' ') { clean[i] = bigString[i]; } } return clean; } #endif STRING_HPP_
[ "jheck10@kent.edu" ]
jheck10@kent.edu
8c546071fa0e4450c9444b7b19862ad051e1ddb0
5943b0e50bfa3c3f413e942e4b39db639c038886
/jni/RansacHeader.h
b02fef628c1c26ae9b7198b31d214b79aa9a9ab6
[]
no_license
akm-sabbir/indoor_navigation_system
48a6c8c60163399ac8a18fa3b49df26334bca47d
bab9ccfa5254976d5714f4d7231c55bacfca228b
refs/heads/master
2020-05-17T12:03:56.311869
2014-08-19T02:19:17
2014-08-19T02:19:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,837
h
/////////////////////////////////////////Initiation of Declaration////////////////////////////////////////// #pragma once #include <cv.h> #include<vector> #include<algorithm> #include "randomGenerator.h" using namespace std; #define DEPTH_WIDTH 640 #define DEPTH_HEIGHT 480 #define BUFFSIZE (DEPTH_WIDTH * DEPTH_HEIGHT) int width = DEPTH_WIDTH; int height = DEPTH_HEIGHT; #define MAX_DEPTH 1500 #define MIN_DEPTH 525 #define RANSAC_THRESHOLD 5 #define INLIER_THRESHOLD 0.50 #define MAXIMUM_TRIALS 1200 #define MAXIMUM_SIM 5 struct point { double x; double y; double z; }; struct plane_s { point A; point B; point C; point normal; }; struct Line{ point A; point B; double det; double coeffX; double coeffY; double C; }; CvSeq* ransacLines = NULL; int write_xyz = 1; int numOfvisitedPoints = 0; int trial_runs = MAXIMUM_TRIALS; int sub_sampling = 119; // prime number for sub sampling char fileName[ 301 ] = "depth_frame0.txt";// provide the input depth file name int npoints_b = 0;//tracking the number of points in a depth range double fx_d = 1.0 / 5.9421434211923247e+02; double fy_d = 1.0 / 5.9104053696870778e+02; double cx_d = 3.3930780975300314e+02; double cy_d = 2.4273913761751615e+02; //point results[BUFFSIZE]; FILE *outFile; int *imageMapRan; int num_inliers; std::vector<int> inliers; plane_s plane; Line Lines1,Lines2; plane_s best_plane; point vanishPoint; int best_num_inliers = 0; std::vector<int> best_inliers; int maxDepth=0; int minDepth =10000; //double depth[BUFFSIZE]; double dist[1000]; long deter; //double depthLookup[2048]; int found = -1; // Local Function Prototypes required by the processings void depthToWorld(int x, int y, int depthValue, point *result); double RawDepthToCM(int depthValue); void maxmin_depth(); void generateDepthLookup( ); int Filter( int min, int max ); int is_colinear( int *idx ); int random_indexes( int *idx, int max ); void Normal(); void Ransac(); int find_lines(); void find_inliers(); vector<int>* initiateVanishing( CvSeq *line, int *imageMaps ); ///////////////////////////// End of Declaration////////////////////////////////////////////// ////////////////////////////////////////////////////////// Start of the Defination//////////////////////////////////////////// /*The following function find the max range and min range of the depth image*/ void init(CvSeq *line, int *maps){ ransacLines = line; imageMapRan = maps; //if(!best_inliers.empty()) //best_inliers.clear(); srand( time( NULL )); return; } /************************************************************/ vector<int>* initiateVanishing( CvSeq *line, int *imageMaps ) { // outFile = fopen("Output.txt", "w+" ); init(line, imageMaps); // generateDepthLookup(); // Initialize the depth table for scaling purpose /* ifstream files( fileName ); if ( files.is_open() ) { int i; for ( i = 0; i < BUFFSIZE; i++) files >> depth[i]; files.close(); } else { printf( " Unable to open %s.\n", fileName ); exit(-1); }*/ // maxmin_depth(); int simulation = 0; best_num_inliers = 0; for (simulation = 0; simulation < MAXIMUM_SIM; simulation++) { found = 0; npoints_b = 0; num_inliers = 0; Ransac(); if (num_inliers > 0){ printf("Model found.\n"); } else{ printf("No model found.\n"); best_inliers.clear(); } } //fclose(outFile); //FILE *fp = freopen("points.txt","w",stdout); //for(int i=0;i<best_num_inliers;i++){ //printf("%lf %lf %lf\n",results[best_inliers[i]].x,results[best_inliers[i]].y,results[best_inliers[i]].z); //} //fclose(fp); return &best_inliers; } void formLines(){ return; } ////////////////ransac algorithm/////////////////////////////////// /*this function filter the point information using the subsampling then call the find_plane function to choose random three numbers from the point cloud and find the plane normal to define the plane then it tries to find the inliers for the plane and store the inlieers if the inliers is greater then the best number of inliers then it is voted as the best model found in this way the whole process run several times*/ void Ransac() { int count = 0; int i; double prob = 0.90; double f = 0.0; // percentage of inliers int N = trial_runs; double no_outliers = 2.2204e-16; npoints_b = ransacLines->total; //Filter( MIN_DEPTH, MAX_DEPTH ); for(i = 0 ; i < npoints_b; i++ ) if(imageMapRan[i] == 1) numOfvisitedPoints++; if(abs(npoints_b - numOfvisitedPoints) < 3){ printf("we cant find any models insufficient data\n"); return ; } printf("No. of lines %d\n",npoints_b); while ( N > count ) { if( find_lines( )){ printf("Not possible to find any models insufficient data may be\n"); break; } find_inliers( ); if (num_inliers > best_num_inliers) { ///finding the best plane/////////////////////// best_num_inliers = num_inliers; ////FOR PLANES SO NO USE OF IT NOW//////////////// found = count; //std:vector<int>::iterator beg = best_inliers.begin(); //std::vector<int>::iterator ends = best_inliers.end(); if(!best_inliers.empty() ) best_inliers.clear(); best_inliers.resize(inliers.size()); copy(inliers.begin(),inliers.end(),best_inliers.begin()); /*for (i = 0; i < num_inliers; i++) best_inliers[i] = inliers[i];*/ f = (double) num_inliers / npoints_b; no_outliers = 1.0 - pow(f,2); if ( no_outliers < 2.2204e-16){ no_outliers = 2.2204e-16; } else if ( no_outliers > ( 1.0 - 2.2204e-16 ) ){ no_outliers = ( 1.0 - 2.2204e-16 ); } N = (int) ( log( 1.0 - prob ) / log( no_outliers ) ); } count++; if (count > trial_runs){ printf("RANSAC reached maximum trials of %d.\n", trial_runs ); break; } if(!inliers.empty()) inliers.clear(); } printf("Number of Inliers %d .\n", best_inliers.size() ); } ///////////Add Time Defination////////////// //////////////////////////////////////////// /*The following function find the inliers by implementing the dot products between the normal vector of the plane and vector that lies over the plane and connect the one of the base point of the plane and the point under observation */ void find_inliers() { int i = 0; num_inliers = 0; point midPoint; double scale,vanishVec; point v1,v2; for (i = 0; i < npoints_b; i++){ /////////this is for the plane and 3D operation////////////////////////////// ///////////////////////End of the operation ///////////////////////////////// if(imageMapRan[i] != 0) continue; CvPoint* p = (CvPoint*)cvGetSeqElem(ransacLines, i); midPoint.x = ((double)(p[0].x + p[1].x))/2; midPoint.y = ((double)(p[0].y + p[1].y))/2; //scale = midPoint.x*midPoint.x + midPoint.y*midPoint.y; v1.x = fabs( p[0].x - midPoint.x); v1.y = fabs( p[0].y - midPoint.y ); v2.x = fabs( vanishPoint.x - midPoint.x ); v2.y = fabs( vanishPoint.y - midPoint.y ); scale = sqrt(v1.x*v1.x + v1.y*v1.y); v1.x /= scale; v1.y /= scale; dist[i] = v1.x*v2.x + v1.y*v2.y; vanishVec = sqrt(v2.x*v2.x+v2.y*v2.y); if ( fabs( dist[i] - vanishVec) < RANSAC_THRESHOLD ) { // inliers[num_inliers] = i; inliers.push_back(i); num_inliers++; } } } /************************************************************************************/ /*The following function find randomly select three points and then ensure that they are not colinear then find the normal by calling the Normal() correspond to the plane formed by these three points*/ void lineConstruction(Line *Lines1,CvPoint *p){ Lines1->A.x = p[0].x; Lines1->A.y = p[0].y; Lines1->B.x = p[1].x; Lines1->B.y = p[1].y; Lines1->coeffX = Lines1->B.y - Lines1->A.y; Lines1->coeffY = Lines1->A.x - Lines1->B.x; Lines1->C = Lines1->coeffX*Lines1->A.x + Lines1->coeffY*Lines1->A.y; } int find_lines( ) { int idx[3]; int count = 0; do { if(random_indexes( idx, npoints_b )) return 1; count++; } while( is_colinear( idx ) && count < 100 ); if (count >= 100) { printf( "unable to find random points.\n"); return 1; // exit (-1); } CvPoint* p1 =(CvPoint*) cvGetSeqElem(ransacLines,idx[0]); CvPoint* p2 =(CvPoint*) cvGetSeqElem(ransacLines,idx[1]); lineConstruction(&Lines1, p1); lineConstruction(&Lines2, p2); //////////////this is for the plane operation and 3D operations////////////////////////// Normal(); return 0; } int random_indexes( int *idx, int max ) { int i; int countS; int low = 0; int high = max; //srand((unsigned int)time(0)); int range = (high - low); int rand_number; for (i = 0; i < 2; i++ ){// as we are looking for lines range is being changed from 3 to 2 countS = 0; do{ rand_number = low + int(range*rand()/(RAND_MAX + 1.0)); idx[ i ] = rand() % max;//rand_number;//randomGenerator(0, max);//rand()% max; countS++; }while(imageMapRan[ idx[ i ] ] != 0 && countS < 3*npoints_b); // if(countS >= 3*npoints_b) // return 1; } return 0; } /*following function try to find out the colineariy of three points by triangulation technique*/ int is_colinear( int *idx ) { double AB; double AC; double BC; //point A; // point B; //point C; if(imageMapRan[idx[0]] != 0 && imageMapRan[idx[1]] !=0) return 1; if (idx[0] == idx[1]) //|| idx[0] == idx[2] || idx[1] == idx[2] ) as line contains only two points return 1; CvPoint* p1= (CvPoint*)cvGetSeqElem(ransacLines, idx[0] ); // for lines we need only two points CvPoint* p2= (CvPoint*)cvGetSeqElem(ransacLines, idx[1] ); long A = p1[1].y - p1[0].y; long B = p1[0].x - p1[1].x; long C = p2[1].y - p2[0].y; long D = p2[0].x - p2[1].x; deter = A*D - B*C; if(deter == 0) return 1; else return 0; //C = results[ idx[2] ]; //////////////this is for the planes//////////////////////////// /* AB = sqrt( ((B.x - A.x) * (B.x - A.x )) + ((B.y - A.y) * (B.y - A.y )) + ((B.z - A.z) * (B.z - A.z ))); AC = sqrt( ((C.x - A.x) * (C.x - A.x )) + ((C.y - A.y) * (C.y - A.y )) + ((C.z - A.z) * (C.z - A.z ))); BC = sqrt( ((C.x - B.x) * (C.x - B.x )) + ((C.y - B.y) * (C.y - B.y )) + ((C.z - B.z) * (C.z - B.z ))); double sum = AB + AC; if ( sum == BC ) return 1; else if((AB+BC)==AC) return 1; else if((AC+BC)==AB) return 1; else return 0;*/ } /*find the normal and scale it to get the unit vector along the normal components*/ void Normal() { // double AB[3]; // double AC[3]; // double n1[3]; //double scale = 1; double determinant = Lines1.coeffX*Lines2.coeffY - Lines1.coeffY*Lines2.coeffX; double x1 = ((double)(Lines2.coeffY*Lines1.C - Lines1.coeffY*Lines2.C))/determinant; double y1 = ((double)(Lines1.coeffX*Lines2.C - Lines2.coeffX*Lines1.C))/determinant; if(fabs(x1 - floor(x1))<0.5) vanishPoint.x =floor( x1); else vanishPoint.x = ceil(x1); vanishPoint.y = fabs(y1 - floor(y1))<0.5 ? floor(y1) : ceil(y1); //////////////this is for the plane part and three dimension////////////////////////////////// } /*Implementation of subsampling */ /*int Filter( int min, int max ) { int counter = 0; int index = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if ( depth[index] < max && depth[index] > min ) { if (!(index % sub_sampling)) { depthToWorld( j, i, depth[index], &(results[counter]) ); counter++; } } index++; } } return counter; }*/ /*****************************************************************************/ /*The following sequence of functions are responsible for mapping the depth information into relative xyz coordinate*/ /*void generateDepthLookup() { for (int i = 0; i < 2048; i++) depthLookup[i] = RawDepthToCM( i ); }*/ double RawDepthToCM(int depthValue) { return (depthValue < 2047) ? (double) (0.1236 * 100 * tan(depthValue / 2842.5 + 1.1863) ) : 0.0; } /*void depthToWorld(int x, int y, int depthValue, point *result) { double value = depthLookup[depthValue]; result->x = (double)((x - cx_d) * value * fx_d); result->y = (double)((y - cy_d) * value * fy_d); result->z = (double)(value); } */ /************************************************/
[ "parvez.uz@gmail.com" ]
parvez.uz@gmail.com
18139b83d1b18efe88df7630241cf5965caeaa25
3ccc0addfcc9ea637761d7f55a3b793be59114cb
/test.cpp
cc5945aa275b99f61398ffc5d7a9a03d3cdf6677
[]
no_license
Can1210/GitTest
e77cde479bb7d6fb49ecd74d0d93d4bdaa03e3b7
be2a4ca9a05b199b42c2a1cc7d029e8a198e6992
refs/heads/master
2020-05-27T05:32:31.391380
2019-05-25T02:12:22
2019-05-25T02:12:22
188,502,712
0
0
null
null
null
null
UTF-8
C++
false
false
83
cpp
void testfunction() { printf("testtest"); printf("あ"); printf("test"); }
[ "-" ]
-
0977b5762b4dab18487d55b6311419ad823d46c6
6c9e6ffbe477b04e262fb52bc5322a55b49a785b
/src/System/EventLock.cpp
b2975f3b1a4c0c5b5d16f81f30a58dd20020b7b2
[]
no_license
orbisTransfer/orbis
641393f7730435a894f8e5af2ddb9a5f77d452a2
c685d253e5100aa4e58ef101fc95b13ede571eb3
refs/heads/master
2021-04-30T10:56:11.404207
2018-02-13T08:02:31
2018-02-13T08:02:31
121,123,776
0
0
null
null
null
null
UTF-8
C++
false
false
4,692
cpp
// Copyright (c) 2018 The Orbis developers // ====================================================================== // ===== Spell of Creation ===== // script inspired by the CNC code, on February 11, 2018 // // ====================================================================== /* , d :8; oo ,888 od88 Y " b "`88888 ,. : 88888888o. Y. `8888888bo "bo d888888888oooooo,. "Yo8:8888888888888Yd8. `8b;Y88888888888888' ,888d"Y888888888888. , P88Y8b.888888888888b. `b :; "8888888888888888P8b d; . Y88888888888888bo ",o ,d8 `"8888888888888888888888",oo. :888888888888888888888P"" ` `88888888888888888888oooooo. : ; ,888888Y888888888888888888888" `'`P""8.`8;`888888888888888888888o. ` ` :; `888888888888888"""8P"o. , '`8 Y88888888888888; :b Yb 8. :. `Y8888888888888; dP `8 ,8d8 " `888888888888d Y; :888d8; 88888888888Pb ; :888' ` o d888888888888; :' oo888bo ,."8888888888888888; ' ' 8888888888888888888888888888; ,.`88booo`Y888888888888888888888888P' :888888888888888888888888888888' ,ooooood888888888888888888888888888888' ""888888888888888888888888888888888888; ,oooooo888888888888888888888888888888888888' "88888888888888888888888888888888888888P ,oo bo ooo88888888888888888888888888888888888Y8 ."8P88d888888888888888888888888888888888888888"`"o. oo888888888888888888888888888888888888888888" 8 d88Y8888888888888888888888888888888888888888' ooo8bYooooo. ,""o888888888888888888888888888888888P":888888888888888888b ` ,d88888888888888888888888888888"' :888888888888888bod8 ,88888888888888888888888888888" `d8888888888888o`88"b ,88888888888888888888888888"" ,88888' 88 Y8b " ,8888888888888888888"" ,; 88' ; `8' P d8888888888888888888boo8888888P" :. ` d888888888888888888888888888888boooo :"Y888888888888P':88888"""8P"88888P' ` :88888888888' 88"" ,dP' :888888. ,88888888888' '` ,88,8b d" d88888888888 dP"`888' Y :888888888; 8' :8888888888. ` :888888888888oo ,ooooo :8888888888888o ,o oo d88888oooo. ' :888888888888888booooood888888888888888888888bo. -hrr- Y88888888888888888888888888888888888"""888888o. "`"Y8888888888888888888888888""""' `"88888b. "888"Y888888888888888" Y888.' `"' `""' `"""""' " , 8888 :. 8888 d888d8o 88;` Y888888; d88; o88888888,o88P:' "ood888888888888"' ,oo88888""888888888. ,o8P"b8YP '`"888888;"b. ' d8"`o8",P """""""8P `; d8; 8; // ============================================================= // ===== it's not an illusion ===== // ===== it's real ===== // // ============================================================= */ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "EventLock.h" #include <System/Event.h> namespace System { EventLock::EventLock(Event& event) : event(event) { while (!event.get()) { event.wait(); } event.clear(); } EventLock::~EventLock() { event.set(); } }
[ "noreply@github.com" ]
noreply@github.com
0ea351a455ce2a2ab4629aa2859ce92bbd53f9e9
b36f34b6a24d019d624d1cc74f5b29062eef2ba4
/frameworks/cocos2d-x/extensions/Particle3D/PU/CCPUSphereColliderTranslator.cpp
32823a473abc019d8d3636a22923680328c9c36b
[ "MIT" ]
permissive
zhongfq/cocos-lua
f49c1639f2c9a2a7678f9ed67e58114986ac882f
c2cf0f36ac0f0c91fb3456b555cacd8e8587be46
refs/heads/main
2023-08-17T17:13:05.705639
2023-08-17T06:06:36
2023-08-17T06:06:36
192,316,318
165
63
MIT
2023-08-14T23:59:30
2019-06-17T09:27:37
C
UTF-8
C++
false
false
3,771
cpp
/**************************************************************************** Copyright (C) 2013 Henry van Merode. All rights reserved. Copyright (c) 2015-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCPUSphereColliderTranslator.h" #include "extensions/Particle3D/PU/CCPUParticleSystem3D.h" #include "extensions/Particle3D/PU/CCPUDynamicAttribute.h" #include "extensions/Particle3D/PU/CCPUDynamicAttributeTranslator.h" #include "extensions/Particle3D/PU/CCPUBaseColliderTranslator.h" NS_CC_BEGIN PUSphereColliderTranslator::PUSphereColliderTranslator() { } //------------------------------------------------------------------------- bool PUSphereColliderTranslator::translateChildProperty( PUScriptCompiler* compiler, PUAbstractNode *node ) { PUPropertyAbstractNode* prop = reinterpret_cast<PUPropertyAbstractNode*>(node); PUAffector* af = static_cast<PUAffector*>(prop->parent->context); PUSphereCollider* affector = static_cast<PUSphereCollider*>(af); if (prop->name == token[TOKEN_RADIUS]) { // Property: radius if (passValidateProperty(compiler, prop, token[TOKEN_RADIUS], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { affector->setRadius(val); return true; } } } else if (prop->name == token[TOKEN_SPHERE_COLLIDER_RADIUS]) { // Property: sphere_collider_radius (Deprecated; replaced by radius) if (passValidateProperty(compiler, prop, token[TOKEN_SPHERE_COLLIDER_RADIUS], VAL_REAL)) { float val = 0.0f; if(getFloat(*prop->values.front(), &val)) { affector->setRadius(val); return true; } } } else if (prop->name == token[TOKEN_INNER_COLLISION]) { // Property: inner_collision if (passValidateProperty(compiler, prop, token[TOKEN_INNER_COLLISION], VAL_BOOL)) { bool val; if(getBoolean(*prop->values.front(), &val)) { affector->setInnerCollision(val); return true; } } } else { // Parse the BaseCollider PUBaseColliderTranslator baseColliderTranslator; return baseColliderTranslator.translateChildProperty(compiler, node); } return false; } bool PUSphereColliderTranslator::translateChildObject( PUScriptCompiler* /*compiler*/, PUAbstractNode* /*node*/ ) { // No objects return false; } NS_CC_END
[ "codetypes@gmail.com" ]
codetypes@gmail.com
e43d3474fea814a6ddd92e44fcc4dd1ec5d21416
66a54367813a7941aa9586382ab1f8447e5bed7b
/617. Merge Two Binary Trees.cpp
efbc52c066ae242f3907328854eb7098560ca0b1
[]
no_license
OgnjenArsenijevic/LeetCode-solutions
46e0a145f80485b145b9357eb78759975b3865fd
1b513a5110effafc0f446f671d45e4ff32e0e6a7
refs/heads/master
2020-04-29T06:29:33.269476
2020-03-30T21:03:12
2020-03-30T21:03:12
175,917,592
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
cpp
///617. Merge Two Binary Trees ///Author: Ognjen Arsenijevic ///username: ognjen1998 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode)); if(t1==nullptr && t2==nullptr) return nullptr; if(t1==nullptr && t2!=nullptr) root->val=t2->val; if(t1!=nullptr && t2==nullptr) root->val=t1->val; if(t1!=nullptr && t2!=nullptr) root->val=t1->val+t2->val; if(t1==nullptr && t2!=nullptr) { root->left=mergeTrees(nullptr,t2->left); root->right=mergeTrees(nullptr,t2->right); } if(t1!=nullptr && t2==nullptr) { root->left=mergeTrees(t1->left,nullptr); root->right=mergeTrees(t1->right,nullptr); } if(t1!=nullptr && t2!=nullptr) { root->left=mergeTrees(t1->left,t2->left); root->right=mergeTrees(t1->right,t2->right); } return root; } };
[ "noreply@github.com" ]
noreply@github.com
fe4555adaf99270a58889b5677a2903f1287ee88
5005d7e9c59866b6a8752264e27e63e4d9433380
/src/menu.hpp
d4127e3250b8aed2cbb76d0daa27829def4d9de2
[]
no_license
niklasnson/SDL2Bootstrap
29bbb20b59e61b75f46269eb29b315e5c5db3df3
4108b1ed09b46f9c974824a87840120fcfa465d3
refs/heads/main
2023-05-04T04:16:43.114947
2021-05-31T05:50:05
2021-05-31T05:50:05
372,277,486
0
0
null
null
null
null
UTF-8
C++
false
false
222
hpp
#ifndef SRC_MENU_HPP #define SRC_MENU_HPP #include "header.hpp" class Menu { public: Menu(void); ~Menu(void); int activeMenuOption; virtual void update(); virtual void draw(SDL_Renderer* renderer); }; #endif
[ "niklasnson@me.com" ]
niklasnson@me.com
536f5cc47abbcc1d00ea264c1e52194517c4fe0b
02c1aa99af5788e953d85bdd3d19ac9d4d498749
/module02/EX02/IFT3100H18_DrawCursor/src/main.cpp
d7114ed5f30ac8f60d7355f4dc0e6cc0e53b363b
[ "MIT" ]
permissive
Masam121/IFT3100H18
30fd6cb37ab909f04c054410f4df4187a21dff38
585692cb28bd7484948ca10bc9babb6139c940e1
refs/heads/master
2020-03-07T19:48:30.513667
2018-03-29T18:14:29
2018-03-29T18:14:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
310
cpp
// IFT3100H18_DrawCursor/main.cpp // Dessiner un curseur en fonction des états et des événements d'un périphérique de pointage et afficher ces informations dans la console. #include "ofMain.h" #include "application.h" int main( ) { ofSetupOpenGL(512, 512, OF_WINDOW); ofRunApp(new Application()); }
[ "philippe.voyer@ift.ulaval.ca" ]
philippe.voyer@ift.ulaval.ca
3c7d3bfc7cd459d250950c1db59b28fd74049152
70048c127df52c9df11acd5bfd43e88a8ee106a5
/src/common/block.hh
f41ee7b0217da39a7372530b9d54478e788c1f66
[ "Apache-2.0" ]
permissive
DICL/VeloxMR
0b6213e32705dacb06f5d484600e1dde95e03443
d726257d0a7e8c5153883991e26e6d36cee4d8dc
refs/heads/mapreduce
2021-05-01T09:23:06.394529
2017-10-09T09:22:00
2017-10-09T09:22:00
53,180,448
8
1
Apache-2.0
2023-03-03T20:21:34
2016-03-05T03:06:27
C++
UTF-8
C++
false
false
84
hh
#pragma once #include <utility> typedef std::pair<std::string, std::string> Block;
[ "vicente.bolea@gmail.com" ]
vicente.bolea@gmail.com
724222d6362c55cfe7e45cf15239be727cb988d8
789d9370c482d52aeff25aaba3fa37d9e032c44d
/thibaud_cenent/Transaction.cpp
16d189374fb85652ba7d872adb76d7ae3e687653
[]
no_license
ThibaudC13/infres10
42bb01994d1b543e27f400191c89999d1b913d9c
84a54e79746c952edb588ce44058d818812af24c
refs/heads/master
2020-06-05T06:06:05.783422
2019-06-18T07:59:00
2019-06-18T07:59:00
192,340,150
0
0
null
2019-06-17T12:11:42
2019-06-17T12:11:42
null
UTF-8
C++
false
false
848
cpp
#include <iostream> #include "Transaction.h" Transaction::Transaction(Account* account, TransactionType transactionType, double amount) { this->account = account; this->transactionType = transactionType; this->amount = amount; } void Transaction::deposit() { this->account->deposit(this->amount); } void Transaction::withdraw() { this->account->withdraw(this->amount); } void Transaction::printBalance(const std::string& threadName) { std::cout << "Thread " << threadName << ", AccountNumber: " << this->account->getAccountNumber() << + ", TransactionType: " << this->getTransactionType() << ", Amount: " << this->amount << std::endl; std::cout << "Account Balance : " << this->account->getAccountBalance() << std::endl; } TransactionType Transaction::getTransactionType() { return this->transactionType; }
[ "Thibaud.Cenent@mines-ales.org" ]
Thibaud.Cenent@mines-ales.org
24f5892b3ff55e7164422cc50707992056548d5f
083100943aa21e05d2eb0ad745349331dd35239a
/aws-cpp-sdk-redshift/source/model/Tag.cpp
04276ca592d3f1f2f14620abd6ba65aff0fdbec8
[ "JSON", "MIT", "Apache-2.0" ]
permissive
bmildner/aws-sdk-cpp
d853faf39ab001b2878de57aa7ba132579d1dcd2
983be395fdff4ec944b3bcfcd6ead6b4510b2991
refs/heads/master
2021-01-15T16:52:31.496867
2015-09-10T06:57:18
2015-09-10T06:57:18
41,954,994
1
0
null
2015-09-05T08:57:22
2015-09-05T08:57:22
null
UTF-8
C++
false
false
2,438
cpp
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/redshift/model/Tag.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Redshift::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; Tag::Tag() : m_keyHasBeenSet(false), m_valueHasBeenSet(false) { } Tag::Tag(const XmlNode& xmlNode) : m_keyHasBeenSet(false), m_valueHasBeenSet(false) { *this = xmlNode; } Tag& Tag::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode keyNode = resultNode.FirstChild("Key"); if(keyNode.IsNull()) { keyNode = resultNode; } if(!keyNode.IsNull()) { m_key = StringUtils::Trim(keyNode.GetText().c_str()); m_keyHasBeenSet = true; } XmlNode valueNode = resultNode.FirstChild("Value"); if(valueNode.IsNull()) { valueNode = resultNode; } if(!valueNode.IsNull()) { m_value = StringUtils::Trim(valueNode.GetText().c_str()); m_valueHasBeenSet = true; } } return *this; } void Tag::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_keyHasBeenSet) { oStream << location << index << locationValue << ".Key=" << StringUtils::URLEncode(m_key.c_str()) << "&"; } if(m_valueHasBeenSet) { oStream << location << index << locationValue << ".Value=" << StringUtils::URLEncode(m_value.c_str()) << "&"; } } void Tag::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_keyHasBeenSet) { oStream << location << ".Key=" << StringUtils::URLEncode(m_key.c_str()) << "&"; } if(m_valueHasBeenSet) { oStream << location << ".Value=" << StringUtils::URLEncode(m_value.c_str()) << "&"; } }
[ "henso@amazon.com" ]
henso@amazon.com
3c109ccd1c09a9ad5658726937b82c88c6fdd2f2
002b4d6f942d59a2fd98b06673ac1b8fd71e4f98
/CPP06/ex02/main.cpp
d25e0de09d4cb0f1dca222599972373f1a0377a6
[]
no_license
Ludrak/CPP
12123b7878399ed804b3c26a60e61a33a8b3f60c
4d7bb50a906b0df88d677c1f7ab9458ad994c5cb
refs/heads/main
2023-08-24T14:48:20.354549
2021-10-22T07:50:37
2021-10-22T07:50:37
371,524,811
0
0
null
null
null
null
UTF-8
C++
false
false
1,590
cpp
#include "A.hpp" #include "B.hpp" #include "C.hpp" #include <cstdlib> #include <sys/time.h> #include <iostream> Base * generate(void) { /* C like random (no std::chrono in C++98) */ struct timeval t; gettimeofday(&t, NULL); std::srand(t.tv_usec); switch (std::rand() % 3) { case 0: std::cout << "Randomly created new A !" << std::endl; return (new A()); case 1: std::cout << "Randomly created new B !" << std::endl; return (new B()); case 2: std::cout << "Randomly created new C !" << std::endl; return (new C()); } return (NULL); } void identify(Base * p) { if (dynamic_cast<A*>(p) != nullptr) std::cout << "[*]" << p << " is instance of A." << std::endl; if (dynamic_cast<B*>(p) != nullptr) std::cout << "[*]" << p << " is instance of B." << std::endl; if (dynamic_cast<C*>(p) != nullptr) std::cout << "[*]" << p << " is instance of C." << std::endl; } void identify(Base & p) { if (dynamic_cast<A*>(&p) != nullptr) std::cout << "[&]" << &p << " is instance of A." << std::endl; if (dynamic_cast<B*>(&p) != nullptr) std::cout << "[&]" << &p << " is instance of B." << std::endl; if (dynamic_cast<C*>(&p) != nullptr) std::cout << "[&]" << &p << " is instance of C." << std::endl; } int main() { int test = 5; for (int i = 0; i < test; i++) { Base *p = generate(); identify(p); identify(*p); std::cout << std::endl; delete p; } }
[ "luca06.robino@gmail.com" ]
luca06.robino@gmail.com
334449534bd4e495f47ab305624365b8cb605832
f1e9a69c9166d67febe851450755c4eab9d4b266
/STLDataStructure/STLDataStructureDlg.cpp
d03954a70393d5ef745c4f3daa6ad7010cb4f252
[]
no_license
jermydu/STLDataStructure
fe1c735051738470eba34d288b82b4927e4b64e5
349b05dea6f6589df03c4904402d119e992d4d3b
refs/heads/master
2023-02-19T09:25:11.177549
2022-08-31T13:50:53
2022-08-31T13:50:53
330,919,039
0
0
null
null
null
null
UTF-8
C++
false
false
35,832
cpp
 // STLDataStructureDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "STLDataStructure.h" #include "STLDataStructureDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif //string 排序 int compareString(const void* a, const void* b) { if (*(string*)a < *(string*)b) return -1; if (*(string*)a == *(string*)b) return 0; if (*(string*)a > * (string*)b) return 1; } // long 比大小 int compareLongs(const void* a, const void* b) { return (*(long*)a - *(long*)b); } //CString转string string toString(CString cs) { #ifdef _UNICODE //如果是unicode工程 USES_CONVERSION; std::string str(W2A(cs)); return str; #else //如果是多字节工程 std::string str(cs.GetBuffer()); cs.ReleaseBuffer(); return str; #endif } //string转CString CString toCString(string str) { #ifdef _UNICODE //如果是unicode工程 USES_CONVERSION; CString s(str.c_str()); CString ans(str.c_str()); return ans; #else //如果是多字节工程 CString ans; ans.Format("%s", str.c_str()); return ans; #endif } // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CSTLDataStructureDlg 对话框 CSTLDataStructureDlg::CSTLDataStructureDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_STLDATASTRUCTURE_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CSTLDataStructureDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_SHOW_TIP, m_ShowTipList); } BEGIN_MESSAGE_MAP(CSTLDataStructureDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_ARRAY, &CSTLDataStructureDlg::OnBnClickedButtonArray) ON_BN_CLICKED(IDC_BUTTON_VECTOR, &CSTLDataStructureDlg::OnBnClickedButtonVector) ON_BN_CLICKED(IDC_BUTTON_LIST, &CSTLDataStructureDlg::OnBnClickedButtonList) ON_BN_CLICKED(IDC_BUTTON_FORWORDLIST, &CSTLDataStructureDlg::OnBnClickedButtonForwordlist) ON_BN_CLICKED(IDC_BUTTON_DEQUE, &CSTLDataStructureDlg::OnBnClickedButtonDeque) ON_BN_CLICKED(IDC_BUTTON_STACK, &CSTLDataStructureDlg::OnBnClickedButtonStack) ON_BN_CLICKED(IDC_BUTTON_QUEUE, &CSTLDataStructureDlg::OnBnClickedButtonQueue) ON_BN_CLICKED(IDC_BUTTON_MULTISET, &CSTLDataStructureDlg::OnBnClickedButtonMultiset) ON_BN_CLICKED(IDC_BUTTON_MULTIMAP, &CSTLDataStructureDlg::OnBnClickedButtonMultimap) ON_BN_CLICKED(IDC_BUTTON_UNORDER_MULTISET, &CSTLDataStructureDlg::OnBnClickedButtonUnorderMultiset) ON_BN_CLICKED(IDC_BUTTON_UNORDER_MULTIMAP, &CSTLDataStructureDlg::OnBnClickedButtonUnorderMultimap) ON_BN_CLICKED(IDC_BUTTON_CLEAR, &CSTLDataStructureDlg::OnBnClickedButtonClear) ON_BN_CLICKED(IDC_BUTTON_SET, &CSTLDataStructureDlg::OnBnClickedButtonSet) ON_BN_CLICKED(IDC_BUTTON_MAP, &CSTLDataStructureDlg::OnBnClickedButtonMap) ON_BN_CLICKED(IDC_BUTTON_UNORDER_SET, &CSTLDataStructureDlg::OnBnClickedButtonUnorderSet) ON_BN_CLICKED(IDC_BUTTON_UNORDER_MAP, &CSTLDataStructureDlg::OnBnClickedButtonUnorderMap) ON_BN_CLICKED(IDC_BUTTON_SEQUENCE_C, &CSTLDataStructureDlg::OnBnClickedButtonSequenceC) ON_BN_CLICKED(IDC_BUTTON_LAMBDA, &CSTLDataStructureDlg::OnBnClickedButtonLambda) ON_BN_CLICKED(IDC_BUTTON_THREAD, &CSTLDataStructureDlg::OnBnClickedButtonThread) ON_BN_CLICKED(IDC_BUTTON_INITIALIZER_LIST, &CSTLDataStructureDlg::OnBnClickedButtonInitializerList) ON_BN_CLICKED(IDC_BUTTON_SIX_COMPONENTS, &CSTLDataStructureDlg::OnBnClickedButtonSixComponents) END_MESSAGE_MAP() // CSTLDataStructureDlg 消息处理程序 CSTLDataStructureDlg* g_pDlg = NULL; BOOL CSTLDataStructureDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 HWND m_hwnd = this->GetSafeHwnd(); g_pDlg = this; return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CSTLDataStructureDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CSTLDataStructureDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CSTLDataStructureDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } //清空信息 void CSTLDataStructureDlg::OnBnClickedButtonClear() { // TODO: 在此添加控件通知处理程序代码 while (m_ShowTipList.GetCount() > 0) { m_ShowTipList.DeleteString(0); } } //显示信息 void CSTLDataStructureDlg::ShowTipToList(CString strTip) { m_ShowTipList.InsertString(0, strTip); while (m_ShowTipList.GetCount() > 200) { m_ShowTipList.DeleteString(200); } } //array void CSTLDataStructureDlg::OnBnClickedButtonArray() { //array 初始化 array<double, 10> ·;//未显式指定元素的值,各个元素的值是不确定的(array 容器不会做默认初始化操作) array<double, 10> array2{};//容器中所有的元素都会被初始化为 0.0。 array<double, 10> array3{ 0.1,0.2,0.3,0.4 };//初始化了前 4 个元素,剩余的元素都会被初始化为 0.0 //元素访问 array<string, 5> words{ "one","two","three","four","five" }; string strword = ""; strword = words[3]; //1 不进行边境检查 strword = words.at(3); //2 进行边境检查 strword = get<3>(words); //3 只能访问模板参数指定的元素,编译器在编译时会对它进行检查 strword = *(words.data() + 3); //4 data 获得首个元素指针 //5 size 获得元素个数 for (size_t i = 0; i < words.size(); ++i) { strword = words[i]; } //6 使用范围循环 for (auto word1:words) { strword = word1; } //7 存储字符串 array<char, 50>a{ 'h','d' }; int n = sizeof(&a[0]); int n1 = strlen("http://c.biancheng.net/stl"); strcpy_s(&a[0], n1 + 1,"http://c.biancheng.net/stl"); printf("%s", &a[0]); printf("%s", &a[1]); ShowTipToList(_T("array++++++++++++++++++++++++")); clock_t timestart = clock(); for (long i = 0; i < ARRAY_SIZE; ++i) { arrayData[i] = rand(); } CString strTip = _T(""); strTip.Format(_T("向array添加%d个元素耗时%d毫秒"), ARRAY_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("array的大小:%d"), arrayData.size()); ShowTipToList(strTip); strTip.Format(_T("array的第一个元素:%d"), arrayData.front()); ShowTipToList(strTip); strTip.Format(_T("array的最后一个元素:%d"), arrayData.back()); ShowTipToList(strTip); strTip.Format(_T("array的地址:0x%x"), arrayData.data()); ShowTipToList(strTip); timestart = clock(); //排序 qsort(arrayData.data(), ARRAY_SIZE, sizeof(long), compareLongs); //sort(arrayData.begin(), arrayData.end()); strTip.Format(_T("array排序耗时%d毫秒"),clock() - timestart); ShowTipToList(strTip); timestart = clock(); //二分查找 long ltag = 2000; long* pItem = (long*)bsearch(&ltag, arrayData.data(), ARRAY_SIZE, sizeof(long), compareLongs); if (pItem) { strTip.Format(_T("array中查找某一个元素耗时%d毫秒"), clock() - timestart); } else { strTip = _T("没有查到"); } ShowTipToList(strTip); ShowTipToList(_T("array++++++++++++++++++++++++")); } //vector 增加空间方式 在新的空间找一个*2的空间 把之前的数据copy过去 1->2->4->8->16 void CSTLDataStructureDlg::OnBnClickedButtonVector() { // TODO: 在此添加控件通知处理程序代码 //初始化 //1、初始化空的vector std::vector<double> v1; v1.reserve(20);//增加容器容量 调用 reserve() 不会影响已存储的元素,也不会生成任何元素 //2、指定初始值和元素个数 std::vector<int> v2{ 2, 3, 5, 7, 11, 13, 17, 19 }; std::vector<int> v3(20);//指定元素个数初始值为0 std::vector<int> v4(20,2);//指定元素个数初始值为2 //4、通过存储元素类型相同的其它 vector 容器,也可以创建新的 vector 容器 std::vector<char>v5(5, 'c'); std::vector<char>v6(v5); //5、用一对指针或者迭代器来指定初始值的范围 int array[] = { 1,2,3 }; std::vector<int>v7(array, array + 2);//values 将保存{1,2} std::vector<int>v8{ 1,2,3,4,5 }; std::vector<int>v9(std::begin(v8), std::begin(v8) + 3);//value2保存{1,2,3} //访问元素(单个元素) vector<int> values{1,2,3,4,5,6,7,8,9}; int n = values[0]; //1、指定下标 不进行边境检查 n = values.at(1); //2、at() 成员函数,当传给 at() 的索引会造成越界时,会抛出std::out_of_range异常 n = values.front(); n = values.back(); //3、首元素 尾元素 n = *(values.data() + 2); //4、values.data()返回首元素地址指针 //访问元素(多个元素) for (int i = 0; i < values.size(); i++) //5、values.size() 返回元素个数 { } for (auto value : values) //6、使用范围循环 { n = value; } for (auto first = values.begin(); first < values.end(); ++first)//7、通过begin/end遍历容器 { n = *first; } ////插入元素 //push_back() 向容器尾部添加元素时,首先创建这个元素,然后再将这个元素拷贝或者移动到容器中(如果是拷贝的话,事后会自行销毁先前创建的这个元素); //emplace_back() 在实现时,则是直接在容器尾部创建这个元素,省去了拷贝或移动元素的过程。 vector<int> value1{}; value1.push_back(1); value1.push_back(2); value1.emplace_back(3); value1.emplace_back(4); CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("vector++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < VECTOR_SIZE; ++i) { CString strindex = _T(""); strindex.Format(_T("%d"), i); //ShowTipToList(strindex); try { snprintf(buf, 10, "%d", rand()); vectorData.push_back((string)buf); } catch (CMemoryException* e) { strTip.Format(_T("vector 最大%d"),i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向vector添加%d个元素耗时%d毫秒"), VECTOR_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("vector的元素大小:%d"), vectorData.size()); ShowTipToList(strTip); strTip.Format(_T("vector的第一个元素:%s"), toCString(vectorData.front())); ShowTipToList(strTip); strTip.Format(_T("vector的最后一个元素:%s"), toCString(vectorData.back())); ShowTipToList(strTip); strTip.Format(_T("vector的地址:0x%x"), vectorData.data()); ShowTipToList(strTip); strTip.Format(_T("vector的实际内存大小:%d"), vectorData.capacity()); ShowTipToList(strTip); //普通查找 timestart = clock(); string sFind = "12679"; auto pItem = find(vectorData.begin(),vectorData.end(), sFind); if (pItem != vectorData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem),clock()-timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } //二分查找 timestart = clock(); sort(vectorData.begin(),vectorData.end()); string *pItemString = (string *)bsearch(&sFind, vectorData.data(), vectorData.size(), sizeof(string), compareString); if (pItemString != NULL) { strTip.Format(_T("通过bsearch找到%s 查询时间%d毫秒"), toCString(*pItemString), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过bsearch没有找到")); } ShowTipToList(_T("vector++++++++++++++++++++++++")); } //list void CSTLDataStructureDlg::OnBnClickedButtonList() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("list++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); listData.push_back((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("list 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向list添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("list的元素大小:%d"), listData.size()); ShowTipToList(strTip); strTip.Format(_T("list可以存放的元素大小:%d"), listData.max_size()); ShowTipToList(strTip); strTip.Format(_T("list的第一个元素:%s"), toCString(listData.front())); ShowTipToList(strTip); strTip.Format(_T("list的最后一个元素:%s"), toCString(listData.back())); ShowTipToList(strTip); //查询 timestart = clock(); string sFind = "12679"; auto pItem = find(listData.begin(), listData.end(), sFind); if (pItem != listData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } //排序 timestart = clock(); listData.sort(); //list内部的sort方法 strTip.Format(_T("通过listsort排序耗时%d毫秒"), clock() - timestart); ShowTipToList(strTip); ShowTipToList(_T("list++++++++++++++++++++++++")); } //ForwordList void CSTLDataStructureDlg::OnBnClickedButtonForwordlist() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("forwardlist++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); forward_listData.push_front((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("forward_listData 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向forward_listData添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("forward_listData可以存放的元素大小:%d"), forward_listData.max_size()); ShowTipToList(strTip); strTip.Format(_T("forward_listData的第一个元素:%s"), toCString(forward_listData.front())); ShowTipToList(strTip); //查询 timestart = clock(); string sFind = "12679"; auto pItem = find(forward_listData.begin(), forward_listData.end(), sFind); if (pItem != forward_listData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } //排序 timestart = clock(); forward_listData.sort(); //list内部的sort方法 strTip.Format(_T("通过forwardlistsort排序耗时%d毫秒"), clock() - timestart); ShowTipToList(strTip); ShowTipToList(_T("forwardlist++++++++++++++++++++++++")); } //deque 双向进出 void CSTLDataStructureDlg::OnBnClickedButtonDeque() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("deque++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); dequeData.push_back((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("list 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向deque添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("deque的元素大小:%d"), dequeData.size()); ShowTipToList(strTip); strTip.Format(_T("deque可以存放的元素大小:%d"), dequeData.max_size()); ShowTipToList(strTip); strTip.Format(_T("deque的第一个元素:%s"), toCString(dequeData.front())); ShowTipToList(strTip); strTip.Format(_T("deque的最后一个元素:%s"), toCString(dequeData.back())); ShowTipToList(strTip); //查询 timestart = clock(); string sFind = "12679"; auto pItem = find(dequeData.begin(), dequeData.end(), sFind); if (pItem != dequeData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } //排序 timestart = clock(); sort(dequeData.begin(), dequeData.end()); //list内部的sort方法 strTip.Format(_T("通过sort排序耗时%d毫秒"), clock() - timestart); ShowTipToList(strTip); ShowTipToList(_T("deque++++++++++++++++++++++++")); } //stack 先进后出 void CSTLDataStructureDlg::OnBnClickedButtonStack() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("stack++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); stackData.push((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("stack 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向stack添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("stack的元素大小:%d"), stackData.size()); ShowTipToList(strTip); strTip.Format(_T("stack的第一个元素:%s"), toCString(stackData.top())); ShowTipToList(strTip); stackData.pop(); strTip.Format(_T("stack的元素大小:%d"), stackData.size()); ShowTipToList(strTip); strTip.Format(_T("stack的第一个元素:%s"), toCString(stackData.top())); ShowTipToList(strTip); ShowTipToList(_T("stack++++++++++++++++++++++++")); } //queue 先进先出 void CSTLDataStructureDlg::OnBnClickedButtonQueue() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("queue++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); queueData.push((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("queue 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向queue添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("queue的元素大小:%d"), queueData.size()); ShowTipToList(strTip); strTip.Format(_T("queue的第一个元素:%s"), toCString(queueData.front())); ShowTipToList(strTip); strTip.Format(_T("queue的最后一个元素:%s"), toCString(queueData.back())); ShowTipToList(strTip); queueData.pop(); strTip.Format(_T("queue的元素大小:%d"), queueData.size()); ShowTipToList(strTip); strTip.Format(_T("queue的第一个元素:%s"), toCString(queueData.front())); ShowTipToList(strTip); strTip.Format(_T("queue的最后一个元素:%s"), toCString(queueData.back())); ShowTipToList(strTip); ShowTipToList(_T("queue++++++++++++++++++++++++")); } //multiset(可以存放重复数值) key value 相同 底层红黑树 void CSTLDataStructureDlg::OnBnClickedButtonMultiset() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("multiset++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); multisetData.insert((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("multiset 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向multiset添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("multiset的元素大小:%d"), multisetData.size()); ShowTipToList(strTip); strTip.Format(_T("multiset可以存放的元素大小:%d"), multisetData.max_size()); ShowTipToList(strTip); //查询 timestart = clock(); string sFind = "12679"; auto pItem1 = ::find(multisetData.begin(), multisetData.end(), sFind); if (pItem1 != multisetData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem1), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } timestart = clock(); auto pItem2 = multisetData.find(sFind); if (pItem2 != multisetData.end()) { strTip.Format(_T("通过multiset.find找到%s 查询时间%d毫秒"), toCString(*pItem2), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过multiset.find没有找到")); } ShowTipToList(_T("multiset++++++++++++++++++++++++")); } //multimap key-value键值对 底层红黑树 可以重复 void CSTLDataStructureDlg::OnBnClickedButtonMultimap() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("multimap++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); //不可以使用[] 进行添加元素 multimapData.insert(pair<long, string>(i, buf)); //将两个值视为一个单元。容器类别map和multimap就是使用pairs来管理其健值/实值(key/value)的成对元素。 } catch (CMemoryException * e) { strTip.Format(_T("multimap 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向multimap添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("multimap的元素大小:%d"), multimapData.size()); ShowTipToList(strTip); strTip.Format(_T("multimap可以存放的元素大小:%d"), multimapData.max_size()); ShowTipToList(strTip); //查询 timestart = clock(); long sFind = 12679; auto pItem2 = multimapData.find(sFind); //find 参数为key if (pItem2 != multimapData.end()) { strTip.Format(_T("通过multimap.find找到key:%d value:%s 查询时间%d毫秒"), (*pItem2).first, toCString((*pItem2).second), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过multimap.find没有找到")); } ShowTipToList(_T("multimap++++++++++++++++++++++++")); } //unordered_multiset 底层哈希表 //篮子要大于等于元素个数,篮子个数大概是元素的2倍 void CSTLDataStructureDlg::OnBnClickedButtonUnorderMultiset() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("unordered_multiset++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); unordered_multisetData.insert((string) buf); } catch (CMemoryException * e) { strTip.Format(_T("unordered_multiset 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向unordered_multiset添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("unordered_multiset的元素大小:%d"), unordered_multisetData.size()); ShowTipToList(strTip); strTip.Format(_T("unordered_multiset可以存放的元素大小:%d"), unordered_multisetData.max_size()); ShowTipToList(strTip); strTip.Format(_T("unordered_multiset篮子个数:%d"), unordered_multisetData.bucket_count()); ShowTipToList(strTip); strTip.Format(_T("unordered_multiset载入因子:%f"), unordered_multisetData.load_factor()); ShowTipToList(strTip); strTip.Format(_T("unordered_multiset最大篮子个数:%d"), unordered_multisetData.max_bucket_count()); ShowTipToList(strTip); strTip.Format(_T("unordered_multiset最大载入因子:%f"), unordered_multisetData.max_load_factor()); ShowTipToList(strTip); for (int i = 0;i<100;++i) { strTip.Format(_T("第[%d]个篮子有[%d]个元素"), i, unordered_multisetData.bucket_size(i)); ShowTipToList(strTip); } //查询 timestart = clock(); string sFind = "12679"; auto pItem1 = ::find(unordered_multisetData.begin(), unordered_multisetData.end(), sFind); if (pItem1 != unordered_multisetData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem1), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } timestart = clock(); auto pItem2 = unordered_multisetData.find(sFind); if (pItem2 != unordered_multisetData.end()) { strTip.Format(_T("通过unordered_multiset.find找到%s 查询时间%d毫秒"), toCString(*pItem2), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过unordered_multiset.find没有找到")); } ShowTipToList(_T("unordered_multiset++++++++++++++++++++++++")); } //unordered_multimap 底层哈希表 void CSTLDataStructureDlg::OnBnClickedButtonUnorderMultimap() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("unordered_multimap++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); unordered_multimapData.insert(pair<long,string>(i, (string)buf)); } catch (CMemoryException * e) { strTip.Format(_T("unordered_multimap 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向unordered_multimap添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("unordered_multimap的元素大小:%d"), unordered_multimapData.size()); ShowTipToList(strTip); strTip.Format(_T("unordered_multimap可以存放的元素大小:%d"), unordered_multimapData.max_size()); ShowTipToList(strTip); strTip.Format(_T("unordered_multimap篮子个数:%d"), unordered_multimapData.bucket_count()); ShowTipToList(strTip); strTip.Format(_T("unordered_multimap载入因子:%f"), unordered_multimapData.load_factor()); ShowTipToList(strTip); strTip.Format(_T("unordered_multimap最大篮子个数:%d"), unordered_multimapData.max_bucket_count()); ShowTipToList(strTip); strTip.Format(_T("unordered_multimap最大载入因子:%f"), unordered_multimapData.max_load_factor()); ShowTipToList(strTip); //查询 timestart = clock(); auto pItem2 = unordered_multimapData.find(12); if (pItem2 != unordered_multimapData.end()) { strTip.Format(_T("通过unordered_multimap.find找到key:%d value:%s 查询时间%d毫秒"), (*pItem2).first,toCString((*pItem2).second), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过unordered_multimap.find没有找到")); } ShowTipToList(_T("unordered_multimap++++++++++++++++++++++++")); } //set 值不可重复 void CSTLDataStructureDlg::OnBnClickedButtonSet() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("set++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); setData.insert((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("set 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向set添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("set的元素大小:%d"), setData.size()); ShowTipToList(strTip); strTip.Format(_T("set可以存放的元素大小:%d"), setData.max_size()); ShowTipToList(strTip); //查询 timestart = clock(); string sFind = "12679"; auto pItem1 = ::find(setData.begin(), setData.end(), sFind); if (pItem1 != setData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem1), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } timestart = clock(); auto pItem2 = setData.find(sFind); if (pItem2 != setData.end()) { strTip.Format(_T("通过set.find找到%s 查询时间%d毫秒"), toCString(*pItem2), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过set.find没有找到")); } ShowTipToList(_T("set++++++++++++++++++++++++")); } //map key不可重复 void CSTLDataStructureDlg::OnBnClickedButtonMap() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("multiset++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); mapData[i] = (string)buf; } catch (CMemoryException * e) { strTip.Format(_T("map 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向map添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("map的元素大小:%d"), mapData.size()); ShowTipToList(strTip); strTip.Format(_T("map可以存放的元素大小:%d"), mapData.max_size()); ShowTipToList(strTip); //查询 timestart = clock(); auto pItem2 = mapData.find(222); if (pItem2 != mapData.end()) { strTip.Format(_T("通过map.find找到key:%d value:%s 查询时间%d毫秒"), (*pItem2).first ,toCString((*pItem2).second), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过map.find没有找到")); } ShowTipToList(_T("map++++++++++++++++++++++++")); } //unorderset 哈希表形式的set void CSTLDataStructureDlg::OnBnClickedButtonUnorderSet() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("unordered_set++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); unordered_setData.insert((string)buf); } catch (CMemoryException * e) { strTip.Format(_T("unordered_set 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向unordered_set添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("unordered_set的元素大小:%d"), unordered_setData.size()); ShowTipToList(strTip); strTip.Format(_T("unordered_set可以存放的元素大小:%d"), unordered_setData.max_size()); ShowTipToList(strTip); //查询 timestart = clock(); string sFind = "12679"; auto pItem1 = ::find(unordered_setData.begin(), unordered_setData.end(), sFind); if (pItem1 != unordered_setData.end()) { strTip.Format(_T("通过find找到%s 查询时间%d毫秒"), toCString(*pItem1), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过find没有找到")); } timestart = clock(); auto pItem2 = unordered_setData.find(sFind); if (pItem2 != unordered_setData.end()) { strTip.Format(_T("通过unordered_set.find找到%s 查询时间%d毫秒"), toCString(*pItem2), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过unordered_set.find没有找到")); } ShowTipToList(_T("unordered_set++++++++++++++++++++++++")); } //unordermap 哈希表形式的map void CSTLDataStructureDlg::OnBnClickedButtonUnorderMap() { // TODO: 在此添加控件通知处理程序代码 CString strTip = _T(""); clock_t timestart = clock(); ShowTipToList(_T("multiset++++++++++++++++++++++++")); char buf[10]; for (long i = 0; i < LIST_SIZE; ++i) { try { snprintf(buf, 10, "%d", rand()); unordered_mapData[i] = (string)buf; } catch (CMemoryException * e) { strTip.Format(_T("unordered_map 最大%d"), i); ShowTipToList(strTip); abort(); } } strTip.Format(_T("向unordered_map添加%d个元素耗时%d毫秒"), LIST_SIZE, clock() - timestart); ShowTipToList(strTip); strTip.Format(_T("unordered_map的元素大小:%d"), unordered_mapData.size()); ShowTipToList(strTip); strTip.Format(_T("unordered_map可以存放的元素大小:%d"), unordered_mapData.max_size()); ShowTipToList(strTip); //查询 timestart = clock(); auto pItem2 = unordered_mapData.find(222); if (pItem2 != unordered_mapData.end()) { strTip.Format(_T("通过unordered_map.find找到key:%d value:%s 查询时间%d毫秒"), (*pItem2).first, toCString((*pItem2).second), clock() - timestart); ShowTipToList(strTip); } else { ShowTipToList(_T("通过unordered_map.find没有找到")); } ShowTipToList(_T("unordered_map++++++++++++++++++++++++")); } #pragma region 顺序表 #define SquenceTableSize 10 //顺序表结构 typedef struct SquenceTable_C { int* head; //动态数组 int length; //顺序表的长度 int size; //顺序表的存储容量 }squenceTable_C; //初始化顺序表 squenceTable_C InitSquenceTable() { squenceTable_C tableTest; tableTest.head = (int*)malloc(10 * sizeof(int)); if (!tableTest.head) { g_pDlg->ShowTipToList(_T("初始化失败!")); } tableTest.size = SquenceTableSize; tableTest.length = 0; return tableTest; } //遍历顺序表 void DisplaySquenceTable(squenceTable_C table) { for (int i = 0;i< table.size;i++) { CString strTmp; strTmp.Format(_T("%d\n"), table.head[i]); g_pDlg->ShowTipToList(strTmp); } } //C 语言实现顺序表 void CSTLDataStructureDlg::OnBnClickedButtonSequenceC() { // TODO: 在此添加控件通知处理程序代码 ShowTipToList(_T("顺序表++++++++++++++++++++++++")); squenceTable_C tableTest = InitSquenceTable(); //向顺序表中添加元素 for (int i = 0; i < SquenceTableSize; i++) { tableTest.head[i] = i; tableTest.length++; } DisplaySquenceTable(tableTest); free(tableTest.head); ShowTipToList(_T("顺序表++++++++++++++++++++++++")); } #pragma endregion //多线程 void CSTLDataStructureDlg::OnBnClickedButtonThread() { // TODO: 在此添加控件通知处理程序代码 } //lambda void CSTLDataStructureDlg::OnBnClickedButtonLambda() { // TODO: 在此添加控件通知处理程序代码 int num[4] = { 4, 2, 3, 1 }; //对 a 数组中的元素进行排序 sort(num, num + 4, [=](int x, int y) -> bool { return x < y; }); for (int n : num) { std::cout << n << " "; } } //统一的类成员初始化语法 void CSTLDataStructureDlg::OnBnClickedButtonInitializerList() { } //六大部件 void CSTLDataStructureDlg::OnBnClickedButtonSixComponents() { int arr[] = {10,20,30,40,50,60,70,80,90}; std::vector<int, allocator<int>> v(arr,arr+9); int count = std::count_if(v.begin(), v.end(), not1(bind2nd(less<int>(), 50))); CString strTip; strTip.Format(TEXT("容器中大于等于50的数字有%d个"), count); ShowTipToList(strTip); }
[ "1979159182@qq.com" ]
1979159182@qq.com
77996c96155f4f7a6d07c2158d6ff019135c4bbf
718bfcc62ecf880fd049c6ff1f567a38146198c3
/MSP/src/include/MSPMutationOperator.h
3b70465cdb73bba20aecdbe874561a82ea3adcfc
[]
no_license
danitico/Metaheuristics
1a0c07337b2f730c5cc50bc8621f3c7e119ec629
83aeddd71fcb1835d0fad097c21e7e6e5fa0e454
refs/heads/master
2020-04-22T22:53:35.824682
2019-06-06T09:21:17
2019-06-06T09:21:17
170,722,349
0
0
null
null
null
null
UTF-8
C++
false
false
1,834
h
/* * MSPMutationOperator.h * * Created on: 15 may. 2019 * Author: chema969 */ #ifndef INCLUDE_MSPMUTATIONOPERATOR_H_ #define INCLUDE_MSPMUTATIONOPERATOR_H_ #include <MSPSolution.h> #include <vector> #include <cstdlib> #include <MSPInstance.h> using namespace std; /** * Class which defines a mutation operator for the MSP. It is based on iterating over all the * genes in the solutions and changing by a value randomly generated according to a probability */ class MSPMutationOperator{ protected: /** * Properties of the class: * _mutProb Mutation probability * _numObjs Number of objects. It is used to reduce the number of queries to the instance * _numKnapsacks Number of knapsack of the problem. It is used to reduce the number of * queries to the instance */ double _mutProb; unsigned _numliterals; /** * Function which mutates a solution * @param[in,out] sol Solution to be mutated */ void mutate(MSPSolution* s){ //Iterate over the objects and, according to a mutation probability, assign them //to a random knapsack (0, 1 or more than 1 genes could be modified) for(unsigned i=0; i< this->_numliterals ;i++){ double randSample=(double)rand()/RAND_MAX; if(randSample < _mutProb){ s->setBool(i,!s->isTrue(i)); } } } public: /** * Constructor * @param[in] mutProb Mutation probability * @param[in] instance Instance of the problem to be considered */ MSPMutationOperator(double mutProb, MSPInstance &instance){ _mutProb = mutProb; _numliterals=instance.getNumberOfLiterals(); } /** * Function which mutates a set of solutions * @param[in,out] sols Solutions to be mutated */ void mutate(vector<MSPSolution*> &sols){ for (MSPSolution* sol : sols){ mutate(sol); } } }; #endif /* INCLUDE_MSPMUTATIONOPERATOR_H_ */
[ "chema969@hotmail.com" ]
chema969@hotmail.com
0c2263bf014deeeb6e25bf923a54b4ef8a1f006e
676c0c3e1d8f09e34df6d252234c1074d2b68ecd
/GLLocomotion/GLLocomotion.h
5572dd5c6c6e376668f28ea3ea88c56414adb040
[ "MIT" ]
permissive
chen0040/cpp-steering-behaviors
bb7340647b04caa8485ffb7c4c5b57ad2ad0feb2
c73d2ae8037556d42440b54ba6eb6190e467fae9
refs/heads/master
2021-01-23T05:44:36.526664
2017-07-22T00:46:36
2017-07-22T00:46:36
92,981,202
3
1
null
null
null
null
UTF-8
C++
false
false
303
h
#ifndef _H_GL_LOCOMOTION_H #define _H_GL_LOCOMOTION_H class Vehicle; class GLLocomotion { public: GLLocomotion(Vehicle* pAgent); virtual ~GLLocomotion(); public: virtual void Update(const long& lElapsedTicks)=0; protected: void EnforceNonPenetration(); protected: Vehicle* m_pAgent; }; #endif
[ "xs0040@gmail.com" ]
xs0040@gmail.com
aaba35edb61c32081d7135f157ec1c1e056e5674
81895fe57e32d5c810fe0b0c4cb69c507b3ec9a8
/countdialog.h
a792e0415fef571b0ecf92560d54dfe254003600
[]
no_license
lynyskyny/Lab_3
e59f10279dd5db4fb5285cb94c8cd86a3de5faf1
5612a2fd21ae06ea3a1385ac5f9911a524e41886
refs/heads/master
2021-08-22T19:56:28.162741
2017-12-01T05:14:25
2017-12-01T05:14:25
112,697,438
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
#ifndef COUNTDIALOG_H #define COUNTDIALOG_H #include <QDialog> #include "queue.h" #include "labeldialog.h" namespace Ui { class CountDialog; } class CountDialog : public QDialog { Q_OBJECT public: explicit CountDialog(Queue *_queue); ~CountDialog(); private: Ui::CountDialog *ui; Queue *queue; LabelDialog *labelDial; private slots: void countMoney(); }; #endif // COUNTDIALOG_H
[ "noreply@github.com" ]
noreply@github.com
99d218495254424a7ceeff2802a06fa667ff8367
6f6bc7eee21f9dbce4a93650c9230402561ce38b
/src/main.cpp
6036d8ab9b273ffcd0c5abb124da4a510603e231
[]
no_license
FelixBrendel/persistent_data_segment
412a4ab45b3a21d6ec11ed4873c65b570665123e
5dc8243727ccc4be8a6540ee44e36f0d82d642e1
refs/heads/main
2023-07-03T10:27:19.157627
2021-08-03T22:38:18
2021-08-03T22:38:18
392,468,311
0
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include <windows.h> #pragma intrinsic(strcat) #include "persistent_data.hpp" int print_int_to_str(int value, char* buffer) { int count = 0, temp; char* ptr = buffer; if (value == 0) { *ptr='0'; count = 1; } else { if (value < 0) { value *= (-1); *ptr++ = '-'; count++; } for(temp=value;temp>0;temp/=10) ptr++; *ptr='\0'; for(temp = value; temp > 0; temp /= 10) { *--ptr = temp % 10 + '0'; count++; } } return count; } auto main() -> int { char text[200] = "You ran this program "; char* ptr = text+21; ptr += print_int_to_str(persistent_data.counter, ptr); strcat(ptr, " times."); MessageBoxA(0, text, "I remember", MB_ICONINFORMATION); persistent_data.counter++; }
[ "felix@brendel.io" ]
felix@brendel.io
88990c4f2806a11d5c44fa54fa6fc4f6ab4cfe2e
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/chrome/browser/upgrade_detector.h
9c1826e5700d57a61d112d8603bcb035de0dc0cb
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
4,928
h
// 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. #ifndef CHROME_BROWSER_UPGRADE_DETECTOR_H_ #define CHROME_BROWSER_UPGRADE_DETECTOR_H_ #include "base/timer/timer.h" #include "chrome/browser/idle.h" #include "ui/gfx/image/image.h" class PrefRegistrySimple; /////////////////////////////////////////////////////////////////////////////// // UpgradeDetector // // This class is a singleton class that monitors when an upgrade happens in the // background. We basically ask Omaha what it thinks the latest version is and // if our version is lower we send out a notification upon: // a) Detecting an upgrade and... // b) When we think the user should be notified about the upgrade. // The latter happens much later, since we don't want to be too annoying. // class UpgradeDetector { public: // The Homeland Security Upgrade Advisory System. enum UpgradeNotificationAnnoyanceLevel { UPGRADE_ANNOYANCE_NONE = 0, // What? Me worry? UPGRADE_ANNOYANCE_LOW, // Green. UPGRADE_ANNOYANCE_ELEVATED, // Yellow. UPGRADE_ANNOYANCE_HIGH, // Red. UPGRADE_ANNOYANCE_SEVERE, // Orange. UPGRADE_ANNOYANCE_CRITICAL, // Red exclamation mark. }; // The two types of icons we know about. enum UpgradeNotificationIconType { UPGRADE_ICON_TYPE_BADGE = 0, // For overlay badging of the wrench menu. UPGRADE_ICON_TYPE_MENU_ICON, // For showing in the wrench menu. }; // Returns the singleton implementation instance. static UpgradeDetector* GetInstance(); virtual ~UpgradeDetector(); static void RegisterPrefs(PrefRegistrySimple* registry); // Whether the user should be notified about an upgrade. bool notify_upgrade() const { return notify_upgrade_; } // Whether the upgrade recommendation is due to Chrome being outdated. bool is_outdated_install() const { return upgrade_available_ == UPGRADE_NEEDED_OUTDATED_INSTALL; } // Notifify this object that the user has acknowledged the critical update // so we don't need to complain about it for now. void acknowledge_critical_update() { critical_update_acknowledged_ = true; } // Whether the user has acknowledged the critical update. bool critical_update_acknowledged() const { return critical_update_acknowledged_; } // When the last upgrade was detected. const base::Time& upgrade_detected_time() const { return upgrade_detected_time_; } // Retrieves the right icon ID based on the degree of severity (see // UpgradeNotificationAnnoyanceLevel, each level has an an accompanying icon // to go with it). |type| determines which class of icons the caller wants, // either an icon appropriate for badging the wrench menu or one to display // within the wrench menu. int GetIconResourceID(UpgradeNotificationIconType type); UpgradeNotificationAnnoyanceLevel upgrade_notification_stage() const { return upgrade_notification_stage_; } protected: UpgradeDetector(); // Sends out UPGRADE_DETECTED notification and record upgrade_detected_time_. void NotifyUpgradeDetected(); // Sends out UPGRADE_RECOMMENDED notification and set notify_upgrade_. void NotifyUpgradeRecommended(); void set_upgrade_notification_stage(UpgradeNotificationAnnoyanceLevel stage) { upgrade_notification_stage_ = stage; } enum UpgradeAvailable { // If no update is available and current install is recent enough. UPGRADE_AVAILABLE_NONE, // If a regular update is available. UPGRADE_AVAILABLE_REGULAR, // If a critical update to Chrome has been installed, such as a zero-day // fix. UPGRADE_AVAILABLE_CRITICAL, // If no update to Chrome has been installed for more than the recommended // time. UPGRADE_NEEDED_OUTDATED_INSTALL, } upgrade_available_; // Whether the user has acknowledged the critical update. bool critical_update_acknowledged_; private: // Initiates an Idle check. See IdleCallback below. void CheckIdle(); // The callback for the IdleCheck. Tells us whether Chrome has received any // input events since the specified time. void IdleCallback(IdleState state); // When the upgrade was detected. base::Time upgrade_detected_time_; // A timer to check to see if we've been idle for long enough to show the // critical warning. Should only be set if |upgrade_available_| is // UPGRADE_AVAILABLE_CRITICAL. base::RepeatingTimer<UpgradeDetector> idle_check_timer_; // The stage at which the annoyance level for upgrade notifications is at. UpgradeNotificationAnnoyanceLevel upgrade_notification_stage_; // Whether we have waited long enough after detecting an upgrade (to see // is we should start nagging about upgrading). bool notify_upgrade_; DISALLOW_COPY_AND_ASSIGN(UpgradeDetector); }; #endif // CHROME_BROWSER_UPGRADE_DETECTOR_H_
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
b59a4432ae099f210586c7f90ed7b27f07132b69
4044fc117cfceaf6b10af6c756515b32232744f6
/src/test/prevector_tests.cpp
7a6bb3542aacdbd96a53c8d4cde3ca5c6e5cbad7
[ "MIT" ]
permissive
PsyTeck/astercoin
075c3c346530de9eb9e003ce49e640d30b6a3f9b
62bd370211e666259092e4de1db668be474fa954
refs/heads/master
2020-03-31T06:22:53.993751
2018-10-08T00:27:22
2018-10-08T00:27:22
145,587,528
0
0
null
null
null
null
UTF-8
C++
false
false
8,027
cpp
// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <vector> #include "prevector.h" #include "random.h" #include "serialize.h" #include "streams.h" #include "test/test_astercoin.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup) template<unsigned int N, typename T> class prevector_tester { typedef std::vector<T> realtype; realtype real_vector; realtype real_vector_alt; typedef prevector<N, T> pretype; pretype pre_vector; pretype pre_vector_alt; typedef typename pretype::size_type Size; bool passed = true; uint32_t insecure_rand_Rz_cache; uint32_t insecure_rand_Rw_cache; template <typename A, typename B> void local_check_equal(A a, B b) { local_check(a == b); } void local_check(bool b) { passed &= b; } void test() { const pretype& const_pre_vector = pre_vector; local_check_equal(real_vector.size(), pre_vector.size()); local_check_equal(real_vector.empty(), pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { local_check(real_vector[s] == pre_vector[s]); local_check(&(pre_vector[s]) == &(pre_vector.begin()[s])); local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s)); local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // local_check(realtype(pre_vector) == real_vector); local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector); local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; BOOST_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[--pos]); } BOOST_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[--pos]); } CDataStream ss1(SER_DISK, 0); CDataStream ss2(SER_DISK, 0); ss1 << real_vector; ss2 << pre_vector; local_check_equal(ss1.size(), ss2.size()); for (Size s = 0; s < ss1.size(); s++) { local_check_equal(ss1[s], ss2[s]); } } public: void resize(Size s) { real_vector.resize(s); local_check_equal(real_vector.size(), s); pre_vector.resize(s); local_check_equal(pre_vector.size(), s); test(); } void reserve(Size s) { real_vector.reserve(s); local_check(real_vector.capacity() >= s); pre_vector.reserve(s); local_check(pre_vector.capacity() >= s); test(); } void insert(Size position, const T& value) { real_vector.insert(real_vector.begin() + position, value); pre_vector.insert(pre_vector.begin() + position, value); test(); } void insert(Size position, Size count, const T& value) { real_vector.insert(real_vector.begin() + position, count, value); pre_vector.insert(pre_vector.begin() + position, count, value); test(); } template<typename I> void insert_range(Size position, I first, I last) { real_vector.insert(real_vector.begin() + position, first, last); pre_vector.insert(pre_vector.begin() + position, first, last); test(); } void erase(Size position) { real_vector.erase(real_vector.begin() + position); pre_vector.erase(pre_vector.begin() + position); test(); } void erase(Size first, Size last) { real_vector.erase(real_vector.begin() + first, real_vector.begin() + last); pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last); test(); } void update(Size pos, const T& value) { real_vector[pos] = value; pre_vector[pos] = value; test(); } void push_back(const T& value) { real_vector.push_back(value); pre_vector.push_back(value); test(); } void pop_back() { real_vector.pop_back(); pre_vector.pop_back(); test(); } void clear() { real_vector.clear(); pre_vector.clear(); } void assign(Size n, const T& value) { real_vector.assign(n, value); pre_vector.assign(n, value); } Size size() { return real_vector.size(); } Size capacity() { return pre_vector.capacity(); } void shrink_to_fit() { pre_vector.shrink_to_fit(); test(); } void swap() { real_vector.swap(real_vector_alt); pre_vector.swap(pre_vector_alt); test(); } ~prevector_tester() { BOOST_CHECK_MESSAGE(passed, "insecure_rand_Rz: " << insecure_rand_Rz_cache << ", insecure_rand_Rw: " << insecure_rand_Rw_cache); } prevector_tester() { seed_insecure_rand(); insecure_rand_Rz_cache = insecure_rand_Rz; insecure_rand_Rw_cache = insecure_rand_Rw; } }; BOOST_AUTO_TEST_CASE(PrevectorTestInt) { for (int j = 0; j < 64; j++) { BOOST_TEST_MESSAGE("PrevectorTestInt " << j); prevector_tester<8, int> test; for (int i = 0; i < 2048; i++) { int r = insecure_rand(); if ((r % 4) == 0) { test.insert(insecure_rand() % (test.size() + 1), insecure_rand()); } if (test.size() > 0 && ((r >> 2) % 4) == 1) { test.erase(insecure_rand() % test.size()); } if (((r >> 4) % 8) == 2) { int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2)); test.resize(new_size); } if (((r >> 7) % 8) == 3) { test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand()); } if (((r >> 10) % 8) == 4) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } if (((r >> 13) % 16) == 5) { test.push_back(insecure_rand()); } if (test.size() > 0 && ((r >> 17) % 16) == 6) { test.pop_back(); } if (((r >> 21) % 32) == 7) { int values[4]; int num = 1 + (insecure_rand() % 4); for (int i = 0; i < num; i++) { values[i] = insecure_rand(); } test.insert_range(insecure_rand() % (test.size() + 1), values, values + num); } if (((r >> 26) % 32) == 8) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } r = insecure_rand(); if (r % 32 == 9) { test.reserve(insecure_rand() % 32); } if ((r >> 5) % 64 == 10) { test.shrink_to_fit(); } if (test.size() > 0) { test.update(insecure_rand() % test.size(), insecure_rand()); } if (((r >> 11) % 1024) == 11) { test.clear(); } if (((r >> 21) % 512) == 12) { test.assign(insecure_rand() % 32, insecure_rand()); } if (((r >> 15) % 64) == 3) { test.swap(); } } } } BOOST_AUTO_TEST_SUITE_END()
[ "35582826+PsyTeck@users.noreply.github.com" ]
35582826+PsyTeck@users.noreply.github.com
c69f157b7b496d5d9e8dbd10cf524e93ed7a2b44
d7e41f16df202fe917d0d6398cb7a0185db0bbac
/include/wise.kernel/server/service/bot/acts/act_loop.hpp
7bdb832bc84a69b176a31a749f35cee6274d9b7f
[ "MIT" ]
permissive
npangunion/wise.kernel
77a60d4e7fcecd69721d9bd106d41f0e5370282a
a44f852f5e7ade2c5f95f5d615daaf154bc69468
refs/heads/master
2020-12-28T16:17:29.077050
2020-05-18T15:42:30
2020-05-18T15:42:30
238,401,519
1
0
null
null
null
null
UHC
C++
false
false
375
hpp
#pragma once #include <wise/service/bot/act.hpp> namespace wise { /// time: millisecs, random: bool 로 지정. 일정 시간 대기후 성공 class act_loop : public act { public: act_loop(flow& owner, config& cfg); private: void on_begin() override; void on_exec() override; void load(); private: uint32_t loop_ = 1; uint32_t current_loop_ = 0; }; } // test
[ "npangunion@gmail.com" ]
npangunion@gmail.com
2f9c41fe6b4373ad53eb1fb272a74939f7cc559d
38c10c01007624cd2056884f25e0d6ab85442194
/chrome/browser/extensions/extension_websocket_apitest.cc
71542ba4ec73b288de74bc15ccbcc52ada727b55
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
548
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "content/public/common/content_paths.h" #include "net/base/test_data_directory.h" #include "net/dns/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) { ASSERT_TRUE(StartWebSocketServer(net::GetWebSocketTestDataDirectory())); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
973d9597f165f0b14f0c7988ef5894427900ec18
9e62f1f0e90d7ca932c8a965e5d938e647524cfa
/CS 5300/WhileStatement.cpp
5fe68d928a7f71c29676d2ad8783d1d6e80a1041
[]
no_license
nfcopier/homework
c07a7a792d6ad29ca5f1c7af38f95b4ef638f2d8
0f9b21bfa94b42847321d29202a99ce00db860ef
refs/heads/master
2022-08-27T09:18:56.862083
2022-08-19T08:27:50
2022-08-19T08:27:50
81,039,868
0
0
null
null
null
null
UTF-8
C++
false
false
106
cpp
// // Created by floris on 3/14/17. // #include "WhileStatement.h" int WhileStatement::labelCount_ = 0;
[ "nfcopier@gmail.com" ]
nfcopier@gmail.com
492889cf0d2de00f7d720933b4fcb07acdb8fca1
5ee0eb940cfad30f7a3b41762eb4abd9cd052f38
/Case_save/case1/800/PMV
2229dd81109fbdcbcb21b619f432c33995a5625d
[]
no_license
mamitsu2/aircond5_play4
052d2ff593661912b53379e74af1f7cee20bf24d
c5800df67e4eba5415c0e877bdeff06154d51ba6
refs/heads/master
2020-05-25T02:11:13.406899
2019-05-20T04:56:10
2019-05-20T04:56:10
187,570,146
0
0
null
null
null
null
UTF-8
C++
false
false
9,457
/*--------------------------------*- C++ -*----------------------------------*========= | \ / F ield | OpenFOAM: The Open Source CFD Toolbox \ / O peration | Website: https://openfoam.org \ / A nd | Version: 6 \/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "800"; object PMV; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 1.746059848144744 1.541278687641951 1.5219080204890756 1.5005573600792326 1.4845313162692828 1.4739565851601428 1.4670804095005754 1.465910496954931 1.4694492568619777 1.4778215359496938 1.4923945757083916 1.514250790514497 1.546623482133163 1.5851844696294175 1.599217211047702 1.649543735063733 1.641903984156204 1.63903894450303 1.6380839152847473 1.6376063976844564 1.6371288780927347 1.635633023565405 1.6316737903647782 1.6300230900587556 1.6291185140404667 1.628959441828096 1.6286166312731258 1.6287024411855557 1.630069509728523 1.632815870156869 1.63330864990619 1.6328311124810475 1.6328311124810475 1.6409489789547804 1.7209880703535343 1.5579066365707162 1.5561770886951747 1.5365999363579785 1.5242304801351365 1.516147217994959 1.5116509570364804 1.5101704278004424 1.5126900110438373 1.51680283667349 1.5228898926132146 1.5342199970593782 1.5517631337148878 1.5740384031114525 1.5945088625627322 1.6165936798033786 1.6070412151382414 1.5887902908164617 1.6409489789547804 1.6385614308915903 1.6366513565115794 1.62645022421669 1.619626181561397 1.6155365425262882 1.6135606227432044 1.6117768648287971 1.6095634852682454 1.6071407252133698 1.6047540618025626 1.60292836868249 1.6012555527338543 1.6014317175456334 1.606154894662859 1.6142056344764253 1.6156384673744209 1.595460612736489 1.7753389260194963 1.5565284716581198 1.587166483252749 1.5763323023424967 1.5730795972289873 1.5713481761473762 1.5713369816044922 1.5726269479006079 1.5735998234293345 1.5708650373545352 1.5642828086342806 1.559016095011702 1.55961152482973 1.5696341001565453 1.592764985829802 1.620892041207561 1.6194592713059297 1.547242826033568 1.5998929475357675 1.6146812419342804 1.6168974373915102 1.6173405098866782 1.6171093311609135 1.6154599815943338 1.6166220394792452 1.6161743363053978 1.6143020790062834 1.6111266790503975 1.6081150304270675 1.6047183290171478 1.6001777173583411 1.5930866532365335 1.5918481438156937 1.6070573746937422 1.5919260075211445 1.5374422752678518 1.8585639546753157 1.5585444509321738 1.6098717861348417 1.6135533358224012 1.625888355681695 1.6374717749079093 1.6470204465478788 1.6545679765294479 1.6531009888993091 1.6363897650717207 1.6078762829326552 1.578146638244717 1.5584937965469567 1.5561233801709602 1.5735973350974195 1.6110435852067668 1.6242351035978237 1.6099129030449877 1.5866063739524778 1.6072166655917868 1.6246708392737441 1.6329788595778736 1.6366763124587065 1.636615545512959 1.6295058124170922 1.618944605759791 1.6098451985297564 1.6022597658523954 1.5968030347293791 1.5937373709704534 1.594856114855895 1.602331751138995 1.619855432928833 1.6199536684971652 1.6122526146973697 1.5680702092672316 1.4922502172486836 1.952820853063135 1.5761998844840954 1.6302232340445584 1.6460031857797692 1.676990251884989 1.7102443951057513 1.7408123914781526 1.761193071818417 1.7421047270241277 1.6928564669617927 1.6341605572151447 1.5823453494376156 1.5474428011867882 1.5378973200713053 1.550334749335466 1.5789474575133673 1.6071021056640096 1.6148606796999738 1.6137897959789982 1.6307911986647603 1.6515570590941402 1.656228088643101 1.6586152597383834 1.6595701136283054 1.6605249591803617 1.66065605939949 1.65116984055518 1.6424870709317176 1.6349817581759005 1.6287521226831425 1.6250246456147983 1.6247710852615873 1.6264057077960221 1.6187292277995344 1.6012008819285035 1.5455133057813037 1.5425677208596005 1.6586152597383834 1.6352273103807453 1.4767007896715636 2.0429052127517964 1.6155235269745818 1.6727572171624978 1.680524202109717 1.7187050362200178 1.7693183590263302 1.7926827077052008 1.819376810380698 1.770806649318244 1.6979718093189033 1.6271149199098476 1.5678075272697123 1.530260467782506 1.5195965435318866 1.5333101412287424 1.5649726481945854 1.6026253708516338 1.6328441819798003 1.6485887946134918 1.6571829633059134 1.6633894456446359 1.667686033387014 1.6700729524879474 1.6710277052328288 1.6719824494409754 1.6719824494409754 1.6715050784050258 1.6705503299264395 1.6691181912230153 1.6662538564745641 1.6619572118389099 1.6524122526595877 1.6408012743297098 1.620909278521622 1.594957120567565 1.5389426598881348 1.5412343937927127 1.5524495553327764 1.547455806339175 1.5541999241598992 2.1261756922621093 1.7071355757278623 1.8134467856987626 1.762633799758331 1.7550741490893373 1.7765572817722644 1.793059740419444 1.770959672583173 1.7245459599117827 1.658792512889963 1.588858607386378 1.5321545882849774 1.5013342325261394 1.5005892842202344 1.5261663997540889 1.5707236024052815 1.6229946797744237 1.6481113213309968 1.6610023788245234 1.6700729524879474 1.6758013405712435 1.6791427572015247 1.681052090441573 1.6820067439998294 1.6824840675061083 1.6820067439998294 1.681529418310943 1.6800974281698227 1.6777107344800597 1.6743692725032724 1.668640807400749 1.6624346252049882 1.65575064820552 1.6405471241779108 1.6067990225436077 1.5551408379836704 1.5375642139276167 1.526538352170377 1.4992617296678716 1.5840686675124087 2.2563813554177776 2.027542508505805 1.9853921494793902 1.8755656926984101 1.8266965187071387 1.800985333769258 1.7749586060776956 1.730944584848555 1.6634806615350877 1.5839386219838616 1.5141089487466113 1.471070483940689 1.4628210866318434 1.4880337595583621 1.5392809846145215 1.606611822228054 1.6433364768828804 1.6633894456446359 1.6762786922864363 1.6834387079623316 1.6872571820573237 1.689643656739407 1.6910755149646364 1.6915527965961843 1.6920300760023739 1.6915527965961843 1.6910755149646364 1.6891663662279304 1.6867798804941954 1.6834387079623316 1.6786654184614387 1.6710277052328288 1.6648216605418098 1.6581378296718812 1.6514535914484167 1.6413393267621028 1.6195987531569374 1.6083531559577118 1.5488630339290204 1.468913391479527 2.447579119584533 2.305630324773834 2.132345934719885 1.9798190836309484 1.8701910890839106 1.7909399707212068 1.7216973724812943 1.6223034554022866 1.512101017179554 1.426179214151455 1.384927702141144 1.3911695764342216 1.4365533114561406 1.511195347232758 1.601309376950721 1.6356963073889386 1.6652990612959901 1.681529418310943 1.6901209450341017 1.694893705586234 1.6972800019798175 1.6991889985843176 1.700059003143891 1.694161539245126 1.6885555929665177 1.6825052754054861 1.6758403344166615 1.6684480687821386 1.6605567038682636 1.6515912722887227 1.6411172811457795 1.6304269334030796 1.6208872642134082 1.6086462616300148 1.5946094383532305 1.5817484827497117 1.5718713609428663 1.5664969911641398 1.555403390094035 1.523738317992455 -2.7486562725397237 -0.7501461457676856 0.05996715285984237 0.4743812282719938 0.674125611070513 0.8204713385035136 0.9661422284557656 1.1117221394641197 1.2580408483069652 1.3998010782655894 1.518648888317597 1.585067737608176 1.6385614308915903 1.668640807400749 1.6867798804941954 1.6933219208589434 1.690108818237315 1.6866003115927553 1.6820412579297752 1.6769371228543903 1.6716132182965204 1.666019932699136 1.659645232963767 1.652972377610134 1.6461005694310729 1.6392466506138121 1.6332077501316153 1.6278830577505117 1.6241509856067926 1.6224042047127418 1.6217738929666599 1.6218129483438497 1.6224809742316182 1.624986816172241 1.6350365165518697 1.6692840061308614 1.7368568587436266 1.5769692870228362 -2.115634831737235 -0.5401049757928956 0.30925971555134757 0.7016584291372789 0.9214261261393341 1.082303009951928 1.2177752674094973 1.3441058519456492 1.466542964563437 1.5535354538455415 1.6066006932201204 1.6222988206101696 1.635202004146641 1.6448897640313354 1.6514579741287863 1.6560826770346588 1.65898868134089 1.6600734860216824 1.659043724870292 1.6577696752219355 1.6550670374990117 1.6525120675586868 1.6497028794827726 1.6467208067477332 1.6437021709496282 1.6408570750976823 1.6389718080504119 1.6375369584836683 1.6382654708060522 1.6420311916972605 1.6501585552451652 1.662071919889026 1.6753247381121525 1.6861736219314665 1.697728040877041 1.7352531972016307 1.6684970194987125 1.6165968528386219 -0.8860446001154754 -1.020923131905718 -0.9066281986776948 0.26886411525431225 0.7464698096120442 1.0006700050707293 1.1812171892310186 1.31831564404531 1.416215402393254 1.481644379709969 1.5298347761182063 1.5645372749368025 1.5883653120487469 1.603461672429611 1.6112707526512986 1.6128418312072013 1.6116661197366913 1.6109999087333156 1.6107141726705116 1.6110984449403685 1.611460625149617 1.6121938171422663 1.6132302402687615 1.6140159518112134 1.6155324184450905 1.6167979194917699 1.6189452052951252 1.6212396395919222 1.6251361699402873 1.630295914179039 1.6384138640454162 1.6515066315373281 1.6735049818667551 1.7129607490526992 1.7473787992865975 1.754056624475305 1.7218846544815067 1.6772257131114565 1.6324076076687983 1.6360993527777936 ) ; boundaryField { ".*" { type zeroGradient; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
7ea020f9144d1b436cd4827fa2cac8fe1ea27462
90047daeb462598a924d76ddf4288e832e86417c
/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h
b203984f265bea3a0542513487a57dd579fc58bf
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
10,025
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_USERS_WALLPAPER_WALLPAPER_MANAGER_H_ #define CHROME_BROWSER_CHROMEOS_LOGIN_USERS_WALLPAPER_WALLPAPER_MANAGER_H_ #include <memory> #include <string> #include <vector> #include "ash/public/interfaces/wallpaper.mojom.h" #include "base/macros.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/customization/customization_wallpaper_downloader.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "components/user_manager/user.h" #include "components/user_manager/user_image/user_image.h" #include "components/user_manager/user_manager.h" #include "components/wallpaper/wallpaper_layout.h" #include "components/wallpaper/wallpaper_manager_base.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "mojo/public/cpp/bindings/binding.h" #include "ui/gfx/image/image_skia.h" namespace chromeos { class WallpaperManager : public wallpaper::WallpaperManagerBase, public ash::mojom::WallpaperPicker, public content::NotificationObserver, public user_manager::UserManager::UserSessionStateObserver { public: class PendingWallpaper; ~WallpaperManager() override; // Creates an instance of Wallpaper Manager. If there is no instance, create // one. Otherwise, returns the existing instance. static void Initialize(); // Gets pointer to singleton WallpaperManager instance. static WallpaperManager* Get(); // Deletes the existing instance of WallpaperManager. Allows the // WallpaperManager to remove any observers it has registered. static void Shutdown(); // wallpaper::WallpaperManagerBase: WallpaperResolution GetAppropriateResolution() override; void AddObservers() override; void EnsureLoggedInUserWallpaperLoaded() override; void InitializeWallpaper() override; void RemoveUserWallpaperInfo(const AccountId& account_id) override; void OnPolicyFetched(const std::string& policy, const AccountId& account_id, std::unique_ptr<std::string> data) override; void SetCustomWallpaper(const AccountId& account_id, const wallpaper::WallpaperFilesId& wallpaper_files_id, const std::string& file, wallpaper::WallpaperLayout layout, user_manager::User::WallpaperType type, const gfx::ImageSkia& image, bool update_wallpaper) override; void SetDefaultWallpaperNow(const AccountId& account_id) override; void SetDefaultWallpaperDelayed(const AccountId& account_id) override; void DoSetDefaultWallpaper( const AccountId& account_id, wallpaper::MovableOnDestroyCallbackHolder on_finish) override; void SetUserWallpaperInfo(const AccountId& account_id, const wallpaper::WallpaperInfo& info, bool is_persistent) override; void ScheduleSetUserWallpaper(const AccountId& account_id, bool delayed) override; void SetWallpaperFromImageSkia(const AccountId& account_id, const gfx::ImageSkia& image, wallpaper::WallpaperLayout layout, bool update_wallpaper) override; void UpdateWallpaper(bool clear_cache) override; size_t GetPendingListSizeForTesting() const override; wallpaper::WallpaperFilesId GetFilesId( const AccountId& account_id) const override; bool SetDeviceWallpaperIfApplicable(const AccountId& account_id) override; // ash::mojom::WallpaperPicker: void Open() override; // content::NotificationObserver: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; // user_manager::UserManager::UserSessionStateObserver: void UserChangedChildStatus(user_manager::User* user) override; private: friend class TestApi; friend class WallpaperManagerBrowserTest; friend class WallpaperManagerBrowserTestDefaultWallpaper; friend class WallpaperManagerPolicyTest; WallpaperManager(); // Returns modifiable PendingWallpaper. // Returns pending_inactive_ or creates new PendingWallpaper if necessary. PendingWallpaper* GetPendingWallpaper(const AccountId& account_id, bool delayed); // This is called by PendingWallpaper when load is finished. void RemovePendingWallpaperFromList(PendingWallpaper* pending); // Set wallpaper to |user_image| controlled by policy. (Takes a UserImage // because that's the callback interface provided by UserImageLoader.) void SetPolicyControlledWallpaper( const AccountId& account_id, std::unique_ptr<user_manager::UserImage> user_image); // This is called when the device wallpaper policy changes. void OnDeviceWallpaperPolicyChanged(); // This is call after checking if the device wallpaper exists. void OnDeviceWallpaperExists(const AccountId& account_id, const std::string& url, const std::string& hash, bool exist); // This is called after the device wallpaper is download (either successful or // failed). void OnDeviceWallpaperDownloaded(const AccountId& account_id, const std::string& hash, bool success, const GURL& url); // Check if the device wallpaper matches the hash that's provided in the // device wallpaper policy setting. void OnCheckDeviceWallpaperMatchHash(const AccountId& account_id, const std::string& url, const std::string& hash, bool match); // This is called when the device wallpaper is decoded successfully. void OnDeviceWallpaperDecoded( const AccountId& account_id, std::unique_ptr<user_manager::UserImage> user_image); // wallpaper::WallpaperManagerBase: void InitializeRegisteredDeviceWallpaper() override; bool GetUserWallpaperInfo(const AccountId& account_id, wallpaper::WallpaperInfo* info) const override; // Returns true if the device wallpaper should be set for the account. bool ShouldSetDeviceWallpaper(const AccountId& account_id, std::string* url, std::string* hash) override; base::FilePath GetDeviceWallpaperDir() override; base::FilePath GetDeviceWallpaperFilePath() override; void OnWallpaperDecoded( const AccountId& account_id, wallpaper::WallpaperLayout layout, bool update_wallpaper, wallpaper::MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) override; void StartLoad(const AccountId& account_id, const wallpaper::WallpaperInfo& info, bool update_wallpaper, const base::FilePath& wallpaper_path, wallpaper::MovableOnDestroyCallbackHolder on_finish) override; void SetCustomizedDefaultWallpaperAfterCheck( const GURL& wallpaper_url, const base::FilePath& downloaded_file, std::unique_ptr<CustomizedWallpaperRescaledFiles> rescaled_files) override; void OnCustomizedDefaultWallpaperResized( const GURL& wallpaper_url, std::unique_ptr<CustomizedWallpaperRescaledFiles> rescaled_files, std::unique_ptr<bool> success, std::unique_ptr<gfx::ImageSkia> small_wallpaper_image, std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) override; void SetDefaultWallpaperPathsFromCommandLine( base::CommandLine* command_line) override; void OnDefaultWallpaperDecoded( const base::FilePath& path, const wallpaper::WallpaperLayout layout, std::unique_ptr<user_manager::UserImage>* result, wallpaper::MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) override; void StartLoadAndSetDefaultWallpaper( const base::FilePath& path, const wallpaper::WallpaperLayout layout, wallpaper::MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage>* result_out) override; void SetDefaultWallpaperPath( const base::FilePath& customized_default_wallpaper_file_small, std::unique_ptr<gfx::ImageSkia> small_wallpaper_image, const base::FilePath& customized_default_wallpaper_file_large, std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) override; void RecordWallpaperAppType() override; mojo::Binding<ash::mojom::WallpaperPicker> binding_; std::unique_ptr<CrosSettings::ObserverSubscription> show_user_name_on_signin_subscription_; std::unique_ptr<CrosSettings::ObserverSubscription> device_wallpaper_image_subscription_; std::unique_ptr<CustomizationWallpaperDownloader> device_wallpaper_downloader_; bool retry_download_if_failed_ = true; // Pointer to last inactive (waiting) entry of 'loading_' list. // NULL when there is no inactive request. PendingWallpaper* pending_inactive_; // Owns PendingWallpaper. // PendingWallpaper deletes itself from here on load complete. // All pending will be finally deleted on destroy. typedef std::vector<scoped_refptr<PendingWallpaper>> PendingList; PendingList loading_; content::NotificationRegistrar registrar_; base::WeakPtrFactory<WallpaperManager> weak_factory_; DISALLOW_COPY_AND_ASSIGN(WallpaperManager); }; } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_LOGIN_USERS_WALLPAPER_WALLPAPER_MANAGER_H_
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
c3c3be8aa6a847d4f723f8229a774e9d53fd1705
b6fa6f42fefacedffbd3d19d5f247750375791e5
/lib/CodeGen/DwarfGenerator.cpp
1e8e661492136f3950269d49bffd177b4857041d
[ "NCSA" ]
permissive
joshkunz/llvm
5c2f1a496b6d1a53312dffb259a79182b39acf5e
8d15f863bd90ef0cbd2699111ab832b468930347
refs/heads/master
2020-06-10T19:33:58.514712
2016-12-08T02:11:03
2016-12-08T02:11:03
75,904,353
0
0
null
2016-12-08T04:57:50
2016-12-08T04:57:50
null
UTF-8
C++
false
false
9,820
cpp
//===--- lib/CodeGen/DwarfGenerator.cpp -------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DwarfGenerator.h" #include "AsmPrinter/DwarfStringPool.h" #include "llvm/ADT/Triple.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/DIE.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h" #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h" #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" #include "llvm/IR/LegacyPassManagers.h" #include "llvm/MC/MCAsmBackend.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCCodeEmitter.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCTargetOptionsCommandFlags.h" #include "llvm/PassAnalysisSupport.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; using namespace dwarf; namespace {} // end anonymous namespace //===----------------------------------------------------------------------===// /// dwarfgen::DIE implementation. //===----------------------------------------------------------------------===// unsigned dwarfgen::DIE::computeSizeAndOffsets(unsigned Offset) { auto &DG = CU->getGenerator(); return Die->computeOffsetsAndAbbrevs(DG.getAsmPrinter(), DG.getAbbrevSet(), Offset); } void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form, uint64_t U) { auto &DG = CU->getGenerator(); Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form, DIEInteger(U)); } void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form, StringRef String) { auto &DG = CU->getGenerator(); if (Form == DW_FORM_string) { Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form, new (DG.getAllocator()) DIEInlineString(String)); } else { Die->addValue( DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form, DIEString(DG.getStringPool().getEntry(*DG.getAsmPrinter(), String))); } } void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form, dwarfgen::DIE &RefDie) { auto &DG = CU->getGenerator(); Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form, DIEEntry(*RefDie.Die)); } void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form, const void *P, size_t S) { auto &DG = CU->getGenerator(); DIEBlock *Block = new (DG.getAllocator()) DIEBlock; for (size_t I = 0; I < S; ++I) Block->addValue(DG.getAllocator(), (dwarf::Attribute)0, dwarf::DW_FORM_data1, DIEInteger(((uint8_t *)P)[I])); Block->ComputeSize(DG.getAsmPrinter()); Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form, Block); } void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form) { auto &DG = CU->getGenerator(); assert(Form == DW_FORM_flag_present); Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form, DIEInteger(1)); } dwarfgen::DIE dwarfgen::DIE::addChild(dwarf::Tag Tag) { auto &DG = CU->getGenerator(); return dwarfgen::DIE(CU, &Die->addChild(llvm::DIE::get(DG.getAllocator(), Tag))); } dwarfgen::DIE dwarfgen::CompileUnit::getUnitDIE() { return dwarfgen::DIE(this, &DU.getUnitDie()); } //===----------------------------------------------------------------------===// /// dwarfgen::Generator implementation. //===----------------------------------------------------------------------===// dwarfgen::Generator::Generator() : Abbreviations(Allocator) {} dwarfgen::Generator::~Generator() = default; llvm::Expected<std::unique_ptr<dwarfgen::Generator>> dwarfgen::Generator::create(Triple TheTriple, uint16_t DwarfVersion) { std::unique_ptr<dwarfgen::Generator> GenUP(new dwarfgen::Generator()); llvm::Error error = GenUP->init(TheTriple, DwarfVersion); if (error) return Expected<std::unique_ptr<dwarfgen::Generator>>(std::move(error)); return Expected<std::unique_ptr<dwarfgen::Generator>>(std::move(GenUP)); } llvm::Error dwarfgen::Generator::init(Triple TheTriple, uint16_t V) { Version = V; std::string ErrorStr; std::string TripleName; // Get the target. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr); if (!TheTarget) return make_error<StringError>(ErrorStr, inconvertibleErrorCode()); TripleName = TheTriple.getTriple(); // Create all the MC Objects. MRI.reset(TheTarget->createMCRegInfo(TripleName)); if (!MRI) return make_error<StringError>(Twine("no register info for target ") + TripleName, inconvertibleErrorCode()); MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName)); if (!MAI) return make_error<StringError>("no asm info for target " + TripleName, inconvertibleErrorCode()); MOFI.reset(new MCObjectFileInfo); MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get())); MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC); MCTargetOptions Options; MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options); if (!MAB) return make_error<StringError>("no asm backend for target " + TripleName, inconvertibleErrorCode()); MII.reset(TheTarget->createMCInstrInfo()); if (!MII) return make_error<StringError>("no instr info info for target " + TripleName, inconvertibleErrorCode()); MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", "")); if (!MSTI) return make_error<StringError>("no subtarget info for target " + TripleName, inconvertibleErrorCode()); MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC); if (!MCE) return make_error<StringError>("no code emitter for target " + TripleName, inconvertibleErrorCode()); Stream = make_unique<raw_svector_ostream>(FileBytes); MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags(); MS = TheTarget->createMCObjectStreamer( TheTriple, *MC, *MAB, *Stream, MCE, *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible, /*DWARFMustBeAtTheEnd*/ false); if (!MS) return make_error<StringError>("no object streamer for target " + TripleName, inconvertibleErrorCode()); // Finally create the AsmPrinter we'll use to emit the DIEs. TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(), None)); if (!TM) return make_error<StringError>("no target machine for target " + TripleName, inconvertibleErrorCode()); Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS))); if (!Asm) return make_error<StringError>("no asm printer for target " + TripleName, inconvertibleErrorCode()); // Set the DWARF version correctly on all classes that we use. MC->setDwarfVersion(Version); Asm->setDwarfVersion(Version); StringPool.reset(new DwarfStringPool(Allocator, *Asm, StringRef())); return Error::success(); } StringRef dwarfgen::Generator::generate() { // Offset from the first CU in the debug info section is 0 initially. unsigned SecOffset = 0; // Iterate over each compile unit and set the size and offsets for each // DIE within each compile unit. All offsets are CU relative. for (auto &CU : CompileUnits) { // Set the absolute .debug_info offset for this compile unit. CU->setOffset(SecOffset); // The DIEs contain compile unit relative offsets. unsigned CUOffset = 11; CUOffset = CU->getUnitDIE().computeSizeAndOffsets(CUOffset); // Update our absolute .debug_info offset. SecOffset += CUOffset; CU->setLength(CUOffset - 4); } Abbreviations.Emit(Asm.get(), MOFI->getDwarfAbbrevSection()); StringPool->emit(*Asm, MOFI->getDwarfStrSection()); MS->SwitchSection(MOFI->getDwarfInfoSection()); for (auto &CU : CompileUnits) { uint16_t Version = CU->getVersion(); auto Length = CU->getLength(); MC->setDwarfVersion(Version); assert(Length != -1U); Asm->EmitInt32(Length); Asm->EmitInt16(Version); Asm->EmitInt32(0); Asm->EmitInt8(CU->getAddressSize()); Asm->emitDwarfDIE(*CU->getUnitDIE().Die); } MS->Finish(); if (FileBytes.empty()) return StringRef(); return StringRef(FileBytes.data(), FileBytes.size()); } bool dwarfgen::Generator::saveFile(StringRef Path) { if (FileBytes.empty()) return false; std::error_code EC; raw_fd_ostream Strm(Path, EC, sys::fs::F_None); if (EC) return false; Strm.write(FileBytes.data(), FileBytes.size()); Strm.close(); return true; } dwarfgen::CompileUnit &dwarfgen::Generator::addCompileUnit() { CompileUnits.push_back(std::unique_ptr<CompileUnit>( new CompileUnit(*this, Version, Asm->getPointerSize()))); return *CompileUnits.back(); }
[ "gclayton@apple.com" ]
gclayton@apple.com
a68950b10e7e19f57298e5487b03ffe248181a3c
eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86
/Grade 10-12/2018 autumn/NOIP/NOIP2018提高组Day1程序包/GD-Senior/answers/GD-0564/money/money.cpp
cb38551c5b0d4e4ccd98c73dc08ea602733081c7
[]
no_license
Orion545/OI-Record
0071ecde8f766c6db1f67b9c2adf07d98fd4634f
fa7d3a36c4a184fde889123d0a66d896232ef14c
refs/heads/master
2022-01-13T19:39:22.590840
2019-05-26T07:50:17
2019-05-26T07:50:17
188,645,194
4
2
null
null
null
null
UTF-8
C++
false
false
848
cpp
#include<bits/stdc++.h> #define fo(i,a,b) for(i=a;i<=b;i++) #define fd(i,a,b) for(i=a;i>=b;i--) #define max(a,b) (a>b?a:b) using namespace std; typedef long long ll; inline int read(){ int n=0,f=1;char c; for(c=getchar();c!='-'&&(c<'0'||c>'9');c=getchar()); if (c=='-') c=getchar(),f=-1; for(;c>='0'&&c<='9';c=getchar()) n=n*10+c-48; return n*f; } const int maxn=25e3+5; int T,i,j,x,n,num,mx,a[105],bz[maxn],bk; int f[maxn],ans; void work(){ n=read(),num=mx=0,bk++; fo(i,1,n) { j=read(); if (bz[j]==bk) continue; a[++num]=j,bz[j]=bk; mx=max(mx,j); } fo(i,1,mx) f[i]=0; fo(i,1,num){ x=a[i]; fo(j,x,mx) f[j]+=f[j-x],f[j]=f[j]>1?2:f[j]; } ans=0; fo(i,1,num) ans+=f[a[i]]==1; printf("%d\n",ans); } int main(){ freopen("money.in","r",stdin); freopen("money.out","w",stdout); f[0]=1; for(T=read();T--;) work(); return 0; }
[ "orion545@qq.com" ]
orion545@qq.com
03f9202d65b5558001c9c3cbfc990b8448095f87
1dbf007249acad6038d2aaa1751cbde7e7842c53
/rds/src/v3/model/ListPredefinedTagRequest.cpp
6cdf56124cb1a37b92709744baf4923f413b1bdb
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
1,511
cpp
#include "huaweicloud/rds/v3/model/ListPredefinedTagRequest.h" namespace HuaweiCloud { namespace Sdk { namespace Rds { namespace V3 { namespace Model { ListPredefinedTagRequest::ListPredefinedTagRequest() { xLanguage_ = ""; xLanguageIsSet_ = false; } ListPredefinedTagRequest::~ListPredefinedTagRequest() = default; void ListPredefinedTagRequest::validate() { } web::json::value ListPredefinedTagRequest::toJson() const { web::json::value val = web::json::value::object(); if(xLanguageIsSet_) { val[utility::conversions::to_string_t("X-Language")] = ModelBase::toJson(xLanguage_); } return val; } bool ListPredefinedTagRequest::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("X-Language"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("X-Language")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setXLanguage(refVal); } } return ok; } std::string ListPredefinedTagRequest::getXLanguage() const { return xLanguage_; } void ListPredefinedTagRequest::setXLanguage(const std::string& value) { xLanguage_ = value; xLanguageIsSet_ = true; } bool ListPredefinedTagRequest::xLanguageIsSet() const { return xLanguageIsSet_; } void ListPredefinedTagRequest::unsetxLanguage() { xLanguageIsSet_ = false; } } } } } }
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
78cddb0d03665ac36ddbd4f3b9062b9ae173c926
d0fb46aecc3b69983e7f6244331a81dff42d9595
/viapi-regen/include/alibabacloud/viapi-regen/model/DisableDataReflowRequest.h
7abf0c12e56bb2ee72f262000321694bec416919
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,412
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_VIAPI_REGEN_MODEL_DISABLEDATAREFLOWREQUEST_H_ #define ALIBABACLOUD_VIAPI_REGEN_MODEL_DISABLEDATAREFLOWREQUEST_H_ #include <alibabacloud/viapi-regen/Viapi_regenExport.h> #include <alibabacloud/core/RpcServiceRequest.h> #include <string> #include <vector> #include <map> namespace AlibabaCloud { namespace Viapi_regen { namespace Model { class ALIBABACLOUD_VIAPI_REGEN_EXPORT DisableDataReflowRequest : public RpcServiceRequest { public: DisableDataReflowRequest(); ~DisableDataReflowRequest(); long getServiceId() const; void setServiceId(long serviceId); private: long serviceId_; }; } // namespace Model } // namespace Viapi_regen } // namespace AlibabaCloud #endif // !ALIBABACLOUD_VIAPI_REGEN_MODEL_DISABLEDATAREFLOWREQUEST_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
f536f73d73b7cc934f6641935e5c6253e8765c61
038fd9e7f469c4e7f7343a10c0183d60050f4b4e
/couchbase-sys/libcouchbase/tests/iotests/t_misc.cc
1abd771e8e956dc4846cf385b9f752f2de5d2d41
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
tinh-phan/couchbase-rs
32abc0119e11da7c8c06e7d610e364a42c493a6d
a6160df405302ea40848efe4751ab7b46dd692ca
refs/heads/master
2020-10-01T00:51:43.324887
2019-12-11T16:54:31
2019-12-11T16:54:31
227,413,790
0
0
Apache-2.0
2019-12-11T16:41:48
2019-12-11T16:41:47
null
UTF-8
C++
false
false
25,465
cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2012-2019 Couchbase, 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 "config.h" #include "iotests.h" #include <map> #include <climits> #include <algorithm> #include "internal.h" /* vbucket_* things from lcb_INSTANCE * */ #include "auth-priv.h" #include <lcbio/iotable.h> #include "bucketconfig/bc_http.h" #define LOGARGS(instance, lvl) instance->settings, "tests-MUT", LCB_LOG_##lvl, __FILE__, __LINE__ extern "C" { static void timings_callback(lcb_INSTANCE *, const void *cookie, lcb_timeunit_t, lcb_U32, lcb_U32, lcb_U32, lcb_U32) { bool *bPtr = (bool *)cookie; *bPtr = true; } } TEST_F(MockUnitTest, testTimings) { lcb_INSTANCE *instance; HandleWrap hw; bool called = false; createConnection(hw, &instance); lcb_enable_timings(instance); std::string key = "counter"; std::string val = "0"; lcb_CMDSTORE *storecmd; lcb_cmdstore_create(&storecmd, LCB_STORE_UPSERT); lcb_cmdstore_key(storecmd, key.c_str(), key.size()); lcb_cmdstore_value(storecmd, val.c_str(), val.size()); ASSERT_EQ(LCB_SUCCESS, lcb_store(instance, NULL, storecmd)); lcb_cmdstore_destroy(storecmd); lcb_wait(instance); lcb_get_timings(instance, &called, timings_callback); lcb_disable_timings(instance); ASSERT_TRUE(called); } namespace { struct TimingInfo { lcb_U64 ns_start; lcb_U64 ns_end; size_t count; TimingInfo() : ns_start(-1), ns_end(-1), count(-1) {} bool operator<(const TimingInfo &other) const { return other.ns_start > ns_start; } bool operator>(const TimingInfo &other) const { return ns_start > other.ns_start; } bool valid() const { return count != -1; } }; static lcb_U64 intervalToNsec(lcb_U64 interval, lcb_timeunit_t unit) { if (unit == LCB_TIMEUNIT_NSEC) { return interval; } else if (unit == LCB_TIMEUNIT_USEC) { return interval * 1000; } else if (unit == LCB_TIMEUNIT_MSEC) { return interval * 1000000; } else if (unit == LCB_TIMEUNIT_SEC) { return interval * 1000000000; } else { return -1; } } struct LcbTimings { LcbTimings() {} std::vector< TimingInfo > m_info; void load(lcb_INSTANCE *); void clear(); TimingInfo infoAt(hrtime_t duration, lcb_timeunit_t unit = LCB_TIMEUNIT_NSEC); size_t countAt(hrtime_t duration, lcb_timeunit_t unit = LCB_TIMEUNIT_NSEC) { return infoAt(duration, unit).count; } void dump() const; }; extern "C" { static void load_timings_callback(lcb_INSTANCE *, const void *cookie, lcb_timeunit_t unit, lcb_U32 min, lcb_U32 max, lcb_U32 total, lcb_U32 maxtotal) { lcb_U64 start = intervalToNsec(min, unit); lcb_U64 end = intervalToNsec(max, unit); LcbTimings *timings = (LcbTimings *)cookie; TimingInfo info; info.ns_start = start; info.ns_end = end; info.count = total; timings->m_info.push_back(info); } } // extern "C" void LcbTimings::load(lcb_INSTANCE *instance) { lcb_get_timings(instance, this, load_timings_callback); std::sort(m_info.begin(), m_info.end()); } TimingInfo LcbTimings::infoAt(hrtime_t duration, lcb_timeunit_t unit) { duration = intervalToNsec(duration, unit); std::vector< TimingInfo >::iterator ii; for (ii = m_info.begin(); ii != m_info.end(); ++ii) { if (ii->ns_start <= duration && ii->ns_end > duration) { return *ii; } } return TimingInfo(); } void LcbTimings::dump() const { std::vector< TimingInfo >::const_iterator ii = m_info.begin(); for (; ii != m_info.end(); ii++) { if (ii->ns_end < 1000) { printf("[%llu-%llu ns] %lu\n", (unsigned long long)ii->ns_start, (unsigned long long)ii->ns_end, (unsigned long long)ii->count); } else if (ii->ns_end < 10000000) { printf("[%llu-%llu us] %lu\n", (unsigned long long)(ii->ns_start / 1000), (unsigned long long)ii->ns_end / 1000, (unsigned long long)ii->count); } else { printf("[%llu-%llu ms] %lu\n", (unsigned long long)(ii->ns_start / 1000000), (unsigned long long)(ii->ns_end / 1000000), (unsigned long long)ii->count); } } } } // namespace struct UnitInterval { lcb_U64 n; lcb_timeunit_t unit; UnitInterval(lcb_U64 n, lcb_timeunit_t unit) : n(n), unit(unit) {} }; static void addTiming(lcb_INSTANCE *instance, const UnitInterval &interval) { hrtime_t n = intervalToNsec(interval.n, interval.unit); lcb_histogram_record(instance->kv_timings, n); } TEST_F(MockUnitTest, testTimingsEx) { lcb_INSTANCE *instance; HandleWrap hw; createConnection(hw, &instance); lcb_disable_timings(instance); lcb_enable_timings(instance); std::vector< UnitInterval > intervals; intervals.push_back(UnitInterval(1, LCB_TIMEUNIT_NSEC)); intervals.push_back(UnitInterval(250, LCB_TIMEUNIT_NSEC)); intervals.push_back(UnitInterval(4, LCB_TIMEUNIT_USEC)); intervals.push_back(UnitInterval(32, LCB_TIMEUNIT_USEC)); intervals.push_back(UnitInterval(942, LCB_TIMEUNIT_USEC)); intervals.push_back(UnitInterval(1243, LCB_TIMEUNIT_USEC)); intervals.push_back(UnitInterval(1732, LCB_TIMEUNIT_USEC)); intervals.push_back(UnitInterval(5630, LCB_TIMEUNIT_USEC)); intervals.push_back(UnitInterval(42, LCB_TIMEUNIT_MSEC)); intervals.push_back(UnitInterval(434, LCB_TIMEUNIT_MSEC)); intervals.push_back(UnitInterval(8234, LCB_TIMEUNIT_MSEC)); intervals.push_back(UnitInterval(1294, LCB_TIMEUNIT_MSEC)); intervals.push_back(UnitInterval(48, LCB_TIMEUNIT_SEC)); for (size_t ii = 0; ii < intervals.size(); ++ii) { addTiming(instance, intervals[ii]); } // Ensure they all exist, at least. Currently we bundle everything LcbTimings timings; timings.load(instance); // timings.dump(); // Measuring in < us ASSERT_EQ(2, timings.countAt(50, LCB_TIMEUNIT_NSEC)); ASSERT_EQ(1, timings.countAt(4, LCB_TIMEUNIT_USEC)); ASSERT_EQ(1, timings.countAt(30, LCB_TIMEUNIT_USEC)); ASSERT_EQ(-1, timings.countAt(900, LCB_TIMEUNIT_USEC)); ASSERT_EQ(1, timings.countAt(940, LCB_TIMEUNIT_USEC)); ASSERT_EQ(1, timings.countAt(1200, LCB_TIMEUNIT_USEC)); ASSERT_EQ(1, timings.countAt(1250, LCB_TIMEUNIT_USEC)); ASSERT_EQ(1, timings.countAt(5600, LCB_TIMEUNIT_USEC)); ASSERT_EQ(1, timings.countAt(40, LCB_TIMEUNIT_MSEC)); ASSERT_EQ(1, timings.countAt(430, LCB_TIMEUNIT_MSEC)); ASSERT_EQ(1, timings.countAt(1, LCB_TIMEUNIT_SEC)); ASSERT_EQ(1, timings.countAt(8, LCB_TIMEUNIT_SEC)); ASSERT_EQ(1, timings.countAt(93, LCB_TIMEUNIT_SEC)); } struct async_ctx { int count; lcbio_pTABLE table; }; extern "C" { static void dtor_callback(const void *cookie) { async_ctx *ctx = (async_ctx *)cookie; ctx->count++; IOT_STOP(ctx->table); } } TEST_F(MockUnitTest, testAsyncDestroy) { lcb_INSTANCE *instance; createConnection(&instance); lcbio_pTABLE iot = instance->iotable; lcb_settings *settings = instance->settings; storeKey(instance, "foo", "bar"); // Now destroy the instance async_ctx ctx; ctx.count = 0; ctx.table = iot; lcb_set_destroy_callback(instance, dtor_callback); lcb_destroy_async(instance, &ctx); lcb_settings_ref(settings); lcbio_table_ref(iot); lcb_run_loop(instance); lcb_settings_unref(settings); lcbio_table_unref(iot); ASSERT_EQ(1, ctx.count); } TEST_F(MockUnitTest, testGetHostInfo) { lcb_INSTANCE *instance; createConnection(&instance); lcb_BOOTSTRAP_TRANSPORT tx; const char *hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG, 0); ASSERT_FALSE(hoststr == NULL); hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG_CONNECTED, 0); lcb_STATUS err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_CONFIG_TRANSPORT, &tx); ASSERT_EQ(LCB_SUCCESS, err); if (tx == LCB_CONFIG_TRANSPORT_HTTP) { ASSERT_FALSE(hoststr == NULL); hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG_CONNECTED, 99); ASSERT_FALSE(hoststr == NULL); } else { if (hoststr) { printf("%s\n", hoststr); } ASSERT_TRUE(hoststr == NULL); } // Get any data node using std::map; using std::string; map< string, bool > smap; // Ensure we only get unique nodes for (lcb_S32 ii = 0; ii < lcb_get_num_nodes(instance); ii++) { const char *cur = lcb_get_node(instance, LCB_NODE_DATA, ii); ASSERT_FALSE(cur == NULL); ASSERT_FALSE(smap[cur]); smap[cur] = true; } lcb_destroy(instance); // Try with no connection err = lcb_create(&instance, NULL); ASSERT_EQ(LCB_SUCCESS, err); hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG_CONNECTED, 0); ASSERT_TRUE(NULL == hoststr); hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG, 0); ASSERT_TRUE(NULL == hoststr); lcb_destroy(instance); } TEST_F(MockUnitTest, testEmptyKeys) { lcb_INSTANCE *instance; HandleWrap hw; createConnection(hw, &instance); union { lcb_CMDENDURE endure; lcb_CMDOBSERVE observe; lcb_CMDBASE base; lcb_CMDSTATS stats; } u; memset(&u, 0, sizeof u); lcb_sched_enter(instance); lcb_CMDGET *get; lcb_cmdget_create(&get); ASSERT_EQ(LCB_EMPTY_KEY, lcb_get(instance, NULL, get)); lcb_cmdget_destroy(get); lcb_CMDGETREPLICA *rget; lcb_cmdgetreplica_create(&rget, LCB_REPLICA_MODE_ANY); ASSERT_EQ(LCB_EMPTY_KEY, lcb_getreplica(instance, NULL, rget)); lcb_cmdgetreplica_destroy(rget); lcb_CMDSTORE *store; lcb_cmdstore_create(&store, LCB_STORE_UPSERT); ASSERT_EQ(LCB_EMPTY_KEY, lcb_store(instance, NULL, store)); lcb_cmdstore_destroy(store); lcb_CMDTOUCH *touch; lcb_cmdtouch_create(&touch); ASSERT_EQ(LCB_EMPTY_KEY, lcb_touch(instance, NULL, touch)); lcb_cmdtouch_destroy(touch); lcb_CMDUNLOCK *unlock; lcb_cmdunlock_create(&unlock); ASSERT_EQ(LCB_EMPTY_KEY, lcb_unlock(instance, NULL, unlock)); lcb_cmdunlock_destroy(unlock); lcb_CMDCOUNTER *counter; lcb_cmdcounter_create(&counter); ASSERT_EQ(LCB_EMPTY_KEY, lcb_counter(instance, NULL, counter)); lcb_cmdcounter_destroy(counter); // Observe and such lcb_MULTICMD_CTX *ctx = lcb_observe3_ctxnew(instance); ASSERT_EQ(LCB_EMPTY_KEY, ctx->addcmd(ctx, (lcb_CMDBASE *)&u.observe)); ctx->fail(ctx); lcb_durability_opts_t dopts; memset(&dopts, 0, sizeof dopts); dopts.v.v0.persist_to = 1; ctx = lcb_endure3_ctxnew(instance, &dopts, NULL); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(LCB_EMPTY_KEY, ctx->addcmd(ctx, (lcb_CMDBASE *)&u.endure)); ctx->fail(ctx); ASSERT_EQ(LCB_SUCCESS, lcb_stats3(instance, NULL, &u.stats)); lcb_sched_fail(instance); } template < typename T > static bool ctlSet(lcb_INSTANCE *instance, int setting, T val) { lcb_STATUS err = lcb_cntl(instance, LCB_CNTL_SET, setting, &val); return err == LCB_SUCCESS; } template <> bool ctlSet< const char * >(lcb_INSTANCE *instance, int setting, const char *val) { return lcb_cntl(instance, LCB_CNTL_SET, setting, (void *)val) == LCB_SUCCESS; } template < typename T > static T ctlGet(lcb_INSTANCE *instance, int setting) { T tmp; lcb_STATUS err = lcb_cntl(instance, LCB_CNTL_GET, setting, &tmp); EXPECT_EQ(LCB_SUCCESS, err); return tmp; } template < typename T > static void ctlGetSet(lcb_INSTANCE *instance, int setting, T val) { EXPECT_TRUE(ctlSet< T >(instance, setting, val)); EXPECT_EQ(val, ctlGet< T >(instance, setting)); } template <> void ctlGetSet< const char * >(lcb_INSTANCE *instance, int setting, const char *val) { EXPECT_TRUE(ctlSet< const char * >(instance, setting, val)); EXPECT_STREQ(val, ctlGet< const char * >(instance, setting)); } static bool ctlSetInt(lcb_INSTANCE *instance, int setting, int val) { return ctlSet< int >(instance, setting, val); } static int ctlGetInt(lcb_INSTANCE *instance, int setting) { return ctlGet< int >(instance, setting); } static bool ctlSetU32(lcb_INSTANCE *instance, int setting, lcb_U32 val) { return ctlSet< lcb_U32 >(instance, setting, val); } static lcb_U32 ctlGetU32(lcb_INSTANCE *instance, int setting) { return ctlGet< lcb_U32 >(instance, setting); } TEST_F(MockUnitTest, testCtls) { lcb_INSTANCE *instance; HandleWrap hw; lcb_STATUS err; createConnection(hw, &instance); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_OP_TIMEOUT, UINT_MAX); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_VIEW_TIMEOUT, UINT_MAX); ASSERT_EQ(LCB_TYPE_BUCKET, ctlGet< lcb_INSTANCE_TYPE >(instance, LCB_CNTL_HANDLETYPE)); ASSERT_FALSE(ctlSet< lcb_INSTANCE_TYPE >(instance, LCB_CNTL_HANDLETYPE, LCB_TYPE_BUCKET)); lcbvb_CONFIG *cfg = ctlGet< lcbvb_CONFIG * >(instance, LCB_CNTL_VBCONFIG); // Do we have a way to verify this? ASSERT_FALSE(cfg == NULL); ASSERT_GT(cfg->nsrv, (unsigned int)0); lcb_io_opt_t io = ctlGet< lcb_io_opt_t >(instance, LCB_CNTL_IOPS); ASSERT_TRUE(io == instance->getIOT()->p); // Try to set it? ASSERT_FALSE(ctlSet< lcb_io_opt_t >(instance, LCB_CNTL_IOPS, (lcb_io_opt_t) "Hello")); // Map a key lcb_cntl_vbinfo_t vbi = {0}; vbi.v.v0.key = "123"; vbi.v.v0.nkey = 3; err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_VBMAP, &vbi); ASSERT_EQ(LCB_SUCCESS, err); // Try to modify it? err = lcb_cntl(instance, LCB_CNTL_SET, LCB_CNTL_VBMAP, &vbi); ASSERT_NE(LCB_SUCCESS, err); ctlGetSet< lcb_ipv6_t >(instance, LCB_CNTL_IP6POLICY, LCB_IPV6_DISABLED); ctlGetSet< lcb_ipv6_t >(instance, LCB_CNTL_IP6POLICY, LCB_IPV6_ONLY); ctlGetSet< lcb_SIZE >(instance, LCB_CNTL_CONFERRTHRESH, UINT_MAX); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_DURABILITY_TIMEOUT, UINT_MAX); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_DURABILITY_INTERVAL, UINT_MAX); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_HTTP_TIMEOUT, UINT_MAX); ctlGetSet< int >(instance, LCB_CNTL_IOPS_DLOPEN_DEBUG, 55); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_CONFIGURATION_TIMEOUT, UINT_MAX); ctlGetSet< int >(instance, LCB_CNTL_RANDOMIZE_BOOTSTRAP_HOSTS, 1); ctlGetSet< int >(instance, LCB_CNTL_RANDOMIZE_BOOTSTRAP_HOSTS, 0); ASSERT_EQ(0, ctlGetInt(instance, LCB_CNTL_CONFIG_CACHE_LOADED)); ASSERT_FALSE(ctlSetInt(instance, LCB_CNTL_CONFIG_CACHE_LOADED, 99)); ctlGetSet< const char * >(instance, LCB_CNTL_FORCE_SASL_MECH, "SECRET"); ctlGetSet< int >(instance, LCB_CNTL_MAX_REDIRECTS, SHRT_MAX); ctlGetSet< int >(instance, LCB_CNTL_MAX_REDIRECTS, -1); ctlGetSet< int >(instance, LCB_CNTL_MAX_REDIRECTS, 0); // LCB_CNTL_LOGGER handled in other tests ctlGetSet< lcb_U32 >(instance, LCB_CNTL_CONFDELAY_THRESH, UINT_MAX); // CONFIG_TRANSPORT. Test that we shouldn't be able to set it ASSERT_FALSE(ctlSet< lcb_BOOTSTRAP_TRANSPORT >(instance, LCB_CNTL_CONFIG_TRANSPORT, LCB_CONFIG_TRANSPORT_LIST_END)); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_CONFIG_NODE_TIMEOUT, UINT_MAX); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_HTCONFIG_IDLE_TIMEOUT, UINT_MAX); ASSERT_FALSE(ctlSet< const char * >(instance, LCB_CNTL_CHANGESET, "deadbeef")); ASSERT_FALSE(ctlGet< const char * >(instance, LCB_CNTL_CHANGESET) == NULL); ctlGetSet< const char * >(instance, LCB_CNTL_CONFIGCACHE, "/foo/bar/baz"); ASSERT_FALSE(ctlSetInt(instance, LCB_CNTL_SSL_MODE, 90)); ASSERT_GE(ctlGetInt(instance, LCB_CNTL_SSL_MODE), 0); ASSERT_FALSE(ctlSet< const char * >(instance, LCB_CNTL_SSL_CACERT, "/tmp")); lcb_U32 ro_in, ro_out; ro_in = LCB_RETRYOPT_CREATE(LCB_RETRY_ON_SOCKERR, LCB_RETRY_CMDS_GET); ASSERT_TRUE(ctlSet< lcb_U32 >(instance, LCB_CNTL_RETRYMODE, ro_in)); ro_out = LCB_RETRYOPT_CREATE(LCB_RETRY_ON_SOCKERR, 0); err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_RETRYMODE, &ro_out); ASSERT_EQ(LCB_SUCCESS, err); ASSERT_EQ(LCB_RETRY_CMDS_GET, LCB_RETRYOPT_GETPOLICY(ro_out)); ASSERT_EQ(LCB_SUCCESS, lcb_cntl_string(instance, "retry_policy", "topochange:get")); ro_out = LCB_RETRYOPT_CREATE(LCB_RETRY_ON_TOPOCHANGE, 0); err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_RETRYMODE, &ro_out); ASSERT_EQ(LCB_RETRY_CMDS_GET, LCB_RETRYOPT_GETPOLICY(ro_out)); ctlGetSet< int >(instance, LCB_CNTL_HTCONFIG_URLTYPE, LCB_HTCONFIG_URLTYPE_COMPAT); ctlGetSet< int >(instance, LCB_CNTL_COMPRESSION_OPTS, LCB_COMPRESS_FORCE); ctlSetU32(instance, LCB_CNTL_CONLOGGER_LEVEL, 3); lcb_U32 tmp; err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_CONLOGGER_LEVEL, &tmp); ASSERT_NE(LCB_SUCCESS, err); ctlGetSet< int >(instance, LCB_CNTL_DETAILED_ERRCODES, 1); ctlGetSet< lcb_U32 >(instance, LCB_CNTL_RETRY_INTERVAL, UINT_MAX); ctlGetSet< lcb_SIZE >(instance, LCB_CNTL_HTTP_POOLSIZE, UINT_MAX); ctlGetSet< int >(instance, LCB_CNTL_HTTP_REFRESH_CONFIG_ON_ERROR, 0); // Allow timeouts to be expressed as fractional seconds. err = lcb_cntl_string(instance, "operation_timeout", "1.0"); ASSERT_EQ(LCB_SUCCESS, err); ASSERT_EQ(1000000, ctlGet< lcb_U32 >(instance, LCB_CNTL_OP_TIMEOUT)); err = lcb_cntl_string(instance, "operation_timeout", "0.255"); ASSERT_EQ(LCB_SUCCESS, err); ASSERT_EQ(255000, ctlGet< lcb_U32 >(instance, LCB_CNTL_OP_TIMEOUT)); // Test default for nmv retry int itmp = ctlGetInt(instance, LCB_CNTL_RETRY_NMV_IMM); ASSERT_NE(0, itmp); err = lcb_cntl_string(instance, "retry_nmv_imm", "0"); ASSERT_EQ(LCB_SUCCESS, err); itmp = ctlGetInt(instance, LCB_CNTL_RETRY_NMV_IMM); ASSERT_EQ(0, itmp); } TEST_F(MockUnitTest, testConflictingOptions) { HandleWrap hw; lcb_INSTANCE *instance; createConnection(hw, &instance); lcb_sched_enter(instance); const char *key = "key"; size_t nkey = 3; const char *value = "value"; size_t nvalue = 5; lcb_CMDSTORE *scmd; lcb_cmdstore_create(&scmd, LCB_STORE_APPEND); lcb_cmdstore_expiry(scmd, 1); lcb_cmdstore_key(scmd, key, nkey); lcb_cmdstore_value(scmd, value, nvalue); lcb_STATUS err; err = lcb_store(instance, NULL, scmd); ASSERT_EQ(LCB_OPTIONS_CONFLICT, err); lcb_cmdstore_expiry(scmd, 0); lcb_cmdstore_flags(scmd, 99); err = lcb_store(instance, NULL, scmd); ASSERT_EQ(LCB_OPTIONS_CONFLICT, err); lcb_cmdstore_expiry(scmd, 0); lcb_cmdstore_flags(scmd, 0); err = lcb_store(instance, NULL, scmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_cmdstore_destroy(scmd); lcb_cmdstore_create(&scmd, LCB_STORE_INSERT); lcb_cmdstore_key(scmd, key, nkey); lcb_cmdstore_cas(scmd, 0xdeadbeef); err = lcb_store(instance, NULL, scmd); ASSERT_EQ(LCB_OPTIONS_CONFLICT, err); lcb_cmdstore_cas(scmd, 0); err = lcb_store(instance, NULL, scmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_CMDCOUNTER *ccmd; lcb_cmdcounter_create(&ccmd); lcb_cmdcounter_key(ccmd, key, nkey); lcb_cmdcounter_expiry(ccmd, 10); err = lcb_counter(instance, NULL, ccmd); ASSERT_EQ(LCB_OPTIONS_CONFLICT, err); lcb_cmdcounter_initial(ccmd, 0); err = lcb_counter(instance, NULL, ccmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_cmdcounter_destroy(ccmd); } TEST_F(MockUnitTest, testDump) { const char *fpname; #ifdef _WIN32 fpname = "NUL:"; #else fpname = "/dev/null"; #endif FILE *fp = fopen(fpname, "w"); if (!fp) { perror(fpname); return; } // Simply try to dump the instance; HandleWrap hw; lcb_INSTANCE *instance; createConnection(hw, &instance); std::vector< std::string > keys; genDistKeys(LCBT_VBCONFIG(instance), keys); for (size_t ii = 0; ii < keys.size(); ii++) { storeKey(instance, keys[ii], keys[ii]); } lcb_dump(instance, fp, LCB_DUMP_ALL); fclose(fp); } TEST_F(MockUnitTest, testRefreshConfig) { SKIP_UNLESS_MOCK(); HandleWrap hw; lcb_INSTANCE *instance; createConnection(hw, &instance); lcb_refresh_config(instance); lcb_wait3(instance, LCB_WAIT_NOCHECK); } extern "C" { static void tickOpCb(lcb_INSTANCE *, int, const lcb_RESPBASE *rb) { int *p = (int *)rb->cookie; *p -= 1; EXPECT_EQ(LCB_SUCCESS, rb->rc); } } TEST_F(MockUnitTest, testTickLoop) { HandleWrap hw; lcb_INSTANCE *instance; lcb_STATUS err; createConnection(hw, &instance); const char *key = "tickKey"; const char *value = "tickValue"; lcb_install_callback(instance, LCB_CALLBACK_STORE, tickOpCb); lcb_CMDSTORE *cmd; lcb_cmdstore_create(&cmd, LCB_STORE_UPSERT); lcb_cmdstore_key(cmd, key, strlen(key)); lcb_cmdstore_value(cmd, value, strlen(value)); err = lcb_tick_nowait(instance); if (err == LCB_CLIENT_FEATURE_UNAVAILABLE) { fprintf(stderr, "Current event loop does not support tick!"); return; } lcb_sched_enter(instance); int counter = 0; for (int ii = 0; ii < 10; ii++) { err = lcb_store(instance, &counter, cmd); ASSERT_EQ(LCB_SUCCESS, err); counter++; } lcb_cmdstore_destroy(cmd); lcb_sched_leave(instance); while (counter) { lcb_tick_nowait(instance); } } TEST_F(MockUnitTest, testEmptyCtx) { HandleWrap hw; lcb_INSTANCE *instance; lcb_STATUS err = LCB_SUCCESS; createConnection(hw, &instance); lcb_MULTICMD_CTX *mctx; lcb_durability_opts_t duropts = {0}; duropts.v.v0.persist_to = 1; mctx = lcb_endure3_ctxnew(instance, &duropts, &err); ASSERT_EQ(LCB_SUCCESS, err); ASSERT_FALSE(mctx == NULL); err = mctx->done(mctx, NULL); ASSERT_NE(LCB_SUCCESS, err); mctx = lcb_observe3_ctxnew(instance); ASSERT_FALSE(mctx == NULL); err = mctx->done(mctx, NULL); ASSERT_NE(LCB_SUCCESS, err); } TEST_F(MockUnitTest, testMultiCreds) { SKIP_IF_CLUSTER_VERSION_IS_HIGHER_THAN(MockEnvironment::VERSION_50); using lcb::Authenticator; HandleWrap hw; lcb_INSTANCE *instance; createConnection(hw, &instance); lcb_BUCKETCRED cred; cred[0] = "protected"; cred[1] = "secret"; lcb_STATUS rc = lcb_cntl(instance, LCB_CNTL_SET, LCB_CNTL_BUCKET_CRED, cred); ASSERT_EQ(LCB_SUCCESS, rc); Authenticator &auth = *instance->settings->auth; lcb::Authenticator::Map::const_iterator res = auth.buckets().find("protected"); ASSERT_NE(auth.buckets().end(), res); ASSERT_EQ("secret", res->second); } extern "C" { static void appendE2BIGcb(lcb_INSTANCE *, int, const lcb_RESPBASE *rb) { lcb_STATUS *e = (lcb_STATUS *)rb->cookie; *e = rb->rc; } } TEST_F(MockUnitTest, testAppendE2BIG) { HandleWrap hw; lcb_INSTANCE *instance; createConnection(hw, &instance); lcb_install_callback(instance, LCB_CALLBACK_STORE, appendE2BIGcb); lcb_STATUS err, res; const char *key = "key"; size_t nkey = strlen(key); size_t nvalue1 = 20 * 1024 * 1024; void *value1 = calloc(nvalue1, sizeof(char)); lcb_CMDSTORE *scmd; lcb_cmdstore_create(&scmd, LCB_STORE_UPSERT); lcb_cmdstore_key(scmd, key, nkey); lcb_cmdstore_value(scmd, (const char *)value1, nvalue1); err = lcb_store(instance, &res, scmd); lcb_cmdstore_destroy(scmd); lcb_wait(instance); ASSERT_EQ(LCB_SUCCESS, res); free(value1); size_t nvalue2 = 1 * 1024 * 1024; void *value2 = calloc(nvalue2, sizeof(char)); lcb_CMDSTORE *acmd; lcb_cmdstore_create(&acmd, LCB_STORE_APPEND); lcb_cmdstore_key(acmd, key, nkey); lcb_cmdstore_value(acmd, (const char *)value2, nvalue2); err = lcb_store(instance, &res, acmd); lcb_cmdstore_destroy(acmd); lcb_wait(instance); ASSERT_EQ(LCB_E2BIG, res); free(value2); } extern "C" { static void existsCb(lcb_INSTANCE *, int, const lcb_RESPEXISTS *rb) { int *e; lcb_respexists_cookie(rb, (void **)&e); *e = lcb_respexists_is_found(rb); } } TEST_F(MockUnitTest, testExists) { HandleWrap hw; lcb_INSTANCE *instance; createConnection(hw, &instance); lcb_install_callback(instance, LCB_CALLBACK_EXISTS, (lcb_RESPCALLBACK)existsCb); std::stringstream ss; ss << "testExistsKey" << time(NULL); std::string key = ss.str(); lcb_STATUS err; lcb_CMDEXISTS *cmd; int res; lcb_cmdexists_create(&cmd); lcb_cmdexists_key(cmd, key.data(), key.size()); res = 0xff; err = lcb_exists(instance, &res, cmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_cmdexists_destroy(cmd); lcb_wait(instance); ASSERT_EQ(0, res); storeKey(instance, key, "value"); lcb_cmdexists_create(&cmd); lcb_cmdexists_key(cmd, key.data(), key.size()); res = 0; err = lcb_exists(instance, &res, cmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_cmdexists_destroy(cmd); lcb_wait(instance); ASSERT_EQ(1, res); }
[ "michael@nitschinger.at" ]
michael@nitschinger.at
4b0264b3498b0b80ee72a7716979b47505cf382c
bcf53f2d60ffe051c2fd437e1a33611927e1a23f
/worldeditor/src/controllers/objectctrlpipeline.cpp
5ae480a65421f00a771b88de9800b56234ffb464
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
xzmagic/thunder
d81cfc23808fe0cd7ad0bcb8ad8ec30130c5d6ae
b3eeb87503fec12b7c76f79aa11dbb3dca5e6a12
refs/heads/master
2020-05-15T06:26:10.619608
2019-04-18T09:24:34
2019-04-18T09:53:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include "objectctrlpipeline.h" #include "rendertexture.h" #include "commandbuffer.h" #define SELECT_MAP "selectMap" #define DEPTH_MAP "depthMap" ObjectCtrlPipeline::ObjectCtrlPipeline() : Pipeline() { RenderTexture *select = Engine::objectCreate<RenderTexture>(); select->setTarget(Texture::RGBA8); select->apply(); m_Targets[SELECT_MAP] = select; m_Buffer->setGlobalTexture(SELECT_MAP, select); } void ObjectCtrlPipeline::draw(Scene *scene, Camera &camera) { // Retrive object id m_Buffer->setRenderTarget({m_Targets[SELECT_MAP]}, m_Targets[DEPTH_MAP]); m_Buffer->clearRenderTarget(true, Vector4(0.0)); m_Buffer->setViewport(0, 0, m_Screen.x, m_Screen.y); cameraReset(camera); drawComponents(ICommandBuffer::RAYCAST, m_Components); Pipeline::draw(scene, camera); }
[ "eprikazchikov@mail.ru" ]
eprikazchikov@mail.ru
e9d5231dded5ca2b96a4a76684d6de425381f9fb
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/generator/integration_tests/golden/v1/internal/golden_kitchen_sink_stub.cc
3d2f0a475301f6f2479e4eec8cf3a863f2aa7172
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
9,022
cc
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: generator/integration_tests/test.proto #include "generator/integration_tests/golden/v1/internal/golden_kitchen_sink_stub.h" #include "google/cloud/grpc_error_delegate.h" #include "google/cloud/internal/async_read_write_stream_impl.h" #include "google/cloud/internal/async_streaming_read_rpc_impl.h" #include "google/cloud/internal/async_streaming_write_rpc_impl.h" #include "google/cloud/internal/streaming_write_rpc_impl.h" #include "google/cloud/status_or.h" #include <generator/integration_tests/test.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace golden_v1_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN GoldenKitchenSinkStub::~GoldenKitchenSinkStub() = default; StatusOr<google::test::admin::database::v1::GenerateAccessTokenResponse> DefaultGoldenKitchenSinkStub::GenerateAccessToken( grpc::ClientContext& client_context, google::test::admin::database::v1::GenerateAccessTokenRequest const& request) { google::test::admin::database::v1::GenerateAccessTokenResponse response; auto status = grpc_stub_->GenerateAccessToken(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::test::admin::database::v1::GenerateIdTokenResponse> DefaultGoldenKitchenSinkStub::GenerateIdToken( grpc::ClientContext& client_context, google::test::admin::database::v1::GenerateIdTokenRequest const& request) { google::test::admin::database::v1::GenerateIdTokenResponse response; auto status = grpc_stub_->GenerateIdToken(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::test::admin::database::v1::WriteLogEntriesResponse> DefaultGoldenKitchenSinkStub::WriteLogEntries( grpc::ClientContext& client_context, google::test::admin::database::v1::WriteLogEntriesRequest const& request) { google::test::admin::database::v1::WriteLogEntriesResponse response; auto status = grpc_stub_->WriteLogEntries(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::test::admin::database::v1::ListLogsResponse> DefaultGoldenKitchenSinkStub::ListLogs( grpc::ClientContext& client_context, google::test::admin::database::v1::ListLogsRequest const& request) { google::test::admin::database::v1::ListLogsResponse response; auto status = grpc_stub_->ListLogs(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } StatusOr<google::test::admin::database::v1::ListServiceAccountKeysResponse> DefaultGoldenKitchenSinkStub::ListServiceAccountKeys( grpc::ClientContext& client_context, google::test::admin::database::v1::ListServiceAccountKeysRequest const& request) { google::test::admin::database::v1::ListServiceAccountKeysResponse response; auto status = grpc_stub_->ListServiceAccountKeys(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return response; } Status DefaultGoldenKitchenSinkStub::DoNothing( grpc::ClientContext& client_context, google::protobuf::Empty const& request) { google::protobuf::Empty response; auto status = grpc_stub_->DoNothing(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } Status DefaultGoldenKitchenSinkStub::Deprecated2( grpc::ClientContext& client_context, google::test::admin::database::v1::GenerateAccessTokenRequest const& request) { google::protobuf::Empty response; auto status = grpc_stub_->Deprecated2(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } std::unique_ptr<google::cloud::internal::StreamingReadRpc<google::test::admin::database::v1::Response>> DefaultGoldenKitchenSinkStub::StreamingRead( std::shared_ptr<grpc::ClientContext> client_context, google::test::admin::database::v1::Request const& request) { auto stream = grpc_stub_->StreamingRead(client_context.get(), request); return std::make_unique<google::cloud::internal::StreamingReadRpcImpl< google::test::admin::database::v1::Response>>( std::move(client_context), std::move(stream)); } std::unique_ptr<::google::cloud::internal::StreamingWriteRpc< google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>> DefaultGoldenKitchenSinkStub::StreamingWrite( std::shared_ptr<grpc::ClientContext> context) { auto response = std::make_unique<google::test::admin::database::v1::Response>(); auto stream = grpc_stub_->StreamingWrite(context.get(), response.get()); return std::make_unique<::google::cloud::internal::StreamingWriteRpcImpl< google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>>( std::move(context), std::move(response), std::move(stream)); } std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc< google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>> DefaultGoldenKitchenSinkStub::AsyncStreamingReadWrite( google::cloud::CompletionQueue const& cq, std::shared_ptr<grpc::ClientContext> context) { return google::cloud::internal::MakeStreamingReadWriteRpc<google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>( cq, std::move(context), [this](grpc::ClientContext* context, grpc::CompletionQueue* cq) { return grpc_stub_->PrepareAsyncStreamingReadWrite(context, cq); }); } Status DefaultGoldenKitchenSinkStub::ExplicitRouting1( grpc::ClientContext& client_context, google::test::admin::database::v1::ExplicitRoutingRequest const& request) { google::protobuf::Empty response; auto status = grpc_stub_->ExplicitRouting1(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } Status DefaultGoldenKitchenSinkStub::ExplicitRouting2( grpc::ClientContext& client_context, google::test::admin::database::v1::ExplicitRoutingRequest const& request) { google::protobuf::Empty response; auto status = grpc_stub_->ExplicitRouting2(&client_context, request, &response); if (!status.ok()) { return google::cloud::MakeStatusFromRpcError(status); } return google::cloud::Status(); } std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc< google::test::admin::database::v1::Response>> DefaultGoldenKitchenSinkStub::AsyncStreamingRead( google::cloud::CompletionQueue const& cq, std::shared_ptr<grpc::ClientContext> context, google::test::admin::database::v1::Request const& request) { return google::cloud::internal::MakeStreamingReadRpc<google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>( cq, std::move(context), request, [this](grpc::ClientContext* context, google::test::admin::database::v1::Request const& request, grpc::CompletionQueue* cq) { return grpc_stub_->PrepareAsyncStreamingRead(context, request, cq); }); } std::unique_ptr<::google::cloud::internal::AsyncStreamingWriteRpc< google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>> DefaultGoldenKitchenSinkStub::AsyncStreamingWrite( google::cloud::CompletionQueue const& cq, std::shared_ptr<grpc::ClientContext> context) { return google::cloud::internal::MakeStreamingWriteRpc<google::test::admin::database::v1::Request, google::test::admin::database::v1::Response>( cq, std::move(context), [this](grpc::ClientContext* context, google::test::admin::database::v1::Response* response, grpc::CompletionQueue* cq) { return grpc_stub_->PrepareAsyncStreamingWrite(context, response, cq); }); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace golden_v1_internal } // namespace cloud } // namespace google
[ "noreply@github.com" ]
noreply@github.com
5558520a6f43842c72086c2ca867c855e489996c
5e325c062e4147971dc85cf09095b0cb5905d100
/hash_table.h
886e12b6d7b3e7154651067a5af691caaa9a4ca1
[]
no_license
foobar/algc
cd581e8a1fd0996759acd64da61d2e806df594dd
52d9183406ee8d17d794dfd7dcbf7ef6114769ec
refs/heads/master
2020-03-22T19:30:25.848675
2018-04-12T13:11:15
2018-04-12T13:11:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,575
h
#pragma once #include <cstdint> #include <libpmemobj++/persistent_ptr.hpp> #include "misc/log.h" constexpr uint64_t HashTableMaxKeyLen = 40; constexpr uint64_t HashTableMaxItemsExp = 20; // 1Mi items, 64MiB in total constexpr uint64_t HashTableMaxItems = 1 << HashTableMaxItemsExp; // constexpr uint64_t FNV_prime = 14695981039346656037U; #pragma pack(push, 1) // Totally 64 bytes struct HashTableItem { char key[HashTableMaxKeyLen]; // 40 bytes int64_t nextKeyOffset; // 8 bytes PMEMoid oid; // 16 bytes }; #pragma pack(pop) struct HashTable { int64_t nItems; int64_t firstOffset; int64_t lastOffset; int64_t loadFactor; HashTableItem items[HashTableMaxItems]; struct Iterator { Iterator operator++() { offset = hashTable->items[offset].nextKeyOffset; first = false; } bool operator!=(const Iterator &rhs) { return !(this->hashTable == rhs.hashTable && this->offset == rhs.offset && this->first == rhs.first); } HashTableItem &operator*() { return this->hashTable->items[this->offset]; } HashTable *hashTable; int64_t offset; bool first; }; Iterator begin() { return Iterator({this, firstOffset, (nItems > 0)}); } Iterator end() { return Iterator({this, firstOffset, false}); } static std::hash<std::string> h; static uint64_t hash(const std::string &key) { uint64_t ret = 0; ret = h(key); return ret % HashTableMaxItems; } /** * If found, it returns the item. * If not found, it returns the item it should be placed in. * @param key * @param found * @return */ HashTableItem &getItem(const std::string &key, bool &found, int64_t &nTried) { if (key.length() >= HashTableMaxKeyLen || key.length() == 0) { AlLogger::Logger::getStdErrLogger().e() << "HashTable::getItem(), empty key or key too long '" << key << "'\n"; abort(); } auto offset = hash(key); // not empty string auto originOffset = offset; nTried = 0; do { nTried++; if (this->items[offset].key[0] == 0) { found = false; return this->items[offset]; } if (strncmp(key.c_str(), this->items[offset].key, HashTableMaxKeyLen) == 0) { found = true; return this->items[offset]; } offset++; if (offset >= HashTableMaxItems) { offset = 0; } } while (offset != originOffset); } bool getKey(const std::string &key, PMEMoid &oid) { bool found; int64_t _; oid = getItem(key, found, _).oid; return found; } bool hasKey(const std::string &key) { bool found; int64_t _; getItem(key, found, _); return found; } bool putKey(const std::string &key, const PMEMoid &oid) { bool found; int64_t nTried; auto &item = getItem(key, found, nTried); // Override value if found if (found) { item.oid = oid; return true; } // hashTable[key] = value strncpy(item.key, key.c_str(), HashTableMaxKeyLen); item.oid = oid; // append new item to the list int64_t offset = ((uint64_t)&item - (uint64_t)this) / sizeof(HashTableItem); if (this->nItems == 0) { this->firstOffset = offset; this->lastOffset = offset; } this->items[this->lastOffset].nextKeyOffset = offset; this->lastOffset = offset; item.nextKeyOffset = this->firstOffset; // Update statistics this->nItems++; if (nTried > this->loadFactor) { this->loadFactor = nTried; } return true; } };
[ "ice_b0und@hotmail.com" ]
ice_b0und@hotmail.com
1e46e4ae0c09d7db2017b11241a86806add744fb
00a0635576429982bd125f96108e0f74253d846f
/src/utils.cc
8574a52895db4d1f01f9a382ad9d2d79516890a7
[ "MIT", "BSD-3-Clause" ]
permissive
cooboyno111/lua-leveldb
00a8a696f5b394922e06abfc09e98d9d7aa072dd
376491685aac413ff28b4e46e22f4fe28b2a1ca3
refs/heads/master
2020-03-19T03:03:49.800050
2018-06-04T09:42:11
2018-06-04T09:42:11
135,690,735
1
0
null
2018-06-01T08:33:06
2018-06-01T08:33:06
null
UTF-8
C++
false
false
2,970
cc
#include "utils.hpp" using namespace std; using namespace leveldb; /** * Converts a Lua parameter into a LevelDB's slice. * Every data stored from Lua is stored with this format. * This functions manage type conversion between Lua's * types and the LevelDB's Slice. */ Slice lua_to_slice(lua_State *L, int i) { // Note: // http://leveldb.org/ says: // "Arbitrary byte arrays // Both keys and values are treated as simple arrays of bytes" const char *data = luaL_checkstring(L, i); return Slice(data, strlen(data)); } /** * Converts a LevelDB's slice into a Lua value. * This the inverse operation of lua_to_slice. * It's used with the get method, the iterator * uses another function for conversion to Lua. */ int string_to_lua(lua_State *L, string value) { // Note: // http://leveldb.org/ says: // "Arbitrary byte arrays // Both keys and values are treated as simple arrays of bytes" lua_pushlstring(L, value.c_str(), value.length()); return 1; } /** * Stringify a boolean */ string bool_tostring(int boolean) { return boolean == 1 ? "true" : "false"; } /** * Stringify a pointer */ string pointer_tostring(void *p) { ostringstream oss (ostringstream::out); if (p != NULL) oss << &p; else oss << "NULL"; return oss.str().c_str(); } /** * Stringify a filter */ string filter_tostring(const FilterPolicy *fp) { return fp == 0 ? "NULL" : fp->Name(); } /** * Check for an Options type. */ Options *check_options(lua_State *L, int index) { Options *opt; luaL_checktype(L, index, LUA_TUSERDATA); // UD-type: complex metatable @ luaopen_leveldb() opt = (Options*)luaL_checkudata(L, index, LVLDB_MT_OPT); luaL_argcheck(L, opt != NULL, index, "'options' expected"); return opt; } /** * Check for a ReadOptions type. */ ReadOptions *check_read_options(lua_State *L, int index) { luaL_checktype(L, index, LUA_TUSERDATA); // UD-type: complex metatable @ luaopen_leveldb() void *ud = luaL_checkudata(L, index, LVLDB_MT_ROPT); luaL_argcheck(L, ud != NULL, index, "'writeOptions' expected"); return (ReadOptions *) ud; } /** * Check for a WriteOptions type. */ WriteOptions *check_write_options(lua_State *L, int index) { luaL_checktype(L, index, LUA_TUSERDATA); // UD-type: complex metatable @ luaopen_leveldb() void *ud = luaL_checkudata(L, index, LVLDB_MT_WOPT); luaL_argcheck(L, ud != NULL, index, "'readOptions' expected"); return (WriteOptions *) ud; } /** * Check for a WriteBatch type. */ WriteBatch *check_writebatch(lua_State *L, int index) { luaL_checktype(L, index, LUA_TUSERDATA); // UD-type: light meta @ lvldb_batch() // LuaJIT doesn't support luaL_checkudata on light userdata // void *ud = luaL_checkudata(L, 1, LVLDB_MT_BATCH); WriteBatch *ud = (WriteBatch*) lua_touserdata(L, 1); luaL_argcheck(L, ud != NULL, index, "'batch' expected"); luaL_argcheck(L, lua_islightuserdata(L, index), index, "'iterator' expected"); return ud; }
[ "2620287+marcopompili@users.noreply.github.com" ]
2620287+marcopompili@users.noreply.github.com
26c6587fa82da58f2639c58f51a143cae195d6f0
3abea59bab16016fc5dcbbe9ebb32999f74112a5
/SDK/Prisoner_Head_functions.cpp
c75365033c6eeabb10a54ba72c3b0971469703ab
[]
no_license
11-BANG-BANG/SCUM-SDK
4de6bd24acfb6a5818eed2841ea044f4bbac1493
38c28ca609d42a7ed084d22ead19f8dc54b1c7be
refs/heads/main
2023-03-22T23:27:46.609110
2021-03-18T13:11:53
2021-03-18T13:11:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
532
cpp
// Name: S, Version: N #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void APrisoner_Head_C::AfterRead() { AEquipmentItem::AfterRead(); } void APrisoner_Head_C::BeforeDelete() { AEquipmentItem::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "39485681+AlexzDK@users.noreply.github.com" ]
39485681+AlexzDK@users.noreply.github.com
87982def7742149436e23e8970cbee4023ff9911
7ccaf6d66baf345b4f001847414b6e4c056242b6
/src/filter2/vtkPCLFilter2.cxx
1e1a03f2f188bb0f4f932aa27c68eacf3c919d86
[ "Apache-2.0" ]
permissive
dys564843131/ParaView-PCLPlugin
037525e133d1390b559dda13c14c8534fc7662e8
a6c13164bfe46796647ea3a7b4433a28d61f0bbc
refs/heads/master
2020-09-28T10:49:39.160619
2019-10-10T14:15:56
2019-10-10T14:15:56
226,762,762
1
0
Apache-2.0
2019-12-09T01:53:24
2019-12-09T01:53:24
null
UTF-8
C++
false
false
2,475
cxx
//============================================================================== // // Copyright 2012-2019 Kitware, 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 "vtkPCLFilter2.h" #include "vtkPolyData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include <pcl/point_types.h> //------------------------------------------------------------------------------ vtkPCLFilter2::vtkPCLFilter2() { this->SetNumberOfInputPorts(2); this->SetNumberOfOutputPorts(1); } //------------------------------------------------------------------------------ vtkPCLFilter2::~vtkPCLFilter2() { } //------------------------------------------------------------------------------ void vtkPCLFilter2::PrintSelf(ostream & os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ int vtkPCLFilter2::FillInputPortInformation( int port, vtkInformation * info ) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); } else if (this->SecondPortOptional && port == 1) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); } return 1; } //------------------------------------------------------------------------------ int vtkPCLFilter2::RequestData( vtkInformation * request, vtkInformationVector * * inputVector, vtkInformationVector * outputVector ) { // Get the polydata and pass it on to the derived classes method. vtkPolyData * inputA = vtkPolyData::GetData(inputVector[0]->GetInformationObject(0)); vtkPolyData * inputB = vtkPolyData::GetData(inputVector[1]->GetInformationObject(0)); vtkPolyData * output = vtkPolyData::GetData(outputVector->GetInformationObject(0)); return this->ApplyPCLFilter2(inputA, inputB, output); }
[ "mike.rye@kitware.com" ]
mike.rye@kitware.com
446769540fae3d19650cb1ba63bd307d71424538
fe844dd71565d9fa8e28649506b07175ead89ab8
/RAII_Samples/PipelineCache/PipelineCache.cpp
7339a914a7f6760d0ab1edee9854cb50d56978b9
[ "Apache-2.0" ]
permissive
res2k/Vulkan-Hpp
22db86c015f9549a05ff9bde4b03e0ae7455f79c
f4b679c7e7f5856d7ab7eecb5826525b5994461e
refs/heads/main
2023-03-20T01:24:50.270902
2023-03-09T09:04:33
2023-03-09T09:04:33
185,830,116
0
0
Apache-2.0
2023-03-12T19:27:09
2019-05-09T15:57:15
C++
UTF-8
C++
false
false
17,972
cpp
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // VulkanHpp Samples : PipelineCache // This sample tries to save and reuse pipeline cache data between runs. #if defined( _MSC_VER ) // no need to ignore any warnings with MSVC #elif defined( __clang__ ) # pragma clang diagnostic ignored "-Wmissing-braces" #elif defined( __GNUC__ ) #else // unknow compiler... just ignore the warnings for yourselves ;) #endif #include "../../samples/utils/geometries.hpp" #include "../../samples/utils/math.hpp" #include "../utils/shaders.hpp" #include "../utils/utils.hpp" #include "SPIRV/GlslangToSpv.h" #include <fstream> #include <iomanip> #include <thread> // For timestamp code (getMilliseconds) #ifdef WIN32 # include <Windows.h> #else # include <sys/time.h> #endif typedef unsigned long long timestamp_t; timestamp_t getMilliseconds() { #ifdef WIN32 LARGE_INTEGER frequency; BOOL useQPC = QueryPerformanceFrequency( &frequency ); if ( useQPC ) { LARGE_INTEGER now; QueryPerformanceCounter( &now ); return ( 1000LL * now.QuadPart ) / frequency.QuadPart; } else { return GetTickCount(); } #else struct timeval now; gettimeofday( &now, NULL ); return ( now.tv_usec / 1000 ) + (timestamp_t)now.tv_sec; #endif } static char const * AppName = "PipelineCache"; static char const * EngineName = "Vulkan.hpp"; int main( int /*argc*/, char ** /*argv*/ ) { try { vk::raii::Context context; vk::raii::Instance instance = vk::raii::su::makeInstance( context, AppName, EngineName, {}, vk::su::getInstanceExtensions() ); #if !defined( NDEBUG ) vk::raii::DebugUtilsMessengerEXT debugUtilsMessenger( instance, vk::su::makeDebugUtilsMessengerCreateInfoEXT() ); #endif vk::raii::PhysicalDevice physicalDevice = vk::raii::PhysicalDevices( instance ).front(); vk::PhysicalDeviceProperties properties = physicalDevice.getProperties(); vk::raii::su::SurfaceData surfaceData( instance, AppName, vk::Extent2D( 500, 500 ) ); std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex = vk::raii::su::findGraphicsAndPresentQueueFamilyIndex( physicalDevice, surfaceData.surface ); vk::raii::Device device = vk::raii::su::makeDevice( physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions() ); vk::raii::CommandPool commandPool = vk::raii::CommandPool( device, { vk::CommandPoolCreateFlagBits::eResetCommandBuffer, graphicsAndPresentQueueFamilyIndex.first } ); vk::raii::CommandBuffer commandBuffer = vk::raii::su::makeCommandBuffer( device, commandPool ); vk::raii::Queue graphicsQueue( device, graphicsAndPresentQueueFamilyIndex.first, 0 ); vk::raii::Queue presentQueue( device, graphicsAndPresentQueueFamilyIndex.second, 0 ); vk::raii::su::SwapChainData swapChainData( physicalDevice, device, surfaceData.surface, surfaceData.extent, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, {}, graphicsAndPresentQueueFamilyIndex.first, graphicsAndPresentQueueFamilyIndex.second ); vk::raii::su::DepthBufferData depthBufferData( physicalDevice, device, vk::Format::eD16Unorm, surfaceData.extent ); vk::raii::su::TextureData textureData( physicalDevice, device ); commandBuffer.begin( vk::CommandBufferBeginInfo() ); textureData.setImage( commandBuffer, vk::su::MonochromeImageGenerator( { 118, 185, 0 } ) ); vk::raii::su::BufferData uniformBufferData( physicalDevice, device, sizeof( glm::mat4x4 ), vk::BufferUsageFlagBits::eUniformBuffer ); glm::mat4x4 mvpcMatrix = vk::su::createModelViewProjectionClipMatrix( surfaceData.extent ); vk::raii::su::copyToDevice( uniformBufferData.deviceMemory, mvpcMatrix ); vk::raii::DescriptorSetLayout descriptorSetLayout = vk::raii::su::makeDescriptorSetLayout( device, { { vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex }, { vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment } } ); vk::raii::PipelineLayout pipelineLayout( device, { {}, *descriptorSetLayout } ); vk::Format colorFormat = vk::su::pickSurfaceFormat( physicalDevice.getSurfaceFormatsKHR( *surfaceData.surface ) ).format; vk::raii::RenderPass renderPass = vk::raii::su::makeRenderPass( device, colorFormat, depthBufferData.format ); glslang::InitializeProcess(); vk::raii::ShaderModule vertexShaderModule = vk::raii::su::makeShaderModule( device, vk::ShaderStageFlagBits::eVertex, vertexShaderText_PT_T ); vk::raii::ShaderModule fragmentShaderModule = vk::raii::su::makeShaderModule( device, vk::ShaderStageFlagBits::eFragment, fragmentShaderText_T_C ); glslang::FinalizeProcess(); std::vector<vk::raii::Framebuffer> framebuffers = vk::raii::su::makeFramebuffers( device, renderPass, swapChainData.imageViews, &depthBufferData.imageView, surfaceData.extent ); vk::raii::su::BufferData vertexBufferData( physicalDevice, device, sizeof( texturedCubeData ), vk::BufferUsageFlagBits::eVertexBuffer ); vk::raii::su::copyToDevice( vertexBufferData.deviceMemory, texturedCubeData, sizeof( texturedCubeData ) / sizeof( texturedCubeData[0] ) ); vk::raii::DescriptorPool descriptorPool = vk::raii::su::makeDescriptorPool( device, { { vk::DescriptorType::eUniformBuffer, 1 }, { vk::DescriptorType::eCombinedImageSampler, 1 } } ); vk::raii::DescriptorSet descriptorSet = std::move( vk::raii::DescriptorSets( device, { *descriptorPool, *descriptorSetLayout } ).front() ); vk::raii::su::updateDescriptorSets( device, descriptorSet, { { vk::DescriptorType::eUniformBuffer, uniformBufferData.buffer, VK_WHOLE_SIZE, nullptr } }, { textureData } ); /* VULKAN_KEY_START */ // Check disk for existing cache data size_t startCacheSize = 0; char * startCacheData = nullptr; std::string cacheFileName = "pipeline_cache_data.bin"; std::ifstream readCacheStream( cacheFileName, std::ios_base::in | std::ios_base::binary ); if ( readCacheStream.good() ) { // Determine cache size readCacheStream.seekg( 0, readCacheStream.end ); startCacheSize = static_cast<size_t>( readCacheStream.tellg() ); readCacheStream.seekg( 0, readCacheStream.beg ); // Allocate memory to hold the initial cache data startCacheData = (char *)std::malloc( startCacheSize ); // Read the data into our buffer readCacheStream.read( startCacheData, startCacheSize ); // Clean up and print results readCacheStream.close(); std::cout << " Pipeline cache HIT!\n"; std::cout << " cacheData loaded from " << cacheFileName << "\n"; } else { // No cache found on disk std::cout << " Pipeline cache miss!\n"; } if ( startCacheData != nullptr ) { // Check for cache validity // // TODO: Update this as the spec evolves. The fields are not defined by the header. // // The code below supports SDK 0.10 Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 a device ID equal to VkPhysicalDeviceProperties::DeviceId written // as a stream of bytes, with the least significant byte first // // 4 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // // // The code must be updated for latest Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 length in bytes of the entire pipeline cache header written as a // stream of bytes, with the least significant byte first // 4 4 a VkPipelineCacheHeaderVersion value written as a stream of bytes, // with the least significant byte first // 8 4 a vendor ID equal to VkPhysicalDeviceProperties::vendorID written // as a stream of bytes, with the least significant byte first // 12 4 a device ID equal to VkPhysicalDeviceProperties::deviceID written // as a stream of bytes, with the least significant byte first // 16 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID uint32_t headerLength = 0; uint32_t cacheHeaderVersion = 0; uint32_t vendorID = 0; uint32_t deviceID = 0; uint8_t pipelineCacheUUID[VK_UUID_SIZE] = {}; memcpy( &headerLength, (uint8_t *)startCacheData + 0, 4 ); memcpy( &cacheHeaderVersion, (uint8_t *)startCacheData + 4, 4 ); memcpy( &vendorID, (uint8_t *)startCacheData + 8, 4 ); memcpy( &deviceID, (uint8_t *)startCacheData + 12, 4 ); memcpy( pipelineCacheUUID, (uint8_t *)startCacheData + 16, VK_UUID_SIZE ); // Check each field and report bad values before freeing existing cache bool badCache = false; if ( headerLength <= 0 ) { badCache = true; std::cout << " Bad header length in " << cacheFileName << ".\n"; std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << headerLength << "\n"; } if ( cacheHeaderVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE ) { badCache = true; std::cout << " Unsupported cache header version in " << cacheFileName << ".\n"; std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << cacheHeaderVersion << "\n"; } if ( vendorID != properties.vendorID ) { badCache = true; std::cout << " Vender ID mismatch in " << cacheFileName << ".\n"; std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << vendorID << "\n"; std::cout << " Driver expects: " << std::hex << std::setw( 8 ) << properties.vendorID << "\n"; } if ( deviceID != properties.deviceID ) { badCache = true; std::cout << " Device ID mismatch in " << cacheFileName << ".\n"; std::cout << " Cache contains: " << std::hex << std::setw( 8 ) << deviceID << "\n"; std::cout << " Driver expects: " << std::hex << std::setw( 8 ) << properties.deviceID << "\n"; } if ( memcmp( pipelineCacheUUID, properties.pipelineCacheUUID, sizeof( pipelineCacheUUID ) ) != 0 ) { badCache = true; std::cout << " UUID mismatch in " << cacheFileName << ".\n"; std::cout << " Cache contains: " << vk::su::UUID( pipelineCacheUUID ) << "\n"; std::cout << " Driver expects: " << vk::su::UUID( properties.pipelineCacheUUID ) << "\n"; } if ( badCache ) { // Don't submit initial cache data if any version info is incorrect free( startCacheData ); startCacheSize = 0; startCacheData = nullptr; // And clear out the old cache file for use in next run std::cout << " Deleting cache entry " << cacheFileName << " to repopulate.\n"; if ( remove( cacheFileName.c_str() ) != 0 ) { std::cerr << "Reading error"; exit( EXIT_FAILURE ); } } } // Feed the initial cache data into cache creation vk::PipelineCacheCreateInfo pipelineCacheCreateInfo( {}, startCacheSize, startCacheData ); vk::raii::PipelineCache pipelineCache( device, pipelineCacheCreateInfo ); // Free our initialData now that pipeline cache has been created free( startCacheData ); startCacheData = NULL; // Time (roughly) taken to create the graphics pipeline timestamp_t start = getMilliseconds(); vk::raii::Pipeline graphicsPipeline = vk::raii::su::makeGraphicsPipeline( device, pipelineCache, vertexShaderModule, nullptr, fragmentShaderModule, nullptr, sizeof( texturedCubeData[0] ), { { vk::Format::eR32G32B32A32Sfloat, 0 }, { vk::Format::eR32G32Sfloat, 16 } }, vk::FrontFace::eClockwise, true, pipelineLayout, renderPass ); timestamp_t elapsed = getMilliseconds() - start; std::cout << " vkCreateGraphicsPipeline time: " << (double)elapsed << " ms\n"; vk::raii::Semaphore imageAcquiredSemaphore( device, vk::SemaphoreCreateInfo() ); // Get the index of the next available swapchain image: vk::Result result; uint32_t imageIndex; std::tie( result, imageIndex ) = swapChainData.swapChain.acquireNextImage( vk::su::FenceTimeout, *imageAcquiredSemaphore ); assert( result == vk::Result::eSuccess ); assert( imageIndex < swapChainData.images.size() ); std::array<vk::ClearValue, 2> clearValues; clearValues[0].color = vk::ClearColorValue( 0.2f, 0.2f, 0.2f, 0.2f ); clearValues[1].depthStencil = vk::ClearDepthStencilValue( 1.0f, 0 ); commandBuffer.beginRenderPass( vk::RenderPassBeginInfo( *renderPass, *framebuffers[imageIndex], vk::Rect2D( vk::Offset2D(), surfaceData.extent ), clearValues ), vk::SubpassContents::eInline ); commandBuffer.bindPipeline( vk::PipelineBindPoint::eGraphics, *graphicsPipeline ); commandBuffer.bindDescriptorSets( vk::PipelineBindPoint::eGraphics, *pipelineLayout, 0, { *descriptorSet }, {} ); commandBuffer.bindVertexBuffers( 0, { *vertexBufferData.buffer }, { 0 } ); commandBuffer.setViewport( 0, vk::Viewport( 0.0f, 0.0f, static_cast<float>( surfaceData.extent.width ), static_cast<float>( surfaceData.extent.height ), 0.0f, 1.0f ) ); commandBuffer.setScissor( 0, vk::Rect2D( vk::Offset2D( 0, 0 ), surfaceData.extent ) ); commandBuffer.draw( 12 * 3, 1, 0, 0 ); commandBuffer.endRenderPass(); commandBuffer.end(); vk::raii::Fence drawFence( device, vk::FenceCreateInfo() ); vk::PipelineStageFlags waitDestinationStageMask( vk::PipelineStageFlagBits::eColorAttachmentOutput ); vk::SubmitInfo submitInfo( *imageAcquiredSemaphore, waitDestinationStageMask, *commandBuffer ); graphicsQueue.submit( submitInfo, *drawFence ); while ( vk::Result::eTimeout == device.waitForFences( { *drawFence }, VK_TRUE, vk::su::FenceTimeout ) ) ; vk::PresentInfoKHR presentInfoKHR( nullptr, *swapChainData.swapChain, imageIndex ); result = presentQueue.presentKHR( presentInfoKHR ); switch ( result ) { case vk::Result::eSuccess: break; case vk::Result::eSuboptimalKHR: std::cout << "vk::Queue::presentKHR returned vk::Result::eSuboptimalKHR !\n"; break; default: assert( false ); // an unexpected result is returned ! } std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) ); // Store away the cache that we've populated. This could conceivably happen // earlier, depends on when the pipeline cache stops being populated // internally. std::vector<uint8_t> endCacheData = pipelineCache.getData(); // Write the file to disk, overwriting whatever was there std::ofstream writeCacheStream( cacheFileName, std::ios_base::out | std::ios_base::binary ); if ( writeCacheStream.good() ) { writeCacheStream.write( reinterpret_cast<char const *>( endCacheData.data() ), endCacheData.size() ); writeCacheStream.close(); std::cout << " cacheData written to " << cacheFileName << "\n"; } else { // Something bad happened std::cout << " Unable to write cache data to disk!\n"; } /* VULKAN_KEY_END */ } catch ( vk::SystemError & err ) { std::cout << "vk::SystemError: " << err.what() << std::endl; exit( -1 ); } catch ( std::exception & err ) { std::cout << "std::exception: " << err.what() << std::endl; exit( -1 ); } catch ( ... ) { std::cout << "unknown error\n"; exit( -1 ); } return 0; }
[ "asuessenbach@nvidia.com" ]
asuessenbach@nvidia.com
c57a956c23e3ad814627fab3479a989114c4dc82
87f6f18984f729ecc59ed320bfaf93790719a1f7
/src/hardware/pin_change_interrupt.hpp
198da3ed388ecdcd0464bf86dddebeb30069a942
[]
no_license
k-ishigaki/motordriver2018
ca2dddfeacf98315873ab5f7b9f43f813a635403
160e29f3f8c46af2afe77a9e4fb963936f26eec9
refs/heads/master
2020-03-27T08:08:27.617422
2019-11-07T12:47:41
2019-11-07T12:47:41
146,223,739
0
0
null
null
null
null
UTF-8
C++
false
false
723
hpp
#ifndef HARDWARE_PIN_CHANGE_INTERRUPT_H #define HARDWARE_PIN_CHANGE_INTERRUPT_H #include "hardware_implementation.hpp" class PinChangeInterrupt { public: /** * Enable function on selected pins. * * To enabling interrupt, the corresponding Interrupt#enable must be also called. * * @param pin positions enabling interrupt */ virtual void enable(uint8_t) = 0; /** * Disable interrupt on selected pins. * * To disable interrupt, the corresponding Interrupt#disable must be also called. * * @param pin positions diabling interrupt */ virtual void disable(uint8_t) = 0; }; #endif
[ "k-ishigaki@frontier.hokudai.ac.jp" ]
k-ishigaki@frontier.hokudai.ac.jp
92c8abcc00ca8fbbed404f444aaa9422282b6644
48a47a3b37c4e820cecf7d8bf57c8562a2240893
/include/Eigen3/src/Geometry/OrthoMethods.h
dd523206940f4e8a38af7feb3ecbed875be4b28a
[]
no_license
crazysnowboy/MatrixExperiments
ad6a83cc5717fd2cb6dba447f4bd15ad480394cc
db52cc8756329f13bf3c9369670df64fa4368e71
refs/heads/master
2021-05-05T16:05:36.785584
2017-09-18T02:15:06
2017-09-18T02:15:06
103,210,710
0
0
null
null
null
null
UTF-8
C++
false
false
9,384
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // 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/. #ifndef EIGEN_ORTHOMETHODS_H #define EIGEN_ORTHOMETHODS_H namespace Eigen { /** \geometry_module \ingroup Geometry_Module * * \returns the cross product of \c *this and \a other * * Here is a very good explanation of cross-product: http://xkcd.com/199/ * * With complex numbers, the cross product is implemented as * \f$ (\mathbf{a}+i\mathbf{b}) \times (\mathbf{c}+i\mathbf{d}) = (\mathbf{a} \times \mathbf{c} - \mathbf{b} \times \mathbf{d}) - i(\mathbf{a} \times \mathbf{d} - \mathbf{b} \times \mathbf{c})\f$ * * \sa MatrixBase::cross3() */ template<typename Derived> template<typename OtherDerived> #ifndef EIGEN_PARSED_BY_DOXYGEN EIGEN_DEVICE_FUNC inline typename MatrixBase<Derived>::template cross_product_return_type<OtherDerived>::type #else inline typename MatrixBase<Derived>::PlainObject #endif MatrixBase<Derived>::cross(const MatrixBase<OtherDerived>& other) const { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,3) EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,3) // Note that there is no need for an expression here since the compiler // optimize such a small temporary very well (even within a complex expression) typename internal::nested_eval<Derived,2>::type lhs(derived()); typename internal::nested_eval<OtherDerived,2>::type rhs(other.derived()); return typename cross_product_return_type<OtherDerived>::type( numext::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)), numext::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)), numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0)) ); } namespace internal { template< int Arch,typename VectorLhs,typename VectorRhs, typename Scalar = typename VectorLhs::Scalar, bool Vectorizable = bool((VectorLhs::Flags&VectorRhs::Flags)&PacketAccessBit)> struct cross3_impl { EIGEN_DEVICE_FUNC static inline typename internal::plain_matrix_type<VectorLhs>::type run(const VectorLhs& lhs, const VectorRhs& rhs) { return typename internal::plain_matrix_type<VectorLhs>::type( numext::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)), numext::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)), numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0)), 0 ); } }; } /** \geometry_module \ingroup Geometry_Module * * \returns the cross product of \c *this and \a other using only the x, y, and z coefficients * * The size of \c *this and \a other must be four. This function is especially useful * when using 4D vectors instead of 3D ones to get advantage of SSE/AltiVec vectorization. * * \sa MatrixBase::cross() */ template<typename Derived> template<typename OtherDerived> EIGEN_DEVICE_FUNC inline typename MatrixBase<Derived>::PlainObject MatrixBase<Derived>::cross3(const MatrixBase<OtherDerived>& other) const { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,4) EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,4) typedef typename internal::nested_eval<Derived,2>::type DerivedNested; typedef typename internal::nested_eval<OtherDerived,2>::type OtherDerivedNested; DerivedNested lhs(derived()); OtherDerivedNested rhs(other.derived()); return internal::cross3_impl<Architecture::Target, typename internal::remove_all<DerivedNested>::type, typename internal::remove_all<OtherDerivedNested>::type>::run(lhs,rhs); } /** \geometry_module \ingroup Geometry_Module * * \returns a matrix expression of the cross product of each column or row * of the referenced expression with the \a other vector. * * The referenced matrix must have one dimension equal to 3. * The result matrix has the same dimensions than the referenced one. * * \sa MatrixBase::cross() */ template<typename ExpressionType, int Direction> template<typename OtherDerived> EIGEN_DEVICE_FUNC const typename VectorwiseOp<ExpressionType,Direction>::CrossReturnType VectorwiseOp<ExpressionType,Direction>::cross(const MatrixBase<OtherDerived>& other) const { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,3) EIGEN_STATIC_ASSERT((internal::is_same<Scalar, typename OtherDerived::Scalar>::value), YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) typename internal::nested_eval<ExpressionType,2>::type mat(_expression()); typename internal::nested_eval<OtherDerived,2>::type vec(other.derived()); CrossReturnType res(_expression().rows(),_expression().cols()); if(Direction==Vertical) { eigen_assert(CrossReturnType::RowsAtCompileTime==3 && "the matrix must have exactly 3 rows"); res.row(0) = (mat.row(1) * vec.coeff(2) - mat.row(2) * vec.coeff(1)).conjugate(); res.row(1) = (mat.row(2) * vec.coeff(0) - mat.row(0) * vec.coeff(2)).conjugate(); res.row(2) = (mat.row(0) * vec.coeff(1) - mat.row(1) * vec.coeff(0)).conjugate(); } else { eigen_assert(CrossReturnType::ColsAtCompileTime==3 && "the matrix must have exactly 3 columns"); res.col(0) = (mat.col(1) * vec.coeff(2) - mat.col(2) * vec.coeff(1)).conjugate(); res.col(1) = (mat.col(2) * vec.coeff(0) - mat.col(0) * vec.coeff(2)).conjugate(); res.col(2) = (mat.col(0) * vec.coeff(1) - mat.col(1) * vec.coeff(0)).conjugate(); } return res; } namespace internal { template<typename Derived, int Size = Derived::SizeAtCompileTime> struct unitOrthogonal_selector { typedef typename plain_matrix_type<Derived>::type VectorType; typedef typename traits<Derived>::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar,2,1> Vector2; EIGEN_DEVICE_FUNC static inline VectorType run(const Derived& src) { VectorType perp = VectorType::Zero(src.size()); Index maxi = 0; Index sndi = 0; src.cwiseAbs().maxCoeff(&maxi); if (maxi==0) { sndi = 1; } RealScalar invnm = RealScalar(1)/(Vector2() << src.coeff(sndi),src.coeff(maxi)).finished().norm(); perp.coeffRef(maxi) = -numext::conj(src.coeff(sndi)) * invnm; perp.coeffRef(sndi) = numext::conj(src.coeff(maxi)) * invnm; return perp; } }; template<typename Derived> struct unitOrthogonal_selector<Derived,3> { typedef typename plain_matrix_type<Derived>::type VectorType; typedef typename traits<Derived>::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; EIGEN_DEVICE_FUNC static inline VectorType run(const Derived& src) { VectorType perp; /* Let us compute the crossed product of *this with a vector * that is not too close to being colinear to *this. */ /* unless the x and y coords are both close to zero, we can * simply take ( -y, x, 0 ) and normalize it. */ if((!isMuchSmallerThan(src.x(), src.z())) || (!isMuchSmallerThan(src.y(), src.z()))) { RealScalar invnm = RealScalar(1)/src.template head<2>().norm(); perp.coeffRef(0) = -numext::conj(src.y())*invnm; perp.coeffRef(1) = numext::conj(src.x())*invnm; perp.coeffRef(2) = 0; } /* if both x and y are close to zero, then the vector is close * to the z-axis, so it's far from colinear to the x-axis for instance. * So we take the crossed product with (1,0,0) and normalize it. */ else { RealScalar invnm = RealScalar(1)/src.template tail<2>().norm(); perp.coeffRef(0) = 0; perp.coeffRef(1) = -numext::conj(src.z())*invnm; perp.coeffRef(2) = numext::conj(src.y())*invnm; } return perp; } }; template<typename Derived> struct unitOrthogonal_selector<Derived,2> { typedef typename plain_matrix_type<Derived>::type VectorType; EIGEN_DEVICE_FUNC static inline VectorType run(const Derived& src) { return VectorType(-numext::conj(src.y()), numext::conj(src.x())).normalized(); } }; } // end namespace internal /** \geometry_module \ingroup Geometry_Module * * \returns a unit vector which is orthogonal to \c *this * * The size of \c *this must be at least 2. If the size is exactly 2, * then the returned vector is a counter clock wise rotation of \c *this, i.e., (-y,x).normalized(). * * \sa cross() */ template<typename Derived> EIGEN_DEVICE_FUNC typename MatrixBase<Derived>::PlainObject MatrixBase<Derived>::unitOrthogonal() const { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) return internal::unitOrthogonal_selector<Derived>::run(derived()); } } // end namespace Eigen #endif // EIGEN_ORTHOMETHODS_H
[ "kailin@ulsee.com" ]
kailin@ulsee.com
01c8b3bd910f1fac615a80bae9a32d10662c727b
1a1f1d1ef040f0259ae09a9dba9a51cb1eff725a
/31.Memberinitializerlist/constructormemberinitializerlist/constructormemberinitializerlist/constructormemberinitializerlist.cpp
a7f022be1418ba165939efc39177b7dcdfd6feae
[ "MIT" ]
permissive
Arslan-Z/cplusplusCHERNO
fc949e12882424ac927ec4edde528e441a4974c8
42a19538a048d2b825e9e5581c329abc2bac5530
refs/heads/master
2023-05-26T19:08:19.977881
2021-06-07T08:21:09
2021-06-07T08:21:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include <iostream> class Entity { private: int m_score; std::string m_Name; public: //write the same order in class members are Entity(): m_score(0),m_Name("unknown") { } Entity(const std::string& name) { m_Name = name; } }; int main() { Entity e; std::cout << "Hello World!\n"; }
[ "shakshamsinha@outlook.com" ]
shakshamsinha@outlook.com
66e5ab34f8d8c8e8260061b02f82d1fa22c779a1
2d3154bdf2ebdcf23395f4f55d8f1875a2819da2
/trunk/Zigbeecomms/CommThread.cpp
c2f380b48dedbfb1e23f30cc9391b081018279af
[]
no_license
BGCX261/zigbee-serial-dll-svn-to-git
f844a0d0b52756b8b9e473f1335b0dcf184ba94a
81cb7b2a8dddd5fd3a71577f53c48dd845342895
refs/heads/master
2020-06-03T08:46:55.988441
2015-08-25T15:39:09
2015-08-25T15:39:09
41,583,564
1
0
null
null
null
null
UHC
C++
false
false
15,133
cpp
#include "stdafx.h" #include "CommThread.h" #include ".\commthread.h" #define PACKET_LOG //--- 클래스 생성자 CCommThread::CCommThread() { //--> 초기는 당연히..포트가 열리지 않은 상태여야겠죠? m_bConnected = FALSE; bGeneralDataFlag = FALSE; m_hThreadRcvTimeout = NULL; mIndex = 0; mReadcnt = 0; //memset(&TxPktBuff,0x00,sizeof(TXPKTBUFF)*100); // sflag = FALSE; } CCommThread::~CCommThread() { } BOOL CCommThread::SetreturnHandle(HWND hwnd){ hStartWnd = hwnd; if(hStartWnd == (HANDLE) -1) return FALSE; return TRUE; } // 포트 sPortName을 dwBaud 속도로 연다. // ThreadWatchComm 함수에서 포트에 무언가 읽혔을 때 MainWnd에 알리기 // 위해 WM_COMM_READ메시지를 보낼때 같이 보낼 wPortID값을 전달 받는다. BOOL CCommThread::OpenPort(CString strPortName, DWORD dwBaud, BYTE byData, BYTE byStop, BYTE byParity ) { // Local 변수. COMMTIMEOUTS timeouts; DCB dcb; DWORD dwThreadID; // overlapped structure 변수 초기화. m_osRead.Offset = 0; m_osRead.OffsetHigh = 0; //--> Read 이벤트 생성에 실패.. if ( !(m_osRead.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) ) { return FALSE; } m_osWrite.Offset = 0; m_osWrite.OffsetHigh = 0; //--> Write 이벤트 생성에 실패.. if (! (m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) { return FALSE; } //--> 포트명 저장.. m_sPortName = strPortName; //--> 실제적인...RS 232 포트 열기.. m_hComm = CreateFile( m_sPortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); //--> 포트 열기에 실해하면.. if (m_hComm == (HANDLE) -1) { //AfxMessageBox("fail Port ofen"); return FALSE; } //===== 포트 상태 설정. ===== // EV_RXCHAR event 설정...데이터가 들어오면.. 수신 이벤트가 발생하게끔.. SetCommMask( m_hComm, EV_RXCHAR); // InQueue, OutQueue 크기 설정. SetupComm( m_hComm, BUFF_SIZE, BUFF_SIZE); // 포트 비우기. PurgeComm( m_hComm, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR); // timeout 설정. timeouts.ReadIntervalTimeout = 0xFFFFFFFF; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 2*CBR_9600 / dwBaud;; timeouts.WriteTotalTimeoutConstant = 0; SetCommTimeouts( m_hComm, &timeouts); // dcb 설정.... 포트의 실제적인..제어를 담당하는 DCB 구조체값 셋팅.. dcb.DCBlength = sizeof(DCB); //--> 현재 설정된 값 중에서.. GetCommState( m_hComm, &dcb); //--> 보드레이트를 바꾸고.. dcb.BaudRate = dwBaud; //--> Data 8 Bit dcb.ByteSize = byData; //--> Noparity dcb.Parity = byParity; //--> 1 Stop Bit dcb.StopBits = byStop; //--> 포트를 재..설정값으로.. 설정해보고.. if( !SetCommState( m_hComm, &dcb) ) { return FALSE; } //Sleep(60); // 포트 감시 쓰레드 생성. m_bConnected = TRUE; ::SendMessage(hStartWnd, WM_COMM_OPEN, 1, 0); //--> 포트 감시 쓰레드 생성. m_hThreadWatchComm = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWatchComm, this, 0, &dwThreadID); //--> 쓰레드 생성에 실패하면.. if (! m_hThreadWatchComm) { //--> 열린 포트를 닫고.. ClosePort(); return FALSE; } check = FALSE; return TRUE; } // 포트를 닫는다. void CCommThread::ClosePort() { //--> 연결되지 않았음. // sflag = FALSE; m_bConnected = FALSE; ::SendMessage(hStartWnd, WM_COMM_OPEN, 0, 0); //DCB dcb; //SetCommState( m_hComm, &dcb); //--> 마스크 해제.. SetCommMask( m_hComm, 0); Sleep(60); //--> 포트 비우기. PurgeComm( m_hComm, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR); //Sleep(60); CloseHandle(m_hComm); //--> 핸들 닫기 } // 포트에 pBuff의 내용을 nToWrite만큼 쓴다. // 실제로 쓰여진 Byte수를 리턴한다. DWORD CCommThread::WriteComm(BYTE *pBuff, DWORD nToWrite) { DWORD dwWritten, dwError, dwErrorFlags; COMSTAT comstat; //--> 포트가 연결되지 않은 상태이면.. if( !m_bConnected ) { return 0; } //--> 인자로 들어온 버퍼의 내용을 nToWrite 만큼 쓰고.. 쓴 갯수를.,dwWrite 에 넘김. if( !WriteFile( m_hComm, pBuff, nToWrite, &dwWritten, &m_osWrite)) { //--> 아직 전송할 문자가 남았을 경우.. if (GetLastError() == ERROR_IO_PENDING) { // 읽을 문자가 남아 있거나 전송할 문자가 남아 있을 경우 Overapped IO의 // 특성에 따라 ERROR_IO_PENDING 에러 메시지가 전달된다. //timeouts에 정해준 시간만큼 기다려준다. while (! GetOverlappedResult( m_hComm, &m_osWrite, &dwWritten, TRUE)) { dwError = GetLastError(); if (dwError != ERROR_IO_INCOMPLETE) { ClearCommError( m_hComm, &dwErrorFlags, &comstat); break; } } } else { dwWritten = 0; ClearCommError( m_hComm, &dwErrorFlags, &comstat); } } //--> 실제 포트로 쓰여진 갯수를 리턴.. return dwWritten; } // 포트로부터 pBuff에 nToWrite만큼 읽는다. // 실제로 읽혀진 Byte수를 리턴한다. DWORD CCommThread::ReadComm(BYTE *pBuff, DWORD nToRead) { DWORD dwRead,dwError, dwErrorFlags; COMSTAT comstat; //--- system queue에 도착한 byte수만 미리 읽는다. ClearCommError( m_hComm, &dwErrorFlags, &comstat); //--> 시스템 큐에서 읽을 거리가 있으면.. dwRead = comstat.cbInQue; if(dwRead > 0) { //--> 버퍼에 일단 읽어들이는데.. 만일..읽어들인값이 없다면.. if( !ReadFile( m_hComm, pBuff, nToRead, &dwRead, &m_osRead) ) { //--> 읽을 거리가 남았으면.. if (GetLastError() == ERROR_IO_PENDING) { //--------- timeouts에 정해준 시간만큼 기다려준다. while (! GetOverlappedResult( m_hComm, &m_osRead, &dwRead, TRUE)) { dwError = GetLastError(); if (dwError != ERROR_IO_INCOMPLETE) { ClearCommError( m_hComm, &dwErrorFlags, &comstat); break; } } } else { dwRead = 0; ClearCommError( m_hComm, &dwErrorFlags, &comstat); } } } //--> 실제 읽어들인 갯수를 리턴. return dwRead; } // 쓰기 데이터 10초 대기 쓰레드 생성함수 BOOL CCommThread::createtimeoutThread(){ //--> 포트 감시 쓰레드 생성. DWORD dwThreadID; BOOL bResult = FALSE; m_hThreadRcvTimeout = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)ThreadRcvTimeout, this, 0, &dwThreadID); if(m_hThreadRcvTimeout) bResult = TRUE; return bResult; } // 쓰기 데이터 10초 대기 쓰레드 DWORD ThreadRcvTimeout(CCommThread* pComm){ int cnt = 0; if(pComm->mCommand == WRITEDATA_CMD) { while(cnt < 10){ Sleep(1000); cnt++; } //10초가 지나서 종료가 되면 fail ::SendMessage(pComm->getHandle(), WM_COMM_READ, pComm->mCommand, FALSE); pComm->m_hThreadRcvTimeout = NULL; } else { while(cnt < 2){ Sleep(1000); cnt++; } //2초가 지나서 종료가 되면 fail ::SendMessage(pComm->getHandle(), WM_COMM_READ, pComm->mCommand, FALSE); pComm->m_hThreadRcvTimeout = NULL; } return TRUE; } // 포트를 감시하고, 읽힌 내용이 있으면 // m_ReadData에 저장한 뒤에 MainWnd에 메시지를 보내어 Buffer의 내용을 // 읽어가라고 신고한다. DWORD ThreadWatchComm(CCommThread* pComm) { DWORD dwEvent; OVERLAPPED os; BOOL bOk = TRUE; BYTE buff[2048]; // 읽기 버퍼 DWORD dwRead; // 읽은 바이트수. // Event, OS 설정. memset( &os, 0, sizeof(OVERLAPPED)); //--> 이벤트 설정.. if( !(os.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL)) ) { bOk = FALSE; } //--> 이벤트 마스크.. if( !SetCommMask( pComm->m_hComm, EV_RXCHAR) ) { bOk = FALSE; } //--> 이벤트나..마스크 설정에 실패함.. if( !bOk ) { //AfxMessageBox("Error while creating ThreadWatchComm, " + pComm->m_sPortName); return FALSE; } while (pComm ->m_bConnected) { dwEvent = 0; // 포트에 읽을 거리가 올때까지 기다린다. WaitCommEvent( pComm->m_hComm, &dwEvent, NULL); //--> 데이터가 수신되었다는 메세지가 발생하면.. if( (dwEvent & EV_RXFLAG || dwEvent & EV_RXCHAR) == (EV_RXFLAG || EV_RXCHAR) ) //if ((dwEvent & EV_RXCHAR) == EV_RXCHAR) { // 포트에서 읽을 수 있는 만큼 읽는다. //--> buff 에 받아놓고.. memset(buff, 0, sizeof(BYTE)*2048); dwRead = pComm->ReadComm( buff, 512); //if(dwRead == 66) { pComm->SetReadData(buff, dwRead); } } } CloseHandle( os.hEvent); //--> 쓰레드 종료가 되겠죠? pComm->m_hThreadWatchComm = NULL; return TRUE; } void CCommThread::SetReadData(BYTE *pBuff, DWORD nData) { int length; int packetType; int i, j; memset(mTempData,0,sizeof(BYTE)*BUFF_SIZE); memcpy(mTempData,pBuff,nData); for(i=0; i<nData; i++) { if(CmdParser(&RxPacket, pBuff[i])) { length = RxPacket.LEN; //broadcast data if(RxPacket.BUF[0] == 0x30 && RxPacket.BUF[1] == 0x0C && RxPacket.BUF[2] == 0x12) { packetType = 1; } //receive data else if(RxPacket.BUF[0] == 0x80 && RxPacket.BUF[1] == 0x80 && RxPacket.BUF[2] == 0x11) { packetType = 2; } else { packetType = 256; } for(j=0; j< length; j++) { m_usData[j] = RxPacket.BUF[j]; } makeRcvData(m_usData[30]); } } } void CCommThread::makeRcvData(BYTE command){ switch(command){ // [10/11/2011 sbhwang] ///////////////////////////////////////////////// case 0xff: mReadcnt = 0; memset(&mRcvData,0x00,sizeof(RECEIVEDATA)); bGeneralDataFlag = TRUE; mRcvData.ID[0] = m_usData[7]; mRcvData.ID[1] = m_usData[8]; for(int i=0; i<30; i++){ mRcvData.SECTION[i] = m_usData[31+i]; } break; ////////////////////////////////////////////////////////////////////////// case 0x10: mReadcnt = 0; memset(&mRcvData,0x00,sizeof(RECEIVEDATA)); bGeneralDataFlag = TRUE; mRcvData.ID[0] = m_usData[7]; mRcvData.ID[1] = m_usData[8]; for(int i=0; i<30; i++){ mRcvData.SECTION[i] = m_usData[31+i]; } break; case 0x20: if(!bGeneralDataFlag) { break; } for(int i=0; i<30; i++){ mRcvData.FACILITY[i] = m_usData[31+i]; } break; case 0x30: if(!bGeneralDataFlag) { break; } for(int i=0; i<30; i++){ mRcvData.PROVIDER[i] = m_usData[31+i]; } break; case 0x40: if(!bGeneralDataFlag) { break; } for(int i=0; i<30; i++){ mRcvData.CUSTOMER[i] = m_usData[31+i]; } break; case 0x50: if(!bGeneralDataFlag) { // if(mCommand != WRITEDATA_CMD) // ::SendMessage(hStartWnd, WM_COMM_READ, mCommand, FALSE); // mReadcnt = 0; break; } mRcvData.TEMPERATURE = (float)m_usData[14+31]+(float)m_usData[15+31]/10; mRcvData.HUMIDITY = (float)m_usData[16+31]+(float)m_usData[17+31]/10; mRcvData.MOISTURE = m_usData[18+31]; ::SendMessage(hStartWnd, WM_COMM_READ, GENERAL_DATA, TRUE); if(mTotalcnt-mIndex > 0) SendTxBuff(); bGeneralDataFlag = FALSE; break; default: if(m_usData[0] == 0x80 && m_usData[1] == 0x80 && m_usData[2] == 0x11); else if(m_usData[0] == 0x30 && m_usData[1] == 0x0c && m_usData[2] == 0x12) { mRcvData.ID[0] = m_usData[7]; mRcvData.ID[1] = m_usData[8]; for(int i=0; i<30; i++){ mRcvData.READINGDATA[i] = m_usData[32+i]; } if(m_hThreadRcvTimeout){ TerminateThread(m_hThreadRcvTimeout,1L); m_hThreadRcvTimeout = NULL; if(mCommand == WRITEDATA_CMD){ if(mIndex > 99) mIndex = 0; memset(&TxPktBuff[mIndex++],0x00,sizeof(TXPKTBUFF)); } } ::SendMessage(hStartWnd, WM_COMM_READ, mCommand, TRUE); } break; /* if(mReadcnt == 2){ memset(&mRcvData,0x00,sizeof(RECEIVEDATA)); if(mCommand == READDATA_CMD) { mRcvData.ID[0] = m_usData[7]; mRcvData.ID[1] = m_usData[8]; for(int i=0; i<30; i++){ mRcvData.READINGDATA[i] = m_usData[31+i]; } ::SendMessage(hStartWnd, WM_COMM_READ, mCommand, TRUE); } else if(mCommand == WRITEDATA_CMD){ if(m_hThreadRcvTimeout){ TerminateThread(m_hThreadRcvTimeout,1L); m_hThreadRcvTimeout = NULL; } if(mIndex > 99) mIndex = 0; memset(&TxPktBuff[mIndex++],0x00,sizeof(TxPktBuff)); ::SendMessage(hStartWnd, WM_COMM_READ, mCommand, TRUE); } else if(mCommand == COMMOVER_CMD){ ::SendMessage(hStartWnd, WM_COMM_READ, mCommand, TRUE); } mReadcnt = 0; } else ++mReadcnt; break; */ } } void CCommThread::SendTxBuff(){ BOOL bResult; for(int i=mIndex; i<mTotalcnt; i++ ){ if(WriteComm(TxPktBuff[i].PKT, TxPktBuff[i].LENGTH)){ mCommand = WRITEDATA_CMD; bResult = TRUE; } if(bResult) createtimeoutThread(); } mIndex = mTotalcnt; } BYTE* CCommThread::GetRealDataArray( ) { return m_usData; //return mTempData; } BYTE* CCommThread::GetReadData( ) { memset(m_rcvData,NULL,33); m_rcvData[0] = m_usData[7]; m_rcvData[1] = m_usData[8]; m_rcvData[2] = m_usData[30]; //data for(int i=0; i<30; i++){ m_rcvData[3+i] = m_usData[31+i]; } return m_rcvData; } RECEIVEDATA CCommThread::GetRCVdata(){ return mRcvData; } bool CCommThread::CmdParser(SERIAL_PKT* pSerial, BYTE data) { static BYTE State = 0; static BYTE Pos; static BYTE * Ptr; static BYTE Chk; switch(State) { case 0: if(data == 0xAA) State = 1; else if(data == 0x48) { Ptr = (BYTE*)(pSerial->BUF); State = 5; Pos = 0; Ptr[Pos] = data; } break; case 1: Ptr = &(pSerial->LEN); *Ptr = data; State = 2; Ptr = (BYTE*)(pSerial->BUF); Pos = 0; Chk = 0; if(pSerial->LEN > (sizeof(pSerial->BUF))) { State = 0; } break; case 2: Ptr[Pos++] = data; Chk += data; if(Pos == pSerial->LEN) State = 3; break; case 3: Ptr = &(pSerial->SUM); * Ptr = data; if((pSerial->SUM == Chk) || (pSerial->SUM == 0)) { State = 4; } else { State = 0; } break; case 4: if(data == 0x55) { State=0; return true; } case 5: Ptr[++Pos] = data; if(Pos == 48) {State = 6;} break; case 6: if(data == 0x30) { Ptr[++Pos] = data; State = 0; pSerial->LEN = Pos; return true; } default: break; } return false; }
[ "you@example.com" ]
you@example.com
86ca3df059f2937c3b21925b7b6d0ce994d42162
33e23e38baf59cef9973ccd9efff65a0b616fabc
/Env.cpp
e24566b1902b2ffa01f55be0f873c22458104fea
[ "Apache-2.0" ]
permissive
IKholopov/checkers-rl
bde5d00934bab2abb1b1854c6bf97000ba36a8f7
e2e05efa4f3691f5374fde1da0c49ee71f5d4777
refs/heads/master
2020-05-02T00:44:03.019079
2019-06-05T22:43:48
2019-06-05T22:43:48
177,676,143
0
0
Apache-2.0
2019-06-05T22:43:50
2019-03-25T22:46:54
C++
UTF-8
C++
false
false
1,355
cpp
#include <Env.h> #include <sstream> #include <thread> CheckersEnv::CheckersEnv(bool american) : game_(std::make_unique<GameLoop>(american)) { } std::shared_ptr<GameState> CheckersEnv::Step(std::shared_ptr<GameState> action) { return game_->Step(action); } GameEnd CheckersEnv::Run(std::shared_ptr<IStrategy> white_strategy, std::shared_ptr<IStrategy> black_strategy, bool verbose) { game_->SetWhiteStrategy(white_strategy); game_->SetBlackStrategy(black_strategy); auto result = game_->EvaluateGame(verbose); return GameEnd{result.first, result.second}; } void CheckersEnv::Reset(bool american, std::shared_ptr<IStrategy> white_strategy, std::shared_ptr<IStrategy> black_strategy, std::shared_ptr<GameState> start_state, int max_steps) { // std::this_thread::sleep_for(std::chrono::milliseconds(500)); game_ = std::make_unique<GameLoop>(american, white_strategy, black_strategy, start_state, max_steps); } std::string CheckersEnv::Render() const { std::stringstream stream; CurrentState()->Dump(stream); return stream.str(); } std::vector<CellStatus> CheckersEnv::StateValue() const { return CurrentState()->StateValue(); }
[ "kholopov96@gmail.com" ]
kholopov96@gmail.com
ae8aa389007bfe9601ef51a44e7826641a5a4028
9288fecafae40d6045871cec408072c3fa5aa2fc
/src/framework/core/util.h
ca8c28e64a58ec5bff527b55d91c203d592fed43
[]
no_license
alzwded/cruftybehemoth
80e5bcf7703bc2f909ea40dd971adc5ce0f20849
45cb3596b9f6444feac59f9c04dbf70bba11645d
refs/heads/master
2021-01-22T11:20:48.518050
2012-09-13T10:21:16
2012-09-13T10:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
487
h
#ifndef CORE_UTIL_H #define CORE_UTIL_H #include <cstddef> namespace Core { //---------- Core::ID // provides runtime ids class ID { public: //========== ID::Next static unsigned long Next(); //========== ID::Reset static void Reset(); private: //========== ID::current static unsigned long current; }; template<class T> struct DerefLess { bool operator()(const T* lhs, const T* rhs) { return (*lhs) < (*rhs); } }; } // namespace #endif
[ "jakkal@jakkal-mini.(none)" ]
jakkal@jakkal-mini.(none)
fbacc063c82e27401b77ba506a747db1b301893f
56ee04007eac69701f0bb4421046eb558b24f6d6
/abc166/a.cpp
8e14f55a65fdcda610ac7e31af4b6bbf692432fb
[]
no_license
tsuba3/atcoder
e5789515d96079a386843f744f0cf594ec663a24
d397e98686cae982b431c098ec288d2994c33152
refs/heads/master
2021-07-01T21:31:45.429120
2021-02-20T13:40:24
2021-02-20T13:40:24
224,573,527
0
0
null
null
null
null
UTF-8
C++
false
false
2,971
cpp
/* _ _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||_ \ | | \\\ - /'| | | | \_| `\`---'// |_/ | \ .-\__ `-. -'__/-. / ___`. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' _> \"". | | : `- \`. ;`. _/; .'/ / .' ; | \ \ `-. \_\_`. _.'_/_/ -' _.' / ===========`-.`___`-.__\ \___ /__.-'_.'_.-'================ Please give me AC. */ #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <algorithm> #include <numeric> #include <string> #include <sstream> #include <complex> #include <bitset> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <unordered_map> #include <unordered_set> #include <utility> #include <chrono> #include <random> using namespace std; using int64 = long long; using uint64 = unsigned long long; using vi = vector<int>; using vl = vector<int64>; using pii = pair<int, int>; using pll = pair<int64, int64>; #define rep(i, n) for (int i = 0; i < (int)(n); ++i) #define all(v) (v).begin(), (v).end() #define print(x) cout << (x) << '\n' #define print2(x, y) cout << (x) << ' ' << (y) << '\n' #define print3(x, y, z) cout << (x) << ' ' << (y) << ' ' << (z) << '\n' #define printn(v) rep(i, (v).size() - 1) cout << (v)[i] << ' '; cout << (v)[n - 1] << '\n'; #define debug(x) cerr << #x << ": " << (x) << '\n' #define debug2(x, y) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << '\n' #define debug3(x, y, z) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << ", " << #z << ": " << (z) << '\n' #define dbg(v) for (size_t _ = 0; _ < v.size(); ++_){cerr << #v << "[" << _ << "] : " << v[_] << '\n';} // constant const int INF = (1<<30) - 1; const int64 INF64 = (1LL<<62) - 1; template<typename T> T gcd(T a, T b) { if (a < b) return gcd(b, a); T r; while ((r = a % b)) { a = b; b = r; } return b; } template<typename T> T lcm(const T a, const T b) { return a / gcd(a, b) * b; } template<typename T> bool chmin(T& a, const T& b) { if (a > b) return a = b, true; else return false; } template<typename T> bool chmax(T& a, const T& b) { if (a < b) return a = b, true; else return false; } // End of template. int main() { cout << fixed << setprecision(15); ios::sync_with_stdio(false); cin.tie(nullptr); // cin.read(buf, sizeof buf); // 注意: ./a.out < in か pbp | ./a.out で入力すること string s; cin >> s; if (s[1] == 'B') s[1] = 'R'; else s[1] = 'B'; print(s); return 0; }
[ "tsubasa.afe@gmail.com" ]
tsubasa.afe@gmail.com
e844fa5398ce725355e5c60d11bad79d67677d57
84fe0b82c11ae24e94f7afe91a99ffef665fe614
/client_qt/src/map.h
7f0e39ea320b0ace424a350c0721846544622cb3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
matteli/histemul
4f11634ab448f176283f8cb16e3976db2813ddd5
61f1ea8e1263b92fd2bead0c808f67940faad802
refs/heads/master
2018-09-29T01:10:18.274900
2018-07-26T09:26:33
2018-07-26T09:26:33
7,499,715
1
0
null
null
null
null
UTF-8
C++
false
false
7,200
h
/*Copyright 2012-2013 Matthieu Nué 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MAP_H #define MAP_H #include <list> #include <vector> #include <forward_list> #include <array> #include <algorithm> #include <iterator> #include <string> #include <QtQuick/QQuickItem> #include <QtQuick/qquickwindow.h> #include <QtGui/QOpenGLFramebufferObject> #include <QtGui/QOpenGLShaderProgram> #include <QColor> #include <QPair> //#include <QQuickItem> #include <QOpenGLFunctions> #include <QNetworkAccessManager> class Map : public QQuickItem, protected QOpenGLFunctions { Q_OBJECT Q_PROPERTY(QString stripe0 READ stripe0 WRITE setStripe0 NOTIFY stripe0Changed) Q_PROPERTY(QString stripe1 READ stripe1 WRITE setStripe1 NOTIFY stripe1Changed) //Q_PROPERTY(quint16 numberVisibleProvince READ numberVisibleProvince) //Q_PROPERTY(QList<QVariant> visibleProvince READ visibleProvince NOTIFY visibleProvinceChanged) Q_PROPERTY(qreal t READ t WRITE setT NOTIFY tChanged) Q_PROPERTY(int top READ top NOTIFY moved) Q_PROPERTY(int left READ left NOTIFY moved) Q_PROPERTY(int topLeftBlock READ topLeftBlock WRITE setTopLeftBlock) public: Map(); ~Map(); Q_ENUMS(EnumDirection) enum EnumDirection { All, OnTopLeft, OnTopRight, OnBottomLeft, OnBottomRight, OnLeft, OnRight, OnTop, OnBottom, None }; QString stripe0() const { return mStripe0; } void setStripe0(QString stripe); QString stripe1() const { return mStripe1; } void setStripe1(QString stripe); qreal t() const { return mT; } void setT(qreal t); int top() const { return mTop; } int left() const { return mLeft; } int topLeftBlock() const { return mTopLeftBlock;} void setTopLeftBlock(int topLeftBlock) {mTopLeftBlock = topLeftBlock; calculateCoordinate();} //quint16 numberVisibleProvince() const { return mNumberVisibleProvince; } Q_INVOKABLE void move(EnumDirection d); Q_INVOKABLE unsigned short hitID(unsigned short x, unsigned short y); Q_INVOKABLE QVariant selectID(unsigned short x, unsigned short y); Q_INVOKABLE void unSelectID(); Q_INVOKABLE void updateLightMap(); void init(unsigned int width, unsigned int height, QUrl url, bool debug, QString player); void resize(QSize size, QSize oldSize); signals: void stripe0Changed(); void stripe1Changed(); void urlChanged(); void tChanged(); void moved(); void visibleProvinceChanged(QSet<quint16> provinceAdded); void provinceModelChanged(QList<QVariant> visibleProvinceChanged); void armyModelChanged(QList<QVariant> armyChanged); public slots: void doJobBeforeRendering(); //void update(); private slots: void writeFps(); void slotProvinceUpdateReply(QNetworkReply* reply); private: //members int mNbVertices; QString mStripe0; QString mStripe1; QString mPlayer; qreal mT; int mWidth, mHeight; int mTopLeftBlock; int mTopBlock; int mLeftBlock; int mTop; int mLeft; int mSizeBorder; bool mCircum; int mColorRiver; QRect mScreen; QRect mBlockScreen; QOpenGLShaderProgram *mProgram; QMatrix4x4 mMatrix; QUrl mUrl; bool mDebug; QQuickWindow *mWindow; QSet<quint16> mVisibleProvince; quint16 mNumberVisibleProvince; struct Light { unsigned short id; std::vector<unsigned char> tree; std::vector<unsigned char> leafGray; std::vector<unsigned short> nearId; }; std::vector<std::list<Light> > mBlock; std::vector<std::map<unsigned short, unsigned short> > mHit; unsigned short mSelectedId; std::vector<QRect> mBoundsProvince; std::vector<QPoint> mPosInQuad; int mNbBlockHeight, mNbBlockWidth, mSizeBlock, mNbBlockScreenWidth, mNbBlockScreenHeight, mLevelInit, mMaxId; bool mWholeWidthBlock, mWholeHeightBlock; std::vector<int>p2; bool mInitGL; bool mInit; QOpenGLFramebufferObject *mFbo = NULL; std::vector<float> mQuadVertices; std::vector<float> mQuadColors; typedef std::array<QColor, 64> ColorShading; std::vector<std::pair<ColorShading, ColorShading> > mShadingColor; std::vector<QString> mShadingColorIndex; //Model::ProvinceAttribute* mFillProvinceAttribute = NULL; //Model::ArrayAttributeVal* mColorFillArrayAttribute = NULL; EnumDirection mNext; bool mWaitForMove; //std::list<unsigned short> mRefreshId; QSet<quint16> mRefreshId; int mFrame = 0; QNetworkAccessManager *mManager = NULL; std::vector<QString> mProText; std::vector<QList<QString>> mProColor; //functions bool initGL(); void initSize(unsigned int width, unsigned int height); std::vector<unsigned short> returnValidIdMap(std::string); bool addLightId(unsigned short id, std::string dir); bool addBoundsId(unsigned short id, std::string dir); bool addHitId(unsigned short id, std::string dir); bool readConfigMap(std::string dir); bool listVisibleProvince(); bool drawMap(); void drawVertices(); void drawBlock(int, int, int); QColor getColor(Light & idInBlock, int & posLeafGray, int colorIndex); int nextBitFromTree(Light &, int &, int &); unsigned char nextLeafGray(Light &, int &); void inspectBlock(Light &, int, int, int &, int &, int, int &, int); void inspectJson(int indexAttibute, QJsonObject obj, int id, QStringList stripe, int indexStripe); inline void drawQuad(int, int, int, QColor); inline void drawPoint(int, int, QColor); void saveMap(); bool initShadingColor(std::string fileName); void calculateShading(int levelInf, int levelSup, QColor col0, QColor col1, int level0, int level1, ColorShading& cs, ColorShading& cs1); void changeTopLeftBlock(int interval); void calculateCoordinate(); void updateDataProvince(); void handleWindowChanged(QQuickWindow *win); }; #endif // MAP_H
[ "matthieu.nue@gmail.com" ]
matthieu.nue@gmail.com
958407da24aaafb7e599a00243945c330473d6ba
13cc4ac7b416533c5a014c44ddf2a0f45caf7d4d
/hittable.h
7aaeddf6d349c1c5d866a479542837d0e5da7ff6
[]
no_license
DMilmont/zSILENCER
60e6d41e6290b71aa1d8f56d0a93cd9892a9cfff
e51bc12e64f3d7fa8da1b91823f4e0cc198fd0d7
refs/heads/master
2021-05-28T13:24:13.732215
2013-11-23T20:44:38
2013-11-23T20:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
#ifndef HITTABLE_H #define HITTABLE_H #include "shared.h" #include "serializer.h" class Hittable { public: Hittable(); void Serialize(bool write, Serializer & data, Serializer * old = 0); void Tick(class Object & object, class World & world); void HandleHit(class Object & object, class World & world, Uint8 x, Uint8 y, class Object & projectile); friend class Renderer; protected: Uint8 health; Uint16 shield; Uint8 state_hit; Uint8 hitx; Uint8 hity; }; #endif
[ "johnny@johnnys-MacBook-Pro.local" ]
johnny@johnnys-MacBook-Pro.local
d26094046758f49e44d342c3d611d607d5b178b1
6d1bb15f0f474afe48b0561a46f882cefd0b3387
/src/quantadb/ClusterTimeService.h
e39e29a24f701fb02ffb0ba95246859f3abf4b58
[ "ISC", "Apache-2.0" ]
permissive
hotneutron/QuantaDB
8f39ef97f2c798f899679089df48937bd30668ce
17b471d48cef4e65a2f1dbf3d1f1bf2cacae4939
refs/heads/master
2023-02-02T06:59:33.206737
2020-12-15T08:07:18
2020-12-15T08:07:18
321,593,111
2
0
null
null
null
null
UTF-8
C++
false
false
5,837
h
/* Copyright 2020 Futurewei Technologies, 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. */ #pragma once #include <x86intrin.h> #include <fcntl.h> #include <stdint.h> #include <time.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <atomic> #include <iostream> #include "Cycles.h" using namespace RAMCloud; namespace QDB { /** * QDB Cluster Time Service: * - High speed and high precision (nano-second) cluster time service * - Issues cluster unique time stamp (logical time stamp, explained below) * - Issues node local time stamp (real clock time stamp) in nanosecond precision. * - Convertion utility converse between logical time stamp and the corresponding real time. * * QDB Cluster Time Service relies on an underlying time synchronization module to sync time to sub-microsecond * precision. There are a few existing such protocols. In this implementation, we use the PTP (IEEE1588) protocol * to synchronize system clocks in the cluster. * * A logical time-stamp is a 64-bit value consisted of <54-bit real clock time in nano-sec><10-bit node id>. * A logical time-stamp is monotonically increasing and unique across the QDB cluster. * * The 10-bit node id field ensures logical time stamp is unique among the cluster nodes. 10 bits implies a * maximum of 1024 nodes can be supported. * * Node id must be unique and is automatically assigned at ClusterTimeService class instantiation time. * Ina production system, node id assignment could be done in an automated fashion (such as plug-in to a * cluster node management sw like zookeeper). In this POC implementation, a light-weight approach is used * by picking up the last number of the IP address of the PTP interface port. * * This implementation depends on PTP to synchronize system closks of all nodes in a cluster. * * There are two linux/unix system library functions to get the system time. One is gettimeofday(3) which is * fast (about ~25ns) but only returns micro-second precision. The other is clock_gettime(3) which returns * nanoseconds time stamp, yet could take ~500ns per call. * * To generate fast nanosecond time stamps, ClusterTimeService uses a background deamon process (or can also be * a background thread which is easier for deployment and testing purpose). The background thread maintais a * shared memory area which holds a nano-seond system timestamp along with a TSC counter which notes the cputime * when the system timestamp was last updated. The ClusterTimeService library reads the nano-second system * timestamp on the shared memory and uses TSC to calculate how much time had passed since the last update to * get the current time. * * EXTRA NOTE. * Using TSC to calculate time is hard to be reliable. * ref: http://oliveryang.net/2015/09/pitfalls-of-TSC-usage/#312-tsc-sync-behaviors-on-smp-system. * * An alternative way to use an atomic counter to replace the TSC counter. This way could generate reliable * monotonically increasing timestamps. */ // ClusterTimeService class ClusterTimeService { public: ClusterTimeService(); ~ClusterTimeService(); // return a local system clock time stamp inline uint64_t getLocalTime() { return getnsec(); /* nt_pair_t *ntp = &tp->nt[tp->pingpong]; uint64_t last_clock = ntp->last_clock; uint64_t last_clock_tsc = ntp->last_clock_tsc; return last_clock + Cycles::toNanoseconds(rdtscp() - last_clock_tsc, tp->cyclesPerSec); */ } private: // static void* update_ts_tracker(void *); // Fast (~25ns) about only at usec precision static inline uint64_t getusec() { struct timeval tv; gettimeofday(&tv,NULL); return (uint64_t)(1000000*tv.tv_sec) + tv.tv_usec; } // Slow (~500ns) about at nsec precision inline uint64_t getnsec() { timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; } // Slow (~500ns) about at nsec precision inline uint64_t getnsec(uint64_t *tsc) { timespec ts; uint64_t tsc1 = rdtscp(); clock_gettime(CLOCK_REALTIME, &ts); uint64_t tsc2 = rdtscp(); *tsc = (tsc1 + tsc2) / 2; return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; } static inline u_int64_t rdtscp() { uint32_t aux; return __rdtscp(&aux); } #if (0) // DISABLE TS_TRACKER #define TS_TRACKER_NAME "DSSN_TS_Tracker" typedef struct { uint64_t last_clock; // nano-sec from the last update uint64_t last_clock_tsc; // TSC counter value of the last_clock } nt_pair_t; typedef struct { volatile uint32_t pingpong; // Ping-pong index. Eiter 0 or 1. nt_pair_t nt[2]; double cyclesPerSec; std::atomic<int> tracker_id; uint32_t heartbeat; clockid_t clockid; // } ts_tracker_t; ts_tracker_t * tp; // pointing to a shared ts_tracker pthread_t tid; int my_tracker_id; bool thread_run_run; bool tracker_init; #endif uint64_t uctr, nctr; // statistics }; // ClusterTimeService } // end namespace QDB
[ "chun.liu@futurewei.com" ]
chun.liu@futurewei.com
c430f1619ad50cb647be0f05fae181682f8e1fa0
69b9cb379b4da73fa9f62ab4b51613c11c29bb6b
/submissions/abc125_a/main.cpp
d3591b4ba969f1562b1a018f5428a066e34ff5fa
[]
no_license
tatt61880/atcoder
459163aa3dbbe7cea7352d84cbc5b1b4d9853360
923ec4d5d4ae5454bc6da2ac877946672ff807e7
refs/heads/main
2023-07-16T16:19:22.404571
2021-08-15T20:54:24
2021-08-15T20:54:24
118,358,608
0
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
//{{{ #include <bits/stdc++.h> using namespace std; #define repX(a,b,c,x,...) x #define repN(a) repX a #define rep(...) repN((__VA_ARGS__,rep3,rep2,loop))(__VA_ARGS__) #define rrep(...) repN((__VA_ARGS__,rrep3,rrep2))(__VA_ARGS__) #define loop(n) rep2(i_,n) #define rep2(i,n) rep3(i,0,n) #define rep3(i,begin,end) for(int i=(int)(begin),i##_end=(int)(end);i<i##_end;++i) #define rrep2(i,n) rrep3(i,n,0) #define rrep3(i,begin,end) for(int i=(int)(begin-1),i##_end=(int)(end);i>=i##_end;--i) #define foreach(x,a) for(auto&x:a) using ll=long long; const ll mod=(ll)1e9+7; //}}} int main(){ int A, B, T; cin >> A >> B >> T; int ans = T / A * B; cout << ans << endl; return 0; }
[ "tatt61880@gmail.com" ]
tatt61880@gmail.com
0cbe3b28c914caa4532f7b6dc9e137bfe00b87e5
ef983014cc7a952033a2e915512f5ff315242a1a
/Graphs/BasicImplementation.cpp
0e86820480391d1f8423f5817694b8f8d5585e47
[]
no_license
manavsinghal157/DSA
a8026625670b981778523957e996aeec3db52b67
d619cd09c2037129d60282f1d62e9ed1fafbddda
refs/heads/master
2022-03-03T16:12:41.496122
2019-10-16T09:24:31
2019-10-16T09:24:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
699
cpp
#include<bits/stdc++.h> using namespace std; void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } void printGraph(vector<int> adj[], int v) { for(int v=0;v<V;++v) { cout<<"\n" Adj List of vertex"<<v<<"\n head"; for(auto x:adj[v]) cout<<"->"x; printf("\n"); } } int main() { int V=5; vector<int> adj[V]; addEdge(adj,0,1); addEdge(adj,0,4); addEdge(adj,1,2); addEdge(adj,1,3); addEdge(adj,1,4); addEdge(adj,2,3); addEdge(adj,3,4); printGraph(adj,V); return 0; }
[ "noreply@github.com" ]
noreply@github.com
2c9048f4d7a5adc8a1e1c1991e437cb7e625fb29
38ef2d2ded3f9b782513e59f42a56d68134a61a3
/include/Classifier/FeatureExtractor.hpp
a7a21deb0bc054f424b5b305d8ba51160fff6baf
[ "MIT" ]
permissive
qianqian121/pointcloud-landmarks-extractor
a7336077d536ad3fec55103d3e07b9894ba228d6
455e547d7db7ac5705a9f08e6b4769c2ee1e3674
refs/heads/master
2022-03-03T12:20:23.231241
2019-11-05T17:41:04
2019-11-05T17:41:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
587
hpp
#ifndef FEATUREEXTRACTOR_HPP #define FEATUREEXTRACTOR_HPP #include <Libs/Structures.hpp> #include <pcl/common/common.h> class FeatureExtractor { public: /** Default constructor */ FeatureExtractor(); /** Default destructor */ virtual ~FeatureExtractor(); bool filterSegment(Segment* candidate, double minHeight, double xyBoundThreshold); void extractEsfFeature(pcl::PointCloud<pcl::PointXYZ>::Ptr segmentCloud, Feature *esfFeature); void extractEigenFeature(Segment *candidate, Feature *eigenFeature); protected: private: }; #endif // FEATUREDESCRIPTOR_H
[ "thomas.akhil17@gmail.com" ]
thomas.akhil17@gmail.com
51494805d3d28b1be46bfc43a3dbbfa839d241df
921e54937006b870a6b33fe97cfec626a220298f
/System New/TurnOn.cpp
930dc9f96176fa2b197e507933c5af07b06f2f56
[]
no_license
NasiphiM/COS214Project
8849e5b1034c19a3361bfb8221a9916efba20df4
7f7416d599989bbc62d91cfe01730771c912ba88
refs/heads/main
2023-09-04T16:21:40.175987
2021-11-23T07:11:42
2021-11-23T07:11:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
/** * command dp * **/ #include "TurnOn.h" TurnOn ::TurnOn(Rocket* r) : Command(r) {} TurnOn ::TurnOn(Engine* e) : Command(e) {} void TurnOn ::execute() { if(getEngineReceiver()!= nullptr) getEngineReceiver()->On(); else getRocketReceiver()->On(); } void TurnOn ::undo() { if(getEngineReceiver()!= nullptr) getEngineReceiver()->Off(); else getRocketReceiver()->Off(); }
[ "noreply@github.com" ]
noreply@github.com
40e941dd8e91b8fb8d63e82660db3a8884ecb1cf
193f6b964b1a030d1e819ca4932fb2b829e2e41c
/DX11_1908/Scene/LightScene.h
474798d79a4cfa020c51af6f81edcbc081beaca4
[]
no_license
fkem79/DX11_Team_HomeSweetHome
cef13f869bee16fb2bbfe401364a2d4293925b2f
27b5b45ddcaaa407eb7e385f0ac63bdbd75c46e2
refs/heads/master
2021-05-18T20:34:29.754175
2020-05-10T16:37:20
2020-05-10T16:37:20
251,392,881
1
0
null
2020-05-08T12:57:25
2020-03-30T18:25:32
C++
UTF-8
C++
false
false
337
h
#pragma once class LightScene : public Scene { private: ModelRender* bunny; ModelRender* plane; LightInfoBuffer* buffer; public: LightScene(); ~LightScene(); virtual void Update() override; virtual void PreRender() override; virtual void Render() override; virtual void PostRender() override; void Export(string name); };
[ "fkemless79@mju.ac.kr" ]
fkemless79@mju.ac.kr
5363a01307d47df5245f66a9383cee495ed62792
5ee0eb940cfad30f7a3b41762eb4abd9cd052f38
/Case_save/case5/2200/epsilon
9d7fd0c4f7a2f15f0a7784da8628d4e2ce8f75d1
[]
no_license
mamitsu2/aircond5_play4
052d2ff593661912b53379e74af1f7cee20bf24d
c5800df67e4eba5415c0e877bdeff06154d51ba6
refs/heads/master
2020-05-25T02:11:13.406899
2019-05-20T04:56:10
2019-05-20T04:56:10
187,570,146
0
0
null
null
null
null
UTF-8
C++
false
false
10,242
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "2200"; object epsilon; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -3 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 0.000522366 0.000686478 0.000727373 0.000840646 0.000957 0.00107687 0.00120612 0.00133294 0.00142238 0.00145287 0.00140847 0.0012861 0.00109778 0.000875024 0.000662001 4.72471e-05 8.28433e-05 0.000117747 0.000116751 0.000105145 9.09005e-05 7.47223e-05 6.07019e-05 4.96315e-05 4.10319e-05 3.43167e-05 2.90157e-05 2.47911e-05 2.1376e-05 1.85295e-05 1.60473e-05 1.37426e-05 1.24971e-05 9.67777e-06 0.00131652 0.00186021 0.000650193 0.000632632 0.000668589 0.000725923 0.000808211 0.000908466 0.000996527 0.00104471 0.00103402 0.000961187 0.000836005 0.000686035 0.000572051 0.000717953 0.000140818 5.65929e-05 0.000133703 0.000142883 0.00013044 0.000111112 9.28896e-05 8.34748e-05 6.72957e-05 5.30973e-05 4.19178e-05 3.33435e-05 2.67924e-05 2.17801e-05 1.79519e-05 1.5127e-05 1.3381e-05 1.26559e-05 3.42701e-05 2.29635e-05 0.00238328 0.00448838 0.000815743 0.000613401 0.000651104 0.000742704 0.000873582 0.00102515 0.00115131 0.00121776 0.00121006 0.00113293 0.00099862 0.000840012 0.000695737 0.00062813 0.000773233 0.00040851 0.000300487 0.000229637 0.000178597 0.00014101 0.000118574 0.000215841 0.00014758 0.000104575 7.67408e-05 5.81459e-05 4.53332e-05 3.62697e-05 2.97551e-05 2.50962e-05 1.89724e-05 1.60194e-05 6.67908e-05 3.69521e-05 0.00382577 0.00920898 0.00130635 0.000643398 0.00066198 0.000799092 0.00101132 0.00123616 0.00139171 0.00145534 0.00142961 0.00132923 0.00116289 0.000973208 0.000802953 0.000688484 0.000668775 0.00126632 0.000718515 0.000433342 0.000290622 0.000209386 0.000159081 0.000135539 0.000307864 0.000230294 0.000183378 0.000151974 0.000128121 0.000108867 9.22744e-05 7.68484e-05 6.13628e-05 3.59596e-05 2.4419e-05 0.000118055 5.01942e-05 0.00578867 0.0162441 0.0025926 0.000820625 0.00074022 0.00094337 0.00132709 0.00162106 0.00176299 0.00178548 0.001716 0.00156854 0.00135687 0.00111217 0.000873691 0.000675552 0.000538552 0.000482655 0.000392754 0.000309369 0.00024213 0.000190298 0.000151461 0.000125628 0.000120377 0.00011088 0.000101508 9.23778e-05 8.30379e-05 7.35824e-05 6.43875e-05 5.58032e-05 4.79809e-05 3.7808e-05 2.96892e-05 8.15583e-05 5.7601e-05 9.29883e-05 0.000158044 0.000221892 0.00848924 0.0239404 0.00579048 0.00169433 0.00126749 0.00162256 0.00213142 0.00232188 0.00233763 0.00226199 0.00211919 0.00190287 0.00161638 0.00128878 0.000967329 0.000698442 0.000508872 0.000397408 0.000325684 0.000267236 0.000215769 0.000173263 0.000140838 0.000119032 0.000108134 0.000102875 9.92591e-05 9.51238e-05 8.92772e-05 8.07674e-05 7.0008e-05 5.91795e-05 4.94656e-05 4.10015e-05 3.6832e-05 5.72522e-05 5.99257e-05 7.16789e-05 0.000295698 0.000255968 0.0114964 0.0284671 0.0116797 0.0053794 0.00401846 0.00400926 0.00379493 0.00350042 0.00321368 0.00295185 0.00267933 0.00234867 0.00194564 0.00150162 0.00107616 0.0007314 0.000498161 0.000363679 0.000286541 0.000231576 0.000186519 0.000151414 0.000126951 0.000112827 0.000107749 0.000108154 0.000110434 0.000112777 0.000113947 0.000112111 0.000103244 9.10727e-05 7.92241e-05 6.93088e-05 6.69871e-05 7.93654e-05 0.000102141 0.00016466 0.00040963 0.000379243 0.0120765 0.0298028 0.0171838 0.0122915 0.00966193 0.00753122 0.00600353 0.00498942 0.00433019 0.00385814 0.00342057 0.00291362 0.00232331 0.00170431 0.00113717 0.000708173 0.000444105 0.000303417 0.000231033 0.000184876 0.000151109 0.000128015 0.000114654 0.000109666 0.00011133 0.00011759 0.000126968 0.000139148 0.000154315 0.000172387 0.000192103 0.00020398 0.000215643 0.000240318 0.00029034 0.000441852 0.00081088 0.00160599 0.0054512 0.00131548 0.0110805 0.0181553 0.0145866 0.0111747 0.00878349 0.00728549 0.0063893 0.00585346 0.00546112 0.00501649 0.0043847 0.00353463 0.0025952 0.00171104 0.000972408 0.000521634 0.000320155 0.000224642 0.000173529 0.000141391 0.000120476 0.000108434 0.000103667 0.00010476 0.000110562 0.000120392 0.00013435 0.000153431 0.000179436 0.000215034 0.000263933 0.000331385 0.000425028 0.00056613 0.000774291 0.00105861 0.00138908 0.00168766 0.0019126 0.00105262 0.0037247 0.00656664 0.00841856 0.00890402 0.00889185 0.00842403 0.00743568 0.00603744 0.00443923 0.00279028 0.00167673 0.000970095 0.000549855 0.000331222 0.000225895 0.000172407 0.000141937 0.000122696 0.00011037 0.000103457 0.000101058 0.000102461 0.000107182 0.000115145 0.000126753 0.000142985 0.000165537 0.000197159 0.000242147 0.000306593 0.000398135 0.000527341 0.000702611 0.000918671 0.00114907 0.00136422 0.00122264 0.000593853 0.00370289 0.00847843 0.00847984 0.00703131 0.00608701 0.00510187 0.00402236 0.00295942 0.00201387 0.00125685 0.000763322 0.000472397 0.000313068 0.000231006 0.000188879 0.000165386 0.000150382 0.000139642 0.000131524 0.000125424 0.000121455 0.000120063 0.000121531 0.000126316 0.000135142 0.000149061 0.000169587 0.000198943 0.00024035 0.00029823 0.000378637 0.000488182 0.000629776 0.000796883 0.000973892 0.0012276 0.000650343 0.000653602 0.00266377 0.0031797 0.00358998 0.00450817 0.00400152 0.0035636 0.0032267 0.00277521 0.00223462 0.00168433 0.00118715 0.000793893 0.000525758 0.000360828 0.000262834 0.00020346 0.000165893 0.000141249 0.000125038 0.000114918 0.000109503 0.000107945 0.000109582 0.000113741 0.000120393 0.000129723 0.00014213 0.000158294 0.00017935 0.000206839 0.000241834 0.000286416 0.000343123 0.000415198 0.000505867 0.000625332 0.000660887 0.000499562 0.000404329 0.000590307 ) ; boundaryField { floor { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 29 ( 0.000662001 4.72471e-05 8.28433e-05 0.000117747 0.000116751 0.000105145 9.09005e-05 7.47223e-05 6.07019e-05 4.96315e-05 4.10319e-05 3.43167e-05 2.90157e-05 2.47911e-05 2.1376e-05 1.85295e-05 1.60473e-05 1.37426e-05 1.24971e-05 9.67777e-06 9.67777e-06 2.29635e-05 3.69521e-05 5.01942e-05 0.000662001 4.72471e-05 5.65929e-05 0.00040851 0.00126632 ) ; } ceiling { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 43 ( 0.00266377 0.0031797 0.00358998 0.00450817 0.00400152 0.0035636 0.0032267 0.00277521 0.00223462 0.00168433 0.00118715 0.000793893 0.000525758 0.000360828 0.000262834 0.00020346 0.000165893 0.000141249 0.000125038 0.000114918 0.000109503 0.000107945 0.000109582 0.000113741 0.000120393 0.000129723 0.00014213 0.000158294 0.00017935 0.000206839 0.000241834 0.000286416 0.000343123 0.000415198 0.000505867 0.000625332 0.000660887 0.000499562 0.000404329 0.000590307 0.0110805 0.0181553 0.00370289 ) ; } sWall { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value uniform 0.00266377; } nWall { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 6(0.000221892 0.000255968 0.000379243 0.000593853 0.000653602 0.000590307); } sideWalls { type empty; } glass1 { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 9(0.000522366 0.00131652 0.00238328 0.00382577 0.00578867 0.00848924 0.0114964 0.0120765 0.0110805); } glass2 { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 2(0.00131548 0.00105262); } sun { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 14 ( 0.000522366 0.000686478 0.000727373 0.000840646 0.000957 0.00107687 0.00120612 0.00133294 0.00142238 0.00145287 0.00140847 0.0012861 0.00109778 0.000875024 ) ; } heatsource1 { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 3(9.29883e-05 0.000158044 0.000221892); } heatsource2 { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 4(0.000717953 0.000140818 0.000140818 0.000773233); } Table_master { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 9(0.000215841 0.00014758 0.000104575 7.67408e-05 5.81459e-05 4.53332e-05 3.62697e-05 2.97551e-05 2.50962e-05); } Table_slave { Cmu 0.09; kappa 0.41; E 9.8; type epsilonWallFunction; value nonuniform List<scalar> 9(0.000307864 0.000230294 0.000183378 0.000151974 0.000128121 0.000108867 9.22744e-05 7.68484e-05 6.13628e-05); } inlet { type turbulentMixingLengthDissipationRateInlet; mixingLength 0.01; phi phi; k k; value uniform 0.000101881; } outlet { type zeroGradient; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
2f956c51feacc37c05c47fd074f2c9d15d033343
7447212ccdb6d479a86847314e4fb9a462c0eb24
/include/utility/semaphore.h
3e138b3fc6b39d2f2ac06312d27002482da6b43a
[ "Unlicense" ]
permissive
Blinjko/LXPlayer
b2475bab95e4fb8b577fbd8bb4b45b736e6066f7
19add4387ec36fb235f8f1424e185b72dbb869a3
refs/heads/master
2022-11-25T17:50:10.699857
2020-08-07T00:42:00
2020-08-07T00:42:00
279,931,818
3
1
null
null
null
null
UTF-8
C++
false
false
728
h
#pragma once #include <mutex> #include <condition_variable> namespace Utility { /* Semaphore class * Description: This is a counting semaphore class * Why not use the one in the STL / Standard Library? * The semaphore in the STL is part of C++20 and I rather avoid using very very new features, when I can just implement them myself. */ class Semaphore { public: Semaphore(int); Semaphore(const Semaphore&) = delete; ~Semaphore(); int count(); int post(); int wait(); private: int m_count; std::mutex m_mutex; std::condition_variable m_condition_variable; }; }
[ "blinjko@gmail.com" ]
blinjko@gmail.com
195deba10179bb99062d4474e649de3f977d98fb
3dc221595e0f049bef7df1faa7dbd932aa20a5a2
/src/g_affinitymatrix.cpp
5e6d7bcfa966ca502d20809e3f85cc5830a5277a
[]
no_license
goyoambrosio/svpg
d17ae76f64dfe62f37a98653b275ae9cfc59dfa9
c50ec3fd788be355ab0b08934647130cb8e48285
refs/heads/master
2021-01-06T14:23:59.172325
2020-02-18T12:58:26
2020-02-18T12:58:26
241,358,950
0
0
null
null
null
null
UTF-8
C++
false
false
5,940
cpp
/**** SoftVision. Software for Computer Vision Gregorio Ambrosio Cestero (goyo@computer.org) System Engineering and Automation Department University of Malaga. Spain $RCSfile: g_affinitymatrix.cpp,v $ $Revision: 1.1 $ $Date: 2000/01/21 13:04:04 $ $Name: $ ****/ /******************************************************************************\ * * SoftVision Toolbox. Software for Computer Vision * * * * Author : Gregorio Ambrosio Cestero (goyo@computer.org) * * System Engineering and Automation Department * * University of Malaga. Spain * * * * Copyright (c) 2000, Gregorio Ambrosio cestero * * All Rights Reserved * * * * Permission to use, copy, modify, and distribute this software and its * * associated documentation for non-commercial purposes is hereby granted, * * provided that the above copyright notice appears in all copies, derivative * * works or modified versions of the software and any portions thereof, and * * that both the copyright notice and this permission notice appear in the * * documentation. Gregorio Ambrosio Cestero (GAC for short) shall be given * * a copy of any such derivative work or modified version of the software and * * GAC shall be granted permission to use, copy, modify and distribute the * * software for his own use and research. This software is experimental. * * GAC does not make any representations regarding the suitability of this * * software for any purpose and GAC will not support the software. * * * * THE SOFTWARE IS PROVIDED AS IS. GAC DOES NOT MAKE ANY WARRANTIES * * EITHER EXPRESS OR IMPLIED WITH REGARD TO THE SOFTWARE. GAC ALSO * * DISCLAIMS ANY WARRANTY THAT THE SOFTWARE IS FREE OF INFRINGEMENT OF ANY * * INTELLECTUAL PROPERTY RIGHTS OF OTHERS. NO OTHER LICENSE EXPRESS OR * * IMPLIED IS HEREBY GRANTED. GAC SHALL NOT BE LIABLE FOR ANY DAMAGES, * * INCLUDING GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, ARISING * * OUT OF THE USE OR INABILITY TO USE THE SOFTWARE. * * * \******************************************************************************/ #include "gacmex.h" #include "Image.h" void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { mxArray *mxM; size_t mxNumRows, mxNumCols; int nrows,ncols; Image I; DoubleMatrix SegmentsMatrix; DoubleMatrix AdjacencyMatrix; Segment S; StructSData SData; StructPGData PGData; StructMiscData MiscData; size_t i; double MaxDistance,d0p,thetap,deltap,C1,C2,C3; /* check for proper number of arguments */ if(nrhs==0) { mexPrintf("===============================================\n"); mexPrintf("affinitymatrix.dll (c)1999 G.A.C. (rv.2)\n"); mexPrintf("Gregorio Ambrosio Cestero\n"); mexPrintf("University of Malaga\n"); mexPrintf("Department of System Engineering and Automation\n"); mexPrintf("Email: goyo@computer.org\n"); mexPrintf("================================================\n"); mexPrintf("Build: %s\n",__TIMESTAMP__); mexPrintf("================================================\n"); mexErrMsgTxt("Eight inputs required."); } else if(nrhs!=8) { mexErrMsgTxt("Eight inputs required."); } else if(nlhs!=1) { mexErrMsgTxt("One output required."); } //Control the correctness of input arguments // if( !mxIsNumeric (prhs[0]) || // !mxIsDouble (prhs[0]) || // mxIsEmpty (prhs[0]) || // mxIsComplex (prhs[0]) ){ // mexErrMsgTxt("The image matrix has the incorrect format"); // } // if( !mxIsNumeric (prhs[1]) || // !mxIsDouble (prhs[1]) || // mxIsEmpty (prhs[1]) || // mxIsComplex (prhs[1]) || // mxGetN (prhs[1])!=5 ){ // mexErrMsgTxt("The segment matrix has the incorrect format"); // } if( !mxIsNumeric (prhs[0]) || !mxIsDouble (prhs[0]) || mxIsEmpty (prhs[0]) || mxIsComplex (prhs[0]) || mxGetN (prhs[0])!=5 ){ mexErrMsgTxt("The segment matrix has the incorrect format"); } for (i=1;i<=7;i++){ nrows = mxGetM(prhs[i]); ncols = mxGetN(prhs[i]); if( !mxIsNumeric(prhs[i]) || !mxIsDouble (prhs[i]) || mxIsEmpty (prhs[i]) || mxIsComplex(prhs[i]) || !(nrows==1 && ncols==1) ) { mexPrintf("Input #%i error\n",i); mexErrMsgTxt("Input must be a scalar."); } } //Extraction of the input values MaxDistance = *mxGetPr(prhs[1]); d0p = *mxGetPr(prhs[2]); thetap = *mxGetPr(prhs[3]); deltap = *mxGetPr(prhs[4]); C1 = *mxGetPr(prhs[5]); C2 = *mxGetPr(prhs[6]); C3 = *mxGetPr(prhs[7]); //Process // mxArray2UcharMatrix(prhs[0],I.Retina); mxArray2DoubleMatrix(prhs[0],SegmentsMatrix); for (i=0;i<SegmentsMatrix.Depth();i++){ S=Segment(SegmentsMatrix[i][1], SegmentsMatrix[i][2], SegmentsMatrix[i][3], SegmentsMatrix[i][4]); S.Label = SegmentsMatrix[i][0]; I.SegmentRetina[S.Label]=S; } AdjacencyMatrix = I.GetAffinityGraph(MaxDistance,d0p,thetap,deltap,C1,C2,C3).GetAdjacencyMatrix(); //Passing to output vars DoubleMatrix2mxArray(AdjacencyMatrix,mxM); plhs[0] = mxM; }
[ "contact@goyoambrosio.com" ]
contact@goyoambrosio.com
1f3f232c61c3c728cc56efec7787eb86740b68b3
55b057d341596852403bfe8ce9ddad45623925c0
/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h
0dc4ef1fe8be78424b6811286fbff4116fa26312
[ "NCSA", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
wydddddd/TripleDoggy
104b3f3ec44689a746cf5601fde3e160d6f05494
b4d4d4701f49caefd9f68a4898ad538b0a5e8f8e
refs/heads/master
2022-07-16T07:08:55.361512
2022-06-28T10:40:15
2022-06-28T10:40:15
369,498,767
0
0
Apache-2.0
2022-06-28T10:42:37
2021-05-21T10:28:47
C++
UTF-8
C++
false
false
2,491
h
//===- DynamicTypeMap.h - Dynamic type map ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides APIs for tracking dynamic type information. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/ImmutableMap.h" #include "clang/AST/Type.h" namespace clang { namespace ento { class MemRegion; /// The GDM component containing the dynamic type info. This is a map from a /// symbol to its most likely type. struct DynamicTypeMap {}; using DynamicTypeMapImpl = llvm::ImmutableMap<const MemRegion *, DynamicTypeInfo>; template <> struct ProgramStateTrait<DynamicTypeMap> : public ProgramStatePartialTrait<DynamicTypeMapImpl> { static void *GDMIndex() { static int index = 0; return &index; } }; /// \brief Get dynamic type information for a region. DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg); /// \brief Set dynamic type information of the region; return the new state. ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg, DynamicTypeInfo NewTy); /// \brief Set dynamic type information of the region; return the new state. inline ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg, QualType NewTy, bool CanBeSubClassed = true) { return setDynamicTypeInfo(State, Reg, DynamicTypeInfo(NewTy, CanBeSubClassed)); } void printDynamicTypeInfo(ProgramStateRef State, raw_ostream &Out, const char *NL, const char *Sep); } // namespace ento } // namespace clang #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H
[ "wjq@loccs.com" ]
wjq@loccs.com
b41d1efa4023cb064de4701dc2107d5f8386c3ef
290064a24540c3ea6457692f5613ad274b0ab4b2
/mainwindow.cpp
565216cd64a26841b2e2a35e54452b79616efbde
[]
no_license
zhdv06/TestQwt
727a623f33da106cbd3a4bcf2bc20e84c8309642
2b2593ed7c14e80566ac10fee95172438b181802
refs/heads/master
2020-07-15T21:58:52.520730
2019-09-01T14:58:39
2019-09-01T14:58:39
205,657,188
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
cpp
#include <qwt_plot.h> #include <qwt_plot_curve.h> #include <qwt_plot_grid.h> #include <qwt_symbol.h> #include <qwt_legend.h> #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // Constructor plot = new QwtPlot(this); plot->setTitle( "Plot Demo" ); plot->setCanvasBackground( Qt::white ); plot->setAxisScale( QwtPlot::yLeft, 0.0, 10.0 ); plot->insertLegend( new QwtLegend() ); grid = new QwtPlotGrid(); grid->attach( plot ); curve = new QwtPlotCurve(); curve->setTitle( "Some Points" ); curve->setPen( Qt::blue, 4 ), curve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); symbol = new QwtSymbol( QwtSymbol::Ellipse, QBrush( Qt::yellow ), QPen( Qt::red, 2 ), QSize( 8, 8 ) ); curve->setSymbol( symbol ); QPolygonF points; points << QPointF( 0.0, 4.4 ) << QPointF( 1.0, 3.0 ) << QPointF( 2.0, 4.5 ) << QPointF( 3.0, 6.8 ) << QPointF( 4.0, 7.9 ) << QPointF( 5.0, 7.1 ); curve->setSamples( points ); curve->attach( plot ); resize( 600, 400 ); setCentralWidget(plot); } MainWindow::~MainWindow() { delete grid; delete curve; }
[ "zhdv06@gmail.com" ]
zhdv06@gmail.com
fdc8f2e91ebadfc335c7f987b1342b9a8bec3a62
0ec9df3bb8b86216e18fe4cb66b6612297245aea
/Sources/CXXBoost/include/boost/algorithm/string/replace.hpp
d861c7490f291a1018cab6e250029991ced50624
[]
no_license
jprescott/BoostTestWithLib
78ae59d1ee801201883cf07ab76b8267fadf7daa
8650523cab467c41be60f3a1c144f556e9a7f25c
refs/heads/master
2022-11-18T14:49:00.664753
2020-07-18T21:45:17
2020-07-18T21:45:17
280,749,418
0
1
null
null
null
null
UTF-8
C++
false
false
31,096
hpp
// Boost string_algo library replace.hpp header file ---------------------------// // Copyright Pavol Droba 2002-2006. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/ for updates, documentation, and revision history. #ifndef BOOST_STRING_REPLACE_HPP #define BOOST_STRING_REPLACE_HPP #include <boost/algorithm/string/config.hpp> #include <boost/range/iterator_range_core.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/iterator.hpp> #include <boost/range/const_iterator.hpp> #include <boost/algorithm/string/find_format.hpp> #include <boost/algorithm/string/finder.hpp> #include <boost/algorithm/string/formatter.hpp> #include <boost/algorithm/string/compare.hpp> /*! \file Defines various replace algorithms. Each algorithm replaces part(s) of the input according to set of searching and replace criteria. */ namespace boost { namespace algorithm { // replace_range --------------------------------------------------------------------// //! Replace range algorithm /*! Replace the given range in the input string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param SearchRange A range in the input to be substituted \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T> inline OutputIteratorT replace_range_copy( OutputIteratorT Output, const Range1T& Input, const iterator_range< BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type>& SearchRange, const Range2T& Format) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::range_finder(SearchRange), ::boost::algorithm::const_formatter(Format)); } //! Replace range algorithm /*! \overload */ template<typename SequenceT, typename RangeT> inline SequenceT replace_range_copy( const SequenceT& Input, const iterator_range< BOOST_STRING_TYPENAME range_const_iterator<SequenceT>::type>& SearchRange, const RangeT& Format) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::range_finder(SearchRange), ::boost::algorithm::const_formatter(Format)); } //! Replace range algorithm /*! Replace the given range in the input string. The input sequence is modified in-place. \param Input An input string \param SearchRange A range in the input to be substituted \param Format A substitute string */ template<typename SequenceT, typename RangeT> inline void replace_range( SequenceT& Input, const iterator_range< BOOST_STRING_TYPENAME range_iterator<SequenceT>::type>& SearchRange, const RangeT& Format) { ::boost::algorithm::find_format( Input, ::boost::algorithm::range_finder(SearchRange), ::boost::algorithm::const_formatter(Format)); } // replace_first --------------------------------------------------------------------// //! Replace first algorithm /*! Replace the first match of the search substring in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT replace_first_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, const Range3T& Format) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::first_finder(Search), ::boost::algorithm::const_formatter(Format) ); } //! Replace first algorithm /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT replace_first_copy( const SequenceT& Input, const Range1T& Search, const Range2T& Format ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::first_finder(Search), ::boost::algorithm::const_formatter(Format) ); } //! Replace first algorithm /*! replace the first match of the search substring in the input with the format string. The input sequence is modified in-place. \param Input An input string \param Search A substring to be searched for \param Format A substitute string */ template<typename SequenceT, typename Range1T, typename Range2T> inline void replace_first( SequenceT& Input, const Range1T& Search, const Range2T& Format ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::first_finder(Search), ::boost::algorithm::const_formatter(Format) ); } // replace_first ( case insensitive ) ---------------------------------------------// //! Replace first algorithm ( case insensitive ) /*! Replace the first match of the search substring in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Format A substitute string \param Loc A locale used for case insensitive comparison \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT ireplace_first_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, const Range3T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::first_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace first algorithm ( case insensitive ) /*! \overload */ template<typename SequenceT, typename Range2T, typename Range1T> inline SequenceT ireplace_first_copy( const SequenceT& Input, const Range2T& Search, const Range1T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::first_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace first algorithm ( case insensitive ) /*! Replace the first match of the search substring in the input with the format string. Input sequence is modified in-place. Searching is case insensitive. \param Input An input string \param Search A substring to be searched for \param Format A substitute string \param Loc A locale used for case insensitive comparison */ template<typename SequenceT, typename Range1T, typename Range2T> inline void ireplace_first( SequenceT& Input, const Range1T& Search, const Range2T& Format, const std::locale& Loc=std::locale() ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::first_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } // replace_last --------------------------------------------------------------------// //! Replace last algorithm /*! Replace the last match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT replace_last_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, const Range3T& Format ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::last_finder(Search), ::boost::algorithm::const_formatter(Format) ); } //! Replace last algorithm /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT replace_last_copy( const SequenceT& Input, const Range1T& Search, const Range2T& Format ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::last_finder(Search), ::boost::algorithm::const_formatter(Format) ); } //! Replace last algorithm /*! Replace the last match of the search string in the input with the format string. Input sequence is modified in-place. \param Input An input string \param Search A substring to be searched for \param Format A substitute string */ template<typename SequenceT, typename Range1T, typename Range2T> inline void replace_last( SequenceT& Input, const Range1T& Search, const Range2T& Format ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::last_finder(Search), ::boost::algorithm::const_formatter(Format) ); } // replace_last ( case insensitive ) -----------------------------------------------// //! Replace last algorithm ( case insensitive ) /*! Replace the last match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Format A substitute string \param Loc A locale used for case insensitive comparison \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT ireplace_last_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, const Range3T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::last_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace last algorithm ( case insensitive ) /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT ireplace_last_copy( const SequenceT& Input, const Range1T& Search, const Range2T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::last_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace last algorithm ( case insensitive ) /*! Replace the last match of the search string in the input with the format string.The input sequence is modified in-place. Searching is case insensitive. \param Input An input string \param Search A substring to be searched for \param Format A substitute string \param Loc A locale used for case insensitive comparison */ template<typename SequenceT, typename Range1T, typename Range2T> inline void ireplace_last( SequenceT& Input, const Range1T& Search, const Range2T& Format, const std::locale& Loc=std::locale() ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::last_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } // replace_nth --------------------------------------------------------------------// //! Replace nth algorithm /*! Replace an Nth (zero-indexed) match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Nth An index of the match to be replaced. The index is 0-based. For negative N, matches are counted from the end of string. \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT replace_nth_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, int Nth, const Range3T& Format ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::nth_finder(Search, Nth), ::boost::algorithm::const_formatter(Format) ); } //! Replace nth algorithm /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT replace_nth_copy( const SequenceT& Input, const Range1T& Search, int Nth, const Range2T& Format ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::nth_finder(Search, Nth), ::boost::algorithm::const_formatter(Format) ); } //! Replace nth algorithm /*! Replace an Nth (zero-indexed) match of the search string in the input with the format string. Input sequence is modified in-place. \param Input An input string \param Search A substring to be searched for \param Nth An index of the match to be replaced. The index is 0-based. For negative N, matches are counted from the end of string. \param Format A substitute string */ template<typename SequenceT, typename Range1T, typename Range2T> inline void replace_nth( SequenceT& Input, const Range1T& Search, int Nth, const Range2T& Format ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::nth_finder(Search, Nth), ::boost::algorithm::const_formatter(Format) ); } // replace_nth ( case insensitive ) -----------------------------------------------// //! Replace nth algorithm ( case insensitive ) /*! Replace an Nth (zero-indexed) match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Nth An index of the match to be replaced. The index is 0-based. For negative N, matches are counted from the end of string. \param Format A substitute string \param Loc A locale used for case insensitive comparison \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT ireplace_nth_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, int Nth, const Range3T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::nth_finder(Search, Nth, is_iequal(Loc) ), ::boost::algorithm::const_formatter(Format) ); } //! Replace nth algorithm ( case insensitive ) /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT ireplace_nth_copy( const SequenceT& Input, const Range1T& Search, int Nth, const Range2T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::nth_finder(Search, Nth, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace nth algorithm ( case insensitive ) /*! Replace an Nth (zero-indexed) match of the search string in the input with the format string. Input sequence is modified in-place. Searching is case insensitive. \param Input An input string \param Search A substring to be searched for \param Nth An index of the match to be replaced. The index is 0-based. For negative N, matches are counted from the end of string. \param Format A substitute string \param Loc A locale used for case insensitive comparison */ template<typename SequenceT, typename Range1T, typename Range2T> inline void ireplace_nth( SequenceT& Input, const Range1T& Search, int Nth, const Range2T& Format, const std::locale& Loc=std::locale() ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::nth_finder(Search, Nth, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } // replace_all --------------------------------------------------------------------// //! Replace all algorithm /*! Replace all occurrences of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT replace_all_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, const Range3T& Format ) { return ::boost::algorithm::find_format_all_copy( Output, Input, ::boost::algorithm::first_finder(Search), ::boost::algorithm::const_formatter(Format) ); } //! Replace all algorithm /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT replace_all_copy( const SequenceT& Input, const Range1T& Search, const Range2T& Format ) { return ::boost::algorithm::find_format_all_copy( Input, ::boost::algorithm::first_finder(Search), ::boost::algorithm::const_formatter(Format) ); } //! Replace all algorithm /*! Replace all occurrences of the search string in the input with the format string. The input sequence is modified in-place. \param Input An input string \param Search A substring to be searched for \param Format A substitute string */ template<typename SequenceT, typename Range1T, typename Range2T> inline void replace_all( SequenceT& Input, const Range1T& Search, const Range2T& Format ) { ::boost::algorithm::find_format_all( Input, ::boost::algorithm::first_finder(Search), ::boost::algorithm::const_formatter(Format) ); } // replace_all ( case insensitive ) -----------------------------------------------// //! Replace all algorithm ( case insensitive ) /*! Replace all occurrences of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive. \param Output An output iterator to which the result will be copied \param Input An input string \param Search A substring to be searched for \param Format A substitute string \param Loc A locale used for case insensitive comparison \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T, typename Range3T> inline OutputIteratorT ireplace_all_copy( OutputIteratorT Output, const Range1T& Input, const Range2T& Search, const Range3T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_all_copy( Output, Input, ::boost::algorithm::first_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace all algorithm ( case insensitive ) /*! \overload */ template<typename SequenceT, typename Range1T, typename Range2T> inline SequenceT ireplace_all_copy( const SequenceT& Input, const Range1T& Search, const Range2T& Format, const std::locale& Loc=std::locale() ) { return ::boost::algorithm::find_format_all_copy( Input, ::boost::algorithm::first_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } //! Replace all algorithm ( case insensitive ) /*! Replace all occurrences of the search string in the input with the format string.The input sequence is modified in-place. Searching is case insensitive. \param Input An input string \param Search A substring to be searched for \param Format A substitute string \param Loc A locale used for case insensitive comparison */ template<typename SequenceT, typename Range1T, typename Range2T> inline void ireplace_all( SequenceT& Input, const Range1T& Search, const Range2T& Format, const std::locale& Loc=std::locale() ) { ::boost::algorithm::find_format_all( Input, ::boost::algorithm::first_finder(Search, is_iequal(Loc)), ::boost::algorithm::const_formatter(Format) ); } // replace_head --------------------------------------------------------------------// //! Replace head algorithm /*! Replace the head of the input with the given format string. The head is a prefix of a string of given size. If the sequence is shorter then required, whole string if considered to be the head. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param N Length of the head. For N>=0, at most N characters are extracted. For N<0, size(Input)-|N| characters are extracted. \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T> inline OutputIteratorT replace_head_copy( OutputIteratorT Output, const Range1T& Input, int N, const Range2T& Format ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::head_finder(N), ::boost::algorithm::const_formatter(Format) ); } //! Replace head algorithm /*! \overload */ template<typename SequenceT, typename RangeT> inline SequenceT replace_head_copy( const SequenceT& Input, int N, const RangeT& Format ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::head_finder(N), ::boost::algorithm::const_formatter(Format) ); } //! Replace head algorithm /*! Replace the head of the input with the given format string. The head is a prefix of a string of given size. If the sequence is shorter then required, the whole string is considered to be the head. The input sequence is modified in-place. \param Input An input string \param N Length of the head. For N>=0, at most N characters are extracted. For N<0, size(Input)-|N| characters are extracted. \param Format A substitute string */ template<typename SequenceT, typename RangeT> inline void replace_head( SequenceT& Input, int N, const RangeT& Format ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::head_finder(N), ::boost::algorithm::const_formatter(Format) ); } // replace_tail --------------------------------------------------------------------// //! Replace tail algorithm /*! Replace the tail of the input with the given format string. The tail is a suffix of a string of given size. If the sequence is shorter then required, whole string is considered to be the tail. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. \param Output An output iterator to which the result will be copied \param Input An input string \param N Length of the tail. For N>=0, at most N characters are extracted. For N<0, size(Input)-|N| characters are extracted. \param Format A substitute string \return An output iterator pointing just after the last inserted character or a modified copy of the input \note The second variant of this function provides the strong exception-safety guarantee */ template< typename OutputIteratorT, typename Range1T, typename Range2T> inline OutputIteratorT replace_tail_copy( OutputIteratorT Output, const Range1T& Input, int N, const Range2T& Format ) { return ::boost::algorithm::find_format_copy( Output, Input, ::boost::algorithm::tail_finder(N), ::boost::algorithm::const_formatter(Format) ); } //! Replace tail algorithm /*! \overload */ template<typename SequenceT, typename RangeT> inline SequenceT replace_tail_copy( const SequenceT& Input, int N, const RangeT& Format ) { return ::boost::algorithm::find_format_copy( Input, ::boost::algorithm::tail_finder(N), ::boost::algorithm::const_formatter(Format) ); } //! Replace tail algorithm /*! Replace the tail of the input with the given format sequence. The tail is a suffix of a string of given size. If the sequence is shorter then required, the whole string is considered to be the tail. The input sequence is modified in-place. \param Input An input string \param N Length of the tail. For N>=0, at most N characters are extracted. For N<0, size(Input)-|N| characters are extracted. \param Format A substitute string */ template<typename SequenceT, typename RangeT> inline void replace_tail( SequenceT& Input, int N, const RangeT& Format ) { ::boost::algorithm::find_format( Input, ::boost::algorithm::tail_finder(N), ::boost::algorithm::const_formatter(Format) ); } } // namespace algorithm // pull names to the boost namespace using algorithm::replace_range_copy; using algorithm::replace_range; using algorithm::replace_first_copy; using algorithm::replace_first; using algorithm::ireplace_first_copy; using algorithm::ireplace_first; using algorithm::replace_last_copy; using algorithm::replace_last; using algorithm::ireplace_last_copy; using algorithm::ireplace_last; using algorithm::replace_nth_copy; using algorithm::replace_nth; using algorithm::ireplace_nth_copy; using algorithm::ireplace_nth; using algorithm::replace_all_copy; using algorithm::replace_all; using algorithm::ireplace_all_copy; using algorithm::ireplace_all; using algorithm::replace_head_copy; using algorithm::replace_head; using algorithm::replace_tail_copy; using algorithm::replace_tail; } // namespace boost #endif // BOOST_REPLACE_HPP
[ "jprescott12@icloud.com" ]
jprescott12@icloud.com
1c04b9be9216d8e35e69dadbb919b95e737fdeb8
bb7645bab64acc5bc93429a6cdf43e1638237980
/Official Windows Platform Sample/Windows 8 app samples/[C++]-Windows 8 app samples/C++/Windows 8 app samples/File picker sample (Windows 8)/C++/Scenario2.xaml.h
59b28ec54c4e2d7de5a195802265b3a771912891
[ "MIT" ]
permissive
Violet26/msdn-code-gallery-microsoft
3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312
df0f5129fa839a6de8f0f7f7397a8b290c60ffbb
refs/heads/master
2020-12-02T02:00:48.716941
2020-01-05T22:39:02
2020-01-05T22:39:02
230,851,047
1
0
MIT
2019-12-30T05:06:00
2019-12-30T05:05:59
null
UTF-8
C++
false
false
995
h
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario2.xaml.h // Declaration of the Scenario2 class // #pragma once #include "pch.h" #include "Scenario2.g.h" #include "MainPage.xaml.h" namespace SDKSample { namespace FilePicker { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public ref class Scenario2 sealed { public: Scenario2(); private: MainPage^ rootPage; void PickFilesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); }; } }
[ "v-tiafe@microsoft.com" ]
v-tiafe@microsoft.com
bf9b081f4e413bc27dab59f4d2e3c33b00355ead
0f7a4119185aff6f48907e8a5b2666d91a47c56b
/sstd_utility/windows_boost/boost/metaparse/is_error.hpp
9c90c30057f3514c01f37237c03fd81be2bdea91
[]
no_license
jixhua/QQmlQuickBook
6636c77e9553a86f09cd59a2e89a83eaa9f153b6
782799ec3426291be0b0a2e37dc3e209006f0415
refs/heads/master
2021-09-28T13:02:48.880908
2018-11-17T10:43:47
2018-11-17T10:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
429
hpp
#ifndef BOOST_METAPARSE_IS_ERROR_HPP #define BOOST_METAPARSE_IS_ERROR_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/metaparse/v1/is_error.hpp> namespace boost { namespace metaparse { using v1::is_error; } } #endif
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
d7ab8194af2885ef6be2684c52ac140d841fa8de
030d422cca69abe4171add39c27a6e94068107be
/swGUI/Tests/TestRenderingSystem.DX11/TestBrushShaderCompilation.cpp
0c33a3515ba834a43378e532158e34b294a7f040
[]
no_license
nieznanysprawiciel/swLibraries
a83a218dfd037ce7b0de17fc61cc83b15f5512d6
9e553510623d3632e673833679da22c2b4420792
refs/heads/master
2021-06-04T09:16:38.469615
2020-04-04T14:11:27
2020-04-04T14:11:27
112,026,985
2
0
null
2020-04-04T14:11:29
2017-11-25T18:52:20
C++
UTF-8
C++
false
false
3,162
cpp
#include "swCommonLib/External/Catch/catch.hpp" #include "swGUI/TestFramework/DX11/TestFramework.DX11.h" #include "swGUI/TestFramework/Testers/Rendering/DrawingTester.h" #include "swGUI/TestFramework/Utils/Mocks/Rendering/FakeDrawing.h" // Include Brushes #include "swGUI/Core/Media/Brushes/SolidColorBrush.h" #include "swGUI/Core/Media/Brushes/LinearGradientBrush.h" #include "swGUI/Core/Media/Brushes/AngleGradientBrush.h" #include "swGUI/Core/Media/Brushes/ImageBrush.h" using namespace sw; using namespace sw::gui; // ================================ // // TEST_CASE( "GUI.Rendering.DX11.Brush.ShaderCompilation.SolidColorBrush", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework* framework = GetGlobalTestFramework(); FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); SolidColorBrushPtr brush = std::make_shared< SolidColorBrush >(); drawing->UpdateBrushShader( framework->GetRenderingSystem()->GetShaderProvider(), brush.get() ); auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); INFO( "[SolidColorBrush] Brush Shader compilation failed." ); CHECK( renderingData.PixelShader != nullptr ); } // ================================ // // TEST_CASE( "GUI.Rendering.DX11.Brush.ShaderCompilation.LinearGradientBrush", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework* framework = GetGlobalTestFramework(); FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); LinearGradientBrushPtr brush = std::make_shared< LinearGradientBrush >(); drawing->UpdateBrushShader( framework->GetRenderingSystem()->GetShaderProvider(), brush.get() ); auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); INFO( "[LinearGradientBrush] Brush Shader compilation failed." ); CHECK( renderingData.PixelShader != nullptr ); } // ================================ // // TEST_CASE( "GUI.Rendering.DX11.Brush.ShaderCompilation.AngleGradientBrush", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework* framework = GetGlobalTestFramework(); FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); AngleGradientBrushPtr brush = std::make_shared< AngleGradientBrush >(); drawing->UpdateBrushShader( framework->GetRenderingSystem()->GetShaderProvider(), brush.get() ); auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); INFO( "[AngleGradientBrush] Brush Shader compilation failed." ); CHECK( renderingData.PixelShader != nullptr ); } // ================================ // // TEST_CASE( "GUI.Rendering.DX11.Brush.ShaderCompilation.ImageBrush", "[GUISystem][RenderingSystem][Drawing]" ) { TestFramework* framework = GetGlobalTestFramework(); FakeDrawingPtr drawing = std::make_shared< FakeDrawing >(); ImageBrushPtr brush = std::make_shared< ImageBrush >(); drawing->UpdateBrushShader( framework->GetRenderingSystem()->GetShaderProvider(), brush.get() ); auto& renderingData = CLASS_TESTER( Drawing )::GetBrushRenderingData( drawing.get() ); INFO( "[ImageBrush] Brush Shader compilation failed." ); CHECK( renderingData.PixelShader != nullptr ); }
[ "nieznany.sprawiciel@gmail.com" ]
nieznany.sprawiciel@gmail.com
79f2dfa4e640b06ea7aed53febf2e484a6e841df
8376730666da8b6f48eb11315c952b1d6bb5db61
/Snowflake/CocosSnowflake.h
d972fed3101a1aee1f6b2eecc3565c0303e81390
[ "MIT" ]
permissive
zamberform/cocostools
869977f2586f07ea146d94d4ae50de4d5ad33c64
6bdeccd087cd9ce6d928dc892b3d59bcb6d29003
refs/heads/master
2021-01-02T08:39:19.291922
2016-11-04T11:34:46
2016-11-04T11:34:46
39,573,953
1
0
null
null
null
null
UTF-8
C++
false
false
657
h
// // CocosSnowflake.h // #include <stdint.h> namespace snowflake { //twitter snowflake method //64 63------------------22---------------------12------0 //uint64_t | 41bit timestamp | 10 bit mechine number| 12 bit sequece which is increasing| extern uint64_t get_time(); class unique_id_t{ public: unique_id_t(); ~unique_id_t(); void set_epoch(uint64_t epoch); void set_machine(int32_t machine); int64_t generate(); private: uint64_t epoch_; uint64_t time_; uint64_t machine_; int32_t sequence_; }; }
[ "brightzamber@gmail.com" ]
brightzamber@gmail.com
73ecfa648c4502809feebf995a776dabbfc6d464
b7f1b4df5d350e0edf55521172091c81f02f639e
/content/network/http_server_properties_pref_delegate.h
a2f88b593e9031558c1b6d29c4ea91a6292337ee
[ "BSD-3-Clause" ]
permissive
blusno1/chromium-1
f13b84547474da4d2702341228167328d8cd3083
9dd22fe142b48f14765a36f69344ed4dbc289eb3
refs/heads/master
2023-05-17T23:50:16.605396
2018-01-12T19:39:49
2018-01-12T19:39:49
117,339,342
4
2
NOASSERTION
2020-07-17T07:35:37
2018-01-13T11:48:57
null
UTF-8
C++
false
false
1,571
h
// Copyright 2017 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. #ifndef CONTENT_NETWORK_HTTP_SERVER_PROPERTIES_PREF_DELEGATE_H_ #define CONTENT_NETWORK_HTTP_SERVER_PROPERTIES_PREF_DELEGATE_H_ #include "base/callback.h" #include "base/macros.h" #include "components/prefs/pref_change_registrar.h" #include "net/http/http_server_properties.h" #include "net/http/http_server_properties_manager.h" class PrefRegistrySimple; namespace content { // Manages disk storage for a net::HttpServerPropertiesManager. class HttpServerPropertiesPrefDelegate : public net::HttpServerPropertiesManager::PrefDelegate { public: // The created object must be destroyed before |pref_service|. explicit HttpServerPropertiesPrefDelegate(PrefService* pref_service); ~HttpServerPropertiesPrefDelegate() override; static void RegisterPrefs(PrefRegistrySimple* pref_registry); // net::HttpServerPropertiesManager::PrefDelegate implementation. const base::DictionaryValue* GetServerProperties() const override; void SetServerProperties(const base::DictionaryValue& value, base::OnceClosure callback) override; void StartListeningForUpdates( const base::RepeatingClosure& callback) override; private: PrefService* pref_service_; PrefChangeRegistrar pref_change_registrar_; DISALLOW_COPY_AND_ASSIGN(HttpServerPropertiesPrefDelegate); }; } // namespace content #endif // CONTENT_NETWORK_HTTP_SERVER_PROPERTIES_PREF_DELEGATE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
5837209d9c302fa3b3d4802773d8392a8efae9e0
5e166ba9964663b3b988f0615003b118fa001496
/src/pub/logic/stock_util.cc
b4e0c202d07154244839aa2bfd2b67b77050c231
[ "Apache-2.0" ]
permissive
smartdata-x/strade
73242d9590a4ac9be78aee5271a9028cd671f007
3c12eb6df81edc598df0a7146ad7d9a4f20d2685
refs/heads/master
2021-04-29T08:16:08.604361
2017-03-22T02:46:58
2017-03-22T02:46:58
77,651,574
0
5
null
2017-03-22T02:46:59
2016-12-30T01:46:28
C++
UTF-8
C++
false
false
317
cc
// Copyright (c) 2015-2015 The KID Authors. All rights reserved. // Created on: 2016年10月13日 Author: zjc #include "stock_util.h" namespace stock_logic { int StockUtil::MONTH_DAY[] = { // Dec,Jan, ... ,Nov 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 }; } /* namespace stock_logic */
[ "zjchuilunmei@gmail.com" ]
zjchuilunmei@gmail.com
0e49db928c390572dbfa6c44e6c55d58bcc133f4
df65d3750bbab451b91c55affcff7aec57ee26f7
/test_parse_robotstxt/main.cpp
b16733481a2bd5204b9fdea9454e5775eb086a33
[]
no_license
pianist/multcher
7dc6bfb30f0630df47887a6f0fbfa00638aa1679
f4ea74cd48ee0a912c3addf84ec8bbe1bf24e166
refs/heads/master
2021-01-01T16:44:36.172453
2015-04-04T02:28:17
2015-04-04T02:28:17
8,693,848
0
0
null
null
null
null
UTF-8
C++
false
false
837
cpp
#include <multcher/robotstxt.hpp> #include <errno.h> #include <string.h> #include <coda/system.h> void test_url(const multcher::domain_robotstxt_t& rtxt, const char* url) { std::string s(url); printf("%s: %s\n", rtxt.check_uri(s) ? "A" : "D", url); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "Usage: ./test_parse_robotstxt robots.txt\n"); return -1; } coda_strt s; if (coda_mmap_file(&s, argv[1]) < 0) { fprintf(stderr, "Can't mmap %s: (%d) %s\n", argv[1], errno, strerror(errno)); return -1; } std::string src(s.data, s.size); multcher::domain_robotstxt_t rtxt; rtxt.parse_from_source(src.c_str(), "bla"); while (!feof(stdin)) { char buf[1024]; if (!fgets(buf, 1024, stdin)) break; char* nl = strpbrk(buf, "\r\n"); if (nl) *nl = 0; test_url(rtxt, buf); } return 0; }
[ "pianist@volga.usrsrc.ru" ]
pianist@volga.usrsrc.ru
ab59b94221e3a2d9f73b60fea708ec4db070e7d1
19c250420c9830c47358f8241025fb9d932fd90f
/ldr/pe_file.h
6e3c34c0c571b73dc8a8c3eed3e6435f70b94525
[]
no_license
redplait/armpatched
b2d6a5a16676f41afce625eaecc24d166a8d9bf4
46ade916717dedbf245a840427b3dac66f6977ae
refs/heads/master
2022-05-17T18:36:41.358674
2022-05-01T10:34:31
2022-05-01T10:34:31
253,850,245
41
10
null
null
null
null
UTF-8
C++
false
false
10,021
h
#pragma once #include "exports_dict.h" #include "load_config.h" /* Standart PE relocation thunk */ typedef struct _RELOC { WORD Offset : 12; WORD Type : 04; } RELOC, *PRELOC; // for auto free struct dumb_free_ptr { dumb_free_ptr() { m_ptr = NULL; } dumb_free_ptr(void *arg) : m_ptr(arg) { } ~dumb_free_ptr() { if ( m_ptr != NULL ) free(m_ptr); } void operator=(void *arg) { if ( (m_ptr != NULL) && (m_ptr != arg) ) free(m_ptr); m_ptr = arg; } void reset() { m_ptr = NULL; } protected: void *m_ptr; }; struct one_export { one_export(); ~one_export(); char *name; WORD ordinal; DWORD rva; int forwarded; }; struct export_address_table { export_address_table() : m_size(0), m_start(0), m_eat(NULL), m_names(NULL) {} ~export_address_table(); int init(DWORD size, DWORD start); DWORD m_size; DWORD m_start; PDWORD m_eat; struct one_export **m_names; }; struct one_section { DWORD va; DWORD vsize; DWORD offset; DWORD size; DWORD flags; char name[IMAGE_SIZEOF_SHORT_NAME + 1]; }; // dirty hacks for export names struct export_name { export_name(export_name const& s) { name = s.name; } export_name(const char *str) { name = str; } bool operator<(const export_name& s) const { return (strcmp(name, s.name) < 0); } bool operator==(const export_name& s) const { return (0 == strcmp(name, s.name)); } const char *name; }; class arm64_pe_file { public: arm64_pe_file(const wchar_t *mod_name); ~arm64_pe_file(); int read(int with_dump); inline DWORD entry_point() const { return m_hdr64.OptionalHeader.AddressOfEntryPoint; } // exports inline DWORD export_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; } inline DWORD export_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; } inline int get_export(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_EXPORT); } // imports inline DWORD import_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; } inline DWORD import_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } int get_import(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_IMPORT); } // delayed imports inline DWORD delayed_import_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress; } inline DWORD delayed_import_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size; } int get_delayed_import(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); } // bound imports inline DWORD bound_import_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].VirtualAddress; } inline DWORD bound_import_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size; } int get_bound_import(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT); } // for resources inline DWORD rsrc_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress; } inline DWORD rsrc_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size; } int get_rsrc(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_RESOURCE); } // security inline DWORD security_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; } inline DWORD security_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; } int get_security(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_SECURITY); } // relocs inline DWORD rel_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress; } inline DWORD rel_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size; } int get_rel(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_BASERELOC); } // arch inline DWORD arch_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress; } inline DWORD arch_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size; } int get_arch(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_ARCHITECTURE); } // GLOBALPTR inline DWORD gp_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress; } inline DWORD gp_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size; } int get_gp(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_GLOBALPTR); } // for TLS inline DWORD tls_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress; } inline DWORD tls_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size; } int get_tls(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_TLS); } // for IAT inline DWORD iat_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress; } inline DWORD iat_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size; } int get_iat(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_IAT); } // load config inline DWORD load_config_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size; } inline DWORD load_config_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress; } inline int get_load_config(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG); } // exceptions inline DWORD exceptions_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress; } inline DWORD exceptions_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size; } inline int get_exceptions(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_EXCEPTION); } // .NET inline DWORD net_addr() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress; } inline DWORD net_size() const { return m_hdr64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size; } inline int get_net(DWORD &addr, DWORD &size) const { return get_xxx(addr, size, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR); } // other fields inline PBYTE base_addr() const { return m_mz; } inline ULONGLONG image_base() const { return m_hdr64.OptionalHeader.ImageBase; } // search section with name const one_section *find_section_by_name(const char *) const; // search only in inited section data const one_section *find_section_rva(DWORD addr) const; // search in whole section content const one_section *find_section_v(DWORD addr) const; // return list of executable sections void get_exec_sections(std::list<one_section> &out_list) const; // return list of all sections with some content void get_nonempty_sections(std::list<one_section> &out_list, int with_resource = 0) const; // exports exports_dict *get_export_dict(); // read relocs PBYTE read_relocs(DWORD &rsize); // load config PBYTE read_load_config(DWORD &readed); void dump_rfg_relocs(); // manual sunset int map_pe(int verb_mode); int apply_relocs(); // sanitizers inline int is_inside(PBYTE psp) const { if ( m_mz == NULL ) return 0; if ( psp < m_mz ) return 0; return (psp < m_mz + m_mz_size); } const char *get_exp_name() const { if ( NULL == m_mz || !m_exp_name ) return NULL; PBYTE res = m_mz + m_exp_name; if ( !is_inside(res) ) return NULL; return (const char *)res; } protected: inline int get_xxx(DWORD &addr, DWORD &size, int idx) const { addr = m_hdr64.OptionalHeader.DataDirectory[idx].VirtualAddress; size = m_hdr64.OptionalHeader.DataDirectory[idx].Size; return (addr && size); } inline DWORD align_size(DWORD size) { return (size + 0xfff) & ~0xfff; } int read_exports(); char *read_ename(DWORD rva); void clean_exports(); std::wstring m_name; std::list<one_section> m_sects; // for file mapping PBYTE m_mz; size_t m_mz_size; FILE *m_fp; IMAGE_NT_HEADERS64 m_hdr64; DWORD m_pe_off; // exports DWORD m_exp_base; // ordinal base DWORD m_exp_name; // IMAGE_EXPORT_DIRECTORY.Name std::map<export_name, struct one_export *> m_enames; std::map<WORD, struct one_export *> m_eords; size_t m_exports_total_size; // EAT export_address_table m_eat; // load config DWORD m_lc_readed; rfg_IMAGE_LOAD_CONFIG_DIRECTORY64 m_lc; };
[ "" ]
6041acfc4666bd58d5533e21e34bb19429a19c56
0e2a1d22585d9dd6643ac806063b68ce01c34a54
/kpl_phylogenetic/kpl_likelihood.h
95af5a1e38ef10c9a553beb9c269ace77c9e7d1e
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kellerberrin/KGL_Gene
d55a6d95e1c1b4b2e5607d4a13277fbefd1d071d
43d7abaf1b073315d792b8d4549ee804b9794e50
refs/heads/master
2023-08-25T03:50:26.356847
2023-08-19T14:07:21
2023-08-19T14:07:21
101,985,829
2
0
null
null
null
null
UTF-8
C++
false
false
4,022
h
// // Created by kellerberrin on 12/12/19. // #ifndef KPL_LIKELIHOOD_H #define KPL_LIKELIHOOD_H #include "kpl_model.h" #include "kpl_tree.h" #include "kpl_geneticdata.h" #include "kpl_xstrom.h" #include "libhmsbeagle/beagle.h" #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <boost/shared_ptr.hpp> #include <boost/range/adaptor/reversed.hpp> #include <map> namespace kellerberrin::phylogenetic { // organization level namespace class Likelihood { public: using SharedPtr = std::shared_ptr<Likelihood>; Likelihood(); ~Likelihood(); void setRooted(bool is_rooted); void setPreferGPU(bool prefer_gpu); void setAmbiguityEqualsMissing(bool ambig_equals_missing); bool usingStoredData() const { return _using_data; } void useStoredData(bool using_data) { _using_data = using_data; } void useUnderflowScaling(bool do_scaling); std::string beagleLibVersion() const; std::string availableResources() const; std::string usedResources() const; void initBeagleLib(); void finalizeBeagleLib(bool use_exceptions); double calcLogLikelihood(const Tree& tree); Data::SharedPtr getData(); void setData(Data::SharedPtr d); void clear(); unsigned calcNumEdgesInFullyResolvedTree() const; unsigned calcNumInternalsInFullyResolvedTree() const; std::shared_ptr<Model> getModel(); void setModel(std::shared_ptr<Model> model_ptr); private: struct InstanceInfo { int handle{-1}; int resourcenumber{-1}; std::string resourcename; unsigned nstates{0}; unsigned nratecateg{0}; unsigned npatterns{0}; unsigned partial_offset{0}; unsigned tmatrix_offset{0}; bool invarmodel{false}; std::vector<unsigned> subsets; }; using instance_pair_t = std::pair<unsigned, int>; unsigned getPartialIndex(Node::PtrNode nd, InstanceInfo & info) const; unsigned getTMatrixIndex(Node::PtrNode nd, InstanceInfo & info, unsigned subset_index) const; void updateInstanceMap(instance_pair_t & p, unsigned subset); void newInstance(unsigned nstates, int nrates, std::vector<unsigned> & subset_indices); void setTipStates(); void setTipPartials(); void setPatternPartitionAssignments(); void setPatternWeights(); void setAmongSiteRateHeterogenetity(); void setModelRateMatrix(); void addOperation(InstanceInfo & info, Node::PtrNode nd, Node::PtrNode lchild, Node::PtrNode rchild, unsigned subset_index); void defineOperations(const Tree& tree); void updateTransitionMatrices(); void calculatePartials(); double calcInstanceLogLikelihood(InstanceInfo & inst, const Tree& tree); // Setup Beagle. [[nodiscard]] static int setBeagleEigenDecomposition(std::shared_ptr<const Model> model_ptr, int beagle_instance, unsigned subset, unsigned instance_subset); [[nodiscard]] static int setBeagleStateFrequencies(std::shared_ptr<const Model> model_ptr, int beagle_instance, unsigned subset, unsigned instance_subset); [[nodiscard]] static int setBeagleAmongSiteRateVariationRates(std::shared_ptr<const Model> model_ptr, int beagle_instance, unsigned subset, unsigned instance_subset); [[nodiscard]] static int setBeagleAmongSiteRateVariationProbs(std::shared_ptr<const Model> model_ptr, int beagle_instance, unsigned subset, unsigned instance_subset); std::shared_ptr<Model> _model; std::vector<InstanceInfo> _instances; std::map<int, std::string> _beagle_error; std::map<int, std::vector<int> > _operations; std::map<int, std::vector<int> > _pmatrix_index; std::map<int, std::vector<double> > _edge_lengths; std::vector<int> _subset_indices; std::vector<int> _parent_indices; std::vector<int> _child_indices; std::vector<int> _tmatrix_indices; std::vector<int> _weights_indices; std::vector<int> _freqs_indices; std::vector<int> _scaling_indices; Data::SharedPtr _data; unsigned _ntaxa; bool _rooted; bool _prefer_gpu; bool _ambiguity_equals_missing; bool _underflow_scaling; bool _using_data; }; } // end Namespace #endif // KPL_LIKELIHOOD_H
[ "james.duncan.mcculloch@gmail.com" ]
james.duncan.mcculloch@gmail.com
b248fd14e2307f50d3a95061b2d2003835901b46
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/PhysicsAnalysis/D3PDMaker/MissingETD3PDMaker/MissingETD3PDMaker/MissingETCompAssociationTool.h
881cba34ae323b5f215a0e532c4d1ffb43c26265
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
2,791
h
// This file's extension implies that it's C, but it's really -*- C++ -*-. /* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ // $Id$ /** * @file MissingETD3PDMaker/MissingETD3PDMaker/MissingETCompAssociationTool.h * @author Jet Goodson <jgoodson@cern.ch>, based on similar tools by scott snyder <snyder@bnl.gov> * @date September, 2010 * @brief Associate electron to MET Composition object */ #ifndef MISSINGETD3PDMAKER_MISSINGETCOMPASSOCIATIONTOOL_H #define MISSINGETD3PDMAKER_MISSINGETCOMPASSOCIATIONTOOL_H #include "D3PDMakerInterfaces/IObjGetterTool.h" #include "D3PDMakerUtils/SingleAssociationTool.h" #include "EventKernel/INavigable4Momentum.h" #include "GaudiKernel/ToolHandle.h" #include "MissingETEvent/MissingET.h" #include "MissingETEvent/MissingEtTruth.h" #include "MissingETEvent/MissingEtCalo.h" #include "MissingETEvent/MissingETComposition.h" namespace D3PD { /** * @brief Associate to particle closest in DR. * * This is a single association tool. * Given an @c INavigable4Momentum object and a container of PAU::gamma objects, * return the object in the container that is associated with the original object. * * Parameters: * Getter - ICollectionGetterTool instance defining the target collection. * */ class MissingETCompAssociationTool : public SingleAssociationTool<INavigable4Momentum, MissingETComposition> { public: typedef SingleAssociationTool<INavigable4Momentum, MissingETComposition> Base; /** * @brief Standard Gaudi tool constructor. * @param type The name of the tool type. * @param name The tool name. * @param parent The tool's Gaudi parent. */ MissingETCompAssociationTool (const std::string& type, const std::string& name, const IInterface* parent); /// Standard Gaudi initialize method. virtual StatusCode initialize(); /** * @brief Create any needed tuple variables. */ virtual StatusCode book(); /** * @brief Return the target object. * @param p The source object for the association. * * Return the target of the association, or 0. */ virtual const MissingETComposition* get(const INavigable4Momentum& p); template<class T> void weighter(const T* objecto, const MissingETComposition* compo); void weighter(const INavigable4Momentum* objecto, const MissingETComposition* compo); private: /// Property: The getter for the target collection. ToolHandle<IObjGetterTool> m_getter; bool m_allowMissing; std::string m_objectType; std::vector<float> *m_vec_weight_px; std::vector<float> *m_vec_weight_py; std::vector<float> *m_vec_weight_ET; std::vector<unsigned int> *m_vec_statusWord; //float *m_px; }; } // namespace D3PD #endif // not MISSINGETD3PDMAKER_MISSINGETCOMPASSOCIATIONTOOL_H
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
aabf073d310e7136e373a07a8f81918874027335
268f1d8aeffd644a9402b5dcde4c92e90c7bcc39
/D03/ex04/SuperTrap.hpp
ff0e14ed989cbd45215e54eb24ba9d9e330d2385
[]
no_license
rbakker96/CPP
1e89cc9c2768da97548e5497815db2748b74e46d
fd5a4546511ef80c57e8c01826be994e052f953f
refs/heads/master
2023-02-10T15:40:11.558328
2021-01-11T15:07:53
2021-01-11T15:07:53
281,352,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,420
hpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* SuperTrap.hpp :+: :+: */ /* +:+ */ /* By: roybakker <roybakker@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/08/18 11:54:44 by roybakker #+# #+# */ /* Updated: 2020/08/18 16:29:59 by roybakker ######## odam.nl */ /* */ /* ************************************************************************** */ #ifndef SUPERTRAP_CLASS_H #define SUPERTRAP_CLASS_H #include <string> #include "NinjaTrap.hpp" #include "FragTrap.hpp" class SuperTrap : public FragTrap, public NinjaTrap { public: SuperTrap(void); SuperTrap(std::string name); SuperTrap(SuperTrap const &src); ~SuperTrap(void); SuperTrap & operator=(SuperTrap const &rhs); void vaulthunter_dot_exe(std::string const & target); void ninjaShoebox(ScavTrap & target); void ninjaShoebox(FragTrap & target); void ninjaShoebox(NinjaTrap & target); }; #endif
[ "57988535+rbakker96@users.noreply.github.com" ]
57988535+rbakker96@users.noreply.github.com
c1d3bbd273e51a3a0e4793e1a20526b6a3a7c23d
105cea794f718d34d0c903f1b4b111fe44018d0e
/content/browser/loader/keep_alive_url_loader.cc
debe3ca6f13bba4093c10c1cdcd5bc7cd0fa9753
[ "BSD-3-Clause" ]
permissive
blueboxd/chromium-legacy
27230c802e6568827236366afe5e55c48bb3f248
e6d16139aaafff3cd82808a4660415e762eedf12
refs/heads/master.lion
2023-08-12T17:55:48.463306
2023-07-21T22:25:12
2023-07-21T22:25:12
242,839,312
164
12
BSD-3-Clause
2022-03-31T17:44:06
2020-02-24T20:44:13
null
UTF-8
C++
false
false
26,827
cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/loader/keep_alive_url_loader.h" #include <vector> #include "base/check_is_test.h" #include "base/functional/bind.h" #include "base/functional/callback_forward.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/typed_macros.h" #include "content/browser/renderer_host/frame_tree_node.h" #include "content/browser/renderer_host/policy_container_host.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/url_loader_throttles.h" #include "content/public/common/url_utils.h" #include "net/base/load_flags.h" #include "net/http/http_request_headers.h" #include "services/network/public/cpp/content_security_policy/content_security_policy.h" #include "services/network/public/cpp/content_security_policy/csp_context.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/url_loader_completion_status.h" #include "services/network/public/mojom/content_security_policy.mojom.h" #include "services/network/public/mojom/early_hints.mojom.h" #include "services/network/public/mojom/fetch_api.mojom-shared.h" #include "services/network/public/mojom/url_request.mojom.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" namespace content { namespace { // A convenient holder to aggregate modified header fields for redirect. struct ModifiedHeaders { ModifiedHeaders() = default; ~ModifiedHeaders() = default; // Not copyable. ModifiedHeaders(const ModifiedHeaders&) = delete; ModifiedHeaders& operator=(const ModifiedHeaders&) = delete; void MergeFrom(const ModifiedHeaders& other) { for (auto& other_removed_header : other.removed_headers) { if (!base::Contains(removed_headers, other_removed_header)) { removed_headers.emplace_back(std::move(other_removed_header)); } } modified_headers.MergeFrom(other.modified_headers); modified_cors_exempt_headers.MergeFrom(other.modified_cors_exempt_headers); } std::vector<std::string> removed_headers; net::HttpRequestHeaders modified_headers; net::HttpRequestHeaders modified_cors_exempt_headers; }; // A ContentSecurityPolicy context for KeepAliveURLLoader. class KeepAliveURLLoaderCSPContext final : public network::CSPContext { public: // network::CSPContext override: void ReportContentSecurityPolicyViolation( network::mojom::CSPViolationPtr violation_params) final { // TODO(crbug.com/1356128): Support reporting violation w/o renderer. } void SanitizeDataForUseInCspViolation( network::mojom::CSPDirectiveName directive, GURL* blocked_url, network::mojom::SourceLocation* source_location) const final { // TODO(crbug.com/1356128): Support reporting violation w/o renderer. } }; // Checks if `url` is allowed by the set of Content-Security-Policy `policies`. // Violation will not be reported back to renderer, as this function must be // called after renderer is gone. // TODO(crbug.com/1431165): Isolated world's CSP is not handled. bool IsRedirectAllowedByCSP( const std::vector<network::mojom::ContentSecurityPolicyPtr>& policies, const GURL& url, const GURL& url_before_redirects, bool has_followed_redirect) { // Sets the CSP Directive for fetch() requests. See // https://w3c.github.io/webappsec-csp/#directive-connect-src // https://fetch.spec.whatwg.org/#destination-table auto directive = network::mojom::CSPDirectiveName::ConnectSrc; // Sets empty as source location is only used when reporting back to renderer. auto empty_source_location = network::mojom::SourceLocation::New(); auto disposition = network::CSPContext::CheckCSPDisposition::CHECK_ALL_CSP; // When reaching here, renderer should have be gone, or at least // `KeepAliveURLLoader::forwarding_client_` is disconnected. return KeepAliveURLLoaderCSPContext().IsAllowedByCsp( policies, directive, url, url_before_redirects, has_followed_redirect, /*is_response_check=*/false, empty_source_location, disposition, /*is_form_submission=*/false); } } // namespace // A custom `blink::URLLoaderThrottle` delegate that only handles relevant // actions. // // Note that a delegate may be called from a throttle asynchronously in a // different thread, e.g. `safe_browsing::BrowserURLLoaderThrottle` runs in IO // thread http://crbug.com/1057253. // // Throttles calling these methods must not be destroyed synchronously. class KeepAliveURLLoader::ThrottleDelegate final : public blink::URLLoaderThrottle::Delegate { public: explicit ThrottleDelegate(base::WeakPtr<KeepAliveURLLoader> loader) : loader_(std::move(loader)), loader_weak_ptr_factory_( std::make_unique<base::WeakPtrFactory<KeepAliveURLLoader>>( loader_.get())) {} // Not copyable. ThrottleDelegate(const ThrottleDelegate&) = delete; ThrottleDelegate& operator=(const ThrottleDelegate&) = delete; // blink::URLLoaderThrottle::Delegate overrides: // Asks `loader_` to abort itself asynchronously. void CancelWithError(int error, base::StringPiece custom_reason) override { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&KeepAliveURLLoader::OnComplete, loader_weak_ptr_factory_->GetWeakPtr(), network::URLLoaderCompletionStatus(error))); return; } if (IsLoaderAliveOnUI()) { GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&KeepAliveURLLoader::OnComplete, loader_->GetWeakPtr(), network::URLLoaderCompletionStatus(error))); } } void Resume() override { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&KeepAliveURLLoader::ResumeReadingBodyFromNet, loader_weak_ptr_factory_->GetWeakPtr())); return; } if (IsLoaderAliveOnUI()) { GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&KeepAliveURLLoader::ResumeReadingBodyFromNet, loader_->GetWeakPtr())); } } void PauseReadingBodyFromNet() override { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&KeepAliveURLLoader::PauseReadingBodyFromNet, loader_weak_ptr_factory_->GetWeakPtr())); return; } if (IsLoaderAliveOnUI()) { GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&KeepAliveURLLoader::PauseReadingBodyFromNet, loader_->GetWeakPtr())); } } void RestartWithFlags(int additional_load_flags) override { NOTREACHED(); } void RestartWithURLResetAndFlags(int additional_load_flags) override { NOTREACHED(); } private: // `loader_` is alive and ready to take actions triggered from in-browser // throttle, i.e. `loader_` is disconnected from renderer. Otherwise, returns // false to avoid early termination when a copy of the same throttle will also // be executed in renderer. // Must be called on UI thread. bool IsLoaderAliveOnUI() const { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return loader_ && !loader_->IsRendererConnected(); } base::WeakPtr<KeepAliveURLLoader> loader_; // `loader_` lives in UI thread. This factory helps verify if `loader_` is // still available from other threads. std::unique_ptr<base::WeakPtrFactory<KeepAliveURLLoader>> loader_weak_ptr_factory_; }; // Maintains a `blink::URLLoaderThrottle` and its delegate's lifetime. class KeepAliveURLLoader::ThrottleEntry { public: ThrottleEntry(base::WeakPtr<KeepAliveURLLoader> loader, std::unique_ptr<blink::URLLoaderThrottle> loader_throttle) : delegate_(std::make_unique<ThrottleDelegate>(std::move(loader))), throttle_(std::move(loader_throttle)) { CHECK(delegate_); CHECK(throttle_); throttle_->set_delegate(delegate_.get()); } ~ThrottleEntry() { // Both `delegate_` and `throttle_` are about to be destroyed, but // `throttle_` may refer to `delegate_` in its dtor. Hence, clear the // pointer from `throttle_` to avoid any UAF. throttle_->set_delegate(nullptr); } // Not copyable. ThrottleEntry(const ThrottleEntry&) = delete; ThrottleEntry& operator=(const ThrottleEntry&) = delete; blink::URLLoaderThrottle& throttle() { return *throttle_; } private: // `delegate_` must live longer than `throttle_`. std::unique_ptr<ThrottleDelegate> delegate_; std::unique_ptr<blink::URLLoaderThrottle> throttle_; }; KeepAliveURLLoader::KeepAliveURLLoader( int32_t request_id, uint32_t options, const network::ResourceRequest& resource_request, mojo::PendingRemote<network::mojom::URLLoaderClient> forwarding_client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory, scoped_refptr<PolicyContainerHost> policy_container_host, BrowserContext* browser_context, base::PassKey<KeepAliveURLLoaderService>, URLLoaderThrottlesGetter url_loader_throttles_getter_for_testing) : request_id_(request_id), resource_request_(resource_request), forwarding_client_(std::move(forwarding_client)), policy_container_host_(std::move(policy_container_host)), initial_url_(resource_request.url), last_url_(resource_request.url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); CHECK(network_loader_factory); CHECK(policy_container_host_); CHECK(!resource_request.trusted_params); CHECK(browser_context); TRACE_EVENT("loading", "KeepAliveURLLoader::KeepAliveURLLoader", "request_id", request_id_, "url", last_url_); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("loading", "KeepAliveURLLoader", request_id_, "url", last_url_); // Asks the network service to create a URL loader with passed in params. network_loader_factory->CreateLoaderAndStart( loader_.BindNewPipeAndPassReceiver(), request_id, options, resource_request, loader_receiver_.BindNewPipeAndPassRemote(), traffic_annotation); loader_receiver_.set_disconnect_handler(base::BindOnce( &KeepAliveURLLoader::OnNetworkConnectionError, base::Unretained(this))); forwarding_client_.set_disconnect_handler(base::BindOnce( &KeepAliveURLLoader::OnRendererConnectionError, base::Unretained(this))); { std::vector<std::unique_ptr<blink::URLLoaderThrottle>> content_throttles = url_loader_throttles_getter_for_testing ? url_loader_throttles_getter_for_testing.Run() : CreateContentBrowserURLLoaderThrottlesForKeepAlive( resource_request_, browser_context, // When `throttles_` need to be run by this loader, the // renderer should have be gone. /*wc_getter=*/base::BindRepeating([]() -> WebContents* { return nullptr; }), FrameTreeNode::kFrameTreeNodeInvalidId); for (auto& content_throttle : content_throttles) { throttle_entries_.emplace_back(std::make_unique<ThrottleEntry>( GetWeakPtr(), std::move(content_throttle))); } } // These throttles are also run by `blink::ThrottlingURLLoader`. However, they // have to be re-run here in case of handling in-browser redirects. // There is already a similar use case that also runs throttles in browser in // `SearchPrefetchRequest::StartPrefetchRequest()`. The review discussion in // https://crrev.com/c/2552723/3 suggests that running them again in browser // is fine. for (auto& throttle_entry : throttle_entries_) { TRACE_EVENT("loading", "KeepAliveURLLoader::KeepAliveURLLoader.WillStartRequest"); bool throttle_deferred = false; auto weak_ptr = GetWeakPtr(); // Marks delegate to ignore abort requests if this is connected to renderer. throttle_entry->throttle().WillStartRequest(&resource_request_, &throttle_deferred); if (!weak_ptr) { // `this` is already destroyed by throttle. return; } if (!IsRendererConnected() && throttle_deferred) { // Only processes a throttle result if this loader is already disconnected // from renderer. We treat deferring as canceling the request. // See also `ThrottleDelegate` which may cancel request asynchronously. OnComplete(network::URLLoaderCompletionStatus(net::ERR_ABORTED)); return; } } } KeepAliveURLLoader::~KeepAliveURLLoader() { TRACE_EVENT("loading", "KeepAliveURLLoader::~KeepAliveURLLoader", "request_id", request_id_); TRACE_EVENT_NESTABLE_ASYNC_END0("loading", "KeepAliveURLLoader", request_id_); } void KeepAliveURLLoader::set_on_delete_callback( OnDeleteCallback on_delete_callback) { on_delete_callback_ = std::move(on_delete_callback); } base::WeakPtr<KeepAliveURLLoader> KeepAliveURLLoader::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void KeepAliveURLLoader::FollowRedirect( const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const net::HttpRequestHeaders& modified_cors_exempt_headers, const absl::optional<GURL>& new_url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::FollowRedirect", "request_id", request_id_, "url", new_url); // Forwards the action to `loader_` in the network service. loader_->FollowRedirect(removed_headers, modified_headers, modified_cors_exempt_headers, new_url); } void KeepAliveURLLoader::SetPriority(net::RequestPriority priority, int intra_priority_value) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::SetPriority", "request_id", request_id_); // Forwards the action to `loader_` in the network service. loader_->SetPriority(priority, intra_priority_value); } void KeepAliveURLLoader::PauseReadingBodyFromNet() { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::FollowRedirect", "request_id", request_id_); if (IsRendererConnected()) { // If the renderer is alive, simply forwards the action to the network // service as the checks are already handled in the renderer. loader_->PauseReadingBodyFromNet(); return; } if (paused_reading_body_from_net_count_ == 0) { // Only sends the action to `loader_` in the network service once before // resuming. loader_->PauseReadingBodyFromNet(); } paused_reading_body_from_net_count_++; if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->PauseReadingBodyFromNetProcessed(this); } } // TODO(crbug.com/1356128): Add test coverage. void KeepAliveURLLoader::ResumeReadingBodyFromNet() { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::ResumeReadingBodyFromNet", "request_id", request_id_); if (IsRendererConnected()) { // If the renderer is alive, simply forwards the action to the network // service as the checks are already handled in the renderer. loader_->ResumeReadingBodyFromNet(); return; } if (paused_reading_body_from_net_count_ == 1) { // Sends the action to `loader_` in the network service. loader_->ResumeReadingBodyFromNet(); } paused_reading_body_from_net_count_--; if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->ResumeReadingBodyFromNetProcessed(this); } } void KeepAliveURLLoader::OnReceiveEarlyHints( network::mojom::EarlyHintsPtr early_hints) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnReceiveEarlyHints", "request_id", request_id_); if (IsRendererConnected()) { // The renderer is alive, forwards the action. forwarding_client_->OnReceiveEarlyHints(std::move(early_hints)); return; } // TODO(crbug.com/1356128): Handle in browser process. } void KeepAliveURLLoader::OnReceiveResponse( network::mojom::URLResponseHeadPtr response, mojo::ScopedDataPipeConsumerHandle body, absl::optional<mojo_base::BigBuffer> cached_metadata) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnReceiveResponse", "request_id", request_id_, "url", last_url_); has_received_response_ = true; // TODO(crbug.com/1424731): The renderer might exit before `OnReceiveRedirect` // or `OnReceiveResponse` is called, or during their execution. In such case, // `forwarding_client_` can't finish response handling. Figure out a way to // negotiate shutdown timing via RenderFrameHostImpl::OnUnloadAck() and // invalidate `forwarding_client_`. if (IsRendererConnected()) { // The renderer is alive, forwards the action. // The receiver may fail to finish reading `response`, so response caching // is not guaranteed. forwarding_client_->OnReceiveResponse(std::move(response), std::move(body), std::move(cached_metadata)); // TODO(crbug.com/1422645): Ensure that attributionsrc response handling is // migrated to browser process. if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->OnReceiveResponseForwarded(this); } return; } if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->OnReceiveResponseProcessed(this); } // No need to wait for `OnComplete()`. // This loader should be deleted immediately to avoid hanged requests taking // up resources. DeleteSelf(); // DO NOT touch any members after this line. `this` is already deleted. } void KeepAliveURLLoader::OnReceiveRedirect( const net::RedirectInfo& redirect_info, network::mojom::URLResponseHeadPtr head) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnReceiveRedirect", "request_id", request_id_); // TODO(crbug.com/1424731): The renderer might exit before `OnReceiveRedirect` // or `OnReceiveResponse` is called, or during their execution. In such case, // `forwarding_client_` can't finish response handling. Figure out a way to // negotiate shutdown timing via RenderFrameHostImpl::OnUnloadAck() and // invalidate `forwarding_client_`. if (IsRendererConnected()) { // The renderer is alive, forwards the action. // Redirects must be handled by the renderer so that it know what URL the // response come from when parsing responses. forwarding_client_->OnReceiveRedirect(redirect_info, std::move(head)); if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->OnReceiveRedirectForwarded(this); } return; } // Handles redirect in browser. See also the call sequence from renderer: // https://docs.google.com/document/d/1ZzxMMBvpqn8VZBZKnb7Go8TWjnrGcXuLS_USwVVRUvY/edit#heading=h.6uwqtijf7dvd // Runs throttles from content embedder. ModifiedHeaders modified; for (auto& throttle_entry : throttle_entries_) { TRACE_EVENT("loading", "KeepAliveURLLoader::OnReceiveRedirect.WillRedirectRequest"); bool throttle_deferred = false; ModifiedHeaders throttle_modified; net::RedirectInfo redirect_info_copy = redirect_info; auto weak_ptr = GetWeakPtr(); throttle_entry->throttle().WillRedirectRequest( &redirect_info_copy, *head, &throttle_deferred, &throttle_modified.removed_headers, &throttle_modified.modified_headers, &throttle_modified.modified_cors_exempt_headers); if (!weak_ptr) { // `this` is already destroyed by throttle. return; } CHECK_EQ(redirect_info_copy.new_url, redirect_info.new_url) << "KeepAliveURLLoader doesn't support throttles changing the URL."; if (throttle_deferred) { // We treat deferring as canceling the request. // See also `ThrottleDelegate` which may cancel request asynchronously. OnComplete(network::URLLoaderCompletionStatus(net::ERR_ABORTED)); return; } modified.MergeFrom(throttle_modified); } if (net::Error err = WillFollowRedirect(redirect_info); err != net::OK) { OnComplete(network::URLLoaderCompletionStatus(err)); return; } // TODO(crbug.com/1356128): Replicate critical logic from the followings: // `ResourceRequestSender::OnReceivedRedirect()`. // `URLLoader::Context::OnReceivedRedirect(). // TODO(crbug.com/1356128): Figure out how to deal with lost ResourceFetcher's // counter & dev console logging (renderer is dead). resource_request_.url = redirect_info.new_url; resource_request_.site_for_cookies = redirect_info.new_site_for_cookies; resource_request_.referrer = GURL(redirect_info.new_referrer); resource_request_.referrer_policy = redirect_info.new_referrer_policy; // Ask the network service to follow the redirect. last_url_ = GURL(redirect_info.new_url); // TODO(crbug.com/1393520): Remove Authorization header upon cross-origin // redirect. if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->OnReceiveRedirectProcessed(this); } // Follows redirect only after all current throttle UI tasks are executed. // Note: there may be throttles running in IO thread, which may send signals // in between `FollowRedirect()` and the next `OnReceiveRedirect()` or // `OnReceiveResponse()`. FollowRedirect(modified.removed_headers, modified.modified_headers, modified.modified_cors_exempt_headers, /*new_url=*/absl::nullopt); } void KeepAliveURLLoader::OnUploadProgress(int64_t current_position, int64_t total_size, base::OnceCallback<void()> callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnUploadProgress", "request_id", request_id_); if (IsRendererConnected()) { // The renderer is alive, forwards the action. forwarding_client_->OnUploadProgress(current_position, total_size, std::move(callback)); return; } // TODO(crbug.com/1356128): Handle in the browser process. } void KeepAliveURLLoader::OnTransferSizeUpdated(int32_t transfer_size_diff) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnTransferSizeUpdated", "request_id", request_id_); if (IsRendererConnected()) { // The renderer is alive, forwards the action. forwarding_client_->OnTransferSizeUpdated(transfer_size_diff); return; } // TODO(crbug.com/1356128): Handle in the browser process. } void KeepAliveURLLoader::OnComplete( const network::URLLoaderCompletionStatus& completion_status) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnComplete", "request_id", request_id_); if (IsRendererConnected()) { // The renderer is alive, forwards the action. forwarding_client_->OnComplete(completion_status); if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->OnCompleteForwarded(this, completion_status); } DeleteSelf(); // DO NOT touch any members after this line. `this` is already deleted. return; } // TODO(crbug.com/1356128): Handle in the browser process. if (observer_for_testing_) { CHECK_IS_TEST(); observer_for_testing_->OnCompleteProcessed(this, completion_status); } DeleteSelf(); // DO NOT touch any members after this line. `this` is already deleted. } bool KeepAliveURLLoader::IsRendererConnected() const { return !!forwarding_client_; } net::Error KeepAliveURLLoader::WillFollowRedirect( const net::RedirectInfo& redirect_info) const { DCHECK_CURRENTLY_ON(BrowserThread::UI); // TODO(crbug.com/1356128): Add logic to handle redirecting to extensions from // `ChromeContentRendererClient::IsSafeRedirectTarget()`. if (!IsSafeRedirectTarget(last_url_, redirect_info.new_url)) { return net::ERR_UNSAFE_REDIRECT; } if (resource_request_.redirect_mode == network::mojom::RedirectMode::kError) { return net::ERR_FAILED; } if (resource_request_.redirect_mode != network::mojom::RedirectMode::kManual) { // Checks if redirecting to `url` is allowed by ContentSecurityPolicy from // the request initiator document. if (!IsRedirectAllowedByCSP( policy_container_host_->policies().content_security_policies, redirect_info.new_url, initial_url_, last_url_ != initial_url_)) { return net::ERR_BLOCKED_BY_CSP; } // TODO(crbug.com/1356128): Refactor logic from // `blink::MixedContentChecker::ShouldBlockFetch()` to support checking // without a frame. } return net::OK; } void KeepAliveURLLoader::OnNetworkConnectionError() { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnNetworkConnectionError", "request_id", request_id_); // The network loader has an error; we should let the client know it's // closed by dropping this, which will in turn make this loader destroyed. forwarding_client_.reset(); } void KeepAliveURLLoader::OnRendererConnectionError() { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT("loading", "KeepAliveURLLoader::OnRendererConnectionError", "request_id", request_id_); if (has_received_response_) { // No need to wait for `OnComplete()`. DeleteSelf(); // DO NOT touch any members after this line. `this` is already deleted. return; } // Otherwise, let this loader continue to handle responses. forwarding_client_.reset(); // TODO(crbug.com/1424731): When we reach here while the renderer is // processing a redirect, we should take over the redirect handling in the // browser process. See TODOs in `OnReceiveRedirect()`. } void KeepAliveURLLoader::DeleteSelf() { CHECK(on_delete_callback_); std::move(on_delete_callback_).Run(); } void KeepAliveURLLoader::SetObserverForTesting( scoped_refptr<TestObserver> observer) { observer_for_testing_ = observer; } } // namespace content
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
52123c3d000c6d4f1704a1e12da38fa50183bb7a
0d5b5ba8b268712fac240a9dcfe1c64802b36694
/src/trasformata.cpp
3918b231a9aa75034201c9ffeb62179c2f87d330
[]
no_license
cecca9596/trasformata
747adc48d76f1cea3a14d3940ef062f798c5b713
1a7d4d8e73c51607af2c8d3b96a6cc8f30eaea13
refs/heads/master
2021-01-19T11:20:47.243574
2017-04-11T16:28:30
2017-04-11T16:28:30
87,955,818
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
cpp
#include "ros/ros.h" #include "sensor_msgs/LaserScan.h" #include "std_msgs/String.h" #include <tf/transform_listener.h> #include <time.h> ros::Publisher share; tf::TransformListener* listener; void call_back(const sensor_msgs::LaserScan::ConstPtr& msg){ ros::Time ora=ros::Time::now(); tf::StampedTransform trasformata; if(listener->canTransform("/base_laser_link","/odom",ora,NULL)){ listener->lookupTransform("/base_laser_link","/odom",ora,trasformata); tf::Vector3 vettore= trasformata.getOrigin(); float x=vettore.getX(); float y=vettore.getY(); tf::Quaternion rotazione=trasformata.getRotation(); float angolo=rotazione.getAngle(); std_msgs::String messaggio; std::stringstream ss; ss <<"coordinate: x :" << x; ss << "y : "<< y; ss << "angolo : "<< angolo; messaggio.data=ss.str(); share.publish(messaggio); } } int main(int argc,char** argv){ ros::init(argc,argv,"trasformata"); tf::TransformListener list1; listener=&list1; ros::NodeHandle l; ros::Subscriber sub=l.subscribe("base_scan",1000,call_back); share = l.advertise<std_msgs::String>("transform", 1000); ros::spin(); return 0; }
[ "laziopenta95@gmail.com" ]
laziopenta95@gmail.com
c217fbc010a82bdb14a47f87d60644a7841bbd21
ca780c75c1e7339ee2cc8802b18c48cf70f10172
/re2c/test/unicode_group_Cs.x--encoding-policy(fail).re
36f8681f2abbaf1d62e3ded3016e627a0e1ec4a5
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
gkantsidis/re2c
b8f793c727dc4cb96ef12d862e687afdeb9fc3b3
8a82ee027744a3a21ae45c70ace0d5076cf591a8
refs/heads/master
2021-05-04T13:25:42.903156
2018-02-06T14:34:06
2018-02-06T14:34:06
120,313,604
1
0
null
2018-02-05T14:12:48
2018-02-05T14:12:48
null
UTF-8
C++
false
false
1,244
re
#include <stdio.h> #include "utf16.h" #define YYCTYPE unsigned short bool scan(const YYCTYPE * start, const YYCTYPE * const limit) { __attribute__((unused)) const YYCTYPE * YYMARKER; // silence compiler warnings when YYMARKER is not used # define YYCURSOR start Cs: /*!re2c re2c:yyfill:enable = 0; Cs = [\ud800-\udfff]; Cs { goto Cs; } * { return YYCURSOR == limit; } */ } static const unsigned int chars_Cs [] = {0xd800,0xdfff, 0x0,0x0}; static unsigned int encode_utf16 (const unsigned int * ranges, unsigned int ranges_count, unsigned short * s) { unsigned short * const s_start = s; for (unsigned int i = 0; i < ranges_count; i += 2) for (unsigned int j = ranges[i]; j <= ranges[i + 1]; ++j) { if (j <= re2c::utf16::MAX_1WORD_RUNE) *s++ = j; else { *s++ = re2c::utf16::lead_surr(j); *s++ = re2c::utf16::trail_surr(j); } } return s - s_start; } int main () { YYCTYPE * buffer_Cs = new YYCTYPE [4098]; unsigned int buffer_len = encode_utf16 (chars_Cs, sizeof (chars_Cs) / sizeof (unsigned int), buffer_Cs); if (!scan (reinterpret_cast<const YYCTYPE *> (buffer_Cs), reinterpret_cast<const YYCTYPE *> (buffer_Cs + buffer_len))) printf("test 'Cs' failed\n"); delete [] buffer_Cs; return 0; }
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
6a42454507d2798262c6af9bc7e1b4e1e6489b4d
2f715979fadf8bfa40b36ac7126749c52669dfcf
/src/ui/IMMPui.cpp
b677b6f5b183ad8f18f8eb45036c14f99663ec4b
[ "MIT" ]
permissive
vuvko/testergui
d88d9839d0c161d88e158351a701768d8db6a823
99ce6737dc72d0ac7d4e21290fa6944d86de29fa
refs/heads/master
2022-11-13T07:49:33.840810
2013-07-05T10:29:48
2013-07-05T10:29:48
275,780,664
0
0
null
null
null
null
UTF-8
C++
false
false
664
cpp
#include "IMMPui.h" namespace mmp { namespace ui { Symbol::Symbol(const Point &p) : pos(p) {} Symbol::Symbol(const Symbol *s) : pos(s->getPoint()) {} Point Symbol::getPoint() const { return pos; } Token::Token(const Point &p, int team) : pos(p), teamId(team) {} Token::Token(const Token *t) : pos(t->getPoint()), teamId(t->getTeamId()) {} Point Token::getPoint() const { return pos; } int Token::getTeamId() const { return teamId; } void IMMPui::ShowError(const std::string error) { QMessageBox::critical(0, "Fatal Error", QString(error.c_str())); } } // end of ui namespace } // end of mmp namespace
[ "6129086+vuvko@users.noreply.github.com" ]
6129086+vuvko@users.noreply.github.com
9f363a3a970cd92c1bab12dc8d7e49fadf9cd08e
8044ffbf432ba844a16eff60b122a9346bd2f12e
/source/tests/CarlaUtils2.cpp
e39255d655c18d1631abe2449e08c12ac0a48f1b
[]
no_license
DanielAeolusLaude/Carla
0c1fbfa9ccaecfaef58157be0a7cf0ee21f80b54
71b9d0cbc497506d1b91f42799e0d233e5f883a4
refs/heads/master
2021-01-16T20:06:22.694983
2015-09-18T09:58:27
2015-09-18T09:58:27
42,896,375
2
0
null
2015-09-21T22:07:31
2015-09-21T22:07:31
null
UTF-8
C++
false
false
4,410
cpp
/* * Carla Utility Tests * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For a full copy of the GNU General Public License see the doc/GPL.txt file. */ #ifdef NDEBUG # error Build this file with debug ON please #endif #define VESTIGE_HEADER #include "CarlaLadspaUtils.hpp" #include "CarlaDssiUtils.cpp" #include "CarlaLv2Utils.hpp" #include "CarlaVstUtils.hpp" // ----------------------------------------------------------------------- static void test_CarlaLadspaUtils() { LADSPA_Descriptor desc; carla_zeroStruct(desc); LADSPA_RDF_Descriptor rdfDesc; delete ladspa_rdf_dup(&rdfDesc); is_ladspa_port_good(0x0, 0x0); is_ladspa_rdf_descriptor_valid(&rdfDesc, &desc); get_default_ladspa_port_value(0x0, -1.0f, 1.0f); } // ----------------------------------------------------------------------- static void test_CarlaDssiUtils() noexcept { const char* const ui = find_dssi_ui("/usr/lib/dssi/trivial_sampler.so", "aa"); CARLA_SAFE_ASSERT(ui != nullptr); if (ui != nullptr) { carla_stdout("%s", ui); assert(std::strcmp(ui, "/usr/lib/dssi/trivial_sampler/trivial_sampler_qt") == 0); delete[] ui; } } // ----------------------------------------------------------------------- static LV2_URID test_lv2_uridMap(LV2_URID_Map_Handle, const char*) { return 1; } static void test_CarlaLv2Utils() { Lv2WorldClass& lv2World(Lv2WorldClass::getInstance()); lv2World.initIfNeeded(std::getenv("LV2_PATH")); // getPlugin const LilvPlugin* const plugin(lv2World.getPluginFromURI("urn:juced:DrumSynth")); CARLA_SAFE_ASSERT(plugin != nullptr); // getState LV2_URID_Map uridMap = { nullptr, test_lv2_uridMap }; LilvState* const state(lv2World.getStateFromURI("http://arcticanaudio.com/plugins/thefunction#preset001", &uridMap)); CARLA_SAFE_ASSERT(state != nullptr); if (state != nullptr) lilv_state_free(state); // load a bunch of plugins to stress test lilv delete lv2_rdf_new("http://arcticanaudio.com/plugins/thefunction", true); delete lv2_rdf_new("http://kunz.corrupt.ch/products/tal-noisemaker", true); delete lv2_rdf_new("http://calf.sourceforge.net/plugins/Reverb", true); delete lv2_rdf_new("http://www.openavproductions.com/fabla", true); delete lv2_rdf_new("http://invadarecords.com/plugins/lv2/meter", true); delete lv2_rdf_new("http://gareus.org/oss/lv2/meters#spectr30stereo", true); delete lv2_rdf_new("http://plugin.org.uk/swh-plugins/revdelay", true); delete lv2_rdf_new("http://lv2plug.in/plugins/eg-scope#Stereo", true); delete lv2_rdf_new("http://kxstudio.sf.net/carla/plugins/carlarack", true); delete lv2_rdf_new("http://guitarix.sourceforge.net/plugins/gxautowah#autowah", true); delete lv2_rdf_new("http://github.com/blablack/ams-lv2/mixer_4ch", true); delete lv2_rdf_new("http://drumgizmo.org/lv2", true); delete lv2_rdf_new("http://synthv1.sourceforge.net/lv2", true); delete lv2_rdf_new("urn:juced:DrumSynth", true); // misc is_lv2_port_supported(0x0); is_lv2_feature_supported("test1"); is_lv2_ui_feature_supported("test2"); } // ----------------------------------------------------------------------- static intptr_t test_vst_dispatcher(AEffect*, int, int, intptr_t, void*, float) { return 0; } static void test_CarlaVstUtils() noexcept { AEffect effect; carla_zeroStruct(effect); effect.dispatcher = test_vst_dispatcher; vstPluginCanDo(&effect, "test"); carla_stdout(vstEffectOpcode2str(effOpen)); carla_stdout(vstMasterOpcode2str(audioMasterAutomate)); } // ----------------------------------------------------------------------- // main int main() { test_CarlaLadspaUtils(); test_CarlaDssiUtils(); test_CarlaLv2Utils(); test_CarlaVstUtils(); return 0; } // -----------------------------------------------------------------------
[ "falktx@gmail.com" ]
falktx@gmail.com
54e7968015ae8a6879d87fdcb7ef35706189a6bb
6be41b0f008e03afbcc858eb95a38cc574223e21
/Qtclient2/Qtclient2/main.cpp
4379b214cf76098a2afefb0966ae1eded9c301a0
[]
no_license
siv-chen/SSS
672fe5992685f595a0ed31a18985a0b648345ba9
4b55be664fb630984ffc6b8e6240ffe5bab49d99
refs/heads/master
2020-08-22T23:33:51.494303
2019-10-21T07:13:01
2019-10-21T07:13:01
216,497,259
1
0
null
null
null
null
UTF-8
C++
false
false
167
cpp
#include "Qtclient2.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Qtclient2 w; w.show(); return a.exec(); }
[ "alex_chen@brogent.com" ]
alex_chen@brogent.com
f867e08109964215b690ad158c14c38fa2df65c6
2478b1510fa1557fa0d568c7c988e6812b266932
/proj_Rabbit/3_Coding/JumpRabbit/Classes/Rabbit.cpp
1f4f94342c2c30007951ff93b075f2d989816fbc
[ "Apache-2.0" ]
permissive
SoulDecoder/Project
3de7764636fa1f786ea7b3ef93ae352c55e76705
26213db388abf336934f65795befa2902979d3db
refs/heads/master
2016-09-05T19:03:42.769094
2014-10-27T15:54:08
2014-10-27T15:54:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
598
cpp
// // Rabbit.cpp // JumpRabbit // // Created by jihaitao on 14-9-10. // // #include "Rabbit.h" bool Rabbit::init(){ Sprite::init(); initWithFile("game_rabbit.png"); Size visibleSize = Director::getInstance()->getVisibleSize(); setPosition(Vec2(visibleSize.width/2,visibleSize.height/2)); Size size = this->getContentSize(); setPhysicsBody(PhysicsBody::createBox(size)); getPhysicsBody()->setRotationEnable(false); getPhysicsBody()->setContactTestBitmask(1); //test getPhysicsBody()->setGravityEnable(true); return true; }
[ "souldecoder@sina.com" ]
souldecoder@sina.com
07c03f7b7ff6ca3a3035084d12611ceb0be993cf
a1cc22bafb4429b53898962b1131333420eddf05
/cmdstan/stan/lib/stan_math/stan/math/prim/fun/lambert_w.hpp
c7b907ad2045dd9c488dcefeb3ad77cb6b138a65
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only" ]
permissive
metrumresearchgroup/Torsten
d9510b00242b9f77cdc989657a4956b3018a5f3a
0168482d400e4b819acadbc28cc817dd1a037c1b
refs/heads/master
2023-09-01T17:44:46.020886
2022-05-18T22:46:35
2022-05-18T22:46:35
124,574,336
50
18
BSD-3-Clause
2023-09-09T06:32:36
2018-03-09T17:48:27
C++
UTF-8
C++
false
false
3,027
hpp
#ifndef STAN_MATH_PRIM_FUN_LAMBERT_W_HPP #define STAN_MATH_PRIM_FUN_LAMBERT_W_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/functor/apply_scalar_unary.hpp> #include <stan/math/prim/fun/boost_policy.hpp> #include <boost/math/special_functions/lambert_w.hpp> namespace stan { namespace math { /** * Compute the Lambert W function on W0 branch for a value x. * * @tparam T type of value * @param x value * @return value of the W0 branch of the Lambert W function for x * @throw std::domain_error if x is less than or equal to `-e^(-1)` */ template <typename T, require_arithmetic_t<T>* = nullptr> inline double lambert_w0(const T& x) { return boost::math::lambert_w0(x, boost_policy_t<>()); } /** * Compute the Lambert W function on W-1 branch for a value x. * * @tparam T type of value * @param x value * @return value of the W-1 branch of the Lambert W function for x * @throw std::domain_error if x is less than or equal to `-e^(-1)` or greater * than or equal to 0 */ template <typename T, require_arithmetic_t<T>* = nullptr> inline double lambert_wm1(const T& x) { return boost::math::lambert_wm1(x, boost_policy_t<>()); } namespace internal { /** * Structure to wrap lambert_w0() so it can be vectorized. * * @tparam T type of variable * @param x variable * @return value of the W0 branch of the Lambert W function at x. * @throw std::domain_error if x is less than or equal to `-e^(-1)` */ struct lambert_w0_fun { template <typename T> static inline T fun(const T& x) { return lambert_w0(x); } }; /** * Structure to wrap lambert_wm1() so it can be vectorized. * * @tparam T type of variable * @param x variable * @return value of the W-1 branch of the Lambert W function at x. * @throw std::domain_error if x is less than or equal to `-e^(-1)` or greater * than or equal to 0 */ struct lambert_wm1_fun { template <typename T> static inline T fun(const T& x) { return lambert_wm1(x); } }; } // namespace internal /** * Vectorized version of lambert_w0(). * * @tparam T type of container * @param x container * @return value of the W0 branch of the Lambert W function for each value in x * @throw std::domain_error if x is less than or equal to `-e^(-1)` */ template <typename T, require_not_stan_scalar_t<T>* = nullptr, require_not_var_matrix_t<T>* = nullptr> inline auto lambert_w0(const T& x) { return apply_scalar_unary<internal::lambert_w0_fun, T>::apply(x); } /** * Vectorized version of lambert_wm1(). * * @tparam T type of container * @param x container * @return value of the W0 branch of the Lambert W function for each value in x * @throw std::domain_error if x is less than or equal to `-e^(-1)` or greater * than or equal to 0 */ template <typename T, require_not_stan_scalar_t<T>* = nullptr, require_not_var_matrix_t<T>* = nullptr> inline auto lambert_wm1(const T& x) { return apply_scalar_unary<internal::lambert_wm1_fun, T>::apply(x); } } // namespace math } // namespace stan #endif
[ "yzhang@c-path.org" ]
yzhang@c-path.org
dfafbe001f0986187ae19d6cd583ede4c18b35db
254e8f6704a30663eea5ea35c393c16cd66c0fd7
/BOJ/ETC/String/15873.cpp
9ec0b7fbaff7826412e506cb623174bed03b99e9
[]
no_license
imnct0805/Study-CPP
6d5a28564f9b8d1fd749d3f5583346b3e0de9fbe
5dd7412de7f48cfd1c0fb29903002c6d992d9424
refs/heads/master
2020-03-25T07:47:39.620731
2018-08-07T06:45:26
2018-08-07T06:45:26
143,582,531
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
#include <iostream> #include <string.h> using namespace std; int main() { char c[5]; scanf("%s", c); int len = strlen(c); if (len == 2) cout << (atoi(c) / 10) + (atoi(c) % 10) << endl; else if (len == 3) { if (c[1] == '0') cout << ((atoi(c) / 100) * 10 + (atoi(c) % 100 / 10)) + (atoi(c) % 10) << endl; else cout << ((atoi(c) / 100) + ((atoi(c) % 100 / 10) * 10 + (atoi(c) % 10))) << endl; } else if (len == 4) cout << 20 << endl; }
[ "imnct0805@gmail.com" ]
imnct0805@gmail.com
336619714786cfb0b7cb0c7e9fbeddd83464b993
6f874ccb136d411c8ec7f4faf806a108ffc76837
/code/VCSamples/VC2008Samples/MFC/ole/wordpad/splash.h
be877e42182263779a1bd9dd85ee7cae9be06366
[ "MIT" ]
permissive
JetAr/ZDoc
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
e81a3adc354ec33345e9a3303f381dcb1b02c19d
refs/heads/master
2022-07-26T23:06:12.021611
2021-07-11T13:45:57
2021-07-11T13:45:57
33,112,803
8
8
null
null
null
null
UTF-8
C++
false
false
1,600
h
// splash.h : header file // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. ///////////////////////////////////////////////////////////////////////////// // CBigIcon window class CBigIcon : public CButton { // Attributes public: CBitmap m_bitmap; CSize m_sizeBitmap; // Operations public: void SizeToContent(); // Implementation protected: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); //{{AFX_MSG(CBigIcon) afx_msg BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CSplash dialog #pragma warning(push) // Disable warning on Create. #pragma warning(disable : 4264) #pragma warning(disable : 4263) class CSplashWnd : public CDialog { private: using CDialog::Create; // Construction public: BOOL Create(CWnd* pParent = NULL); // Dialog Data //{{AFX_DATA(CSplashWnd) enum { IDD = IDD_SPLASH }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Implementation protected: CBigIcon m_icon; // self-draw button // Generated message map functions //{{AFX_MSG(CSplashWnd) virtual BOOL OnInitDialog(); //}}AFX_MSG }; #pragma warning(pop)
[ "126.org@gmail.com" ]
126.org@gmail.com
22a6e563dc6fc2227fe18edc1ebd0bd6a979d3f0
146d134168c9e348e66e52e34c1296e5023d0df3
/src/FocusControl.hh
4de4310a1b2954de503f21697daf17feb20a3b72
[ "MIT" ]
permissive
ystk/debian-fluxbox
1e5810e63baf250b1665b6d6736754be4627f8ea
973f6b0a10e45221ae31e1f6e3a5b0b24b640b5a
refs/heads/master
2016-09-06T09:00:28.608741
2010-07-12T11:23:08
2010-07-12T11:23:08
35,472,683
1
0
null
null
null
null
UTF-8
C++
false
false
6,686
hh
// FocusControl.hh // Copyright (c) 2006 Fluxbox Team (fluxgen at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef FOCUSCONTROL_HH #define FOCUSCONTROL_HH #include <list> #include "FbTk/Resource.hh" #include "FocusableList.hh" class ClientPattern; class WinClient; class FluxboxWindow; class Focusable; class BScreen; /** * Handles window focus for a specific screen. * It also holds the static "global" focused window */ class FocusControl { public: typedef std::list<Focusable *> Focusables; /// main focus model enum FocusModel { MOUSEFOCUS = 0, ///< focus follows mouse CLICKFOCUS ///< focus on click }; /// focus model for tabs enum TabFocusModel { MOUSETABFOCUS = 0, ///< tab focus follows mouse CLICKTABFOCUS ///< tab focus on click }; /// focus direction for windows enum FocusDir { FOCUSUP, ///< window is above FOCUSDOWN, ///< window is down FOCUSLEFT, ///< window is left FOCUSRIGHT ///< window is right }; explicit FocusControl(BScreen &screen); /// cycle previous focuable void prevFocus() { cycleFocus(m_focused_list, 0, true); } /// cycle next focusable void nextFocus() { cycleFocus(m_focused_list, 0, false); } /** * Cycle focus for a set of windows. * @param winlist the windowlist to cycle through * @param pat pattern for matching focusables * @param reverse reverse the cycle order */ void cycleFocus(const FocusableList &winlist, const ClientPattern *pat = 0, bool reverse = false); void goToWindowNumber(const FocusableList &winlist, int num, const ClientPattern *pat = 0); /// sets the focused window on a screen void setScreenFocusedWindow(WinClient &win_client); /// sets the main focus model void setFocusModel(FocusModel model); /// sets tab focus model void setTabFocusModel(TabFocusModel model); /// stop cycling mode void stopCyclingFocus(); /** * Do directional focus mode. * @param win current window * @param dir direction from current window to focus. */ void dirFocus(FluxboxWindow &win, FocusDir dir); /// @return true if focus mode is mouse focus bool isMouseFocus() const { return focusModel() == MOUSEFOCUS; } /// @return true if tab focus mode is mouse tab focus bool isMouseTabFocus() const { return tabFocusModel() == MOUSETABFOCUS; } /// @return true if cycling is in progress bool isCycling() const { return m_cycling_list != 0; } /// Appends a client to the front of the focus list void addFocusBack(WinClient &client); /// Appends a client to the front of the focus list void addFocusFront(WinClient &client); void addFocusWinBack(Focusable &win); void addFocusWinFront(Focusable &win); void setFocusBack(FluxboxWindow &fbwin); /// @return main focus model FocusModel focusModel() const { return *m_focus_model; } /// @return tab focus model TabFocusModel tabFocusModel() const { return *m_tab_focus_model; } /// @return true if newly created windows are focused bool focusNew() const { return *m_focus_new; } /// @return last focused client in a specific workspace, or NULL. Focusable *lastFocusedWindow(int workspace); WinClient *lastFocusedWindow(FluxboxWindow &group, WinClient *ignore_client = 0); /// @return focus list in creation order const FocusableList &creationOrderList() const { return m_creation_order_list; } /// @return the focus list in focused order const FocusableList &focusedOrderList() const { return m_focused_list; } const FocusableList &creationOrderWinList() const { return m_creation_order_win_list; } const FocusableList &focusedOrderWinList() const { return m_focused_win_list; } /// remove client from focus list void removeClient(WinClient &client); /// remove window from focus list void removeWindow(Focusable &win); /// starts terminating this control void shutdown(); /// do fallback focus for screen if normal focus control failed. static void revertFocus(BScreen &screen); // like revertFocus, but specifically related to this window (transients etc) static void unfocusWindow(WinClient &client, bool full_revert = true, bool unfocus_frame = false); static void setFocusedWindow(WinClient *focus_to); static void setFocusedFbWindow(FluxboxWindow *focus_to) { s_focused_fbwindow = focus_to; } static void setExpectingFocus(WinClient *client) { s_expecting_focus = client; } static WinClient *focusedWindow() { return s_focused_window; } static FluxboxWindow *focusedFbWindow() { return s_focused_fbwindow; } static WinClient *expectingFocus() { return s_expecting_focus; } private: BScreen &m_screen; FbTk::Resource<FocusModel> m_focus_model; FbTk::Resource<TabFocusModel> m_tab_focus_model; FbTk::Resource<bool> m_focus_new; // This list keeps the order of window focusing for this screen // Screen global so it works for sticky windows too. FocusableList m_focused_list; FocusableList m_creation_order_list; FocusableList m_focused_win_list; FocusableList m_creation_order_win_list; Focusables::const_iterator m_cycling_window; const FocusableList *m_cycling_list; Focusable *m_was_iconic; WinClient *m_cycling_last; static WinClient *s_focused_window; static FluxboxWindow *s_focused_fbwindow; static WinClient *s_expecting_focus; static bool s_reverting; }; #endif // FOCUSCONTROL_HH
[ "skerlet@swc.toshiba.co.jp" ]
skerlet@swc.toshiba.co.jp
3ab690a91477b6c800cfd218b45e625229cc4013
44e0614acf303ae9b4284b40b3bd1224b3824939
/APP/ProcNetCmd/NetCmdGetInputSignalResol.cpp
b429bb296e7c493b2154273dc288215f8299519f
[]
no_license
zdevt/CtrlBox
f76e8d2d84f68a54c632146365e95093e1c7eefe
737b748759a32cf268be5d88fc4d487f1f30122b
refs/heads/master
2023-03-28T21:02:49.145365
2021-03-31T23:32:22
2021-03-31T23:32:22
353,516,798
1
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
/* * ===================================================================================== * * Filename: NetCmdGetInputSignalResol.cpp * * Description: * * Version: 1.0 * Created: 01/06/2015 03:13:23 AM EST * Revision: none * Compiler: gcc * * Author: zt (), * Company: * * ===================================================================================== */ #include <string> #include "NetCmdGetInputSignalResol.h" #include "MainboardInterface.h" NetCmdGetInputSignalResol::NetCmdGetInputSignalResol ( ) { } NetCmdGetInputSignalResol::~NetCmdGetInputSignalResol() { } int NetCmdGetInputSignalResol::HandleCmd ( vechar& cmd, vechar& rsp ) { if ( cmd.size() < ( sizeof ( MCP_HEADER_t ) ) ) return 0; get_inputsignalresol_t get_inputsignalresol; #if defined(__arm__) GET_MBPTR->GetInputSignalResol ( get_inputsignalresol.width, get_inputsignalresol.height ); #endif HandleRsp ( cmd, rsp, MCP_RET_GET_INPUTSIGNALRESOL, reinterpret_cast<char*> ( &get_inputsignalresol ), sizeof ( get_inputsignalresol ) ); return 0; } std::shared_ptr<NetCmd> NetCmdGetInputSignalResol::GetObj ( ) { return std::make_shared<NetCmdGetInputSignalResol> ( ); }
[ "zhangtao.hawk@qq.com" ]
zhangtao.hawk@qq.com
97e61758b2f9ed112b7a81ef85864f86d0553b98
6a8e0b9614077a8ebb49880dee7d479f4a72a16b
/WatchDirectory.h
5688b929687995c52062d12832ece020b58e7594
[]
no_license
phongth7/WatchDirectory
848356a4eb8b64220be9dbf0f29e69f0a4474fc1
c058f001ebf26ecb65be51dd41d7abe12c0019f8
refs/heads/master
2020-03-29T04:51:48.921426
2017-07-09T19:01:43
2017-07-09T19:01:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,715
h
#pragma once /* * WatchDirectory - Allows you to get a callback when the contents of a directory has changed. * Currently implemented for windows platforms only. To be used in debug builds to get a callback so you can hot reload data that has changed. * On non-windows platforms the implementation does nothing but does NOT require you to "#ifdef" out your code for those platforms. * * How to Use: * * //implement a DirectoryWatcher interface * class MyClass : public DirectoryWatcher * { * public: * virtual void OnDirChanged(const char* path) * { * //The Directory was changed * }; * }; * * //Make a WatchDirectory and tell it which dir to watch * WatchDirectory watchDir; * watchDir.Watch("C:\\Users\\davep\\Dropbox\\Public"); * * //Set who is the listener for changes * MyClass watcher; * watchDir.SetCallBack(watcher); * * //call process once per frame or at interval you would like to monitor for changes * while ( true ) * { * watchDir.Process(); * Sleep(2000); * } */ /*! \brief Inteface to an object that can recieve a callback when a directory has changed */ class DirectoryWatcher { public: virtual ~DirectoryWatcher() = 0 {} virtual void OnDirChanged(const char* path) = 0; }; /*! \brief default implementation of directory watcher that does nothing. */ class WatchDirectoryImplNull { public: void SetCallBack(DirectoryWatcher& callback) {} void Watch(const char* pathName) {} void Process() {} }; #if defined(WIN32) ////////////////// Windows Start //////////////////////////// //see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365261(v=vs.85).aspx - Obtaining Directory Change Notifications // Basic include required for windows builds #ifndef UNICODE #define UNICODE #endif #include <SDKDDKVer.h> // Including SDKDDKVer.h defines the highest available Windows platform. #include <windows.h> #include <stdio.h> // printf /*! \brief Windows 32/64 implentation of the directory watcher */ class WatchDirectoryImplWin32 { public: WatchDirectoryImplWin32(); void SetCallBack(DirectoryWatcher& callback); void Watch(const char* pathName); void Process(); HANDLE m_changeHndl; ///< The handle to the directory being watched wchar_t m_path[MAX_PATH]; ///< The path being watched DirectoryWatcher* m_watcher; ///< This object gets the call back when the folder has changed }; WatchDirectoryImplWin32::WatchDirectoryImplWin32() : m_changeHndl(INVALID_HANDLE_VALUE) , m_watcher(NULL) { } void WatchDirectoryImplWin32::SetCallBack(DirectoryWatcher& watcher) { m_watcher = &watcher; } void WatchDirectoryImplWin32::Watch(const char* pathName) { const bool watchSubtree = false; size_t pReturnValue; mbstowcs_s(&pReturnValue, m_path, MAX_PATH, pathName, MAX_PATH); HANDLE changeHndl = FindFirstChangeNotification(m_path, watchSubtree, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_FILE_NAME); if (changeHndl != INVALID_HANDLE_VALUE) { m_changeHndl = changeHndl; } else { printf("\n ERROR: FindFirstChangeNotification function failed %d.\n", GetLastError()); } } void WatchDirectoryImplWin32::Process() { if (m_changeHndl == INVALID_HANDLE_VALUE) { return; //nothing to wait for } // Wait for notification. printf("\nWaiting for notification to: '%ls'\n", m_path); const DWORD waitTimeMs = 0; const DWORD dwWaitStatus = WaitForMultipleObjects(1, &m_changeHndl, FALSE, waitTimeMs); switch (dwWaitStatus) { case WAIT_OBJECT_0: // A file was created, renamed, or deleted in the directory. printf("file was changed in the watch folder"); if (m_watcher) { m_watcher->OnDirChanged("PATH"); } if (FindNextChangeNotification(m_changeHndl) == FALSE) { printf("\n ERROR: FindNextChangeNotification function failed %d.\n", GetLastError()); } break; } } ////////////////// Windows End //////////////////////////// #endif /*! \brief Used to watch the a directory for changes and recieve a notification when anything in that directory has been changed */ class WatchDirectory { public: /*! \brief Set the object that will recieve a call back if the directory has changed. */ inline void SetCallBack(DirectoryWatcher& watcher) { m_wd.SetCallBack(watcher); } /*! \brief Cancels any watch on an existing directory and watches the directoyr given by #pathName parameter */ inline void Watch(const char* pathName) { m_wd.Watch(pathName); } /*! \brief Call once per frame to watch for any directory change and issue a call back */ inline void Process() { m_wd.Process(); } private: //Pmpl for the actual WatchDirectory depending on the platform. #if defined(WIN32) WatchDirectoryImplWin32 m_wd; #else WatchDirectoryImplNull m_wd; ///< default impl that does nothing. #endif };
[ "davepoo@hotmail.com" ]
davepoo@hotmail.com
8c46c5bcf2f32da60b51cf0043a5348be44f61a7
7e8c72c099b231078a763ea7da6bba4bd6bac77b
/other_projects/base_station_monitor/Client/reference SDK/General_NetSDK_Chn_IS_V3.36.0.R.100505/Demo/分类应用/参数配置/ClientDemo5/ConfigAlarmMotionArea.h
ff352787185e28234e63cea2bdfd5b80c8c59563
[]
no_license
github188/demodemo
fd910a340d5c5fbf4c8755580db8ab871759290b
96ed049eb398c4c188a688e9c1bc2fe8cd2dc80b
refs/heads/master
2021-01-12T17:16:36.199708
2012-08-15T14:20:51
2012-08-15T14:20:51
71,537,068
1
2
null
2016-10-21T06:38:22
2016-10-21T06:38:22
null
UTF-8
C++
false
false
2,132
h
#if !defined(AFX_CONFIGALARMMOTIONAREA_H__3DA25876_BE0B_4847_9843_4F9E62F60406__INCLUDED_) #define AFX_CONFIGALARMMOTIONAREA_H__3DA25876_BE0B_4847_9843_4F9E62F60406__INCLUDED_ #include "dhnetsdk.h" #include "ConfigAlarmMotionAreaBlock.h" #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ConfigAlarmMotionArea.h : header file // ///////////////////////////////////////////////////////////////////////////// // CConfigAlarmMotionArea dialog class CConfigAlarmMotionArea : public CDialog { // Construction public: CConfigAlarmMotionArea(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CConfigAlarmMotionArea) enum { IDD = IDD_CONFIG_ALARM_MOTION_AREA }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CConfigAlarmMotionArea) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CConfigAlarmMotionArea) virtual void OnOK(); virtual BOOL OnInitDialog(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: void SetArea(BYTE *area, WORD wRows, WORD wCols); BYTE *GetArea(){return (BYTE*)m_myArea;} void RecordPoint(BYTE x, BYTE y); void ReleasePoint(); void MovePoint(DWORD dwParm, BYTE x, BYTE y); private: CConfigAlarmMotionAreaBlock m_block[DH_MOTION_ROW][DH_MOTION_COL]; BYTE m_myArea[DH_MOTION_ROW][DH_MOTION_COL]; CRect m_rect; int m_blckWid; int m_blckHght; BOOL m_bDrawing; POINT m_stpoint; POINT m_lastpoint; WORD m_wRows; WORD m_wCols; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CONFIGALARMMOTIONAREA_H__3DA25876_BE0B_4847_9843_4F9E62F60406__INCLUDED_)
[ "thinkinnight@b18a5524-d64a-0410-9f42-ad3cd61580fb" ]
thinkinnight@b18a5524-d64a-0410-9f42-ad3cd61580fb
42b5d6c7f68ede997d485143ebdcd68b9c629101
374969626877d6f93b4de2786152b9aae24598e8
/Resources/old_hw_countdown.cpp
c012a4e1eebfc9bc5237bbd4c4f5c8196b8b9b21
[]
no_license
vchek/Pacemaker
7735a2f5cf6f1f42ee2e2046921badc55a95043c
63d126f40bda4a97048c9257de7ec4598123c243
refs/heads/master
2021-05-06T09:36:39.673694
2017-12-15T04:11:32
2017-12-15T04:11:32
114,064,259
0
0
null
null
null
null
UTF-8
C++
false
false
5,424
cpp
#define MQTTCLIENT_QOS2 1 #define IAP_LOCATION 0x1FFF1FF1 #define COMMAND 54 #include "TextLCD.h" #include "ESP8266Interface.h" #include "MQTTNetwork.h" #include "MQTTmbed.h" #include "MQTTClient.h" #include "TCPSocket.h" #include "mbed.h" #include "rtos.h" #include <string> unsigned long command[5]; unsigned long output[5]; unsigned long command2[5]; unsigned long output2[5]; typedef void (*IAP)(unsigned long[],unsigned long[]); IAP iap_entry; ESP8266Interface wifi(p28, p27); Serial pc(USBTX, USBRX); Thread thread; TextLCD lcd(p15, p16, p17, p18, p19, p20, TextLCD::LCD16x2); void messageArrived(MQTT::MessageData& md) { MQTT::Message &message = md.message; lcd.printf("%s\n\n", (char*)message.payload); //return; } void my_thread(MQTT::Client<MQTTNetwork, Countdown> client) { while (true) { client.yield(1000); } } void mqt(NetworkInterface *myfi) { MQTTNetwork mqttNetwork(myfi); MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork); const char* broker = "35.188.242.1"; int port = 1883; //pc.printf("Connecting to %s:%d\r\n", broker, port); int rc = mqttNetwork.connect(broker, port); if (rc != 0) printf("rc from TCP connect is %d\r\n", rc); const int len = snprintf(NULL, 0, "%lx-%lx%lx%lx%lx", output2[1], output[1], output[2], output[3], output[4]); char buf[len+1]; snprintf(buf, len+1, "%lx-%lx%lx%lx%lx", output2[1], output[1], output[2], output[3], output[4]); //pc.printf("%s\r\n", buf); MQTTPacket_connectData data = MQTTPacket_connectData_initializer; Countdown countdown; data.clientID.cstring = buf; //strcat(strcat("<",buf),">"); data.username.cstring = "mbed"; data.password.cstring = "homework"; //data.keepAlive = 10; const int t = snprintf(NULL, 0, "cis541/hw-mqtt/%s/data", buf); char send_topic[t+1]; char pub_topic[t+1]; snprintf(send_topic, t+1, "cis541/hw-mqtt/%s/data", buf); snprintf(pub_topic, t+1, "cis541/hw-mqtt/%s/echo", buf); //pc.printf("%s, %s\r\n", data.clientID.cstring, topic); if ((rc = client.connect(data)) != 0) printf("rc from MQTT connect is %d\r\n", rc); if ((rc = client.subscribe(pub_topic, MQTT::QOS0, messageArrived)) != 0) printf("rc from MQTT subscribe is %d\r\n", rc); //thread.start(my_thread(client)); //countdown.countdown(5); pc.printf("message\r\n"); MQTT::Message message; char arr[100]; message.qos = MQTT::QOS0; message.retained = false; message.dup = false; while(true) { countdown.countdown(5); while(countdown.expired() != true) { //countdown.countdown(5); //pc.printf("counted down\r\n"); } int mess = rand()%100; sprintf(arr, "%d", mess); message.payload = (void*)arr; message.payloadlen = strlen(arr); //pc.printf("sending"); rc = client.publish(send_topic, message); //pc.printf("%d", rc); client.yield(1); //pc.printf("%s",arr); //client.yield(1); } } void printhttp(NetworkInterface *myfi) { TCPSocket socket; nsapi_error_t response; socket.open(myfi); response = socket.connect("35.188.242.1", 80); if(0 != response) { printf("Error connecting: %d\n", response); socket.close(); return; } // Send a simple http request char sbuffer[] = "GET / HTTP/1.1\r\nHost: 35.188.242.1\r\n\r\n"; nsapi_size_t size = strlen(sbuffer); while(size) { response = socket.send(sbuffer+response, size); if (response < 0) { printf("Error sending data: %d\n", response); socket.close(); return; } else { size -= response; //printf("sent %d [%.*s]\n", response, strstr(sbuffer, "\r\n")-sbuffer, sbuffer); } } // Recieve a simple http response and print out the response line char rbuffer[128]; response = socket.recv(rbuffer, sizeof rbuffer); if (response < 0) { printf("Error receiving data: %d\n", response); } else { while (!(response < 0)) { pc.printf("%s", rbuffer); response = socket.recv(rbuffer, sizeof rbuffer); } } socket.close(); } int main(int argc, char* argv[]) { //pc.printf("%s",wifi.get_mac_address()); pc.printf("Start\r\n"); command[0] = 58; command2[0] = 54; iap_entry = (IAP) IAP_LOCATION; iap_entry (command, output); iap_entry (command2, output2); int ret = wifi.connect("goHAMCO!", "whatisthepassword"); if (ret != 0) { printf("\nConnection error\n"); return -1; } lcd.printf("Connected\r\n"); lcd.printf("HTTP = 1 \nMQTT = 2\r\n"); int command = pc.getc(); if (command == '1') { lcd.printf("Milestone 1\n\n"); printhttp(&wifi); } else { pc.printf("Milestone 2\r\n"); mqt(&wifi); //pc.printf("DONEZO"); return 0; } // Close the socket to return its memory and bring down the network interface //socket.close(); wifi.disconnect(); //pc.printf("DONEZO"); return 0; }
[ "tristrumtuttle@gmail.com" ]
tristrumtuttle@gmail.com
1ce1c131073a0112ad7cc8049f992c0d44831207
5e6943ef0183cc59ab8392060472ccc561700c24
/src/brick/callback_internal.h
40684cd08450d426ba5b2a54c24d8461b9fec9c2
[]
no_license
israel-Liu/brick
88b7ea62c79fc0fc250a60a482d81543c48ec795
9b4e4011df7c0bdede945d98bcd1e0a5ac535773
refs/heads/master
2022-04-20T10:00:47.049834
2020-04-24T03:32:07
2020-04-24T03:32:07
96,489,912
0
0
null
null
null
null
UTF-8
C++
false
false
5,827
h
// Copyright (c) 2012 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. // This file contains utility functions and classes that help the // implementation, and management of the Callback objects. #ifndef BRICK_CALLBACK_INTERNAL_H_ #define BRICK_CALLBACK_INTERNAL_H_ #include "brick/base_export.h" #include "brick/callback_forward.h" #include "brick/macros.h" #include "brick/memory/ref_counted.h" namespace base { struct FakeBindState; namespace internal { class CallbackBase; class CallbackBaseCopyable; class BindStateBase; template <typename Functor, typename... BoundArgs> struct BindState; struct BindStateBaseRefCountTraits { static void Destruct(const BindStateBase*); }; template <typename T, bool IsScalar = std::is_scalar<T>::value> struct PassingTraits; template <typename T> struct PassingTraits<T, false> { using Type = T&&; }; template <typename T> struct PassingTraits<T, true> { using Type = T; }; template <typename T> using PassingTraitsType = typename PassingTraits<T>::Type; // BindStateBase is used to provide an opaque handle that the Callback // class can use to represent a function object with bound arguments. It // behaves as an existential type that is used by a corresponding // DoInvoke function to perform the function execution. This allows // us to shield the Callback class from the types of the bound argument via // "type erasure." // At the base level, the only task is to add reference counting data. Don't use // RefCountedThreadSafe since it requires the destructor to be a virtual method. // Creating a vtable for every BindState template instantiation results in a lot // of bloat. Its only task is to call the destructor which can be done with a // function pointer. class BRICK_EXPORT BindStateBase : public RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits> { public: REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE(); using InvokeFuncStorage = void(*)(); private: BindStateBase(InvokeFuncStorage polymorphic_invoke, void (*destructor)(const BindStateBase*)); BindStateBase(InvokeFuncStorage polymorphic_invoke, void (*destructor)(const BindStateBase*), bool (*is_cancelled)(const BindStateBase*)); ~BindStateBase() = default; friend struct BindStateBaseRefCountTraits; friend class RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits>; friend class CallbackBase; friend class CallbackBaseCopyable; // Whitelist subclasses that access the destructor of BindStateBase. template <typename Functor, typename... BoundArgs> friend struct BindState; friend struct ::base::FakeBindState; bool IsCancelled() const { return is_cancelled_(this); } // In C++, it is safe to cast function pointers to function pointers of // another type. It is not okay to use void*. We create a InvokeFuncStorage // that that can store our function pointer, and then cast it back to // the original type on usage. InvokeFuncStorage polymorphic_invoke_; // Pointer to a function that will properly destroy |this|. void (*destructor_)(const BindStateBase*); bool (*is_cancelled_)(const BindStateBase*); DISALLOW_COPY_AND_ASSIGN(BindStateBase); }; // Holds the Callback methods that don't require specialization to reduce // template bloat. // CallbackBase<MoveOnly> is a direct base class of MoveOnly callbacks, and // CallbackBase<Copyable> uses CallbackBase<MoveOnly> for its implementation. class BRICK_EXPORT CallbackBase { public: CallbackBase(CallbackBase&& c) noexcept; CallbackBase& operator=(CallbackBase&& c) noexcept; explicit CallbackBase(const CallbackBaseCopyable& c); CallbackBase& operator=(const CallbackBaseCopyable& c); explicit CallbackBase(CallbackBaseCopyable&& c) noexcept; CallbackBase& operator=(CallbackBaseCopyable&& c) noexcept; // Returns true if Callback is null (doesn't refer to anything). bool is_null() const { return !bind_state_; } explicit operator bool() const { return !is_null(); } // Returns true if the callback invocation will be nop due to an cancellation. // It's invalid to call this on uninitialized callback. bool IsCancelled() const; // Returns the Callback into an uninitialized state. void Reset(); protected: using InvokeFuncStorage = BindStateBase::InvokeFuncStorage; // Returns true if this callback equals |other|. |other| may be null. bool EqualsInternal(const CallbackBase& other) const; constexpr inline CallbackBase(); // Allow initializing of |bind_state_| via the constructor to avoid default // initialization of the scoped_refptr. explicit CallbackBase(BindStateBase* bind_state); InvokeFuncStorage polymorphic_invoke() const { return bind_state_->polymorphic_invoke_; } // Force the destructor to be instantiated inside this translation unit so // that our subclasses will not get inlined versions. Avoids more template // bloat. ~CallbackBase(); scoped_refptr<BindStateBase> bind_state_; }; constexpr CallbackBase::CallbackBase() = default; // CallbackBase<Copyable> is a direct base class of Copyable Callbacks. class BRICK_EXPORT CallbackBaseCopyable : public CallbackBase { public: CallbackBaseCopyable(const CallbackBaseCopyable& c); CallbackBaseCopyable(CallbackBaseCopyable&& c) noexcept; CallbackBaseCopyable& operator=(const CallbackBaseCopyable& c); CallbackBaseCopyable& operator=(CallbackBaseCopyable&& c) noexcept; protected: constexpr CallbackBaseCopyable() = default; explicit CallbackBaseCopyable(BindStateBase* bind_state) : CallbackBase(bind_state) {} ~CallbackBaseCopyable() = default; }; } // namespace internal } // namespace base #endif // BRICK_CALLBACK_INTERNAL_H_
[ "israel.liu.theForger@gmail.com" ]
israel.liu.theForger@gmail.com
eaa89de660deeb56d694258e15b8ea2adf57a0d1
dc6577e13b23b45c2b9cd3a6c7b63a37b549871c
/gameone 2.0/test/bgm.h
67c105151f84456f02eb4bdbf095da198cbe8b89
[]
no_license
ruc-zyy/game-2.0
b79d76e72cd5db9a53ebb1df8738511817447419
1e2642eb5286b99b80392e1b453c4626b52eeb8d
refs/heads/master
2022-11-09T20:27:14.536366
2020-06-29T03:53:48
2020-06-29T03:53:48
275,556,790
0
0
null
null
null
null
UTF-8
C++
false
false
246
h
#ifndef BGM_H #define BGM_H #include <QObject> class QMediaPlayer; class bgm:public QObject { public: explicit bgm(QObject *parent = 0); void startBGM(); private: QMediaPlayer *m_backgroundMusic; }; #endif // BGM_H
[ "noreply@github.com" ]
noreply@github.com
3e2366ba73b736c859ff7141fa71bc2aa9bdd79c
ca805a49a84b5d54b7eac85feff78a8bdec4a233
/2069.cpp
9338027794b97c448fbad8edaf6c630d236748ed
[]
no_license
lcy8417/backjoon-online-judge
523a888cce80b82f447732876a6972c0c8c5dc0e
042966b069faf68589fe77a9311af42498d91a51
refs/heads/main
2023-08-10T14:08:48.671399
2021-09-19T12:57:49
2021-09-19T12:57:49
348,651,035
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); int n, m, maxi = 1, mini = 1; cin >> n >> m; if(n < m){ int temp = n; n = m; m = temp; } for(int i = 2; i <= n; i++) if(n % i == 0 && m % i == 0) maxi = i; mini = maxi * (n/maxi) * (m/maxi); cout << maxi << "\n" << mini; }
[ "noreply@github.com" ]
noreply@github.com
56812a781c94c14fa12b9b42e2af068ea1f07e65
6bf32823312ef8f09b298ae5a5c765d60a415d88
/server/src/drivers/scr_server/scr_server_20rest.cpp
2c705b79b60c37fcc380b2afb4dc65a3e310f0cc
[]
no_license
ahmadelsallab/Torcs
8f25d07b06d8cb45f78c9fb21c8e93e5ebd5ffb5
49184455e88cec602c4ba1b64a8b17750835888a
refs/heads/master
2020-06-05T04:49:16.128018
2016-07-27T13:35:56
2016-07-27T13:35:56
192,318,525
0
0
null
null
null
null
UTF-8
C++
false
false
26,606
cpp
/*************************************************************************** file : scr_server.cpp copyright : (C) 2007 Daniele Loiacono ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifdef _WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <iostream> #include <sstream> #include <ctime> #include <tgf.h> #include <track.h> #include <car.h> #include <raceman.h> #include <robottools.h> #include <robot.h> #include "sensors.h" #include "SimpleParser.h" #include "CarControl.h" #include "ObstacleSensors.h" // ALL GRAPHICS RELATED #include "tgfclient.h" // How to attach the grCam object to the driver in order to snapshot from every car? //#include "grscreen.h" //#include "../modules/graphic/ssgraph/grscreen.h" #ifdef _WIN32 typedef sockaddr_in tSockAddrIn; typedef int socklen_t; #define CLOSE(x) closesocket(x) #define INVALID(x) x == INVALID_SOCKET #else typedef int SOCKET; typedef struct sockaddr_in tSockAddrIn; #define CLOSE(x) close(x) #define INVALID(x) x < 0 #endif #ifndef _WIN32 #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #endif #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include <time.h> #include <fcntl.h> /*** defines for TCP *****/ #define TCP_ID "SCR" #define TCP_DEFAULT_TIMEOUT 10000 #define TCP_MSGLEN 1000 //#define __TCP_SERVER_VERBOSE__ /************************/ static int TCP_TIMEOUT = TCP_DEFAULT_TIMEOUT; #define NBBOTS 10 #define RACE_RESTART 1 #define RACE_PAUSE 2 //#define __STEP_LIMIT__ 10000 //#define __DISABLE_RESTART__ //#define __PRINT_RACE_RESULTS__ double __SENSORS_RANGE__; #define __FOCUS_RANGE__ 200 /*** Noise definitions ***/ #define __NOISE_STD__ 0.1 #define __OPP_NOISE_STD__ 0.02 #define __FOCUS_NOISE_STD__ 0.01 #ifdef __PRINT_RACE_RESULTS__ static tdble bestLap[NBBOTS]; static tdble damages[NBBOTS]; static tdble totalTime[NBBOTS]; static int position[NBBOTS]; static int curPosition=0; static int bonusBest; static int bonusDamage; static char *trackName; #endif static tTrack *curTrack; static int RESTARTING[NBBOTS]; static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s); static void newrace(int index, tCarElt* car, tSituation *s); static void drive(int index, tCarElt* car, tSituation *s); static void endrace(int index, tCarElt *car, tSituation *s); static void shutdown(int index); static int InitFuncPt(int index, void *pt); static double normRand(double avg,double std); /**** variables for TCP ***/ static int listenSocket[NBBOTS], serverSocket[NBBOTS]; socklen_t clientAddressLength[NBBOTS]; tSockAddrIn clientAddress[NBBOTS], serverAddress[NBBOTS]; /************************************************/ static tdble oldAccel[NBBOTS]; static tdble oldBrake[NBBOTS]; static tdble oldSteer[NBBOTS]; static tdble oldClutch[NBBOTS]; static tdble prevDist[NBBOTS]; static tdble distRaced[NBBOTS]; static int oldFocus[NBBOTS];//ML static int oldGear[NBBOTS]; static Sensors *trackSens[NBBOTS]; static ObstacleSensors *oppSens[NBBOTS]; static Sensors *focusSens[NBBOTS];//ML static float trackSensAngle[NBBOTS][19]; static const char* botname[NBBOTS] = {"scr_server 1", "scr_server 2", "scr_server 3", "scr_server 4", "scr_server 5", "scr_server 6", "scr_server 7", "scr_server 8", "scr_server 9", "scr_server 10"}; static unsigned long total_tics[NBBOTS]; class image_server { private: int cam_width; int cam_height; int img_width; int img_height; int imgsize; unsigned char* cam_data; bool debug; public: image_server(){ int Window; int xw, yw; int winX, winY; void *handle; const int BUFSIZE = 1024; char buf[BUFSIZE]; snprintf(buf, BUFSIZE, "%s%s", GetLocalDir(), GFSCR_CONF_FILE); handle = GfParmReadFile(buf, GFPARM_RMODE_STD | GFPARM_RMODE_CREAT); xw = (int)GfParmGetNum(handle, GFSCR_SECT_PROP, GFSCR_ATT_X, (char*)NULL, 640); yw = (int)GfParmGetNum(handle, GFSCR_SECT_PROP, GFSCR_ATT_Y, (char*)NULL, 480); winX = (int)GfParmGetNum(handle, GFSCR_SECT_PROP, GFSCR_ATT_WIN_X, (char*)NULL, xw); winY = (int)GfParmGetNum(handle, GFSCR_SECT_PROP, GFSCR_ATT_WIN_Y, (char*)NULL, yw); cam_width = winX; cam_height = winY; img_width = 320; img_height = 240; imgsize = img_width*img_height*3; cam_data = new unsigned char[imgsize]; debug = true; } ~image_server(){ if(cam_data!=NULL) delete cam_data; cam_data = NULL; } std::string send_image(int id){ const clock_t begin_time = clock(); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_ALIGNMENT, 4); glReadBuffer(GL_FRONT); int x = id % 2; int y = id / 2; int xoff = x*img_width; int yoff = y*img_height; glReadPixels(xoff, yoff, img_width, img_height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)cam_data); // this line does not work at all std::string img((const char*)cam_data,imgsize); //about 0.5 ms ... //std::cout << "TORCS server#"<<id<<" = Grabbing Time = "<<float( clock () - begin_time ) / CLOCKS_PER_SEC * 1000 << " ms"<<std::endl; return img; } inline int getWidth(){return img_width;} inline int getHeight(){return img_height;} }; static image_server impipe; /* * Module entry point */ extern "C" int scr_server(tModInfo *modInfo) { memset(modInfo, 0, 10*sizeof(tModInfo)); for (int i = 0; i < NBBOTS; i++) { modInfo[i].name = strdup(botname[i]); // name of the module (short). modInfo[i].desc = strdup(botname[i]); // Description of the module (can be long). modInfo[i].fctInit = InitFuncPt;// Init function. modInfo[i].gfId = ROB_IDENT; // Supported framework version. modInfo[i].index = i; // Indices from 0 to 9. } return 0; } /* Module interface initialization. */ static int InitFuncPt(int index, void *pt) { tRobotItf *itf = (tRobotItf *)pt; itf->rbNewTrack = initTrack; /* Give the robot the track view called */ /* for every track change or new race */ itf->rbNewRace = newrace; /* Start a new race */ itf->rbDrive = drive; /* Drive during race */ itf->rbPitCmd = NULL; itf->rbEndRace = endrace; /* End of the current race */ itf->rbShutdown = shutdown; /* Called before the module is unloaded */ itf->index = index; /* Index used if multiple interfaces */ #ifdef _WIN32 /* WinSock Startup */ WSADATA wsaData={0}; WORD wVer = MAKEWORD(2,2); int nRet = WSAStartup(wVer,&wsaData); if(nRet == SOCKET_ERROR) { std::cout << "Failed to init WinSock library" << std::endl; exit(1); } #endif return 0; } /* Called for every track change or new race. */ static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s) { curTrack = track; *carParmHandle = NULL; #ifdef _PRINT_RACE_RESULTS__ trackName = strrchr(track->filename, '/') + 1; #endif } static void wait_for_identification(int index) { bool identified = false; char line[TCP_MSGLEN]; while (!identified) { clientAddressLength[index] = sizeof(clientAddress[index]); listenSocket[index] = accept(serverSocket[index], (struct sockaddr *) &clientAddress[index], (socklen_t*)&clientAddressLength[index]); if (listenSocket[index] < 0) perror("ERROR on accept"); //fcntl(serverSocket[index], F_SETFL, O_NONBLOCK); /* Change the socket into non-blocking state */ // Set line to all zeroes memset(line, 0x0, TCP_MSGLEN); if( recv(listenSocket[index], line, TCP_MSGLEN, 0) < 0 ) { std::cerr << "Error: problem in receiving from the listen socket"; exit(1); } // compare received string with the ID if (strncmp(line,TCP_ID,3)==0) { std::string initStr(line); if (SimpleParser::parse(initStr,std::string("init"),trackSensAngle[index],19)==false) { for (int i = 0; i < 19; ++i) { trackSensAngle[index][i] = -90 + 10.0*i; std::cout << "trackSensAngle[" << i << "] " << trackSensAngle[index][i] << std::endl; } } char line[TCP_MSGLEN]; sprintf(line,"***identified***"); // Sending the car state to the client if (sendto(listenSocket[index], line, strlen(line) + 1, 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0) std::cerr << "Error: cannot send identification message"; identified=true; } } } /* Start a new race. */ static void newrace(int index, tCarElt* car, tSituation *s) { total_tics[index]=0; /*********************************************************************************** ************************* TCP client identification ******************************** ***********************************************************************************/ bool identified=false; char line[TCP_MSGLEN]; // Set timeout if (getTimeout()>0) TCP_TIMEOUT = getTimeout(); //Set sensor range if (strcmp(getVersion(),"2009")==0) { __SENSORS_RANGE__ = 100; printf("*****2009*****\n"); } else if (strcmp(getVersion(),"2010")==0 || strcmp(getVersion(),"2011")==0 || strcmp(getVersion(),"2012")==0 || strcmp(getVersion(),"2013")==0) __SENSORS_RANGE__ = 200; else { printf("%s is not a recognized version",getVersion()); exit(0); } serverSocket[index] = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket[index] < 0) { std::cerr << "Error: cannot create ServerSocket!"; exit(1); } int enable = 1; if (setsockopt(serverSocket[index], SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0){ std::cerr << "setsockopt(REUSEADDR) failed!"; exit(1); } //impipes[index].init(getUDPListenPort()+index); //will modify name later to TCPListenPort() srand(time(NULL)); memset(&serverAddress[index], 0, sizeof(serverAddress[index])); memset(&clientAddress[index], 0, sizeof(clientAddress[index])); // Bind listen socket to listen port. serverAddress[index].sin_family = AF_INET; serverAddress[index].sin_addr.s_addr = htonl(INADDR_ANY); serverAddress[index].sin_port = htons(getUDPListenPort()+index); while (bind(serverSocket[index], (struct sockaddr *) &serverAddress[index], sizeof(serverAddress[index])) < 0) { std::cerr << std::endl << "cannot bind socket" << std::endl; //exit(1); sleep(1); } // Wait for connections from clients. listen(serverSocket[index], 1); std::cout << "Waiting for request on port " << getUDPListenPort()+index << "\n"; wait_for_identification(index); focusSens[index] = new Sensors(car, 5);//ML for (int i = 0; i < 5; ++i) {//ML focusSens[index]->setSensor(i,(car->_focusCmd)+i-2.0,200);//ML }//ML // Initialization of track sensors trackSens[index] = new Sensors(car, 19); for (int i = 0; i < 19; ++i) { trackSens[index]->setSensor(i,trackSensAngle[index][i],__SENSORS_RANGE__); #ifdef __TCP_SERVER_VERBOSE__ std::cout << "Set Track Sensors " << i+1 << " at angle " << trackSensAngle[index][i] << std::endl; #endif } // Initialization of opponents sensors oppSens[index] = new ObstacleSensors(36, curTrack, car, s, (int) __SENSORS_RANGE__); prevDist[index]=-1; } /* Drive during race. */ static void drive(int index, tCarElt* car, tSituation *s) { total_tics[index]++; #ifdef __PRINT_RACE_RESULTS__ bestLap[index]=car->_bestLapTime; damages[index]=car->_dammage; totalTime[index]=car->_timeBehindLeader; #endif #ifdef __DISABLE_RESTART__ if (RESTARTING[index]==1) { char line[101]; clientAddressLength[index] = sizeof(clientAddress[index]); // Set line to all zeroes memset(line, 0x0, 101); if (recvfrom(listenSocket[index], line, 100, 0, (struct sockaddr *) &clientAddress[index], &clientAddressLength[index]) < 0) { std::cerr << "Error: problem in receiving from the listen socket"; exit(1); } #ifdef __TCP_SERVER_VERBOSE__ // show the client's IP address std::cout << " from " << inet_ntoa(clientAddress[index].sin_addr); // show the client's port number. std::cout << ":" << ntohs(clientAddress[index].sin_port) << "\n"; // Show the line std::cout << " Received: " << line << "\n"; #endif // compare received string with the ID if (strncmp(line,TCP_ID,3)==0) { #ifdef __TCP_SERVER_VERBOSE__ std::cout << "IDENTIFIED" << std::endl; #endif char line[TCP_MSGLEN]; sprintf(line,"***identified***"); // Sending the car state to the client if (sendto(listenSocket[index], line, strlen(line) + 1, 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0) std::cerr << "Error: cannot send identification message"; RESTARTING[index]=0; } } #endif // local variables for TCP struct timeval timeVal; fd_set readSet; // computing distance to middle float dist_to_middle = 2*car->_trkPos.toMiddle/(car->_trkPos.seg->width); // computing the car angle wrt the track axis float angle = RtTrackSideTgAngleL(&(car->_trkPos)) - car->_yaw; NORM_PI_PI(angle); // normalize the angle between -PI and + PI //Update focus sensors' angle for (int i = 0; i < 5; ++i) { focusSens[index]->setSensor(i,(car->_focusCmd)+i-2.0,200); } // update the value of track sensors only as long as the car is inside the track float trackSensorOut[19]; float focusSensorOut[5];//ML if (dist_to_middle<=1.0 && dist_to_middle >=-1.0 ) { trackSens[index]->sensors_update(); for (int i = 0; i < 19; ++i) { trackSensorOut[i] = trackSens[index]->getSensorOut(i); if (getNoisy()) trackSensorOut[i] *= normRand(1,__NOISE_STD__); } focusSens[index]->sensors_update();//ML if ((car->_focusCD <= car->_curLapTime + car->_curTime)//ML Only send focus sensor reading if cooldown is over && (car->_focusCmd != 360))//ML Only send focus reading if requested by client {//ML for (int i = 0; i < 5; ++i) { focusSensorOut[i] = focusSens[index]->getSensorOut(i); if (getNoisy()) focusSensorOut[i] *= normRand(1,__FOCUS_NOISE_STD__); } car->_focusCD = car->_curLapTime + car->_curTime + 1.0;//ML Add cooldown [seconds] }//ML else//ML {//ML for (int i = 0; i < 5; ++i)//ML focusSensorOut[i] = -1;//ML During cooldown send invalid focus reading }//ML } else { for (int i = 0; i < 19; ++i) { trackSensorOut[i] = -1; } for (int i = 0; i < 5; ++i) { focusSensorOut[i] = -1; } } // update the value of opponent sensors float oppSensorOut[36]; oppSens[index]->sensors_update(s); for (int i = 0; i < 36; ++i) { oppSensorOut[i] = oppSens[index]->getObstacleSensorOut(i); if (getNoisy()) oppSensorOut[i] *= normRand(1,__OPP_NOISE_STD__); } float wheelSpinVel[4]; for (int i=0; i<4; ++i) { wheelSpinVel[i] = car->_wheelSpinVel(i); } if (prevDist[index]<0) { prevDist[index] = car->race.distFromStartLine; } float curDistRaced = car->race.distFromStartLine - prevDist[index]; prevDist[index] = car->race.distFromStartLine; if (curDistRaced>100) { curDistRaced -= curTrack->length; } if (curDistRaced<-100) { curDistRaced += curTrack->length; } distRaced[index] += curDistRaced; /********************************************************************** ****************** Building state string ***************************** **********************************************************************/ string stateString; stateString = SimpleParser::stringify("angle", angle); stateString += SimpleParser::stringify("curLapTime", float(car->_curLapTime)); if (getDamageLimit()) stateString += SimpleParser::stringify("damage", car->_dammage); else stateString += SimpleParser::stringify("damage", car->_fakeDammage); stateString += SimpleParser::stringify("distFromStart", car->race.distFromStartLine); stateString += SimpleParser::stringify("distRaced", distRaced[index]); stateString += SimpleParser::stringify("fuel", car->_fuel); stateString += SimpleParser::stringify("gear", car->_gear); stateString += SimpleParser::stringify("lastLapTime", float(car->_lastLapTime)); stateString += SimpleParser::stringify("opponents", oppSensorOut, 36); stateString += SimpleParser::stringify("racePos", car->race.pos); stateString += SimpleParser::stringify("rpm", car->_enginerpm*10); stateString += SimpleParser::stringify("speedX", float(car->_speed_x * 3.6)); stateString += SimpleParser::stringify("speedY", float(car->_speed_y * 3.6)); stateString += SimpleParser::stringify("speedZ", float(car->_speed_z * 3.6)); stateString += SimpleParser::stringify("track", trackSensorOut, 19); stateString += SimpleParser::stringify("trackPos", dist_to_middle); stateString += SimpleParser::stringify("wheelSpinVel", wheelSpinVel, 4); stateString += SimpleParser::stringify("z", car->_pos_Z - RtTrackHeightL(&(car->_trkPos))); stateString += SimpleParser::stringify("focus", focusSensorOut, 5);//ML int width = impipe.getWidth(); int height = impipe.getHeight(); stateString += SimpleParser::stringify("cam_width", width); stateString += SimpleParser::stringify("cam_height", height); char line[TCP_MSGLEN]; memset(line,'0',TCP_MSGLEN); sprintf(line,"%s",stateString.c_str()); if (RESTARTING[index]==0) { #ifdef __TCP_SERVER_VERBOSE__ std::cout << "Sending: " << line << std::endl; #endif #ifdef __STEP_LIMIT__ if (total_tics[index]>__STEP_LIMIT__) { RESTARTING[index] = 1; car->RESTART=1; char fileName[200]; sprintf(fileName,"%s.txt",trackName); printf("%s.txt\n",trackName); FILE *f = fopen (fileName,"a"); printf("Dist_raced %lf\n",distRaced[index]); fprintf(f,"Dist_raced %lf\n",distRaced[index]); fclose(f); return; } #endif //printf("size of first message = %d\n",strlen(line)); // Sending the car state to the client if (sendto(listenSocket[index], line, 1000, 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0){ std::cerr << "Error: cannot send car state"; //sleep(0.001); } // Sending the image after std::string im_msg = impipe.send_image(index); if (sendto(listenSocket[index], im_msg.c_str(), im_msg.size(), 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0){ std::cerr << "Error: cannot send car image"; } // Set timeout for client answer FD_ZERO(&readSet); FD_SET(listenSocket[index], &readSet); timeVal.tv_sec = 0; timeVal.tv_usec = TCP_TIMEOUT; memset(line, 0x0,1000 ); if (select(listenSocket[index]+1, &readSet, NULL, NULL, &timeVal)) { // Read the client controller action memset(line, 0x0,TCP_MSGLEN ); // Zero out the buffer. int numRead = recv(listenSocket[index], line, TCP_MSGLEN, 0); //if (numRead < 0) //{ //handle it? //std::cerr << "Error, cannot get any response from the client!"; //CLOSE(listenSocket[index]); //exit(1); //} #ifdef __TCP_SERVER_VERBOSE__ std::cout << "Received: " << line << std::endl; #endif std::string lineStr(line); CarControl carCtrl(lineStr); if (carCtrl.getMeta()==RACE_RESTART) { RESTARTING[index] = 1; #ifdef __DISABLE_RESTART__ char line[TCP_MSGLEN]; sprintf(line,"***restart***"); // Sending the car state to the client if (sendto(listenSocket[index], line, strlen(line) + 1, 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0) std::cerr << "Error: cannot send restart message"; #else car->RESTART=1; #endif } //std::cout<<"CarControl#"<<index<<" "<<lineStr<<std::endl; // Set controls command and store them in variables oldAccel[index] = car->_accelCmd = carCtrl.getAccel(); oldBrake[index] = car->_brakeCmd = carCtrl.getBrake(); oldGear[index] = car->_gearCmd = carCtrl.getGear(); oldSteer[index] = car->_steerCmd = carCtrl.getSteer(); oldClutch[index] = car->_clutchCmd = carCtrl.getClutch(); oldFocus[index] = car->_focusCmd = carCtrl.getFocus();//ML } else { //#ifdef __TCP_SERVER_VERBOSE__ std::cout << "Timeout for client answer\n"; //#endif // If no new controls are availables uses old ones... car->_accelCmd = oldAccel[index]; car->_brakeCmd = oldBrake[index]; car->_gearCmd = oldGear[index]; car->_steerCmd = oldSteer[index]; car->_clutchCmd = oldClutch[index]; car->_focusCmd = oldFocus[index];//ML } } else { car->_accelCmd = oldAccel[index]; car->_brakeCmd = oldBrake[index]; car->_gearCmd = oldGear[index]; car->_steerCmd = oldSteer[index]; car->_clutchCmd = oldClutch[index]; car->_focusCmd = oldFocus[index];//ML } } /* End of the current race */ static void endrace(int index, tCarElt *car, tSituation *s) { RESTARTING[index]=0; if (trackSens != NULL) { delete trackSens[index]; trackSens[index] = NULL; } if (oppSens[index] != NULL) { delete oppSens[index]; oppSens[index] = NULL; } if (focusSens[index] != NULL)//ML { delete focusSens[index]; focusSens[index] = NULL; } } /* Called before the module is unloaded */ static void shutdown(int index) { #ifdef __PRINT_RACE_RESULTS__ #define max_pos 8 int points[]={10,8,6,5,4,3,2,1}; curPosition++; position[index]=curPosition; if (curPosition==1) { bonusBest=index; bonusDamage=index; } else { if (bestLap[index] < bestLap[bonusBest] && bestLap[index] > 0) bonusBest=index; if (damages[index] < damages[bonusDamage]) bonusDamage=index; } if (curPosition==max_pos) { char fileName[200]; sprintf(fileName,"%s.txt",trackName); printf("%s.txt\n",trackName); FILE *f = fopen (fileName,"a"); for(int i = 0; i<max_pos; i++) { int curPoints = points[position[i]-1]; if (bonusBest==i) curPoints+=2; if (bonusDamage==i) curPoints+=2; fprintf(f,"driver-%d,%d,%d,%f,%f,%f\n",i+1,position[i],curPoints,totalTime[i],bestLap[i],damages[i]); printf("driver-%d,%d,%d,%f,%f,%f\n",i+1,position[i],curPoints,totalTime[i],bestLap[i],damages[i]); } fprintf(f,"\n\n\n"); fclose(f); } //std::cout << "car,pos,points,time,bestLap,damages"<< std::endl; //std::cout << "champ" << (index+1) <<"," << position <<"," << points[position-1] <<"," << totalTime[index] <<"," << bestLap[index] <<"\t" << damages[index]<< std::endl; #endif if (RESTARTING[index]!=1) { char line[TCP_MSGLEN]; sprintf(line,"***shutdown***"); // Sending the car state to the client if (sendto(listenSocket[index], line, strlen(line) + 1, 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0) std::cerr << "Error: cannot send shutdown message"; } else { char line[TCP_MSGLEN]; sprintf(line,"***restart***"); // Sending the car state to the client if (sendto(listenSocket[index], line, strlen(line) + 1, 0, (struct sockaddr *) &clientAddress[index], sizeof(clientAddress[index])) < 0) std::cerr << "Error: cannot send shutdown message"; } RESTARTING[index]=0; if (trackSens[index] != NULL) { delete trackSens[index]; trackSens[index] = NULL; } if (focusSens[index] != NULL)//ML { delete focusSens[index]; focusSens[index] = NULL; } if (oppSens[index] != NULL) { delete oppSens[index]; oppSens[index] = NULL; } printf("CLOSE Listen Socket \n"); shutdown(listenSocket[index], SHUT_RDWR); close(listenSocket[index]); shutdown(serverSocket[index], SHUT_RDWR); close(serverSocket[index]); } double normRand(double avg,double std) { double x1, x2, w, y1, y2; do { x1 = 2.0 * rand()/(double(RAND_MAX)) - 1.0; x2 = 2.0 * rand()/(double(RAND_MAX)) - 1.0; w = x1 * x1 + x2 * x2; } while ( w >= 1.0 ); w = sqrt( (-2.0 * log( w ) ) / w ); y1 = x1 * w; y2 = x2 * w; return y1*std + avg; }
[ "ahmad.elsallab@gmail.com" ]
ahmad.elsallab@gmail.com
77a8b69a1e1011de075407a59959bdf8a0c1cfd4
8726841917e4999289451334c356e97f966ee776
/C++/367 Valid Perfect Square.cpp
5101b06a9f43fc5dbdac8877fe18c44917b81a2d
[]
no_license
weiho1122/LeetCode
cf890eaf3b8299897431564d811c52d1a95f6d94
ac986cb0ccba053afbb21b7fe6ec8fa5f767da5e
refs/heads/master
2021-01-11T02:04:40.560365
2016-09-13T00:09:04
2016-09-13T00:09:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
423
cpp
//Binary Search class Solution { public: bool isPerfectSquare(int num) { long left = 0, right = num; while(left <= right){ long mid = (left + right) / 2; if(mid*mid > num){ right = mid - 1; }else if(mid*mid < num){ left = mid + 1; }else{ return true; } } return false; } };
[ "zhangweiqi357@gmail.com" ]
zhangweiqi357@gmail.com
58ae181f67755bbb0d4934055a58692691f66d24
bc8987a779a5f21f3fb5b961944f96ff479b4836
/HackerEarth/ArraysAndVectors/MaximumSumSubArray.cpp
de18b81d80534439608cddef87a26de96bfa4352
[]
no_license
Aditya1788/DataStructuresAndAlgorithms
4ffdfdff76597aa23b9bdcfbdb694b99684425d6
44b50a41e0683488225ee8a9953af0468e272a86
refs/heads/master
2023-03-22T14:35:27.898734
2021-03-16T23:54:21
2021-03-16T23:54:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
420
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll call(ll arr[], ll n){ ll localMax = arr[0]; ll maximum = arr[0]; for(ll i=1;i<n;i++){ localMax = max(localMax + arr[i] , arr[i]); maximum = max(maximum, localMax); } return maximum; } int main(){ ll arr[8]={-2,-4,9,-1,8,5,-10,11}; cout << "The maximum sum subarray is: " << endl; cout << call(arr,8) << endl; return 0; }
[ "kitsarpgyawali@gmail.com" ]
kitsarpgyawali@gmail.com
971c259ae51f50ac8a0886b61e1b87dad4db17f5
cb438ea6c4a38cdfef86e8da77494c916a643f12
/PlaySketch/Box2D-new/Examples/TestBed/Tests/CCDTest.h
45514e855cf429f5b07e934c86dc2f26ff12a8b3
[ "Zlib" ]
permissive
SummerTree/playsketch
d638d6bac9264b98a8ca407f0eecdc31f8f38202
3580de21b2fc3cc6cb6974f39892af6e602a6e9e
refs/heads/master
2020-12-31T02:02:28.057892
2013-01-28T14:05:45
2013-01-28T14:05:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,995
h
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef CCD_TEST_H #define CCD_TEST_H class CCDTest : public Test { public: CCDTest() { #if 0 m_world->m_gravity.SetZero(); { b2PolygonDef sd; sd.SetAsBox(0.1f, 10.0f); sd.density = 0.0f; b2BodyDef bd; bd.position.Set(0.0f, 20.0f); b2Body* body = m_world->CreateBody(&bd); body->CreateShape(&sd); } { b2PolygonDef sd; sd.SetAsBox(0.1f, 2.0f); sd.density = 1.0f; sd.restitution = 0.0f; m_angularVelocity = RandomFloat(-50.0f, 50.0f); //m_angularVelocity = 8.5009336f; b2BodyDef bd; bd.type = b2BodyDef::e_dynamicBody; bd.position.Set(50.0f, 20.0f); b2Body* body = m_world->CreateBody(&bd); body->CreateShape(&sd); body->SetMassFromShapes(); body->SetLinearVelocity(b2Vec2(-200.0f, 0.0f)); body->SetAngularVelocity(m_angularVelocity); } #elif 0 { b2PolygonDef sd; sd.SetAsBox(10.0f, 0.1f); sd.density = 0.0f; b2BodyDef bd; bd.type = b2BodyDef::e_static; bd.position.Set(0.0f, -0.2f); b2Body* ground = m_world->CreateBody(&bd); ground->CreateShape(&sd); } { b2PolygonDef sd; sd.SetAsBox(2.0f, 0.1f); sd.density = 1.0f; sd.restitution = 0.0f; b2BodyDef bd1; bd1.type = b2BodyDef::e_dynamic; bd1.isBullet = true; bd1.allowSleep = false; bd1.position.Set(0.0f, 20.0f); b2Body* b1 = m_world->Create(&bd1); b1->CreateShape(&sd); b1->SetMassFromShapes(); b1->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); sd.SetAsBox(1.0f, 0.1f); b2BodyDef bd2; bd2.type = b2BodyDef::e_dynamic; bd2.isBullet = true; bd2.allowSleep = false; bd2.position.Set(0.0f, 20.2f); b2Body* b2 = m_world->Create(&bd2); b2->CreateShape(&sd); b2->SetMassFromShapes(); b2->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); sd.SetAsBox(0.25f, 0.25f); sd.density = 10.0f; b2BodyDef bd3; bd3.type = b2BodyDef::e_dynamic; bd3.isBullet = true; bd3.allowSleep = false; bd3.position.Set(0.0f, 100.0f); b2Body* b3 = m_world->Create(&bd3); b3->CreateShape(&sd); b3->SetMassFromShapes(); b3->SetLinearVelocity(b2Vec2(0.0f, -150.0f)); } #else const float32 k_restitution = 1.4f; { b2BodyDef bd; bd.position.Set(0.0f, 20.0f); b2Body* body = m_world->CreateBody(&bd); b2PolygonDef sd; sd.density = 0.0f; sd.restitution = k_restitution; sd.SetAsBox(0.1f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0f); body->CreateShape(&sd); sd.SetAsBox(0.1f, 10.0f, b2Vec2(10.0f, 0.0f), 0.0f); body->CreateShape(&sd); sd.SetAsBox(0.1f, 10.0f, b2Vec2(0.0f, -10.0f), 0.5f * b2_pi); body->CreateShape(&sd); sd.SetAsBox(0.1f, 10.0f, b2Vec2(0.0f, 10.0f), -0.5f * b2_pi); body->CreateShape(&sd); } #if 0 { b2PolygonDef sd_bottom; sd_bottom.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -1.0f), 0.0f); sd_bottom.density = 4.0f; b2PolygonDef sd_top; sd_top.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, 1.0f), 0.0f); sd_top.density = 4.0f; b2PolygonDef sd_left; sd_left.SetAsBox(0.1f, 1.0f, b2Vec2(-1.0f, 0.0f), 0.0f); sd_left.density = 4.0f; b2PolygonDef sd_right; sd_right.SetAsBox(0.1f, 1.0f, b2Vec2(1.0f, 0.0f), 0.0f); sd_right.density = 4.0f; b2BodyDef bd; bd.type = b2BodyDef::e_dynamicBody; bd.position.Set(0.0f, 15.0f); b2Body* body = m_world->CreateBody(&bd); body->CreateShape(&sd_bottom); body->CreateShape(&sd_top); body->CreateShape(&sd_left); body->CreateShape(&sd_right); body->SetMassFromShapes(); } #elif 1 { b2PolygonDef sd_bottom; sd_bottom.SetAsBox( 1.5f, 0.15f ); sd_bottom.density = 4.0f; b2PolygonDef sd_left; sd_left.SetAsBox(0.15f, 2.7f, b2Vec2(-1.45f, 2.35f), 0.2f); sd_left.density = 4.0f; b2PolygonDef sd_right; sd_right.SetAsBox(0.15f, 2.7f, b2Vec2(1.45f, 2.35f), -0.2f); sd_right.density = 4.0f; b2BodyDef bd; bd.position.Set( 0.0f, 15.0f ); b2Body* body = m_world->CreateBody(&bd); body->CreateShape(&sd_bottom); body->CreateShape(&sd_left); body->CreateShape(&sd_right); body->SetMassFromShapes(); } #else { b2BodyDef bd; bd.type = b2BodyDef::e_dynamic; bd.position.Set(-5.0f, 20.0f); bd.isBullet = true; b2Body* body = m_world->CreateBody(&bd); body->SetAngularVelocity(RandomFloat(-50.0f, 50.0f)); b2PolygonDef sd; sd.SetAsBox(0.1f, 4.0f); sd.density = 1.0f; sd.restitution = 0.0f; body->CreateShape(&sd); body->SetMassFromShapes(); } #endif for (int32 i = 0; i < 0; ++i) { b2BodyDef bd; bd.position.Set(0.0f, 15.0f + i); bd.isBullet = true; b2Body* body = m_world->CreateBody(&bd); body->SetAngularVelocity(RandomFloat(-50.0f, 50.0f)); b2CircleDef sd; sd.radius = 0.25f; sd.density = 1.0f; sd.restitution = 0.0f; body->CreateShape(&sd); body->SetMassFromShapes(); } #endif } static Test* Create() { return new CCDTest; } float32 m_angularVelocity; }; #endif
[ "a0077978@gmail.com" ]
a0077978@gmail.com
b3f3dee80a447de873b2e277cf4f8fc60d1a6818
9631d51cdca680beea07540af3a41d00c0d8d08b
/Reference_Variables/Reference_var.cpp
9bcae2435051cd022bc40a889fb223995d4e4505
[]
no_license
Prabhjotsk19/cpp-learning
b5b34c65ab775ef3796a9ce6f931edcc339fe286
372ff4e0b362d9245f5b7e6586cba0e6484b28a5
refs/heads/master
2020-06-14T00:19:05.031221
2019-07-09T11:27:05
2019-07-09T11:27:05
194,833,840
1
0
null
null
null
null
UTF-8
C++
false
false
2,963
cpp
#include <iostream> using namespace std; struct user_data { string name; int age; }; // Modify the age of person void modify_age(user_data &person){ person.age = 12; } // swap two numbers void swap(int &x, int &y){ int temp = x; x = y; y = temp; } // function return reference to x or y int & Returning_by_Refrerence(int &x, int &y){ if (x > y) return x; // it means int & x = ... ; else return y; } int main(){ // Refernce Variables int number = 34; // Refernce to number int & num = number; // both the varibles number and num refer to same data object in the memory cout << num << " " << number << endl; cout << &num << " " << &number << endl; // changing num also changing number num = 23; cout << num << " " << number << endl; string fruit = "Mango"; const string & ref_fruit = fruit; cout << fruit << " " << ref_fruit << endl; // ref_fruit = "Orange"; // ref_fruit is declared constant but fruit does not fruit = "Orange"; cout << fruit << " " << ref_fruit << endl; // Refernce Variables must be initialized at the time of declaration // int & num1 -> error : 'num1' declared as reference but not initialized ; // Reference to arrays int n[10]; n[9] = 12; int & x = n[9]; // xis alias for n[9] -> last element of array n[10] cout << x << endl; // initialize reference to a literal //char & a = '\n'; //cout << "c++ is a easy language!" << a; // reference to pointers int m = 23; int * p = &m; // pointer point to m int & number1 = *p; // number1 refer to pointer p but indirectly to m cout << m << " " << *p << " " << number1 << endl; // More // int & number2 = 34; // creates a int object number2 with value 34 // Reference to structures user_data person1 = {"John", 23}; user_data & person1_reference = person1; cout << person1.name << " " << person1_reference.name << endl; // reference to structures in functions parametres modify_age(person1); cout << person1.age << " " << person1_reference.age << endl; // Reference to classes // later on // Major Application in passing arguments to functions // Call by Reference int a = 23 , b = 324; cout << "Value of a and b before swapping is : " << a << " " << b << "\n"; swap(a, b); // value of x and y is changed in function swap() // but x and y are reference for a and b respectively so value of a and b also cout << "Value of a and b after swapping is : " << a << " " << b << "\n"; // Returning values by refer int digit1 = 34, digit2 = 67; int greater_digit = Returning_by_Refrerence(digit1, digit2); int a1 ; Returning_by_Refrerence(digit1, digit2) = 12; cout << digit2 << endl; cout << greater_digit << endl; return 0; } /* References Variables are other name for my variables References -> Characteristics (vs Pointers) 1. no NULL references 2. Once initialized and created can't be changed their value 3. must be initialized when declared 4. are of same type of initialized variables */
[ "pskaler2015@gmail.com" ]
pskaler2015@gmail.com
7cebe583550058c4fbc391e6a28f615f439be890
1c818a1e212018b143adb2c6d001cf78c3718039
/MapFinderApp/MapFinderApp/Room.h
3688f5515558af3788e426aff892ab671a1f262c
[ "MIT" ]
permissive
Cwagner213/LevelCreator
5d2846d6003f5b44f440e2a845d9d734c10c1ef8
dd8f093e3465298daf94ffe9952939c3225e7eeb
refs/heads/master
2020-03-29T01:52:32.267588
2019-02-20T18:17:19
2019-02-20T18:17:19
149,411,255
0
0
null
null
null
null
UTF-8
C++
false
false
165
h
#pragma once #include "stdafx.h" #include <stdlib.h> #include "Vector2.h" class Room { public: unsigned int width; unsigned int height; Vector2 origin; };
[ "cjwagner211@gmail.com" ]
cjwagner211@gmail.com
d60b696067fb5f6f7b61aadaa3990f4aacf61a94
aecf4944523b50424831f8af3debef67e3163b97
/net.ssa/xr_3da/xrGame/AI/Stalker/ai_stalker_space.h
509cec16a4ef92a8d3fdb5ed0ecbc4fe37f0c47a
[]
no_license
xrLil-Batya/gitxray
bc8c905444e40c4da5d77f69d03b41d5b9cec378
58aaa5185f7a682b8cf5f5f376a2e5b6ca16fed4
refs/heads/main
2023-03-31T07:43:57.500002
2020-12-12T21:12:25
2020-12-12T21:12:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,958
h
//////////////////////////////////////////////////////////////////////////// // Module : ai_stalker_space.h // Created : 28.03.2003 // Modified : 28.03.2003 // Author : Dmitriy Iassenev // Description : Stalker types and structures //////////////////////////////////////////////////////////////////////////// #pragma once #define MAX_HEAD_TURN_ANGLE (1.f*PI_DIV_4) namespace StalkerSpace { enum EStalkerSounds { eStalkerSoundDie = u32(0), eStalkerSoundDieInAnomaly, eStalkerSoundInjuring, eStalkerSoundHumming, eStalkerSoundAlarm, eStalkerSoundAttack, eStalkerSoundBackup, eStalkerSoundDetour, eStalkerSoundSearch, eStalkerSoundInjuringByFriend, eStalkerSoundPanicHuman, eStalkerSoundPanicMonster, eStalkerSoundTolls, eStalkerSoundGrenadeAlarm, eStalkerSoundFriendlyGrenadeAlarm, eStalkerSoundNeedBackup, eStalkerSoundRunningInDanger, // eStalkerSoundWalkingInDanger, eStalkerSoundKillWounded, eStalkerSoundEnemyCriticallyWounded, eStalkerSoundEnemyKilledOrWounded, eStalkerSoundScript, eStalkerSoundDummy = u32(-1), }; enum EStalkerSoundMasks { eStalkerSoundMaskAnySound = u32(0), eStalkerSoundMaskDie = u32(-1), eStalkerSoundMaskDieInAnomaly = u32(-1), eStalkerSoundMaskInjuring = u32(-1), eStalkerSoundMaskInjuringByFriend = u32(-1), eStalkerSoundMaskNonTriggered = u32(1 << 31) | (1 << 30), eStalkerSoundMaskNoHumming = (1 << 29), eStalkerSoundMaskFree = eStalkerSoundMaskNoHumming | eStalkerSoundMaskNonTriggered, eStalkerSoundMaskHumming = 1 | eStalkerSoundMaskFree, eStalkerSoundMaskNoDanger = (1 << 28), eStalkerSoundMaskDanger = eStalkerSoundMaskNoDanger | eStalkerSoundMaskNonTriggered, eStalkerSoundMaskAlarm = (1 << 0) | eStalkerSoundMaskDanger, eStalkerSoundMaskAttack = (1 << 1) | eStalkerSoundMaskDanger, eStalkerSoundMaskBackup = (1 << 2) | eStalkerSoundMaskDanger, eStalkerSoundMaskDetour = (1 << 3) | eStalkerSoundMaskDanger, eStalkerSoundMaskSearch = (1 << 4) | eStalkerSoundMaskDanger, eStalkerSoundMaskNeedBackup = (1 << 5) | eStalkerSoundMaskDanger, eStalkerSoundMaskMovingInDanger = (1 << 6) | eStalkerSoundMaskDanger, eStalkerSoundMaskKillWounded = (1 << 7) | eStalkerSoundMaskDanger, eStalkerSoundMaskEnemyCriticallyWounded = (1 << 8) | eStalkerSoundMaskDanger, eStalkerSoundMaskEnemyKilledOrWounded = (1 << 9) | eStalkerSoundMaskDanger, eStalkerSoundMaskPanicHuman = eStalkerSoundMaskDanger, eStalkerSoundMaskPanicMonster = eStalkerSoundMaskDanger, eStalkerSoundMaskTolls = eStalkerSoundMaskDanger, eStalkerSoundMaskGrenadeAlarm = eStalkerSoundMaskDanger, eStalkerSoundMaskFriendlyGrenadeAlarm = eStalkerSoundMaskDanger, eStalkerSoundMaskDummy = u32(-1), }; enum EBodyAction { eBodyActionNone = u32(0), eBodyActionHello, eBodyActionDummy = u32(-1), }; };
[ "admin@localhost" ]
admin@localhost
e0daa80f66db81597ced9fd58e0688dd52d155c0
b38890c218497424f798ceddef03cfa435dec240
/framecode/frame/clockwork.h
de3f0b2fdb093959896d79a115ab139c2f967f21
[]
no_license
sontran1001/Informatica
4ce5520f8f4cfa3cf08917e53b91564dc1a15c27
ff4a7685eed567082c94633108a9aa4c5a5348c2
refs/heads/master
2021-01-01T03:51:13.618807
2016-06-09T21:19:51
2016-06-09T21:19:51
58,767,545
0
0
null
2016-05-13T19:47:44
2016-05-13T19:35:33
null
UTF-8
C++
false
false
595
h
#ifndef __CLOCKWORK_H__ // this is done to avoid multiple inclusions #define __CLOCKWORK_H__ #include "Arduino.h" typedef unsigned long int micros_t; typedef void (*CallbackType)(unsigned long); class Clockwork { public: void init(unsigned int period_ms, CallbackType cb); Clockwork(unsigned int period_ms); // overloading Clockwork(unsigned int period_ms, CallbackType cb); void start(); bool stop(); private: micros_t _period_ms; micros_t _last_start; micros_t _last_stop; micros_t _tet; // time execution task CallbackType _cb; }; #endif
[ "sontn.ac@gmail.com" ]
sontn.ac@gmail.com
7f92fb1c88841b5c914ef6dd92dd08ea6bb2609f
e2420b2bb142a8cdc6d48f3cdfe682d7cfb9d434
/Source/GoodGame/Public/GoodGameInstance.h
1239e59799cd29466e6afdf2329fe40581e53ca7
[]
no_license
JetBoom/GoodGame
eb4a393381e6e4cc22d2cfacf34f2e47a1e6bfe1
1eea93c0ac82ea44b297e313c4a4c0828a0901db
refs/heads/master
2022-01-06T08:06:06.498035
2018-07-02T21:00:09
2018-07-02T21:00:09
78,500,334
1
0
null
null
null
null
UTF-8
C++
false
false
224
h
#pragma once #include "Engine/GameInstance.h" #include "GoodGameInstance.generated.h" UCLASS() class GOODGAME_API UGoodGameInstance : public UGameInstance { GENERATED_BODY() public: virtual void Init() override; };
[ "williammoodhe@gmail.com" ]
williammoodhe@gmail.com
7af039ac67db4a83b8efb10530c88fffb7ba8a7d
3843a9367ee129eb2dccd2411fef840ba652c82d
/Database/movie.cpp
9dbfe4780f03ef2c2f0b968d23bf700ec5a15a50
[]
no_license
nouryehia/Database
a7458cf0ec15f40cdde6f9358a5f69c9412f2ca1
add4f6ac0deb9679547227993bc34b5b92331df5
refs/heads/master
2021-05-07T04:01:21.593041
2017-12-04T07:59:47
2017-12-04T07:59:47
111,067,728
0
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
//cpp class for movie class. #include "movie.h" movie::movie(char t[80], int y, char di[80], char du[80], double r) : media(t, y){ //constructor. strcpy(director, di); strcpy(duration, du); rating = r; type = 3; } char* movie::getDirector(){ // get director. return director; } char* movie::getDuration(){ //get duration. return duration; } double movie::getRating(){ //get rating. return rating; } void movie::printInfo(){ //print info. cout << endl << title << " (Movie)" << endl << "Year: " << year << endl << "Director: " << director << endl << "Duration: " << duration << endl << "Rating: " << rating << endl; }
[ "32072322+nouryehia@users.noreply.github.com" ]
32072322+nouryehia@users.noreply.github.com
6dde9215affb67e1571762a79d1672cf7d9d8b5a
1dc7faa5c243f25b7e6b93072ac7f9f8060b4fbd
/components/include/IUpdatable.h
8931740792d9481fc8d82634396db1dd2fb09bd9
[ "MIT" ]
permissive
matheusvxf/Lighting-and-Shaders
b3dc961c3f4c5e2fe8f5721d345201cfc3f6fc95
c555cbae2a4c882a0d13d1b5e4daa5c39c020c32
refs/heads/master
2020-05-19T08:43:11.583229
2015-04-21T22:55:16
2015-04-21T22:55:16
34,141,351
0
0
null
null
null
null
UTF-8
C++
false
false
250
h
#pragma once #include "Vector3.h" #include <list> class IUpdatable { public: static std::list<IUpdatable*> list; IUpdatable(); ~IUpdatable(); virtual void update() = 0; virtual void apply_force(const Vector3& force) = 0; };
[ "matheusventuryne@gmail.com" ]
matheusventuryne@gmail.com
b8e413245814bc9232c81859aa249845bed16967
fb381224be13ed84e8e63bd7bf013dd10d58d924
/Code/Engine/Foundation/Algorithm/Implementation/HashableStruct_inl.h
7687692f22673f8fcf0854eb3007fb6eea41ca49
[ "MIT" ]
permissive
bethau/ezEngine
1b768f95801dd2367dc30675f8febb5cbb625819
059684c8d9ed7e33f8e68f218ff42a7decf668ee
refs/heads/master
2022-08-22T06:48:55.549276
2020-02-11T23:36:43
2020-02-11T23:36:43
247,667,175
0
0
MIT
2020-03-16T09:57:54
2020-03-16T09:57:53
null
UTF-8
C++
false
false
345
h
#include <Foundation/Algorithm/HashingUtils.h> #include <Foundation/Memory/MemoryUtils.h> template <typename T> ezHashableStruct<T>::ezHashableStruct() { ezMemoryUtils::ZeroFill<T>(static_cast<T*>(this), 1); } template <typename T> ezUInt32 ezHashableStruct<T>::CalculateHash() const { return ezHashingUtils::xxHash32(this, sizeof(T)); }
[ "jan@krassnigg.de" ]
jan@krassnigg.de
136cbd923b5ab326e20ab83d7c520e7fe00aee25
d826c7fce2be06ba9b7ddf2e25eddbb2aa9176ef
/final/Game.h
c0435b7574d236b5a0d444f4717dee91bb53d056
[]
no_license
nicksssssss/csc-233-projects
069f729012003767e80ce0c236d88b5615587592
47095a3ae3f65275a54b2f69f03863fc1ee9508d
refs/heads/master
2021-02-16T22:53:36.786662
2020-05-22T03:17:55
2020-05-22T03:17:55
245,050,820
0
0
null
null
null
null
UTF-8
C++
false
false
415
h
#ifndef GAME_H #define GAME_H #include "Board.h" #include "Player.h" #include "SuperBadGuy.h" class Game { public: //constructors Game(); Game(int); Game(int, int); int turn(); int checkForCollision(); void makeBoard(); void printGame(); private: std::vector<SuperBadGuy> dudes; Board board; Player player; }; #endif
[ "nswalbach8@gmail.com" ]
nswalbach8@gmail.com