nuThreadPool::JobTicket nuThreadPool::JobArena::entryJob(const nuTaskSet& task_set) { Job* p_job = new Job(task_set); queueEntry(p_job); setCondition(HAS_DATA); return JobTicket(p_job); }
TopicTemplate::TopicTemplate(const char *trKey) : Wt::WTemplate(tr(trKey)) { setInternalPathEncoding(true); #ifndef WT_TARGET_JAVA setCondition("if:cpp", true); setCondition("if:java", false); bindString("doc-url", "http://www.webtoolkit.eu/wt/doc/reference/html/"); #else setCondition("if:cpp", false); setCondition("if:java", true); bindString("doc-url", "http://www.webtoolkit.eu/" "jwt/latest/doc/javadoc/eu/webtoolkit/jwt/"); #endif }
// 设置属性 bool TriggerObject::setProperty(uint id , const Any &value) { if(id > ID_NullObject_Begin && id < ID_NullObject_End) return NullObject::setProperty(id , value); switch(id) { case ID_Trigger: // 触发器设置 { return true; } break; case ID_TriggerCondition: // 满足条件 { setCondition(any_cast<bool>(value)); return true; } break; case ID_TriggerOnEnterEvent: // 进入事件 { setOnEnterEvent(any_cast<String>(value)); return true; } break; case ID_TriggerOnLeaveEvent: // 退出事件 { setOnLeaveEvent(any_cast<String>(value)); return true; } break; default: return false; break; } }
void AuthWidget::createOAuthLoginView() { if (!model_->oAuth().empty()) { setCondition("if:oauth", true); WContainerWidget *icons = new WContainerWidget(); icons->setInline(isInline()); for (unsigned i = 0; i < model_->oAuth().size(); ++i) { const OAuthService *auth = model_->oAuth()[i]; WImage *w = new WImage("css/oauth-" + auth->name() + ".png", icons); w->setToolTip(auth->description()); w->setStyleClass("Wt-auth-icon"); w->setVerticalAlignment(AlignMiddle); OAuthProcess *const process = auth->createProcess(auth->authenticationScope()); #ifndef WT_TARGET_JAVA w->clicked().connect(process, &OAuthProcess::startAuthenticate); #else process->connectStartAuthenticate(w->clicked()); #endif process->authenticated().connect (boost::bind(&AuthWidget::oAuthDone, this, process, _1)); WObject::addChild(process); } bindWidget("icons", icons); } }
void WTemplateFormView::updateViewField(WFormModel *model, WFormModel::Field field) { const std::string var = field; if (model->isVisible(field)) { setCondition("if:" + var, true); WWidget *edit = resolveWidget(var); if (!edit) { edit = createFormWidget(field); if (!edit) { LOG_ERROR("updateViewField: createFormWidget('" << field << "') returned 0"); return; } bindWidget(var, edit); } WFormWidget *fedit = dynamic_cast<WFormWidget *>(edit); if (fedit) { if (fedit->validator() != model->validator(field) && model->validator(field)) fedit->setValidator(model->validator(field)); updateViewValue(model, field, fedit); } else updateViewValue(model, field, edit); WText *info = resolve<WText *>(var + "-info"); if (!info) { info = new WText(); bindWidget(var + "-info", info); } bindString(var + "-label", model->label(field)); const WValidator::Result& v = model->validation(field); info->setText(v.message()); indicateValidation(field, model->isValidated(field), info, edit, v); edit->setDisabled(model->isReadOnly(field)); } else { setCondition("if:" + var, false); bindEmpty(var); bindEmpty(var + "-info"); } }
QtScriptForceCondition3D::QtScriptForceCondition3D(QString condition, QString u, QString v, QString w, ForceType fType) { x_ = y_ = z_ = 0.0; setCondition(condition, u, v, w); setForceType(fType); }
void MSBuildQbsProductProject::addFiles(const GeneratableProject &project, const GeneratableProductData &product) { auto itemGroup = new MSBuildItemGroup(this); std::map<QString, MSBuildFileItem *> sourceFileNodes; std::map<QString, QStringList> sourceFileEnabledConfigurations; // Create a ClCompile item for each source file, keeping track of which configurations that // file's containing group is enabled in QMapIterator<QString, qbs::ProductData> productDataIt(product.data); while (productDataIt.hasNext()) { productDataIt.next(); for (const auto &group : productDataIt.value().groups()) { for (const auto &sourceArtifact : group.allSourceArtifacts()) { const auto filePath = sourceArtifact.filePath(); if (sourceFileNodes.find(filePath) == sourceFileNodes.end()) { sourceFileNodes.insert({ filePath, fileItemForFileTags(sourceArtifact.fileTags(), itemGroup) }); } auto fileItem = sourceFileNodes[filePath]; QString path = project.baseBuildDirectory().relativeFilePath(filePath); // The path still might not be relative (for example if the file item is // located on a different drive) if (QFileInfo(path).isRelative()) path = QStringLiteral("$(ProjectDir)") + path; fileItem->setFilePath(path); if (group.isEnabled()) sourceFileEnabledConfigurations[filePath] << productDataIt.key(); } } } // Add ExcludedFromBuild item metadata to each file for each configuration // where that file's containing group is disabled for (const auto &sourceFileNode : sourceFileNodes) { QMapIterator<QString, qbs::Project> projIt(project.projects); while (projIt.hasNext()) { projIt.next(); if (!sourceFileEnabledConfigurations[sourceFileNode.first].contains(projIt.key())) { auto metadata = new MSBuildItemMetadata( QStringLiteral("ExcludedFromBuild"), QStringLiteral("true"), sourceFileNode.second); metadata->setCondition(QStringLiteral("'$(Configuration)|$(Platform)'=='") + MSBuildUtils::fullName(projIt.value()) + QStringLiteral("'")); } } } auto import = new MSBuildImport(this); import->setProject(QStringLiteral("$(VCTargetsPath)\\Microsoft.Cpp.targets")); }
void HospitalInternalPaymentForm::create() { m_conditionGroup = new QButtonGroup(this); m_summarizing = new QRadioButton; m_summarizing->setText(QObject::tr("汇总")); m_particulars = new QRadioButton; m_particulars->setText(QObject::tr("明细")); m_conditionGroup->addButton(m_particulars,0); m_conditionGroup->addButton(m_summarizing,1); connect(m_summarizing, SIGNAL(clicked(bool)), this, SLOT(setCondition())); connect(m_particulars, SIGNAL(clicked(bool)), this, SLOT(setCondition())); connect(m_startDateEdit, SIGNAL(dateChanged(QDate)),this, SLOT(setCondition())); connect(m_endDateEdit, SIGNAL(dateChanged(QDate)),this, SLOT(setCondition())); m_allDueIncomeEdit->setReadOnly(true); m_allDueIncomeEdit->setStyleSheet(g_strLineEditNoBorder); }
QtScriptFemCondition3D::QtScriptFemCondition3D(const QtScriptFemCondition3D &femCondition) { isU_ = femCondition.isU_; u_ = femCondition.u_; isV_ = femCondition.isV_; v_ = femCondition.v_; isW_ = femCondition.isW_; w_ = femCondition.w_; script_ = femCondition.script_; setCondition(script_); }
QtScriptFemCondition3D::QtScriptFemCondition3D(QString condition, bool isU, double u, bool isV, double v, bool isW, double w) { isU_ = isU; u_ = u; isV_ = isV; v_ = v; isW_= isW; w_ = w; script_ = condition; setCondition(script_); }
void AuthWidget::updatePasswordLoginView() { if (model_->passwordAuth()) { setCondition("if:passwords", true); updateView(model_); WInteractWidget *login = resolve<WInteractWidget *>("login"); if (!login) { login = new WPushButton(tr("Wt.Auth.login")); login->clicked().connect(this, &AuthWidget::attemptPasswordLogin); bindWidget("login", login); model_->configureThrottling(login); if (model_->baseAuth()->emailVerificationEnabled()) { WText *text = new WText(tr("Wt.Auth.lost-password")); text->clicked().connect(this, &AuthWidget::handleLostPassword); bindWidget("lost-password", text); } else bindEmpty("lost-password"); if (registrationEnabled_) { WInteractWidget *w; if (!basePath_.empty()) { w = new WAnchor (WLink(WLink::InternalPath, basePath_ + "register"), tr("Wt.Auth.register")); } else { w = new WText(tr("Wt.Auth.register")); w->clicked().connect(this, &AuthWidget::registerNewUser); } bindWidget("register", w); } else bindEmpty("register"); if (model_->baseAuth()->emailVerificationEnabled() && registrationEnabled_) bindString("sep", " | "); else bindEmpty("sep"); } model_->updateThrottling(login); } else { bindEmpty("lost-password"); bindEmpty("sep"); bindEmpty("register"); bindEmpty("login"); } }
void nuThreadPool::JobArena::schedulerProc(void* param) { nuThreadPool* p_pool = static_cast< nuThreadPool* >(param); NU_TRACE("Opening job arena.\n"); mCondition.lock(); while(!mExit) { if(mUnfinishedJob > 0) nuThread::usleep(500); while(mConditionValue == EMPTY && mUnfinishedJob == 0) { mState = STATE_WAIT; mCondition.wait(); if(mExit) break; } if(mExit) break; mState = STATE_RUNNING; if(mUnfinishedJob == 0) setCondition(EMPTY); if(!mJobList.empty()) processFinishedJob(); if(!mEntryList.empty()) processJobEntry(); if(!mJobList.empty()) { for(ui32 ui = 0; ui < MAX_WORKER; ui++) { Worker& worker = p_pool->mWorker[ui]; if(worker.isIdling()) { Task* p_task = getAvailableTask(); if(p_task) worker.assignTask(p_task); else break; } } } } mCondition.unlock(); mState = STATE_IDLE; NU_TRACE("Closing job arena.\n"); }
ConditionWidget::ConditionWidget(ComplexCondition* condition, QWidget *parent) : QListView(parent) { mModel = new QStandardItemModel(this); setModel(mModel); setEditTriggers(QAbstractItemView::NoEditTriggers); setItemDelegate(new ConditionWidgetDelegate(this)); setCondition(condition); setContextMenuPolicy(Qt::ActionsContextMenu); mSelectedCondition = 0; QAction* deleteAction = new QAction(QIcon(":/media/delete.png"), tr("Delete"), this); deleteAction->setShortcut(QKeySequence::Delete); deleteAction->setShortcutContext(Qt::WidgetShortcut); addAction(deleteAction); connect(deleteAction, SIGNAL(triggered()), this, SLOT(onDeleteTriggered())); }
void Fence9::setFence(GLenum condition) { if (!mQuery) { mQuery = mRenderer->allocateEventQuery(); if (!mQuery) { return gl::error(GL_OUT_OF_MEMORY); } } HRESULT result = mQuery->Issue(D3DISSUE_END); ASSERT(SUCCEEDED(result)); setCondition(condition); setStatus(GL_FALSE); }
void NotificationItem::restoreState(QSettings* settings) { //settings = Core::ICore::instance()->settings(); setSoundCollectionPath(Utils::PathUtils().InsertDataPath(settings->value(QLatin1String("SoundCollectionPath"), tr("")).toString())); setCurrentLanguage(settings->value(QLatin1String("CurrentLanguage"), tr("")).toString()); setDataObject(settings->value(QLatin1String("DataObject"), tr("")).toString()); setObjectField(settings->value(QLatin1String("ObjectField"), tr("")).toString()); setCondition(settings->value(QLatin1String("RangeLimit"), tr("")).toInt()); setSound1(settings->value(QLatin1String("Sound1"), tr("")).toString()); setSound2(settings->value(QLatin1String("Sound2"), tr("")).toString()); setSound3(settings->value(QLatin1String("Sound3"), tr("")).toString()); setSayOrder(settings->value(QLatin1String("SayOrder"), tr("")).toInt()); QVariant value = settings->value(QLatin1String("Value1"), tr("")); setSingleValue(value); setValueRange2(settings->value(QLatin1String("Value2"), tr("")).toDouble()); setRetryValue(settings->value(QLatin1String("Repeat"), tr("")).toInt()); setLifetime(settings->value(QLatin1String("ExpireTimeout"), tr("")).toInt()); setMute(settings->value(QLatin1String("Mute"), tr("")).toInt()); }
void Fence11::setFence(GLenum condition) { if (!mQuery) { D3D11_QUERY_DESC queryDesc; queryDesc.Query = D3D11_QUERY_EVENT; queryDesc.MiscFlags = 0; if (FAILED(mRenderer->getDevice()->CreateQuery(&queryDesc, &mQuery))) { return gl::error(GL_OUT_OF_MEMORY); } } mRenderer->getDeviceContext()->End(mQuery); setCondition(condition); setStatus(GL_FALSE); }
Node<BranchNode>::Link IfStatementParser::ifStatement() { auto branch = Node<BranchNode>::make(); branch->setTrace(current().trace); branch->setCondition(expression()); branch->setSuccessBlock(block(IF_BLOCK)); skip(-1); // Go back to the block termination token if (accept(TT::ELSE)) { skip(); // Else-if structure if (accept(TT::IF)) { skip(); branch->setFailiureBlock(ifStatement()); // Simple else block } else if (accept(TT::DO)) { branch->setFailiureBlock(block(CODE_BLOCK)); } else { throw Error("SyntaxError", "Else must be followed by a block or an if statement", current().trace); } } return branch; }
void KCValidity::loadOdfValidationCondition(QString &valExpression, const KCValueParser *parser) { if (isEmpty()) return; QString value; if (valExpression.indexOf("<=") == 0) { value = valExpression.remove(0, 2); setCondition(KCConditional::InferiorEqual); } else if (valExpression.indexOf(">=") == 0) { value = valExpression.remove(0, 2); setCondition(KCConditional::SuperiorEqual); } else if (valExpression.indexOf("!=") == 0) { //add Differentto attribute value = valExpression.remove(0, 2); setCondition(KCConditional::DifferentTo); } else if (valExpression.indexOf('<') == 0) { value = valExpression.remove(0, 1); setCondition(KCConditional::Inferior); } else if (valExpression.indexOf('>') == 0) { value = valExpression.remove(0, 1); setCondition(KCConditional::Superior); } else if (valExpression.indexOf('=') == 0) { value = valExpression.remove(0, 1); setCondition(KCConditional::Equal); } else kDebug(36003) << " I don't know how to parse it :" << valExpression; if (restriction() == KCValidity::Date) { setMinimumValue(parser->tryParseDate(value)); } else if (restriction() == KCValidity::Date) { setMinimumValue(parser->tryParseTime(value)); } else { bool ok = false; setMinimumValue(KCValue(value.toDouble(&ok))); if (!ok) { setMinimumValue(KCValue(value.toInt(&ok))); if (!ok) kDebug(36003) << " Try to parse this value :" << value; #if 0 if (!ok) setMinimumValue(value); #endif } } }
void Machinery::setup(const kerberos::StringMap & settings) { // ----------------------------------------------------------- // Creates condition, algorithms, expositors, heuristics and io handlers. LINFO << "Starting conditions: " + settings.at("condition"); std::vector<Condition *> conditions = Factory<Condition>::getInstance()->createMultiple(settings.at("condition")); for(int i = 0; i < conditions.size(); i++) { conditions[i]->setup(settings); } setCondition(conditions); LINFO << "Starting algorithm: " + settings.at("algorithm"); Algorithm * algorithm = Factory<Algorithm>::getInstance()->create(settings.at("algorithm")); algorithm->setup(settings); setAlgorithm(algorithm); LINFO << "Starting expositor: " + settings.at("expositor"); Expositor * expositor = Factory<Expositor>::getInstance()->create(settings.at("expositor")); expositor->setup(settings); setExpositor(expositor); LINFO << "Starting heuristic: " + settings.at("heuristic"); Heuristic * heuristic = Factory<Heuristic>::getInstance()->create(settings.at("heuristic")); heuristic->setup(settings); setHeuristic(heuristic); LINFO << "Starting io devices: " + settings.at("io"); std::vector<Io *> ios = Factory<Io>::getInstance()->createMultiple(settings.at("io")); for(int i = 0; i < ios.size(); i++) { ios[i]->setup(settings); } setIo(ios); }
void RegistrationWidget::update() { if (model_->passwordAuth()) bindString("password-description", tr("Wt.Auth.password-registration")); else bindEmpty("password-description"); updateView(model_); if (!created_) { WLineEdit *password = resolve<WLineEdit *> (RegistrationModel::ChoosePasswordField); WLineEdit *password2 = resolve<WLineEdit *> (RegistrationModel::RepeatPasswordField); WText *password2Info = resolve<WText *> (RegistrationModel::RepeatPasswordField + std::string("-info")); if (password && password2 && password2Info) model_->validatePasswordsMatchJS(password, password2, password2Info); } WAnchor *isYou = resolve<WAnchor *>("confirm-is-you"); if (!isYou) { isYou = new WAnchor(std::string("#"), tr("Wt.Auth.confirm-is-you")); isYou->hide(); bindWidget("confirm-is-you", isYou); } if (model_->isConfirmUserButtonVisible()) { if (!isYou->clicked().isConnected()) isYou->clicked().connect(this, &RegistrationWidget::confirmIsYou); isYou->show(); } else isYou->hide(); if (model_->isFederatedLoginVisible()) { if (!conditionValue("if:oauth")) { setCondition("if:oauth", true); if (model_->passwordAuth()) bindString("oauth-description", tr("Wt.Auth.or-oauth-registration")); else bindString("oauth-description", tr("Wt.Auth.oauth-registration")); WContainerWidget *icons = new WContainerWidget(); icons->addStyleClass("Wt-field"); for (unsigned i = 0; i < model_->oAuth().size(); ++i) { const OAuthService *service = model_->oAuth()[i]; WImage *w = new WImage("css/oauth-" + service->name() + ".png", icons); w->setToolTip(service->description()); w->setStyleClass("Wt-auth-icon"); w->setVerticalAlignment(AlignMiddle); OAuthProcess *const process = service->createProcess(service->authenticationScope()); w->clicked().connect(process, &OAuthProcess::startAuthenticate); process->authenticated().connect (boost::bind(&RegistrationWidget::oAuthDone, this, process, _1)); WObject::addChild(process); } bindWidget("icons", icons); } } else { setCondition("if:oauth", false); bindEmpty("icons"); } if (!created_) { WPushButton *okButton = new WPushButton(tr("Wt.Auth.register")); WPushButton *cancelButton = new WPushButton(tr("Wt.WMessageBox.Cancel")); bindWidget("ok-button", okButton); bindWidget("cancel-button", cancelButton); okButton->clicked().connect(this, &RegistrationWidget::doRegister); cancelButton->clicked().connect(this, &RegistrationWidget::close); created_ = true; } }
void QXmppStanza::Error::setConditionFromStr(const QString& type) { if(type == "bad-request") setCondition(BadRequest); else if(type == "conflict") setCondition(Conflict); else if(type == "feature-not-implemented") setCondition(FeatureNotImplemented); else if(type == "forbidden") setCondition(Forbidden); else if(type == "gone") setCondition(Gone); else if(type == "internal-server-error") setCondition(InternalServerError); else if(type == "item-not-found") setCondition(ItemNotFound); else if(type == "jid-malformed") setCondition(JidMalformed); else if(type == "not-acceptable") setCondition(NotAcceptable); else if(type == "not-allowed") setCondition(NotAllowed); else if(type == "not-authorized") setCondition(NotAuthorized); else if(type == "payment-required") setCondition(PaymentRequired); else if(type == "recipient-unavailable") setCondition(RecipientUnavailable); else if(type == "redirect") setCondition(Redirect); else if(type == "registration-required") setCondition(RegistrationRequired); else if(type == "remote-server-not-found") setCondition(RemoteServerNotFound); else if(type == "remote-server-timeout") setCondition(RemoteServerTimeout); else if(type == "resource-constraint") setCondition(ResourceConstraint); else if(type == "service-unavailable") setCondition(ServiceUnavailable); else if(type == "subscription-required") setCondition(SubscriptionRequired); else if(type == "undefined-condition") setCondition(UndefinedCondition); else if(type == "unexpected-request") setCondition(UnexpectedRequest); else setCondition(static_cast<QXmppStanza::Error::Condition>(-1)); }
UpdatePasswordWidget::UpdatePasswordWidget(const User& user, const AbstractPasswordService& auth, Login& login, bool promptPassword, WContainerWidget *parent) : WTemplate(tr("Wt.Auth.template.update-password"), parent), user_(user), promptPassword_(promptPassword), validated_(false), enterPasswordFields_(0) { addFunction("id", &WTemplate::Functions::id); addFunction("tr", &WTemplate::Functions::tr); WLineEdit *nameEdit = new WLineEdit(user.identity(Identity::LoginName)); nameEdit->disable(); nameEdit->addStyleClass("Wt-disabled"); bindWidget("user-name", nameEdit); WPushButton *okButton = new WPushButton(tr("Wt.WMessageBox.Ok")); WPushButton *cancelButton = new WPushButton(tr("Wt.WMessageBox.Cancel")); if (promptPassword_) { setCondition("if:old-password", true); WLineEdit *oldPasswd = new WLineEdit(); WText *oldPasswdInfo = new WText(); enterPasswordFields_ = new EnterPasswordFields(auth, oldPasswd, oldPasswdInfo, okButton, this); oldPasswd->setFocus(); bindWidget("old-password", oldPasswd); bindWidget("old-password-info", oldPasswdInfo); } WLineEdit *password = new WLineEdit(); password->setEchoMode(WLineEdit::Password); password->keyWentUp().connect (boost::bind(&UpdatePasswordWidget::checkPassword, this)); password->changed().connect (boost::bind(&UpdatePasswordWidget::checkPassword, this)); WText *passwordInfo = new WText(); WLineEdit *password2 = new WLineEdit(); password2->setEchoMode(WLineEdit::Password); password2->changed().connect (boost::bind(&UpdatePasswordWidget::checkPassword2, this)); WText *password2Info = new WText(); bindWidget("choose-password", password); bindWidget("choose-password-info", passwordInfo); bindWidget("repeat-password", password2); bindWidget("repeat-password-info", password2Info); model_ = new RegistrationModel(auth.baseAuth(), *user.database(), login, this); model_->addPasswordAuth(&auth); model_->setValue(RegistrationModel::LoginName, user.identity(Identity::LoginName)); model_->setValue(RegistrationModel::Email, WT_USTRING::fromUTF8(user.email() + " " + user.unverifiedEmail())); model_->validatePasswordsMatchJS(password, password2, password2Info); passwordInfo->setText(model_->validationResult (RegistrationModel::Password).message()); password2Info->setText(model_->validationResult (RegistrationModel::Password2).message()); okButton->clicked().connect(this, &UpdatePasswordWidget::doUpdate); cancelButton->clicked().connect(this, &UpdatePasswordWidget::close); bindWidget("ok-button", okButton); bindWidget("cancel-button", cancelButton); if (!promptPassword_) password->setFocus(); }
int readNWSLine(Project* project, char *line, int fileFormat, DateTime day1, DateTime day2) // // Input: line = line of data from rainfall data file // fileFormat = code of data file's format // day1 = starting day of record of interest // day2 = ending day of record of interest // Output: returns -1 if past end of desired record, 0 if data line could // not be read successfully or 1 if line read successfully // Purpose: reads a line of data from a rainfall data file and writes its // data to the rain interface file. // { char flag1, flag2, isMissing; DateTime date1; long result = 1; int k, y, m, d, n; int hour, minute; long v; float x; int lineLength = strlen(line)-1; int nameLength = 0; // --- get year, month, & day from line switch ( fileFormat ) { case NWS_TAPE: if ( lineLength <= 30 ) return 0; if (sscanf(&line[17], "%4d%2d%4d%3d", &y, &m, &d, &n) < 4) return 0; k = 30; break; case NWS_SPACE_DELIMITED: if ( project->hasStationName ) nameLength = 31; if ( lineLength <= 28 + nameLength ) return 0; k = 18 + nameLength; if (sscanf(&line[k], "%4d %2d %2d", &y, &m, &d) < 3) return 0; k = k + 10; break; case NWS_COMMA_DELIMITED: if ( lineLength <= 28 ) return 0; if ( sscanf(&line[18], "%4d,%2d,%2d", &y, &m, &d) < 3 ) return 0; k = 28; break; case NWS_ONLINE_60: case NWS_ONLINE_15: if ( lineLength <= project->DataOffset + 23 ) return 0; if ( sscanf(&line[project->DataOffset], "%4d%2d%2d", &y, &m, &d) < 3 ) return 0; k = project->DataOffset + 8; break; default: return 0; } // --- see if date is within period of record requested date1 = datetime_encodeDate(y, m, d); if ( day1 != NO_DATE && date1 < day1 ) return 0; if ( day2 != NO_DATE && date1 > day2 ) return -1; // --- read each recorded rainfall time, value, & codes from line while ( k < lineLength ) { flag1 = 0; flag2 = 0; v = 99999; hour = 25; minute = 0; switch ( fileFormat ) { case NWS_TAPE: n = sscanf(&line[k], "%2d%2d%6ld%c%c", &hour, &minute, &v, &flag1, &flag2); k += 12; break; case NWS_SPACE_DELIMITED: n = sscanf(&line[k], " %2d%2d %6ld %c %c", &hour, &minute, &v, &flag1, &flag2); k += 16; break; case NWS_COMMA_DELIMITED: n = sscanf(&line[k], ",%2d%2d,%6ld,%c,%c", &hour, &minute, &v, &flag1, &flag2); k += 16; break; case NWS_ONLINE_60: case NWS_ONLINE_15: n = sscanf(&line[k], " %2d:%2d", &hour, &minute); n += sscanf(&line[project->ValueOffset], "%8ld %c", &v, &flag1); // --- ending hour 0 is really hour 24 of previous day if ( hour == 0 ) { hour = 24; date1 -= 1.0; } k += lineLength; break; default: n = 0; } // --- check that we at least have an hour, minute & value // (codes might be left off of the line) if ( n < 3 || hour >= 25 ) break; // --- set special condition code & update daily & hourly counts setCondition(project,flag1); if ( project->Condition == DELETED_PERIOD || project->Condition == MISSING_PERIOD || flag1 == 'M' ) isMissing = TRUE; else if ( v >= 9999 ) isMissing = TRUE; else isMissing = FALSE; // --- handle accumulation codes if ( flag1 == 'a' ) { project->AccumStartDate = date1 + datetime_encodeTime(hour, minute, 0); } else if ( flag1 == 'A' ) { saveAccumRainfall(project,date1, hour, minute, v); } // --- handle all other conditions else { // --- convert rain measurement to inches & save it x = (float)v / 100.0f; if ( x > 0 || isMissing ) saveRainfall(project,date1, hour, minute, x, isMissing); } // --- reset condition code if special condition period ended if ( flag1 == 'A' || flag1 == '}' || flag1 == ']') project->Condition = 0; } return result; }
int Actionary::loadExecutionSteps(MetaAction* act) { return setCondition(act, 3); }
ASTNode::Link XMLParser::parseXMLNode(rapidxml::xml_node<>* node) { auto safeAttr = [node](std::string what, std::string defaultValue = "") -> std::string { auto attr = node->first_attribute(what.c_str()); if (attr != nullptr) return attr->value(); else return defaultValue; }; auto requiredAttr = [node](std::string what) -> std::string { auto attr = node->first_attribute(what.c_str()); if (attr != nullptr) return attr->value(); else throw XMLParseError("Can't find required attribute", { METADATA_PAIRS, {"missing attribute", what} }); }; auto funArgs = [node, &safeAttr]() -> FunctionSignature::Arguments { FunctionSignature::Arguments args {}; std::vector<std::string> stringArgs = split(safeAttr("args"), ','); for (auto& arg : stringArgs) { std::vector<std::string> namePlusTypes = split(arg, ':'); std::vector<std::string> types = split(namePlusTypes[1], ' '); args.push_back(std::make_pair(namePlusTypes[0], TypeList(ALL(types)))); } return args; }; auto funRet = [node, &safeAttr]() -> TypeInfo { std::vector<std::string> returnTypes = split(safeAttr("return"), ' '); return returnTypes.size() == 0 ? nullptr : TypeInfo(TypeList(ALL(returnTypes))); }; auto funBlock = [=](Node<FunctionNode>::Link f) { if (!f->isForeign()) { auto codeBlock = node->first_node("block"); if (codeBlock == nullptr) throw XMLParseError("Method missing code block", {METADATA_PAIRS}); f->setCode(Node<BlockNode>::staticPtrCast(parseXMLNode(codeBlock))); } }; auto getVisibility = [node, &safeAttr]() -> Visibility { return fromString(safeAttr("visibility", "private")); }; auto boolAttr = [node, &safeAttr](std::string what) -> bool { return safeAttr(what, "false") == "true"; }; if (node == nullptr) throw XMLParseError("Null node", {METADATA_PAIRS}); std::string name = node->name(); if (name == "block") { std::string type = safeAttr("type", "code"); BlockType bt = type == "root" ? ROOT_BLOCK : type == "if" ? IF_BLOCK : type == "function" ? FUNCTION_BLOCK : CODE_BLOCK; auto block = Node<BlockNode>::make(bt); parseChildren(node, block); return block; } else if (name == "return") { auto retNode = Node<ReturnNode>::make(); auto val = node->first_node("expr"); if (val != nullptr) retNode->setValue(Node<ExpressionNode>::dynPtrCast(parseXMLNode(val))); return retNode; } else if (name == "expr") { TokenType tokenType = TT::findByPrettyName(requiredAttr("type")); std::string data = requiredAttr("value"); std::unique_ptr<Token> content; if (tokenType == TT::OPERATOR) { content = std::make_unique<Token>(tokenType, Operator::find(data), defaultTrace); } else { content = std::make_unique<Token>(tokenType, data, defaultTrace); } auto expr = Node<ExpressionNode>::make(*content); parseChildren(node, expr); return expr; } else if (name == "decl") { Node<DeclarationNode>::Link decl; std::string ident = requiredAttr("ident"); bool isDynamic = boolAttr("dynamic"); if (isDynamic) { decl = Node<DeclarationNode>::make(ident, TypeList {}); } else { std::string tlValue = requiredAttr("types"); auto vec = split(tlValue, ' '); decl = Node<DeclarationNode>::make(ident, TypeList(ALL(vec))); } auto expr = node->first_node("expr"); if (expr != nullptr) { decl->setInit(Node<ExpressionNode>::dynPtrCast(parseXMLNode(expr))); } return decl; } else if (name == "branch") { auto branch = Node<BranchNode>::make(); auto cond = node->first_node(); if (cond == nullptr) throw XMLParseError("Missing condition in branch", {METADATA_PAIRS}); branch->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond))); auto success = cond->next_sibling(); if (success == nullptr) throw XMLParseError("Missing success node in branch", {METADATA_PAIRS}); branch->setSuccessBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(success))); auto blockFailiure = success->next_sibling("block"); if (blockFailiure != nullptr) { branch->setFailiureBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(blockFailiure))); } auto branchFailiure = success->next_sibling("branch"); if (branchFailiure != nullptr) { branch->setFailiureBlock(Node<BranchNode>::dynPtrCast(parseXMLNode(branchFailiure))); } return branch; } else if (name == "loop") { auto loop = Node<LoopNode>::make(); auto init = node->first_node("loop_init"); if (init != nullptr) { loop->setInit(Node<DeclarationNode>::dynPtrCast(parseXMLNode(init))); } auto cond = node->first_node("loop_condition"); if (cond != nullptr) { loop->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond))); } auto update = node->first_node("loop_update"); if (update != nullptr) { loop->setUpdate(Node<ExpressionNode>::dynPtrCast(parseXMLNode(update))); } auto code = node->first_node("block"); if (code != nullptr) { loop->setCode(Node<BlockNode>::dynPtrCast(parseXMLNode(code))); } return loop; } else if (name == "loop_init" || name == "loop_condition" || name == "loop_update") { return parseXMLNode(node->first_node()); } else if (name == "break") { return Node<BreakLoopNode>::make(); } else if (name == "function") { std::string ident = safeAttr("ident"); bool isForeign = boolAttr("foreign"); auto n = Node<FunctionNode>::make(ident, FunctionSignature(funRet(), funArgs()), isForeign); funBlock(n); if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign function", {METADATA_PAIRS}); return n; } else if (name == "type") { std::string typeName = requiredAttr("name"); std::vector<std::string> inheritTypes = split(safeAttr("inherits"), ' '); auto typeNode = Node<TypeNode>::make(typeName, TypeList(ALL(inheritTypes))); parseChildren(node, typeNode); return typeNode; } else if (name == "member") { std::string ident = requiredAttr("ident"); std::vector<std::string> types = split(safeAttr("types"), ' '); auto member = Node<MemberNode>::make(ident, TypeList(ALL(types)), boolAttr("static"), getVisibility()); auto init = node->first_node("expr"); if (init != nullptr) { member->setInit(Node<ExpressionNode>::staticPtrCast(parseXMLNode(init))); } return member; } else if (name == "method") { std::string ident = safeAttr("ident"); bool isForeign = boolAttr("foreign"); auto method = Node<MethodNode>::make(ident, FunctionSignature(funRet(), funArgs()), getVisibility(), boolAttr("static"), isForeign); funBlock(method); if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign method", {METADATA_PAIRS}); return method; } else if (name == "constructor") { auto constructor = Node<ConstructorNode>::make(funArgs(), getVisibility()); funBlock(constructor); return constructor; } throw XMLParseError("Unknown type of node", {METADATA_PAIRS, {"node name", name}}); }
int Actionary::loadPreparatorySpec(MetaAction* act) { return setCondition(act, 2); }
int Actionary::loadCulminationCond(MetaAction* act) { return setCondition(act, 1); }
int Actionary::loadApplicabilityCond(MetaAction* act) { return setCondition(act, 0); }
int readNWSLine(char *line, int fileFormat, DateTime day1, DateTime day2) // // Input: line = line of data from rainfall data file // fileFormat = code of data file's format // day1 = starting day of record of interest // day2 = ending day of record of interest // Output: returns -1 if past end of desired record, 0 if data line could // not be read successfully or 1 if line read successfully // Purpose: reads a line of data from a rainfall data file and writes its // data to the rain interface file. // { char flag1, flag2, isMissing; DateTime date1; long result = 1; int k, y, m, d, n; int hour, minute; long v; float x; int lineLength = strlen(line)-1; // --- get year, month, & day from line switch ( fileFormat ) { case NWS_TAPE: if ( lineLength <= 30 ) return 0; if (sscanf(&line[17], "%4d%2d%4d%3d", &y, &m, &d, &n) < 4) return 0; k = 30; break; case NWS_SPACE_DELIMITED: if ( lineLength <= 28 ) return 0; if (sscanf(&line[18], "%4d %2d %2d", &y, &m, &d) < 3) return 0; k = 28; break; case NWS_COMMA_DELIMITED: if ( lineLength <= 28 ) return 0; if ( sscanf(&line[18], "%4d,%2d,%2d", &y, &m, &d) < 3 ) return 0; k = 28; break; default: return 0; } // --- see if date is within period of record requested date1 = datetime_encodeDate(y, m, d); if ( day1 != NO_DATE && date1 < day1 ) return 0; if ( day2 != NO_DATE && date1 > day2 ) return -1; // --- read each recorded rainfall time, value, & codes from line while ( k < lineLength ) { switch ( fileFormat ) { case NWS_TAPE: n = sscanf(&line[k], "%2d%2d%6d%c%c", &hour, &minute, &v, &flag1, &flag2); k += 12; break; case NWS_SPACE_DELIMITED: n = sscanf(&line[k], " %2d%2d %6d %c %c", &hour, &minute, &v, &flag1, &flag2); k += 16; break; case NWS_COMMA_DELIMITED: n = sscanf(&line[k], ",%2d%2d,%6d,%c,%c", &hour, &minute, &v, &flag1, &flag2); k += 16; break; } if ( n < 5 || hour >= 25 ) break; // --- set special condition code & update daily & hourly counts setCondition(flag1); if ( Condition != NO_CONDITION ) isMissing = TRUE; else if ( v == 99999 ) isMissing = TRUE; else isMissing = FALSE; // --- convert rain measurement from hundreth's of an inch & save it x = (float)v / 100.0; if ( x > 0 ) saveRainfall(date1, hour, minute, x, isMissing); // --- reset condition code if special condition period ended if ( flag1 == 'A' || flag1 == '}' || flag1 == ']') Condition = 0; } return result; }
ASTNode::Link StatementParser::statement() { if (accept(TT::TYPE)) { return type(); } else if (accept(TT::IF)) { skip(); return ifStatement(); } else if (accept(TT::FOR)) { auto loop = Node<LoopNode>::make(); loop->setTrace(current().trace); skip(); // Skip "for" loop->setInit(declaration(false)); expectSemi(); loop->setCondition(expression(false)); expectSemi(); loop->setUpdate(expression(false)); loop->setCode(block(CODE_BLOCK)); return loop; } if (accept(TT::WHILE)) { skip(); // Skip "while" auto loop = Node<LoopNode>::make(); loop->setTrace(current().trace); loop->setCondition(expression()); loop->setCode(block(CODE_BLOCK)); return loop; } else if (accept(TT::DO)) { return block(CODE_BLOCK); } else if (accept(TT::DEFINE)) { auto decl = declaration(); expectSemi(); return decl; } else if (accept(TT::IDENTIFIER)) { skip(); if (accept(TT::IDENTIFIER) || accept(",")) { skip(-1); // Go back to the prev identifier auto decl = declaration(); expectSemi(); return decl; } else { skip(-1); // Get the entire expression auto e = expression(); expectSemi(); return e; } } else if (accept(TT::BREAK)) { skip(); return Node<BreakLoopNode>::make(); } else if (accept(TT::CONTINUE)) { throw InternalError("Unimplemented", {METADATA_PAIRS, {"token", "loop continue"}}); } else if (accept(TT::RETURN)) { auto trace = current().trace; skip(); // Skip "return" auto retValue = expression(false); expectSemi(); auto retNode = Node<ReturnNode>::make(); retNode->setTrace(trace); if (retValue != nullptr) retNode->setValue(retValue); return retNode; } else if (accept(TT::FUNCTION)) { return function(); } else if (accept(TT::FOREIGN)) { return function(true); } else { auto e = expression(); expectSemi(); return e; } }