void GameWidget::newGame() { for(int i=0;i<Max;i++) { for(int j=0;j<Max;j++) { map[i][j]->setVisible(false); map[i][j]->reBrothers(); map[i][j]->setInit(); } } for(int i=0;i<hCount;i++) { for(int j=0;j<wCount;j++) { map[i][j]->setVisible(true); connect(map[i][j],SIGNAL(start()),this,SLOT(createGame())); connect(map[i][j],SIGNAL(isOpen()),this,SLOT(openBlock())); connect(map[i][j],SIGNAL(isBoom()),this,SLOT(gameMiss())); connect(map[i][j],SIGNAL(isFlag()),this,SLOT(isFlag())); connect(map[i][j],SIGNAL(disFlag()),this,SLOT(disFlag())); map[i][j]->unLocked(); } } firstRun=1; emit mineSum(MineCount); }
void WidgetAnimator::_afterFinished() { if( isFlag( removeParent ) ) { parent()->deleteLater(); } else if( isFlag( removeSelf ) ) deleteLater(); emit _onFinishSignal(); }
void PositionAnimator::beforeDraw(gfx::Engine& painter ) { if( enabled() && parent() && isFlag( isActive ) ) { if( fabs(_d->currentPos.x() - _d->stopPos.x() ) > 0.5f || fabs( _d->currentPos.y() - _d->stopPos.y() ) > 0.5f ) { if( _d->stopPos.x() == ANIMATOR_UNUSE_VALUE ) _d->stopPos.setX( int(_d->currentPos.x() ) ); if( _d->stopPos.y() == ANIMATOR_UNUSE_VALUE ) _d->stopPos.setY( int(_d->currentPos.y() ) ); float fps = 1000.f / float( DateTime::elapsedTime() - _d->lastTimeUpdate + 1 ); _d->lastTimeUpdate = DateTime::elapsedTime(); float step = _d->stopPos.getDistanceFrom( _d->startPos ) / float( fps * ( _d->time / 1000.f ) ); float offsetX = _d->stopPos.x() - _d->currentPos.x(); float signX = offsetX < 0 ? -1.f : 1.f; float offsetY = _d->stopPos.y() - _d->currentPos.y(); float signY = offsetY < 0 ? -1.f : 1.f; if( _d->speed.x() != 0 || _d->speed.y() != 0 ) { offsetX = _d->speed.x(); offsetY = _d->speed.y(); } _d->currentPos += PointF( signX * std::min<float>( step, fabs( offsetX ) ), signY * std::min<float>( step, fabs( offsetY ) ) ); parent()->setPosition( _d->currentPos.toPoint() ); } else { resetFlag( isActive ); if( isFlag( debug ) ) { parent()->setPosition( _d->startPos ); return; } parent()->setVisible( isFlag( showParent ) ); _afterFinished(); } } Widget::beforeDraw( painter ); }
TER SetRegularKey::doApply () { auto const sle = view().peek( keylet::account(account_)); if (mFeeDue == zero) sle->setFlag (lsfPasswordSpent); if (ctx_.tx.isFieldPresent (sfRegularKey)) { sle->setAccountID (sfRegularKey, ctx_.tx.getAccountID (sfRegularKey)); } else { if (sle->isFlag (lsfDisableMaster) && !view().peek (keylet::signers (account_))) // Account has disabled master key and no multi-signer signer list. return tecNO_ALTERNATIVE_KEY; sle->makeFieldAbsent (sfRegularKey); } return tesSUCCESS; }
void StudentList::registerStudentRecord() { int id; string name; int kor; int math; int eng; while (1) { if (isFlag() == false) { break; } else { cout << "학생의 인적사항을 입력하시오" << endl; cout << "학번 : "; cin >> id; cout << "이름 : "; cin >> name; cout << "학생의 성적을 입력하시오" << endl; cout << "국어 : "; cin >> kor; cout << "수학 : "; cin >> math; cout << "영어 : "; cin >> eng; Student s(id, name, kor, math, eng); // 학생 Entity 생성자 insertStudent(s); // 학생 Entity의 정보를 List 객체 배열에 할당; } cout << "학번, 이름, 성적 입력 후 더 입력?(y/n)" << endl; char select; cin >> select; switch (select) { case 'y': case 'Y': flag = true; break; case 'n': case 'N': flag = false; break; default: cout << "잘못 입력하셨습니다." << endl; break; } } flag = true; // 메뉴에서 재등록을 위한 초기화 }
void PrimeSieve::doSmallPrime(const SmallPrime& sp) { if (sp.firstPrime >= start_ && sp.lastPrime <= stop_) { // callback prime numbers if (sp.index == 0) { if (isFlag(CALLBACK_PRIMES_OBJ)) cb_->callback(sp.firstPrime); if (isFlag(CALLBACK_PRIMES_OBJ_TN)) cb_tn_->callback(sp.firstPrime, threadNum_); if (isFlag(CALLBACK_PRIMES)) callback_(sp.firstPrime); if (isFlag(CALLBACK_PRIMES_TN)) callback_tn_(sp.firstPrime, threadNum_); if (isFlag(CALLBACK_PRIMES_C)) reinterpret_cast<callback_c_t>(callback_)(sp.firstPrime); if (isFlag(CALLBACK_PRIMES_C_TN)) reinterpret_cast<callback_c_tn_t>(callback_tn_)(sp.firstPrime, threadNum_); } if (isCount(sp.index)) counts_[sp.index]++; if (isPrint(sp.index)) std::cout << sp.str << '\n'; } }
void WidgetAnimator::beforeDraw(gfx::Engine& painter ) { //! draw self area in debug mode if( isFlag( debug ) ) { // painter->drawRectangleOutline( getAbsoluteRect(), Color( 0xff, 0xff, 0xff, 0 ), &getAbsoluteClippingRectRef() ); //Font font( Font::builtinName ); //if( font.available() ) // font.Draw( getInternalName(), getAbsoluteRect(), getResultColor(), true, true, NULL ); } Widget::beforeDraw( painter ); }
void FileListBox::_updateItemText(gfx::Engine& painter, ListBoxItem& item, const Rect& textRect, Font font, const Rect& frameRect ) { ListBox::_updateItemText( painter, item, textRect, font, frameRect ); if( !isFlag( showExtension ) ) { item.clear(); std::string text = vfs::Path( item.text() ).baseName( false ).toString(); Rect finalRect = font.getTextRect( text, Rect( Point(), frameRect.size() ), align::upperLeft, align::center ); item.draw( text, font, finalRect.lefttop() + Point( 10, 0) ); } if( isFlag( showTime ) ) { Font f = Font::create( FONT_1 ); std::string timeStr = item.data( "time" ).toString(); Rect finalRect = f.getTextRect( timeStr, Rect( Point(), frameRect.size() ), align::lowerRight, align::center ); item.draw( timeStr, f, finalRect.lefttop() - Point( 10, 0) ); } }
NotTEC Transactor::checkSingleSign (PreclaimContext const& ctx) { auto const id = ctx.tx.getAccountID(sfAccount); auto const sle = ctx.view.read( keylet::account(id)); auto const hasAuthKey = sle->isFieldPresent (sfRegularKey); // Consistency: Check signature & verify the transaction's signing // public key is authorized for signing. auto const spk = ctx.tx.getSigningPubKey(); if (!publicKeyType (makeSlice (spk))) { JLOG(ctx.j.trace()) << "checkSingleSign: signing public key type is unknown"; return tefBAD_AUTH; // FIXME: should be better error! } auto const pkAccount = calcAccountID ( PublicKey (makeSlice (spk))); if (pkAccount == id) { // Authorized to continue. if (sle->isFlag(lsfDisableMaster)) return tefMASTER_DISABLED; } else if (hasAuthKey && (pkAccount == sle->getAccountID (sfRegularKey))) { // Authorized to continue. } else if (hasAuthKey) { JLOG(ctx.j.trace()) << "checkSingleSign: Not authorized to use account."; return tefBAD_AUTH; } else { JLOG(ctx.j.trace()) << "checkSingleSign: Not authorized to use account."; return tefBAD_AUTH_MASTER; } return tesSUCCESS; }
/// Calculate the sieving status. /// @param processed Sum of recently processed segments. /// bool PrimeSieve::updateStatus(uint64_t processed, bool waitForLock) { if (isParallelPrimeSieveChild()) { toUpdate_ += processed; if (parent_->updateStatus(toUpdate_, waitForLock)) toUpdate_ = 0; } else { processed_ += processed; double percent = processed_ * 100.0 / (getInterval() + 1); double old = percent_; percent_ = std::min(percent, 100.0); if (isFlag(PRINT_STATUS)) printStatus(old, percent_); } return true; }
// Permet de poser un drapeau void putFlag(int x, int y) { // On execute le contenue seulement si la case n'a pas été minée if(isMined(x, y) == FALSE) { // On vérifie qu'il n'y a pas déjà un drapeau if(isFlag(x, y) == FALSE) { // On vérifie que l'on a pas mis plus de drapeau que de bombes if(nbFlags < NB_BOMBS) { // On choisit nos couleurs textbackground(B_FLAG); textcolor(C_FLAG); // On affiche le drapeau printf("%c", A_FLAG); // On ajoute le drapeau à la liste addFlag(x, y); } else { // On affiche une erreur msgZone(C_WARNING, B_WARNING); printf("You can't use more"); gotoxy(mapX+OFFSET_X+(BORDER*2), OFFSET_Y+18); printf("than %d flags", NB_BOMBS); } } else // Sinon on enlève le drapeau existant { // On choisit nos couleurs textbackground(B_MAP); textcolor(C_MAP); // On remet un case non miné printf("%c", A_MAP); // On enleve le drapeau du tableau removeFlag(x, y); } } }
bool Arguments::evaluate(int argc, char* argv[]) { // parse program arguments vector<string> args(argv + 1, argv + argc); bool is_valid = true; errors_.clear(); for (auto i = options_.begin(); i != options_.end(); ++i) { // configured options auto option = i->second; bool found = false; for (auto j = args.begin(); j != args.end(); ++j) { // given arguments string arg_name = *j; stringstream aux; aux << "-" << option->shortName(); string opt_short = aux.str(); string opt_long = "--" + option->longName(); if ((option->hasShortName() && arg_name == opt_short) || (arg_name == opt_long)) { if (!option->isFlag()) { option->value(*++j); } found = true; } } if (!found && option->required()) { stringstream ss; ss << "Option \"" << option->longName() << "\" is required!" << endl; errors_ = ss.str(); is_valid = false; break; } } return is_valid; }
UnicodeString & NumberFormatTestTuple::toString( UnicodeString &appendTo) const { appendTo.append("{"); UBool first = TRUE; for (int32_t i = 0; i < kNumberFormatTestTupleFieldCount; ++i) { if (!isFlag(i)) { continue; } if (!first) { appendTo.append(", "); } first = FALSE; appendTo.append(gFieldData[i].name); appendTo.append(": "); gFieldData[i].ops->toString(getFieldAddress(i), appendTo); } appendTo.append("}"); return appendTo; }
void parseArgs(int argCount, char* args[]) { bool hasSourceFile = false; if (argCount < 2) { abort("no parameters specified"); } for (int i = 1; i < argCount; i++) { if (isFlag(args[i])) { switch(args[i][1]) { case 'd': DEBUG_FLAG = true; break; default: std::stringstream ss; ss << "unrecognized parameter: \"" << args[i] << "\""; abort(ss.str()); } } else { sourceFileName = args[i]; fixPath(&sourceFileName); sourceFileBaseName = sourceFileName.substr(0,sourceFileName.find_last_of('.')); } } }
void ParseArguments::parse(const char * const argv[], int argc) { m_map.clear(); std::string currentfield; for (int i = 0; i < argc; i++) { if (currentfield.empty()) { const char *s = argv[i]; if (s[0] == '-') { // a flag std::string str(s+1); if (isFlag(str, m_flagfields)) { m_flags.insert(str); } else { currentfield.swap(str); } } else { m_arguments.push_back(s); } } else { const char *s = argv[i]; m_map[currentfield] = s; currentfield.clear(); } } }
// Convert a C++ object at an arbitary address to Python. PyObject *Chimera::toPyObject(void *cpp) const { if (_metatype == PyQt_PyObject::metatype) { if (_type) { // SIP knows the type (therefore it isn't really wrapped in a // PyQt_PyObject) but it's not registered with Qt. if (_name.endsWith('*')) cpp = *reinterpret_cast<void **>(cpp); return sipConvertFromType(cpp, _type, 0); } else { // Otherwise unwrap the Python object. PyQt_PyObject *pyobj_wrapper = reinterpret_cast<PyQt_PyObject *>(cpp); if (!pyobj_wrapper->pyobject) { PyErr_SetString(PyExc_TypeError, "unable to convert a QVariant back to a Python object"); return 0; } Py_INCREF(pyobj_wrapper->pyobject); return pyobj_wrapper->pyobject; } } PyObject *py = 0; switch (_metatype) { case QMetaType::Bool: py = PyBool_FromLong(*reinterpret_cast<bool *>(cpp)); break; case QMetaType::Int: if (isFlag()) { py = sipConvertFromType(cpp, _type, 0); } else if (isEnum()) { py = sipConvertFromEnum(*reinterpret_cast<int *>(cpp), _type); } else { py = SIPLong_FromLong(*reinterpret_cast<int *>(cpp)); } break; case QMetaType::UInt: { long ui = *reinterpret_cast<unsigned int *>(cpp); if (ui < 0) py = PyLong_FromUnsignedLong((unsigned long)ui); else py = SIPLong_FromLong(ui); break; } case QMetaType::Double: py = PyFloat_FromDouble(*reinterpret_cast<double *>(cpp)); break; case QMetaType::VoidStar: py = sipConvertFromVoidPtr(*reinterpret_cast<void **>(cpp)); break; case QMetaType::Long: py = SIPLong_FromLong(*reinterpret_cast<long *>(cpp)); break; case QMetaType::LongLong: py = PyLong_FromLongLong(*reinterpret_cast<qlonglong *>(cpp)); break; case QMetaType::Short: py = SIPLong_FromLong(*reinterpret_cast<short *>(cpp)); break; case QMetaType::Char: case QMetaType::UChar: py = SIPBytes_FromStringAndSize(reinterpret_cast<char *>(cpp), 1); break; case QMetaType::ULong: py = PyLong_FromUnsignedLong(*reinterpret_cast<unsigned long *>(cpp)); break; case QMetaType::ULongLong: py = PyLong_FromUnsignedLongLong(*reinterpret_cast<qulonglong *>(cpp)); break; case QMetaType::UShort: py = SIPLong_FromLong(*reinterpret_cast<unsigned short *>(cpp)); break; case QMetaType::Float: py = PyFloat_FromDouble(*reinterpret_cast<float *>(cpp)); break; case QMetaType::QObjectStar: py = sipConvertFromType(*reinterpret_cast<void **>(cpp), sipType_QObject, 0); break; case QMetaType::QWidgetStar: if (sipType_QWidget) py = sipConvertFromType(*reinterpret_cast<void **>(cpp), sipType_QWidget, 0); break; case QMetaType::QVariantList: { QVariantList *ql = reinterpret_cast<QVariantList *>(cpp); py = PyList_New(ql->size()); if (py) { for (int i = 0; i < ql->size(); ++i) { PyObject *val_obj = toAnyPyObject(ql->at(i)); if (!val_obj) { Py_DECREF(py); py = 0; break; } PyList_SET_ITEM(py, i, val_obj); } } break; } case QMetaType::QVariantMap: { py = PyDict_New(); if (py) { QVariantMap *qm = reinterpret_cast<QVariantMap *>(cpp); for (QVariantMap::const_iterator it = qm->constBegin(); it != qm->constEnd(); ++it) if (!add_variant_to_dict(py, it.key(), it.value())) { Py_DECREF(py); py = 0; break; } } break; } #if QT_VERSION >= 0x040500 case QMetaType::QVariantHash: { py = PyDict_New(); if (py) { QVariantHash *qh = reinterpret_cast<QVariantHash *>(cpp); for (QVariantHash::const_iterator it = qh->constBegin(); it != qh->constEnd(); ++it) if (!add_variant_to_dict(py, it.key(), it.value())) { Py_DECREF(py); py = 0; break; } } break; } #endif case -1: { char *s = *reinterpret_cast<char **>(cpp); if (s) { py = SIPBytes_FromString(s); } else { Py_INCREF(Py_None); py = Py_None; } break; } default: if (_type) { if (_name.endsWith('*')) { py = sipConvertFromType(*reinterpret_cast<void **>(cpp), _type, 0); } else { // Make a copy as it is a value type. void *copy = QMetaType::construct(_metatype, cpp); py = sipConvertFromNewType(copy, _type, 0); if (!py) QMetaType::destroy(_metatype, copy); } } } if (!py) PyErr_Format(PyExc_TypeError, "unable to convert a C++ '%s' instance to a Python object", _name.constData()); return py; }
bool PrimeSieve::isCount(int index) const { return isFlag(COUNT_PRIMES << index); }
// Parse the given C++ type name. bool Chimera::parse_cpp_type(const QByteArray &type) { _name = type; // Resolve any types. QByteArray resolved = resolve_types(type); if (resolved.isEmpty()) return false; // See if the type is known to Qt. _metatype = QMetaType::type(resolved.constData()); // If not then use the PyQt_PyObject wrapper. if (_metatype == QMetaType::Void) _metatype = PyQt_PyObject::metatype; // See if the type (without a pointer) is known to SIP. bool is_ptr = resolved.endsWith('*'); if (is_ptr) { resolved.chop(1); if (resolved.endsWith('*')) return false; } _type = sipFindType(resolved.constData()); if (!_type) { // This is the only fundamental pointer type recognised by Qt. if (_metatype == QMetaType::VoidStar) return true; // This is 'int', 'bool', etc. if (_metatype != PyQt_PyObject::metatype && !is_ptr) return true; if ((resolved == "char" || resolved == "const char") && is_ptr) { // This is a special value meaning a (hopefully) '\0' terminated // string. _metatype = -1; return true; } // This is an explicit 'PyQt_PyObject'. if (resolved == "PyQt_PyObject" && !is_ptr) return true; return false; } if (sipTypeIsNamespace(_type)) return false; if (sipTypeIsClass(_type)) { set_flag(); if (is_ptr) { PyTypeObject *type_obj = sipTypeAsPyTypeObject(_type); if (sipType_QWidget && PyType_IsSubtype(type_obj, sipTypeAsPyTypeObject(sipType_QWidget))) { _metatype = QMetaType::QWidgetStar; } else if (PyType_IsSubtype(type_obj, sipTypeAsPyTypeObject(sipType_QObject))) { _metatype = QMetaType::QObjectStar; } } } // We don't support pointers to enums. if (sipTypeIsEnum(_type) && is_ptr) _type = 0; if (sipTypeIsEnum(_type) || isFlag()) _metatype = QMetaType::Int; return true; }
// Parse the given Python type object. bool Chimera::parse_py_type(PyTypeObject *type_obj) { const sipTypeDef *td = sipTypeFromPyTypeObject(type_obj); if (td) { if (sipTypeIsNamespace(td)) return false; _type = td; _name = sipTypeName(td); if (sipTypeIsClass(td)) set_flag(); if (sipTypeIsEnum(td) || isFlag()) { _metatype = QMetaType::Int; } else { bool is_a_QObject = PyType_IsSubtype(type_obj, sipTypeAsPyTypeObject(sipType_QObject)); // If there is no assignment helper then assume it is a // pointer-type. if (!get_assign_helper()) _name.append('*'); _metatype = QMetaType::type(_name.constData()); // This will deal with cases where the registered type is a // super-class and specifically allows for multiple inheritance. // The problem we are solving is that we want a QGraphicsWidget to // be handled as a QGraphicsItem (which Qt registers) rather than a // QObject, specifically in the value passed as a QVariant to // QGraphicsItem::itemChange(). This solution means that it will // always be passed as a QGraphicsItem, even if there are // circumstances where it should be passed as a QObject. If we // come across such a circumstance then we may need to remove this // and implement a more specific solution in %MethodCode for the // various itemChange() implementations. if (_metatype == 0 && is_a_QObject) { PyObject *mro = type_obj->tp_mro; Q_ASSERT(PyTuple_Check(mro)); Q_ASSERT(PyTuple_GET_SIZE(mro) >= 3); for (SIP_SSIZE_T i = 1; i < PyTuple_GET_SIZE(mro) - 1; ++i) { PyTypeObject *sc = (PyTypeObject *)PyTuple_GET_ITEM(mro, i); if (sc == sipSimpleWrapper_Type || sc == sipWrapper_Type) continue; QByteArray sc_name(sc->tp_name); // QObjects are always pointers. sc_name.append('*'); _metatype = QMetaType::type(sc_name.constData()); if (_metatype >= QMetaType::User) { _type = sipTypeFromPyTypeObject(sc); _name = sc_name; _py_type = (PyObject *)sc; Py_INCREF(_py_type); return true; } } } // If it is a user type then it must be a type that SIP knows // about but was registered by Qt. if (_metatype < QMetaType::User) { if (sipType_QWidget && PyType_IsSubtype(type_obj, sipTypeAsPyTypeObject(sipType_QWidget))) { _metatype = QMetaType::QWidgetStar; } else if (is_a_QObject) { _metatype = QMetaType::QObjectStar; } else if (!sipIsExactWrappedType((sipWrapperType *)type_obj)) { // It must be a (non-QObject, non-QWidget) Python // sub-class so make sure it gets wrapped in a // PyQt_PyObject. _type = 0; _metatype = PyQt_PyObject::metatype; _name.clear(); } } } } #if PY_MAJOR_VERSION >= 3 else if (type_obj == &PyUnicode_Type) { _type = sipType_QString; _metatype = QMetaType::QString; } #else else if (type_obj == &PyString_Type || type_obj == &PyUnicode_Type) { // In this case we accept that the reverse conversion will result in an // object of a different type (i.e. a QString rather than a Python // string). _type = sipType_QString; _metatype = QMetaType::QString; } #endif else if (type_obj == &PyBool_Type) { _metatype = QMetaType::Bool; } #if PY_MAJOR_VERSION < 3 else if (type_obj == &PyInt_Type) { // We choose to map to a C++ int, even though a Python int is // potentially much larger, as it represents the most common usage in // Qt. However we will allow a larger type to be used if the context // is right. _metatype = QMetaType::Int; _inexact = true; } #endif else if (type_obj == &PyLong_Type) { // We choose to map to a C++ int for the same reasons as above and to // be consistent with Python3 where everything is a long object. If // this isn't appropriate the user can always use a string to specify // the exact C++ type they want. _metatype = QMetaType::Int; _inexact = true; } else if (type_obj == &PyFloat_Type) { _metatype = QMetaType::Double; } // Fallback to using a PyQt_PyObject. if (_metatype == QMetaType::Void) _metatype = PyQt_PyObject::metatype; // If there is no name so far then use the meta-type name. if (_name.isEmpty()) _name = QMetaType::typeName(_metatype); _py_type = (PyObject *)type_obj; Py_INCREF(_py_type); return true; }
inline void QtArgCmdLine::parse( bool parseAfterIgnoreRest ) { checkArgumentsCorrectness(); QString lastArgNameOrFlag; while( !m_context.atEnd() ) { const QString & arg = m_context.next(); QString name, nameWithoutDelims; { QString value; splitArgumentAndValue( arg, name, value ); nameWithoutDelims = removeDelimiters( name ); if( !value.isNull() ) m_context.prepend( value ); } // Argument. if( isArgument( arg ) ) { if( nameWithoutDelims.isEmpty() ) { if( !parseAfterIgnoreRest ) return; else continue; } QtArgIface * argument = findArgument( nameWithoutDelims ); lastArgNameOrFlag = name; if( argument != NULL ) { argument->process( m_context ); argument->visit( m_context ); argument->checkConstraint(); } else throw QtArgUnknownArgumentEx( QString::fromLatin1( "Unknown argument: %1" ) .arg( name ) ); } // Flag. else if( isFlag( arg ) ) { for( int i = 0, i_max = nameWithoutDelims.length() - 1; i <= i_max; ++i ) { QtArgIface * argument = findArgument( nameWithoutDelims[ i ] ); lastArgNameOrFlag = QString( m_delimiter ) + nameWithoutDelims[ i ]; if( i != i_max ) { QStringList dummyArgsList( nameWithoutDelims .right( nameWithoutDelims.length() - i - 1 ) ); QtArgCmdLineContext dummyContext( dummyArgsList ); if( argument->process( dummyContext ) ) { argument->visit( m_context ); argument->checkConstraint(); break; } } else argument->process( m_context ); argument->visit( m_context ); argument->checkConstraint(); } } // Something unexpected. else throw QtArgUnexpectedOptionEx( QString::fromLatin1( "Unexpected option: %1. " "Argument \"%2\" doesn't expect any values." ) .arg( name ).arg( lastArgNameOrFlag ) ); } checkMandatoryArguments(); }
// Convert a Python object to a QVariant. bool Chimera::fromPyObject(PyObject *py, QVariant *var, bool strict) const { // Deal with the simple case of wrapping the Python object rather than // converting it. if (_type != sipType_QVariant && _metatype == PyQt_PyObject::metatype) { // If the type was specified by a Python type (as opposed to // 'PyQt_PyObject') then check the object is an instance of it. if (_py_type && !PyObject_IsInstance(py, _py_type)) return false; *var = keep_as_pyobject(py); return true; } // Let any registered convertors have a go first. for (int i = 0; i < _registered_QVariant_convertors.count(); ++i) { bool ok; if (_registered_QVariant_convertors.at(i)(py, var, &ok)) return ok; } int iserr = 0, value_class_state; void *ptr_class, *value_class = 0; // Temporary storage for different types. union { bool tmp_bool; int tmp_int; unsigned int tmp_unsigned_int; double tmp_double; void *tmp_void_ptr; long tmp_long; qlonglong tmp_qlonglong; short tmp_short; char tmp_char; unsigned long tmp_unsigned_long; qulonglong tmp_qulonglong; unsigned short tmp_unsigned_short; unsigned char tmp_unsigned_char; float tmp_float; } tmp_storage; void *variant_data = &tmp_storage; PyErr_Clear(); QVariant variant; int metatype_used = _metatype; switch (_metatype) { case QMetaType::Bool: tmp_storage.tmp_bool = PyLong_AsLong(py); break; case QMetaType::Int: if (!_inexact || isEnum() || isFlag()) { // It must fit into a C++ int. #if PY_MAJOR_VERSION >= 3 tmp_storage.tmp_int = PyLong_AsLong(py); #else tmp_storage.tmp_int = PyInt_AsLong(py); #endif } else { // Fit it into the smallest C++ type we can. qlonglong qll = PyLong_AsLongLong(py); if (PyErr_Occurred()) { // Try again in case the value is unsigned and will fit with // the extra bit. PyErr_Clear(); qulonglong qull = static_cast<qulonglong>(PyLong_AsUnsignedLongLong(py)); if (PyErr_Occurred()) { // It won't fit into any C++ type so pass it as a Python // object. PyErr_Clear(); *var = keep_as_pyobject(py); metatype_used = QMetaType::Void; } else { tmp_storage.tmp_qulonglong = qull; metatype_used = QMetaType::ULongLong; } } else if ((qlonglong)(int)qll == qll) { // It fits in a C++ int. tmp_storage.tmp_int = qll; } else if ((qulonglong)(unsigned int)qll == (qulonglong)qll) { // The extra bit is enough for it to fit. tmp_storage.tmp_unsigned_int = qll; metatype_used = QMetaType::UInt; } else { // This fits. tmp_storage.tmp_qlonglong = qll; metatype_used = QMetaType::LongLong; } } break; case QMetaType::UInt: tmp_storage.tmp_unsigned_int = sipLong_AsUnsignedLong(py); break; case QMetaType::Double: tmp_storage.tmp_double = PyFloat_AsDouble(py); break; case QMetaType::VoidStar: tmp_storage.tmp_void_ptr = sipConvertToVoidPtr(py); break; case QMetaType::Long: tmp_storage.tmp_long = PyLong_AsLong(py); break; case QMetaType::LongLong: tmp_storage.tmp_qlonglong = PyLong_AsLongLong(py); break; case QMetaType::Short: tmp_storage.tmp_short = PyLong_AsLong(py); break; case QMetaType::Char: if (SIPBytes_Check(py) && SIPBytes_GET_SIZE(py) == 1) tmp_storage.tmp_char = *SIPBytes_AS_STRING(py); else iserr = 1; break; case QMetaType::ULong: tmp_storage.tmp_unsigned_long = sipLong_AsUnsignedLong(py); break; case QMetaType::ULongLong: tmp_storage.tmp_qulonglong = static_cast<qulonglong>(PyLong_AsUnsignedLongLong(py)); break; case QMetaType::UShort: tmp_storage.tmp_unsigned_short = sipLong_AsUnsignedLong(py); break; case QMetaType::UChar: if (SIPBytes_Check(py) && SIPBytes_GET_SIZE(py) == 1) tmp_storage.tmp_unsigned_char = *SIPBytes_AS_STRING(py); else iserr = 1; break; case QMetaType::Float: tmp_storage.tmp_float = PyFloat_AsDouble(py); break; case QMetaType::QObjectStar: tmp_storage.tmp_void_ptr = sipForceConvertToType(py, sipType_QObject, 0, SIP_NO_CONVERTORS, 0, &iserr); break; case QMetaType::QWidgetStar: if (sipType_QWidget) { tmp_storage.tmp_void_ptr = sipForceConvertToType(py, sipType_QWidget, 0, SIP_NO_CONVERTORS, 0, &iserr); } else { iserr = 1; } break; case QMetaType::QVariantList: { QVariantList ql; if (to_QVariantList(py, ql)) { *var = QVariant(ql); metatype_used = QMetaType::Void; } else { iserr = 1; } break; } case QMetaType::QVariantMap: { QVariantMap qm; if (to_QVariantMap(py, qm)) { *var = QVariant(qm); metatype_used = QMetaType::Void; } else if (strict) { iserr = 1; } else { // Assume the failure is because the key was the wrong type. PyErr_Clear(); *var = keep_as_pyobject(py); metatype_used = QMetaType::Void; } break; } #if QT_VERSION >= 0x040500 case QMetaType::QVariantHash: { QVariantHash qh; if (to_QVariantHash(py, qh)) { *var = QVariant(qh); metatype_used = QMetaType::Void; } else { iserr = 1; } break; } #endif case -1: metatype_used = QMetaType::VoidStar; if (SIPBytes_Check(py)) tmp_storage.tmp_void_ptr = SIPBytes_AS_STRING(py); else if (py == Py_None) tmp_storage.tmp_void_ptr = 0; else iserr = 1; break; default: if (_type) { if (_name.endsWith('*')) { ptr_class = sipForceConvertToType(py, _type, 0, SIP_NO_CONVERTORS, 0, &iserr); variant_data = &ptr_class; } else { value_class = sipForceConvertToType(py, _type, 0, SIP_NOT_NONE, &value_class_state, &iserr); variant_data = value_class; } } else { // This is a class we don't recognise. iserr = 1; } } if (iserr || PyErr_Occurred()) { PyErr_Format(PyExc_TypeError, "unable to convert a Python '%s' object to a C++ '%s' instance", Py_TYPE(py)->tp_name, _name.constData()); iserr = 1; } else if (_type == sipType_QVariant) { *var = QVariant(*reinterpret_cast<QVariant *>(variant_data)); } else if (metatype_used != QMetaType::Void) { *var = QVariant(metatype_used, variant_data); } // Release any temporary value-class instance now that QVariant will have // made a copy. if (value_class) sipReleaseType(value_class, _type, value_class_state); return (iserr == 0); }
TER SetTrust::doApply () { TER terResult = tesSUCCESS; STAmount const saLimitAmount (tx().getFieldAmount (sfLimitAmount)); bool const bQualityIn (tx().isFieldPresent (sfQualityIn)); bool const bQualityOut (tx().isFieldPresent (sfQualityOut)); Currency const currency (saLimitAmount.getCurrency ()); AccountID uDstAccountID (saLimitAmount.getIssuer ()); // true, iff current is high account. bool const bHigh = account_ > uDstAccountID; auto const sle = view().peek( keylet::account(account_)); std::uint32_t const uOwnerCount = sle->getFieldU32 (sfOwnerCount); // The reserve required to create the line. Note that we allow up to // two trust lines without requiring a reserve because being able to // exchange currencies is a powerful Ripple feature. // // This is also a security feature: if you're a gateway and you want to // be able to let someone use your services, you would otherwise have to // give them enough XRP to cover the incremental reserve for their trust // line. If they had no intention of using your services, they could use // the XRP for their own purposes. So we make it possible for gateways // to fund accounts in a way where there's no incentive to trick them // into creating an account you have no intention of using. XRPAmount const reserveCreate ((uOwnerCount < 2) ? XRPAmount (zero) : view().fees().accountReserve(uOwnerCount + 1)); std::uint32_t uQualityIn (bQualityIn ? tx().getFieldU32 (sfQualityIn) : 0); std::uint32_t uQualityOut (bQualityOut ? tx().getFieldU32 (sfQualityOut) : 0); if (bQualityOut && QUALITY_ONE == uQualityOut) uQualityOut = 0; std::uint32_t const uTxFlags = tx().getFlags (); bool const bSetAuth = (uTxFlags & tfSetfAuth); bool const bSetNoRipple = (uTxFlags & tfSetNoRipple); bool const bClearNoRipple = (uTxFlags & tfClearNoRipple); bool const bSetFreeze = (uTxFlags & tfSetFreeze); bool const bClearFreeze = (uTxFlags & tfClearFreeze); auto viewJ = ctx_.app.journal ("View"); if (bSetAuth && !(sle->getFieldU32 (sfFlags) & lsfRequireAuth)) { j_.trace << "Retry: Auth not required."; return tefNO_AUTH_REQUIRED; } if (account_ == uDstAccountID) { // The only purpose here is to allow a mistakenly created // trust line to oneself to be deleted. If no such trust // lines exist now, why not remove this code and simply // return an error? SLE::pointer sleDelete = view().peek ( keylet::line(account_, uDstAccountID, currency)); if (sleDelete) { j_.warning << "Clearing redundant line."; return trustDelete (view(), sleDelete, account_, uDstAccountID, viewJ); } else { j_.trace << "Malformed transaction: Can not extend credit to self."; return temDST_IS_SRC; } } SLE::pointer sleDst = view().peek (keylet::account(uDstAccountID)); if (!sleDst) { j_.trace << "Delay transaction: Destination account does not exist."; return tecNO_DST; } STAmount saLimitAllow = saLimitAmount; saLimitAllow.setIssuer (account_); SLE::pointer sleRippleState = view().peek ( keylet::line(account_, uDstAccountID, currency)); if (sleRippleState) { STAmount saLowBalance; STAmount saLowLimit; STAmount saHighBalance; STAmount saHighLimit; std::uint32_t uLowQualityIn; std::uint32_t uLowQualityOut; std::uint32_t uHighQualityIn; std::uint32_t uHighQualityOut; auto const& uLowAccountID = !bHigh ? account_ : uDstAccountID; auto const& uHighAccountID = bHigh ? account_ : uDstAccountID; SLE::ref sleLowAccount = !bHigh ? sle : sleDst; SLE::ref sleHighAccount = bHigh ? sle : sleDst; // // Balances // saLowBalance = sleRippleState->getFieldAmount (sfBalance); saHighBalance = -saLowBalance; // // Limits // sleRippleState->setFieldAmount (!bHigh ? sfLowLimit : sfHighLimit, saLimitAllow); saLowLimit = !bHigh ? saLimitAllow : sleRippleState->getFieldAmount (sfLowLimit); saHighLimit = bHigh ? saLimitAllow : sleRippleState->getFieldAmount (sfHighLimit); // // Quality in // if (!bQualityIn) { // Not setting. Just get it. uLowQualityIn = sleRippleState->getFieldU32 (sfLowQualityIn); uHighQualityIn = sleRippleState->getFieldU32 (sfHighQualityIn); } else if (uQualityIn) { // Setting. sleRippleState->setFieldU32 (!bHigh ? sfLowQualityIn : sfHighQualityIn, uQualityIn); uLowQualityIn = !bHigh ? uQualityIn : sleRippleState->getFieldU32 (sfLowQualityIn); uHighQualityIn = bHigh ? uQualityIn : sleRippleState->getFieldU32 (sfHighQualityIn); } else { // Clearing. sleRippleState->makeFieldAbsent (!bHigh ? sfLowQualityIn : sfHighQualityIn); uLowQualityIn = !bHigh ? 0 : sleRippleState->getFieldU32 (sfLowQualityIn); uHighQualityIn = bHigh ? 0 : sleRippleState->getFieldU32 (sfHighQualityIn); } if (QUALITY_ONE == uLowQualityIn) uLowQualityIn = 0; if (QUALITY_ONE == uHighQualityIn) uHighQualityIn = 0; // // Quality out // if (!bQualityOut) { // Not setting. Just get it. uLowQualityOut = sleRippleState->getFieldU32 (sfLowQualityOut); uHighQualityOut = sleRippleState->getFieldU32 (sfHighQualityOut); } else if (uQualityOut) { // Setting. sleRippleState->setFieldU32 (!bHigh ? sfLowQualityOut : sfHighQualityOut, uQualityOut); uLowQualityOut = !bHigh ? uQualityOut : sleRippleState->getFieldU32 (sfLowQualityOut); uHighQualityOut = bHigh ? uQualityOut : sleRippleState->getFieldU32 (sfHighQualityOut); } else { // Clearing. sleRippleState->makeFieldAbsent (!bHigh ? sfLowQualityOut : sfHighQualityOut); uLowQualityOut = !bHigh ? 0 : sleRippleState->getFieldU32 (sfLowQualityOut); uHighQualityOut = bHigh ? 0 : sleRippleState->getFieldU32 (sfHighQualityOut); } std::uint32_t const uFlagsIn (sleRippleState->getFieldU32 (sfFlags)); std::uint32_t uFlagsOut (uFlagsIn); if (bSetNoRipple && !bClearNoRipple && (bHigh ? saHighBalance : saLowBalance) >= zero) { uFlagsOut |= (bHigh ? lsfHighNoRipple : lsfLowNoRipple); } else if (bClearNoRipple && !bSetNoRipple) { uFlagsOut &= ~(bHigh ? lsfHighNoRipple : lsfLowNoRipple); } if (bSetFreeze && !bClearFreeze && !sle->isFlag (lsfNoFreeze)) { uFlagsOut |= (bHigh ? lsfHighFreeze : lsfLowFreeze); } else if (bClearFreeze && !bSetFreeze) { uFlagsOut &= ~(bHigh ? lsfHighFreeze : lsfLowFreeze); } if (QUALITY_ONE == uLowQualityOut) uLowQualityOut = 0; if (QUALITY_ONE == uHighQualityOut) uHighQualityOut = 0; bool const bLowDefRipple = sleLowAccount->getFlags() & lsfDefaultRipple; bool const bHighDefRipple = sleHighAccount->getFlags() & lsfDefaultRipple; bool const bLowReserveSet = uLowQualityIn || uLowQualityOut || ((uFlagsOut & lsfLowNoRipple) == 0) != bLowDefRipple || (uFlagsOut & lsfLowFreeze) || saLowLimit || saLowBalance > zero; bool const bLowReserveClear = !bLowReserveSet; bool const bHighReserveSet = uHighQualityIn || uHighQualityOut || ((uFlagsOut & lsfHighNoRipple) == 0) != bHighDefRipple || (uFlagsOut & lsfHighFreeze) || saHighLimit || saHighBalance > zero; bool const bHighReserveClear = !bHighReserveSet; bool const bDefault = bLowReserveClear && bHighReserveClear; bool const bLowReserved = (uFlagsIn & lsfLowReserve); bool const bHighReserved = (uFlagsIn & lsfHighReserve); bool bReserveIncrease = false; if (bSetAuth) { uFlagsOut |= (bHigh ? lsfHighAuth : lsfLowAuth); } if (bLowReserveSet && !bLowReserved) { // Set reserve for low account. adjustOwnerCount(view(), sleLowAccount, 1, viewJ); uFlagsOut |= lsfLowReserve; if (!bHigh) bReserveIncrease = true; } if (bLowReserveClear && bLowReserved) { // Clear reserve for low account. adjustOwnerCount(view(), sleLowAccount, -1, viewJ); uFlagsOut &= ~lsfLowReserve; } if (bHighReserveSet && !bHighReserved) { // Set reserve for high account. adjustOwnerCount(view(), sleHighAccount, 1, viewJ); uFlagsOut |= lsfHighReserve; if (bHigh) bReserveIncrease = true; } if (bHighReserveClear && bHighReserved) { // Clear reserve for high account. adjustOwnerCount(view(), sleHighAccount, -1, viewJ); uFlagsOut &= ~lsfHighReserve; } if (uFlagsIn != uFlagsOut) sleRippleState->setFieldU32 (sfFlags, uFlagsOut); if (bDefault || badCurrency() == currency) { // Delete. terResult = trustDelete (view(), sleRippleState, uLowAccountID, uHighAccountID, viewJ); } // Reserve is not scaled by load. else if (bReserveIncrease && mPriorBalance < reserveCreate) { j_.trace << "Delay transaction: Insufficent reserve to add trust line."; // Another transaction could provide XRP to the account and then // this transaction would succeed. terResult = tecINSUF_RESERVE_LINE; } else { view().update (sleRippleState); j_.trace << "Modify ripple line"; } } // Line does not exist. else if (! saLimitAmount && // Setting default limit. (! bQualityIn || ! uQualityIn) && // Not setting quality in or setting default quality in. (! bQualityOut || ! uQualityOut) && // Not setting quality out or setting default quality out. (! ((view().flags() & tapENABLE_TESTING) || view().rules().enabled(featureTrustSetAuth, ctx_.config.features)) || ! bSetAuth)) { j_.trace << "Redundant: Setting non-existent ripple line to defaults."; return tecNO_LINE_REDUNDANT; } else if (mPriorBalance < reserveCreate) // Reserve is not scaled by load. { j_.trace << "Delay transaction: Line does not exist. Insufficent reserve to create line."; // Another transaction could create the account and then this transaction would succeed. terResult = tecNO_LINE_INSUF_RESERVE; } else { // Zero balance in currency. STAmount saBalance ({currency, noAccount()}); uint256 index (getRippleStateIndex ( account_, uDstAccountID, currency)); j_.trace << "doTrustSet: Creating ripple line: " << to_string (index); // Create a new ripple line. terResult = trustCreate (view(), bHigh, account_, uDstAccountID, index, sle, bSetAuth, bSetNoRipple && !bClearNoRipple, bSetFreeze && !bClearFreeze, saBalance, saLimitAllow, // Limit for who is being charged. uQualityIn, uQualityOut, viewJ); } return terResult; }
// Fonction executé lorsque l'utilisateur choisit une case void mineCase(int x, int y) { int countBomb = 0; // permet de compter les bombes aux alentours int i, j; // Variable de recherche // On vérifie que c'est pas la deuxième fois que l'utilisateur appuie ici if(isMined(x, y) != TRUE) { // On marque cette position comme déjà miner minedX[nbMined] = x; minedY[nbMined] = y; nbMined++; } // On se positionne sur la case à miner gotoxy(x, y); if(isBomb(x, y)) { // S'il mine une bombe, la partie est teminé endGame(); } else { // // On compte les bombes aux alentours // // On définie la première case de recherche sur l'axe Y if(y != OFFSET_Y) i = y-1; else i = y; // On parcourt en Y for (i; i <= y+1 && i < mapY+OFFSET_Y; i++) { // On définie la première case de recherche sur l'axe X if(x != OFFSET_X) j = x-1; else j = x; // Puis en X for (j; j <= x+1 && j < mapX+OFFSET_X; j++) { if(i != y || j != x) { if(isBomb(j, i) == TRUE) countBomb++; // S'il y a une bombe, on l'ajoute } } } // On vérifie que le joueur n'avait pas posé un drapeau ici if(isFlag(x, y)) removeFlag(x, y); // On l'enlève si c'était le cas // On choisit nos couleurs textbackground(B_MINED); textcolor(C_MINED); if(countBomb > 0) // S'il y a des bombes aux alentours on affiche le nombre { // On change la couleur switch(countBomb) { case 1:textcolor(LIGHTBLUE);break; case 2:textcolor(LIGHTGREEN);break; case 3:textcolor(LIGHTRED);break; case 4:textcolor(BLUE);break; case 5:textcolor(RED);break; case 6:textcolor(RED);break; case 7:textcolor(RED);break; case 8:textcolor(RED);break; } // On affiche le nombre printf("%d", countBomb); } else // Sinon on affiche un vide et on va voir plus loin { printf("%c", A_MINED); // // On mine aussi aux alentours // // On définie la première case de recherche sur l'axe Y if(y != OFFSET_Y) i = y-1; else i = y; // On parcourt en Y for (i; i <= y+1 && i < mapY+OFFSET_Y; i++) { // On définie la première case de recherche sur l'axe X if(x != OFFSET_X) j = x-1; else j = x; // Puis en X for (j; j <= x+1 && j < mapX+OFFSET_X; j++) if((i != y || j != x) && isMined(j, i) != TRUE) mineCase(j, i); // On mine à coté } } } }
bool PrimeSieve::isStatus() const { return isFlag(PRINT_STATUS, CALCULATE_STATUS); }
bool PrimeSieve::isPrint() const { return isFlag(PRINT_PRIMES, PRINT_SEPTUPLETS); }
bool PrimeSieve::isCount() const { return isFlag(COUNT_PRIMES, COUNT_SEPTUPLETS); }
bool PrimeSieve::isCallback() const { return isFlag(CALLBACK_PRIMES, CALLBACK_PRIMES_C_TN); }
bool ParseArguments::flag(const std::string &field) { return isFlag(field, m_flags); }
/* * Check for primitives * Flags, Registers, Numbers, Addresses and parentheses */ Condition* Primitive(const char** str, Condition* c) { if (isFlag(next)) /* Flags */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_FLAG; c->value1 = next; } else { c->type2 = TYPE_FLAG; c->value2 = next; } scan(str); return c; } else if (isRegister(next)) /* Registers */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_REG; c->value1 = next; } else { c->type2 = TYPE_REG; c->value2 = next; } scan(str); return c; } else if (isPCBank(next)) /* PC Bank */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_PC_BANK; c->value1 = next; } else { c->type2 = TYPE_PC_BANK; c->value2 = next; } scan(str); return c; } else if (isDataBank(next)) /* Data Bank */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_DATA_BANK; c->value1 = next; } else { c->type2 = TYPE_DATA_BANK; c->value2 = next; } scan(str); return c; } else if (next == '#') /* Numbers */ { unsigned int number = 0; if (!getNumber(&number, str)) { return 0; } if (c->type1 == TYPE_NO) { c->type1 = TYPE_NUM; c->value1 = number; } else { c->type2 = TYPE_NUM; c->value2 = number; } return c; } else if (next == '$') /* Addresses */ { if ((**str >= '0' && **str <= '9') || (**str >= 'A' && **str <= 'F')) /* Constant addresses */ { unsigned int number = 0; if (!getNumber(&number, str)) { return 0; } if (c->type1 == TYPE_NO) { c->type1 = TYPE_ADDR; c->value1 = number; } else { c->type2 = TYPE_ADDR; c->value2 = number; } return c; } else if (**str == '[') /* Dynamic addresses */ { scan(str); Parentheses(str, c, '[', ']'); if (c->type1 == TYPE_NO) { c->type1 = TYPE_ADDR; } else { c->type2 = TYPE_ADDR; } return c; } else { return 0; } } else if (next == '(') { return Parentheses(str, c, '(', ')'); } return 0; }
bool PrimeSieve::isPrint(int index) const { return isFlag(PRINT_PRIMES << index); }