本文整理汇总了C++中QList::empty方法的典型用法代码示例。如果您正苦于以下问题:C++ QList::empty方法的具体用法?C++ QList::empty怎么用?C++ QList::empty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QList
的用法示例。
在下文中一共展示了QList::empty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: sendCoins
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nRefHeight)
{
mpq total = 0;
QSet<QString> setAddress;
QString hex;
if(recipients.empty())
{
return OK;
}
if ( nRefHeight < 0 )
nRefHeight = nBestHeight;
// Pre-check input data for validity
foreach(const SendCoinsRecipient &rcp, recipients)
{
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
setAddress.insert(rcp.address);
if(rcp.amount <= 0)
{
return InvalidAmount;
}
total += rcp.amount;
}
if(recipients.size() > setAddress.size())
{
return DuplicateAddress;
}
if(total > getBalance(nRefHeight))
{
return AmountExceedsBalance;
}
mpq qBalReq = total + nTransactionFee;
if(qBalReq > getBalance(nRefHeight))
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
}
{
LOCK2(cs_main, wallet->cs_wallet);
// Sendmany
std::vector<std::pair<CScript, mpq> > vecSend;
foreach(const SendCoinsRecipient &rcp, recipients)
{
CScript scriptPubKey;
scriptPubKey.SetDestination(CNiCoInAddress(rcp.address.toStdString()).Get());
vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
}
CWalletTx wtx;
CReserveKey keyChange(wallet);
mpq nFeeRequired = 0;
bool fCreated = wallet->CreateTransaction(vecSend, nRefHeight, wtx, keyChange, nFeeRequired);
if(!fCreated)
{
if(qBalReq > wallet->GetBalance(nRefHeight))
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
}
return TransactionCreationFailed;
}
if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
{
return Aborted;
}
if(!wallet->CommitTransaction(wtx, keyChange))
{
return TransactionCommitFailed;
}
hex = QString::fromStdString(wtx.GetHash().GetHex());
}
示例2: sendCoins
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
qint64 total = 0;
QSet<QString> setAddress;
QString hex;
if(recipients.empty())
{
return OK;
}
if(isAnonymizeOnlyUnlocked())
{
return AnonymizeOnlyUnlocked;
}
// Pre-check input data for validity
foreach(const SendCoinsRecipient &rcp, recipients)
{
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
setAddress.insert(rcp.address);
if(rcp.amount <= 0)
{
return InvalidAmount;
}
total += rcp.amount;
}
if(recipients.size() > setAddress.size())
{
return DuplicateAddress;
}
int64_t nBalance = 0;
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins, true, coinControl);
BOOST_FOREACH(const COutput& out, vCoins)
nBalance += out.tx->vout[out.i].nValue;
if(total > nBalance)
{
return AmountExceedsBalance;
}
if((total + nTransactionFee) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
}
{
LOCK2(cs_main, wallet->cs_wallet);
// Sendmany
std::vector<std::pair<CScript, int64_t> > vecSend;
foreach(const SendCoinsRecipient &rcp, recipients)
{
CScript scriptPubKey;
scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
}
CWalletTx wtx;
CReserveKey keyChange(wallet);
int64_t nFeeRequired = 0;
std::string strFailReason;
bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason, coinControl);
if(!fCreated)
{
if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
}
return TransactionCreationFailed;
}
if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
{
return Aborted;
}
if(!wallet->CommitTransaction(wtx, keyChange))
{
return TransactionCommitFailed;
}
hex = QString::fromStdString(wtx.GetHash().GetHex());
}
示例3: if
void System::layout2()
{
VBox* b = vbox();
if (b) {
b->layout();
setbbox(b->bbox());
return;
}
setPos(0.0, 0.0);
QList<std::pair<int,SysStaff*>> visibleStaves;
int firstStaffIdx = -1;
int lastStaffIdx = 0;
int firstStaffInitialIdx = -1;
int lastStaffInitialIdx = 0;
Measure* fm = firstMeasure();
for (int i = 0; i < _staves.size(); ++i) {
Staff* s = score()->staff(i);
SysStaff* ss = _staves[i];
if (s->show() && ss->show()) {
visibleStaves.append(std::pair<int,SysStaff*>(i, ss));
if (firstStaffIdx == -1)
firstStaffIdx = i;
if (i > lastStaffIdx)
lastStaffIdx = i;
if (fm && fm->visible(i)) {
if (firstStaffInitialIdx == -1)
firstStaffInitialIdx = i;
lastStaffInitialIdx = i;
}
}
else {
ss->setbbox(QRectF()); // already done in layout() ?
}
}
if (firstStaffIdx == -1)
firstStaffIdx = 0;
if (firstStaffInitialIdx == -1)
firstStaffInitialIdx = 0;
qreal _spatium = spatium();
qreal y = 0.0;
qreal minVerticalDistance = score()->styleP(StyleIdx::minVerticalDistance);
qreal staffDistance = score()->styleP(StyleIdx::staffDistance);
qreal akkoladeDistance = score()->styleP(StyleIdx::akkoladeDistance);
if (visibleStaves.empty()) {
qDebug("====no visible staves, staves %d, score staves %d", _staves.size(), score()->nstaves());
}
for (auto i = visibleStaves.begin();; ++i) {
SysStaff* ss = i->second;
int si1 = i->first;
Staff* staff = score()->staff(si1);
auto ni = i + 1;
qreal h = staff->height();
if (ni == visibleStaves.end()) {
ss->setYOff(staff->lines() == 1 ? _spatium * staff->mag() : 0.0);
ss->bbox().setRect(_leftMargin, y, width() - _leftMargin, h);
break;
}
int si2 = ni->first;
qreal dist = h;
switch (staff->innerBracket()) {
case BracketType::BRACE:
dist += akkoladeDistance;
break;
case BracketType::NORMAL:
case BracketType::SQUARE:
case BracketType::LINE:
case BracketType::NO_BRACKET:
dist += staffDistance;
break;
}
dist += score()->staff(si2)->userDist();
for (MeasureBase* mb : ml) {
if (!mb->isMeasure())
continue;
Measure* m = toMeasure(mb);
Shape& s1 = m->staffShape(si1);
Shape& s2 = m->staffShape(si2);
qreal d = s1.minVerticalDistance(s2) + minVerticalDistance;
dist = qMax(dist, d);
Spacer* sp = m->mstaff(si1)->_vspacerDown;
if (sp) {
if (sp->spacerType() == SpacerType::FIXED) {
dist = staff->height() + sp->gap();
break;
}
else
dist = qMax(dist, staff->height() + sp->gap());
}
//.........这里部分代码省略.........
示例4: templatePathSelectionChanged
void TemplateOptionsWidget::templatePathSelectionChanged()
{
const QList<QListWidgetItem *> selectedPaths = m_ui->m_templatePathListWidget->selectedItems();
m_ui->m_removeTemplatePathButton->setEnabled(!selectedPaths.empty());
}
示例5: setSql
void QgsPgTableModel::setSql( const QModelIndex &index, const QString &sql )
{
if ( !index.isValid() || !index.parent().isValid() )
{
return;
}
//find out schema name and table name
QModelIndex schemaSibling = index.sibling( index.row(), DbtmSchema );
QModelIndex tableSibling = index.sibling( index.row(), DbtmTable );
QModelIndex geomSibling = index.sibling( index.row(), DbtmGeomCol );
if ( !schemaSibling.isValid() || !tableSibling.isValid() || !geomSibling.isValid() )
{
return;
}
QString schemaName = itemFromIndex( schemaSibling )->text();
QString tableName = itemFromIndex( tableSibling )->text();
QString geomName = itemFromIndex( geomSibling )->text();
QList<QStandardItem *> schemaItems = findItems( schemaName, Qt::MatchExactly, DbtmSchema );
if ( schemaItems.empty() )
{
return;
}
QStandardItem *schemaItem = schemaItems.at( DbtmSchema );
int n = schemaItem->rowCount();
for ( int i = 0; i < n; i++ )
{
QModelIndex currentChildIndex = indexFromItem( schemaItem->child( i, DbtmSchema ) );
if ( !currentChildIndex.isValid() )
{
continue;
}
QModelIndex currentTableIndex = currentChildIndex.sibling( i, DbtmTable );
if ( !currentTableIndex.isValid() )
{
continue;
}
QModelIndex currentGeomIndex = currentChildIndex.sibling( i, DbtmGeomCol );
if ( !currentGeomIndex.isValid() )
{
continue;
}
if ( itemFromIndex( currentTableIndex )->text() == tableName && itemFromIndex( currentGeomIndex )->text() == geomName )
{
QModelIndex sqlIndex = currentChildIndex.sibling( i, DbtmSql );
if ( sqlIndex.isValid() )
{
itemFromIndex( sqlIndex )->setText( sql );
break;
}
}
}
}
示例6: renderFeature
bool QgsPointDistanceRenderer::renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer, bool selected, bool drawVertexMarker )
{
Q_UNUSED( drawVertexMarker );
Q_UNUSED( context );
Q_UNUSED( layer );
//check if there is already a point at that position
if ( !feature.hasGeometry() )
return false;
QgsMarkerSymbol* symbol = firstSymbolForFeature( feature, context );
//if the feature has no symbol (eg, no matching rule in a rule-based renderer), skip it
if ( !symbol )
return false;
//point position in screen coords
QgsGeometry geom = feature.geometry();
QgsWkbTypes::Type geomType = geom.wkbType();
if ( QgsWkbTypes::flatType( geomType ) != QgsWkbTypes::Point )
{
//can only render point type
return false;
}
QString label;
if ( mDrawLabels )
{
label = getLabel( feature );
}
QgsCoordinateTransform xform = context.coordinateTransform();
QgsFeature transformedFeature = feature;
if ( xform.isValid() )
{
geom.transform( xform );
transformedFeature.setGeometry( geom );
}
double searchDistance = mTolerance * QgsSymbolLayerUtils::mapUnitScaleFactor( context, mToleranceUnit, mToleranceMapUnitScale );
QgsPoint point = transformedFeature.geometry().asPoint();
QList<QgsFeatureId> intersectList = mSpatialIndex->intersects( searchRect( point, searchDistance ) );
if ( intersectList.empty() )
{
mSpatialIndex->insertFeature( transformedFeature );
// create new group
ClusteredGroup newGroup;
newGroup << GroupedFeature( transformedFeature, symbol, selected, label );
mClusteredGroups.push_back( newGroup );
// add to group index
mGroupIndex.insert( transformedFeature.id(), mClusteredGroups.count() - 1 );
mGroupLocations.insert( transformedFeature.id(), point );
}
else
{
// find group with closest location to this point (may be more than one within search tolerance)
QgsFeatureId minDistFeatureId = intersectList.at( 0 );
double minDist = mGroupLocations.value( minDistFeatureId ).distance( point );
for ( int i = 1; i < intersectList.count(); ++i )
{
QgsFeatureId candidateId = intersectList.at( i );
double newDist = mGroupLocations.value( candidateId ).distance( point );
if ( newDist < minDist )
{
minDist = newDist;
minDistFeatureId = candidateId;
}
}
int groupIdx = mGroupIndex[ minDistFeatureId ];
ClusteredGroup& group = mClusteredGroups[groupIdx];
// calculate new centroid of group
QgsPoint oldCenter = mGroupLocations.value( minDistFeatureId );
mGroupLocations[ minDistFeatureId ] = QgsPoint(( oldCenter.x() * group.size() + point.x() ) / ( group.size() + 1.0 ),
( oldCenter.y() * group.size() + point.y() ) / ( group.size() + 1.0 ) );
// add to a group
group << GroupedFeature( transformedFeature, symbol, selected, label );
// add to group index
mGroupIndex.insert( transformedFeature.id(), groupIdx );
}
return true;
}
示例7: prepareTransaction
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl)
{
qint64 total = 0;
QList<SendCoinsRecipient> recipients = transaction.getRecipients();
std::vector<std::pair<CScript, int64_t> > vecSend;
if(recipients.empty())
{
return OK;
}
QSet<QString> setAddress; // Used to detect duplicates
int nAddresses = 0;
// Pre-check input data for validity
foreach(const SendCoinsRecipient &rcp, recipients)
{
if (rcp.paymentRequest.IsInitialized())
{ // PaymentRequest...
int64_t subtotal = 0;
const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
for (int i = 0; i < details.outputs_size(); i++)
{
const payments::Output& out = details.outputs(i);
if (out.amount() <= 0) continue;
subtotal += out.amount();
const unsigned char* scriptStr = (const unsigned char*)out.script().data();
CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, out.amount()));
}
if (subtotal <= 0)
{
return InvalidAmount;
}
total += subtotal;
}
else
{ // User-entered bitcoin address / amount:
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
if(rcp.amount <= 0)
{
return InvalidAmount;
}
setAddress.insert(rcp.address);
++nAddresses;
CScript scriptPubKey;
scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, rcp.amount));
total += rcp.amount;
}
}
if(setAddress.size() != nAddresses)
{
return DuplicateAddress;
}
qint64 nBalance = getBalance(coinControl);
if(total > nBalance)
{
return AmountExceedsBalance;
}
if((total + nTransactionFee) > nBalance)
{
transaction.setTransactionFee(nTransactionFee);
return SendCoinsReturn(AmountWithFeeExceedsBalance);
}
{
LOCK2(cs_main, wallet->cs_wallet);
transaction.newPossibleKeyChange(wallet);
int64_t nFeeRequired = 0;
std::string strFailReason;
CWalletTx *newTx = transaction.getTransaction();
CReserveKey *keyChange = transaction.getPossibleKeyChange();
bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl);
transaction.setTransactionFee(nFeeRequired);
if(!fCreated)
{
if((total + nFeeRequired) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance);
}
emit message(tr("Send Coins"), QString::fromStdString(strFailReason),
CClientUIInterface::MSG_ERROR);
return TransactionCreationFailed;
}
}
return SendCoinsReturn(OK);
}
示例8: while
SPuzzleTrace *CBDTracer<OpenListType>::trace( const int depthLimit,
const bool iterativeDeepening,
const bool graphSearch,
const CPuzzleGraphModel *graph ) const
{
bool goalFound = false;
int openNoForward = 0;
int evalNoForward = 1 + 1*graphSearch;
int openNoBackward = 2 + 1*graphSearch;
int evalNoBackward = 3 + 2*graphSearch;
int depth;
//if( graphSearch ) evalNo++;
SPuzzleTrace *newTrace = new SPuzzleTrace;
if( graph->getStartNode() == NULL ) return newTrace;
newTrace->s_aiName = "name";
newTrace->s_columnNames.append("open");
if( graphSearch ) newTrace->s_columnNames.append("closed");
newTrace->s_columnNames.append("eval");
newTrace->s_columnNames.append("open");
if( graphSearch ) newTrace->s_columnNames.append("closed");
newTrace->s_columnNames.append("eval");
newTrace->s_columnNames.append("");
if(iterativeDeepening)
depth = 0;
else
depth = depthLimit;
while(depth <= depthLimit && !goalFound)
{
SPuzzleCall *curDepth = new SPuzzleCall;
OpenListType openForward, openBackward;
CClosedList closedForward, closedBackward;
CSATraceNode evalNodeForward, evalNodeBackward;
bool exaustedForward = false;
bool exaustedBackward = false;
QList<SPuzzleNode *> goals = graph->getGoalNodeList();
QList< CSATraceNode > historyForward;
QList< CSATraceNode > historyBackward;
if(goals.empty())
{
curDepth->s_comment = "Cannot commence bi-directional search - no goals";
newTrace->s_depths.append( curDepth );
return newTrace;
}
openForward.push( CSATraceNode( graph->getStartNode() ) );
openBackward.push( CSATraceNode( goals.first() ) );
for(;;)
{
SBDLine *curLine = new SBDLine;
if(exaustedForward)
{
curLine->s_strings.append( QString() ); // open
curLine->s_strings.append( QString() ); // eval
if( graphSearch )
curLine->s_strings.append( QString() ); // closed
goto backward;
}
////////////////////////////////////////////
// Forward Search
////////////////////////////////////////////
evalNodeForward = openForward.top();
curLine->s_strings.append( openForward.getString() );
if( graphSearch ) curLine->s_strings.append( closedForward.getString() );
curLine->s_strings.append( openForward.getEvalString() );
historyForward.append( evalNodeForward );
if( historyBackward.contains( evalNodeForward ) )
{
// GOAL FOUND!
goalFound = true;
// Add relevant comment and break out of loop
//curLine->s_strings.append(
//goalString(graph, curDepth->s_lines, evalNode, openNo, evalNo) );
int index = historyBackward.indexOf( evalNodeForward );
int cost = evalNodeForward.getCost() + historyBackward[index].getCost();
// Midpoint may have different
curDepth->s_lines.append( curLine );
curDepth->s_comment =
//.........这里部分代码省略.........
示例9: fetchResults
void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &c, QgsFeedback *feedback )
{
QgsLocatorContext context( c );
// ideally this should not be required, as well behaved callers
// will NOT fire up a new fetchResults call while an existing one is
// operating/waiting to be canceled...
cancelRunningQuery();
// if no feedback object was passed, create one that is owned by this object
// to ensure that filters ALWAYS receive a valid feedback
if ( !feedback )
{
mOwnedFeedback.reset( new QgsFeedback() );
feedback = mOwnedFeedback.get();
}
else
{
mOwnedFeedback.reset( nullptr );
}
mFeedback = feedback;
QList< QgsLocatorFilter * > activeFilters;
QString searchString = string;
QString prefix = searchString.left( std::max( searchString.indexOf( ' ' ), 0 ) );
if ( !prefix.isEmpty() )
{
for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
{
if ( filter->activePrefix() == prefix && filter->enabled() )
{
activeFilters << filter;
}
}
context.usingPrefix = !activeFilters.empty();
}
if ( !activeFilters.isEmpty() )
{
searchString = searchString.mid( prefix.length() + 1 );
}
else
{
for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
{
if ( filter->useWithoutPrefix() && filter->enabled() )
{
activeFilters << filter;
}
}
}
QList< QgsLocatorFilter *> threadedFilters;
for ( QgsLocatorFilter *filter : qgis::as_const( activeFilters ) )
{
filter->clearPreviousResults();
std::unique_ptr< QgsLocatorFilter > clone( filter->clone() );
connect( clone.get(), &QgsLocatorFilter::resultFetched, clone.get(), [this, filter]( QgsLocatorResult result )
{
result.filter = filter;
emit filterSentResult( result );
} );
clone->prepare( searchString, context );
if ( clone->flags() & QgsLocatorFilter::FlagFast )
{
// filter is fast enough to fetch results on the main thread
clone->fetchResults( searchString, context, feedback );
}
else
{
// run filter in background
threadedFilters.append( clone.release() );
}
}
mActiveThreads.clear();
for ( QgsLocatorFilter *filter : qgis::as_const( threadedFilters ) )
{
QThread *thread = new QThread();
mActiveThreads.append( thread );
filter->moveToThread( thread );
connect( thread, &QThread::started, filter, [filter, searchString, context, feedback]
{
if ( !feedback->isCanceled() )
filter->fetchResults( searchString, context, feedback );
filter->emit finished();
}, Qt::QueuedConnection );
connect( filter, &QgsLocatorFilter::finished, thread, &QThread::quit );
connect( filter, &QgsLocatorFilter::finished, filter, &QgsLocatorFilter::deleteLater );
connect( thread, &QThread::finished, thread, [this, thread]
{
mActiveThreads.removeAll( thread );
if ( mActiveThreads.empty() )
emit finished();
} );
connect( thread, &QThread::finished, thread, &QThread::deleteLater );
thread->start();
}
if ( mActiveThreads.empty() )
emit finished();
//.........这里部分代码省略.........
示例10: applyOperator
bool RemoveBiasOperator::applyOperator(Individual *individual, CommandExecutor*) {
NeuralNetwork *net = dynamic_cast<NeuralNetwork*>(individual->getGenome());
if(net == 0) {
Core::log("RemoveBiasOperator: Could not apply operator because individual did not "
"provide a NeuralNetwork as genome!");
return false;
}
QString generationDate = QString::number(Evolution::getEvolutionManager()
->getCurrentGenerationValue()->get());
QList<Neuron*> neurons = net->getNeurons();
QList<Neuron*> consideredNeurons = neurons;
//remove protected neurons and neurons without bias values.
{
for(QListIterator<Neuron*> i(neurons); i.hasNext();) {
Neuron *neuron = i.next();
if(neuron->getBiasValue().get() == 0.0) {
consideredNeurons.removeAll(neuron);
continue;
}
if(neuron->hasProperty(NeuralNetworkConstants::TAG_ELEMENT_PROTECTED)) {
consideredNeurons.removeAll(neuron);
continue;
}
if(neuron->hasProperty(NeuralNetworkConstants::TAG_NEURON_PROTECT_BIAS_EXISTENCE)) {
consideredNeurons.removeAll(neuron);
continue;
}
else if(neuron->hasProperty(NeuralNetworkConstants::TAG_NEURON_PROTECT_BIAS)) {
consideredNeurons.removeAll(neuron);
continue;
}
}
}
double probability = mRemoveProbability->get();
int maxNumberOfRemovedBiases = mMaximalNumberOfRemovedBiases->get();
for(int i = 0; i < maxNumberOfRemovedBiases && !consideredNeurons.empty(); ++i) {
if(Random::nextDouble() >= probability) {
continue;
}
Neuron *neuron = consideredNeurons.value(Random::nextInt(consideredNeurons.size()));
if(neuron == 0) {
continue;
}
consideredNeurons.removeAll(neuron);
neuron->getBiasValue().set(0.0);
neuron->setProperty(NeuralNetworkConstants::PROP_ELEMENT_MODIFIED);
//mark the individual as significantly modified
individual->setProperty(EvolutionConstants::TAG_GENOME_SIGNIFICANT_CHANGE,
generationDate);
individual->setProperty(EvolutionConstants::TAG_GENOME_CHANGE_SUMMARY,
individual->getProperty(EvolutionConstants::TAG_GENOME_CHANGE_SUMMARY)
+ ",N:" + QString::number(neuron->getId()) + ":rB");
}
return true;
}
示例11: slotReceivedQuote
void KEquityPriceUpdateDlg::slotReceivedQuote(const QString& _id, const QString& _symbol, const QDate& _date, const double& _price)
{
QList<QTreeWidgetItem*> foundItems = lvEquityList->findItems(_id, Qt::MatchExactly, ID_COL);
QTreeWidgetItem* item = 0;
if (! foundItems.empty())
item = foundItems.at(0);
QTreeWidgetItem* next = 0;
if (item) {
if (_price > 0.0f && _date.isValid()) {
QDate date = _date;
if (date > QDate::currentDate())
date = QDate::currentDate();
double price = _price;
QString id = _id.toUtf8();
MyMoneySecurity sec;
if (_id.contains(" ") == 0) {
MyMoneySecurity security = MyMoneyFile::instance()->security(id);
QString factor = security.value("kmm-online-factor");
if (!factor.isEmpty()) {
price *= MyMoneyMoney(factor).toDouble();
}
try {
sec = MyMoneyFile::instance()->security(id);
sec = MyMoneyFile::instance()->security(sec.tradingCurrency());
} catch (const MyMoneyException &) {
sec = MyMoneySecurity();
}
} else {
QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
if (splitrx.indexIn(_id) != -1) {
try {
sec = MyMoneyFile::instance()->security(splitrx.cap(2).toUtf8());
} catch (const MyMoneyException &) {
sec = MyMoneySecurity();
}
}
}
item->setText(PRICE_COL, KGlobal::locale()->formatMoney(price, sec.tradingSymbol(), KMyMoneyGlobalSettings::pricePrecision()));
item->setText(DATE_COL, date.toString(Qt::ISODate));
logStatusMessage(i18n("Price for %1 updated (id %2)", _symbol, _id));
// make sure to make OK button available
btnOK->setEnabled(true);
} else {
logErrorMessage(i18n("Received an invalid price for %1, unable to update.", _symbol));
}
prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
item->setSelected(false);
// launch the NEXT one ... in case of m_fUpdateAll == false, we
// need to parse the list to find the next selected one
next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(item) + 1);
if (!m_fUpdateAll) {
while (next && !next->isSelected()) {
prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(next) + 1);
}
}
} else {
logErrorMessage(i18n("Received a price for %1 (id %2), but this symbol is not on the list. Aborting entire update.", _symbol, _id));
}
if (next) {
m_webQuote.launch(next->text(SYMBOL_COL), next->text(ID_COL), next->text(SOURCE_COL));
} else {
finishUpdate();
}
}
示例12: traitementTrame
/*----------------------------------*
* Méthode traitement de la trame *
*----------------------------------*/
bool Ihm::traitementTrame(QString trame){
//témoin timer affichage
if (ui->lbActivite->isEnabled())
ui->lbActivite->setEnabled(false);
else
ui->lbActivite->setEnabled(true);
//qDebug() << "[1] dans traitement";
//décodage trame
QString num_badge, sens, mouvement, num_lecteur;
//séparation des parties de la trame
num_badge = trame.mid(3,3); //numéro de badge
//suppression mauvais badge
if(num_badge == "000") {
qDebug("Mauvais badge.");
//obtenir date
QString date = QDateTime::currentDateTime().toString();
ui->txtAlarme->textCursor().insertText(date+"<Erreur> Mauvais badge num=000\n");
curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
return false;
}
sens = trame.mid(1,2); //niveau de réception du tag
mouvement = trame.mid(6,3); //niveau de mouvement mesuré
num_lecteur = trame.mid(9,2); //numéro du lecteur
//conversion des valeurs en int à partir de ASCII hexa et mise à l'échelle
//c'est-Ã -dire conversion de l'hexadécimal en décimal
int num_badge_i = num_badge.toInt(0,16);
int sens_i = sens.toInt(0,16);
int num_lecteur_i = num_lecteur.toInt(0,16);
int mouvement_i = mouvement.toInt(0,16);
//si le badge n'existe pas dans la BDD
if(!pBdd->badgeExiste(num_badge)){
//obtenir date
QString date = QDateTime::currentDateTime().toString();
ui->txtAlarme->textCursor().insertText(date+"<Erreur><Badge "+num_badge+QString::fromUtf8("> Badge inconnu dans la Base de données\n"));
curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
return false;
}
//badge n'existe pas sur l'IHM
if(!pDynamique.BadgeActif[num_badge_i]){
//Historique des événements (log) : nouveau badge
pBdd->setLog(1, num_badge_i); //1=nouveau badge
tll = new T_ListeLabel();
for(int i=0 ; i<MAXLECTEURS ; i++){ // init à 100
for(int j=0 ; j<MAXVAL ; j++){
tll->moySens[i][j]=100;
}
}
for(int i=0 ; i<MAXLECTEURS ; i++){
tll->sdp[i]=0; //sens de passage
tll->sdpMem[i]=0;
}
memset(tll->indMoy, 0, sizeof(tll->indMoy)); //init à 0
//obtenir vue(s) en fonction du lecteur
//déclaration QList
QList<T_TupleLecteurS> listeTupleL;
pBdd->getVueFctLect(num_lecteur_i, &listeTupleL);
//récupération des infos dans la liste
if (!listeTupleL.empty()){
for (int i = 0; i < listeTupleL.count(); i++) {
int num_vue = listeTupleL.at(i).num_vue;
//se placer sur l'onglet
QWidget *onglet;
onglet = pDynamique.onglet[num_vue];
//nouveau label dynamique pour un badge
tll->labelB[num_vue][num_badge_i] = new QLabel(onglet);
//The object will be deleted when control returns to the event loop.//ps: j'aime bien ce commentaire !
connect (tll->labelB[num_vue][num_badge_i], SIGNAL(destroyed()), tll->labelB[num_vue][num_badge_i], SLOT(deleteLater()));
//sauvegarde de ce label dans Dynamique
pDynamique.labelB[num_vue][num_badge_i] = tll->labelB[num_vue][num_badge_i];
//qDebug() << pDynamique.labelB[num_vue][num_badge_i];
//réglage par défaut du nouveau badge
tll->labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/DefaultConfigure.png"));
tll->labelB[num_vue][num_badge_i]->setGeometry(590, 620, 20, 20); // largeur hauteur à définir
}
}
//.........这里部分代码省略.........
示例13: switch
//.........这里部分代码省略.........
case VariationExtensions:
title = "Extensions for: " + word;
condition.type = SearchCondition::PatternMatch;
condition.stringValue = "*?" + word;
spec.conditions.append(condition);
topSpecs.append(spec);
condition.stringValue = word + "?*";
spec.conditions.clear();
spec.conditions.append(condition);
middleSpecs.append(spec);
condition.stringValue = "*?" + word + "?*";
spec.conditions.clear();
spec.conditions.append(condition);
bottomSpecs.append(spec);
topTitle = "Front Extensions";
middleTitle = "Back Extensions";
bottomTitle = "Double Extensions";
forceAlphabetSort = true;
break;
case VariationTranspositions:
title = "Transpositions for: " + word;
condition.type = SearchCondition::PatternMatch;
for (int i = 0; i < int(word.length()); ++i) {
condition.stringValue = word.left(i) + word.mid(i + 1, 1) +
word.mid(i, 1) + word.right(word.length() - i - 2);
spec.conditions.clear();
spec.conditions.append(condition);
topSpecs.append(spec);
}
topTitle = "Transpositions";
break;
default: break;
}
if (!wordEngine->isAcceptable(lexicon, word))
title += "*";
setWindowTitle(title);
wordLabel->setText(title);
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
// Populate the top list
QList<WordTableModel::WordItem> wordItems = getWordItems(topSpecs);
// FIXME: Probably not the right way to get alphabetical sorting instead
// of alphagram sorting
if (forceAlphabetSort)
MainSettings::setWordListGroupByAnagrams(false);
topModel->addWords(wordItems);
if (forceAlphabetSort)
MainSettings::setWordListGroupByAnagrams(origGroupByAnagrams);
int topWords = topModel->rowCount();
topTitle += " : " + QString::number(topWords) + " word";
if (topWords != 1)
topTitle += "s";
topLabel->setText(topTitle);
// Populate the middle list
if (!middleSpecs.empty()) {
wordItems = getWordItems(middleSpecs);
// FIXME: Probably not the right way to get alphabetical sorting
// instead of alphagram sorting
if (forceAlphabetSort)
MainSettings::setWordListGroupByAnagrams(false);
middleModel->addWords(wordItems);
if (forceAlphabetSort)
MainSettings::setWordListGroupByAnagrams(origGroupByAnagrams);
int middleWords = middleModel->rowCount();
middleTitle += " : " + QString::number(middleWords) + " word";
if (middleWords != 1)
middleTitle += "s";
middleLabel->setText(middleTitle);
}
// Populate the bottom list
if (!bottomSpecs.empty()) {
wordItems = getWordItems(bottomSpecs);
// FIXME: Probably not the right way to get alphabetical sorting
// instead of alphagram sorting
if (forceAlphabetSort)
MainSettings::setWordListGroupByAnagrams(false);
bottomModel->addWords(wordItems);
if (forceAlphabetSort)
MainSettings::setWordListGroupByAnagrams(origGroupByAnagrams);
int bottomWords = bottomModel->rowCount();
bottomTitle += " : " + QString::number(bottomWords) + " word";
if (bottomWords != 1)
bottomTitle += "s";
bottomLabel->setText(bottomTitle);
}
QApplication::restoreOverrideCursor();
}
示例14: sendCoins
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
{
qint64 total = 0;
QSet<QString> setAddress;
QString hex;
if(recipients.empty())
{
return OK;
}
// Pre-check input data for validity
foreach(const SendCoinsRecipient &rcp, recipients)
{
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
setAddress.insert(rcp.address);
if(rcp.amount <= 0)
{
return InvalidAmount;
}
total += rcp.amount;
}
if(recipients.size() > setAddress.size())
{
return DuplicateAddress;
}
if(total > getBalance())
{
return AmountExceedsBalance;
}
if((total + nTransactionFee) > getBalance())
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
}
{
LOCK2(cs_main, wallet->cs_wallet);
// Sendmany
std::vector<std::pair<CScript, int64> > vecSend;
foreach(const SendCoinsRecipient &rcp, recipients)
{
CScript scriptPubKey;
scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
}
CWalletTx wtx;
CReserveKey keyChange(wallet);
int64 nFeeRequired = 0;
std::string strFailReason;
bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if(!fCreated)
{
if((total + nFeeRequired) > wallet->GetBalance())
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
}
emit message(tr("Send Coins"), QString::fromStdString(strFailReason),
CClientUIInterface::MSG_ERROR);
return TransactionCreationFailed;
}
if(!uiInterface.ThreadSafeAskFee(nFeeRequired))
{
return Aborted;
}
if(!wallet->CommitTransaction(wtx, keyChange))
{
return TransactionCommitFailed;
}
hex = QString::fromStdString(wtx.GetHash().GetHex());
}
示例15: prepareTransaction
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl)
{
CAmount total = 0;
bool fSubtractFeeFromAmount = false;
QList<SendCoinsRecipient> recipients = transaction.getRecipients();
std::vector<CRecipient> vecSend;
if(recipients.empty())
{
return OK;
}
// This should never really happen, yet another safety check, just in case.
if(wallet->IsLocked()) {
return TransactionCreationFailed;
}
QSet<QString> setAddress; // Used to detect duplicates
int nAddresses = 0;
// Pre-check input data for validity
Q_FOREACH(const SendCoinsRecipient &rcp, recipients)
{
if (rcp.fSubtractFeeFromAmount)
fSubtractFeeFromAmount = true;
if (rcp.paymentRequest.IsInitialized())
{ // PaymentRequest...
CAmount subtotal = 0;
const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
for (int i = 0; i < details.outputs_size(); i++)
{
const payments::Output& out = details.outputs(i);
if (out.amount() <= 0) continue;
subtotal += out.amount();
const unsigned char* scriptStr = (const unsigned char*)out.script().data();
CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
CAmount nAmount = out.amount();
CRecipient recipient = {scriptPubKey, nAmount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
if (subtotal <= 0)
{
return InvalidAmount;
}
total += subtotal;
}
else
{ // User-entered dash address / amount:
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
if(rcp.amount <= 0)
{
return InvalidAmount;
}
setAddress.insert(rcp.address);
++nAddresses;
CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
CRecipient recipient = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient);
total += rcp.amount;
}
}
if(setAddress.size() != nAddresses)
{
return DuplicateAddress;
}
CAmount nBalance = getBalance(coinControl);
if(total > nBalance)
{
return AmountExceedsBalance;
}
{
LOCK2(cs_main, wallet->cs_wallet);
transaction.newPossibleKeyChange(wallet);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
CWalletTx *newTx = transaction.getTransaction();
CReserveKey *keyChange = transaction.getPossibleKeyChange();
if(recipients[0].fUseInstantSend && total > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN){
Q_EMIT message(tr("Send Coins"), tr("InstantSend doesn't support sending values that high yet. Transactions are currently limited to %1 DASH.").arg(sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)),
CClientUIInterface::MSG_ERROR);
return TransactionCreationFailed;
}
bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl, true, recipients[0].inputType, recipients[0].fUseInstantSend);
transaction.setTransactionFee(nFeeRequired);
if (fSubtractFeeFromAmount && fCreated)
//.........这里部分代码省略.........