/** * Create a function from an expression. * @param expr :: The input expression * @param parentAttributes :: An output map filled with the attribute name & values of the parent function * @return A pointer to the created function */ IFunction_sptr FunctionFactoryImpl::createSimple(const Expression& expr, std::map<std::string,std::string>& parentAttributes)const { if (expr.name() == "=" && expr.size() > 1) { return createFunction(expr.terms()[1].name()); } if (expr.name() != "," || expr.size() == 0) { inputError(expr.str()); } const std::vector<Expression>& terms = expr.terms(); std::vector<Expression>::const_iterator term = terms.begin(); if (term->name() != "=") inputError(expr.str()); if (term->terms()[0].name() != "name" && term->terms()[0].name() != "composite") { throw std::invalid_argument("Function name must be defined before its parameters"); } std::string fnName = term->terms()[1].name(); IFunction_sptr fun = createFunction(fnName); for(++term;term!=terms.end();++term) {// loop over function's parameters/attributes if (term->name() != "=") inputError(expr.str()); std::string parName = term->terms()[0].name(); std::string parValue = term->terms()[1].str(); if (fun->hasAttribute(parName)) {// set attribute if (parValue.size() > 1 && parValue[0] == '"') {// remove the double quotes parValue = parValue.substr(1,parValue.size()-2); } IFunction::Attribute att = fun->getAttribute(parName); att.fromString(parValue); fun->setAttribute(parName,att); } else if (parName.size() >= 10 && parName.substr(0,10) == "constraint") {// or it can be a list of constraints addConstraints(fun,(*term)[1]); } else if (parName == "ties") { addTies(fun,(*term)[1]); } else if (!parName.empty() && parName[0] == '$') { parName.erase(0,1); parentAttributes[parName] = parValue; } else {// set initial parameter value fun->setParameter(parName,atof(parValue.c_str())); } }// for term fun->applyTies(); return fun; }
bool BlockExpandLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { /* Initialize the basic parent class */ Layer::init(layerMap, parameterMap); CHECK_EQ(config_.inputs_size(), 1); const BlockExpandConfig& blockConf = config_.inputs(0).block_expand_conf(); blockH_ = blockConf.block_y(); blockW_ = blockConf.block_x(); strideH_ = blockConf.stride_y(); strideW_ = blockConf.stride_x(); paddingH_ = blockConf.padding_y(); paddingW_ = blockConf.padding_x(); channels_ = blockConf.channels(); imgSizeH_ = blockConf.img_size_y(); imgSizeW_ = blockConf.img_size_x(); std::vector<size_t> strides = {(size_t)strideH_, (size_t)strideW_}; std::vector<size_t> paddings = {(size_t)paddingH_, (size_t)paddingW_}; std::vector<size_t> blocks = {(size_t)blockH_, (size_t)blockW_}; createFunction(forward_, "BlockExpand", FuncConfig() .set("strides", strides) .set("paddings", paddings) .set("blocks", blocks)); createFunction(backward_, "BlockExpandGrad", FuncConfig() .set("strides", strides) .set("paddings", paddings) .set("blocks", blocks)); return true; }
bool CosSimVecMatLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { Layer::init(layerMap, parameterMap); CHECK_EQ(inputLayers_.size(), 2U); size_t dataDim = inputLayers_[0]->getSize(); size_t numKeys = getSize(); size_t memoryDim = inputLayers_[1]->getSize(); CHECK_EQ(dataDim * numKeys, memoryDim) << "Dimension mismatch"; tmpRow0 = Matrix::create(nullptr, /* height= */ 1, dataDim, /* trans= */ false, useGpu_); tmpRow1 = Matrix::create(nullptr, /* height= */ 1, dataDim, /* trans= */ false, useGpu_); tmpRow2 = Matrix::create(nullptr, /* height= */ numKeys, 1, /* trans= */ false, useGpu_); tmpRow3 = Matrix::create(nullptr, /* height= */ numKeys, 1, /* trans= */ false, useGpu_); tmpMtx0 = Matrix::create(nullptr, /* height= */ numKeys, dataDim, /* trans= */ false, useGpu_); tmpMtx1 = Matrix::create(nullptr, /* height= */ numKeys, dataDim, /* trans= */ false, useGpu_); CHECK(tmpRow0 && tmpRow1 && tmpRow2 && tmpRow3 && tmpMtx0 && tmpMtx1); createFunction(forward_, "CosSimForward", FuncConfig().set("scale", (real)config_.cos_scale())); createFunction(backward_, "CosSimBackward", FuncConfig().set("scale", (real)config_.cos_scale())); return true; }
/** Calls Gaussian1D as a child algorithm to fit the offset peak in a spectrum * * @param s :: The Workspace Index to fit * @param isAbsolbute :: Whether to calculate an absolute offset * @return The calculated offset value */ double GetDetectorOffsets::fitSpectra(const int64_t s, bool isAbsolbute) { // Find point of peak centre const auto &yValues = inputW->y(s); auto it = std::max_element(yValues.cbegin(), yValues.cend()); const double peakHeight = *it; const double peakLoc = inputW->x(s)[it - yValues.begin()]; // Return if peak of Cross Correlation is nan (Happens when spectra is zero) // Pixel with large offset will be masked if (std::isnan(peakHeight)) return (1000.); IAlgorithm_sptr fit_alg; try { // set the ChildAlgorithm no to log as this will be run once per spectra fit_alg = createChildAlgorithm("Fit", -1, -1, false); } catch (Exception::NotFoundError &) { g_log.error("Can't locate Fit algorithm"); throw; } auto fun = createFunction(peakHeight, peakLoc); fit_alg->setProperty("Function", fun); fit_alg->setProperty("InputWorkspace", inputW); fit_alg->setProperty<int>( "WorkspaceIndex", static_cast<int>(s)); // TODO what is the right thing to do here? fit_alg->setProperty("StartX", m_Xmin); fit_alg->setProperty("EndX", m_Xmax); fit_alg->setProperty("MaxIterations", 100); IFunction_sptr fun_ptr = createFunction(peakHeight, peakLoc); fit_alg->setProperty("Function", fun_ptr); fit_alg->executeAsChildAlg(); std::string fitStatus = fit_alg->getProperty("OutputStatus"); // Pixel with large offset will be masked if (fitStatus != "success") return (1000.); // std::vector<double> params = fit_alg->getProperty("Parameters"); API::IFunction_sptr function = fit_alg->getProperty("Function"); double offset = function->getParameter(3); // params[3]; // f1.PeakCentre offset = -1. * offset * m_step / (m_dreference + offset * m_step); // factor := factor * (1+offset) for d-spacemap conversion so factor cannot be // negative if (isAbsolbute) { // translated from(DIdeal - FittedPeakCentre)/(FittedPeakCentre) // given by Matt Tucker in ticket #10642 offset += (m_dideal - m_dreference) / m_dreference; } return offset; }
bool ScaleSubRegionLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { Layer::init(layerMap, parameterMap); CHECK_EQ(static_cast<int>(inputLayers_.size()), 2); auto& conf = config_.inputs(0).scale_sub_region_conf(); value_ = conf.value(); createFunction(forward_, "ScaleSubRegion", FuncConfig().set("value", value_)); createFunction( backward_, "ScaleSubRegionGrad", FuncConfig().set("value", value_)); return true; }
void GameStateManager::SetState(StringId newState) { // Leave current state if (stateInstance_) { delete stateInstance_; stateInstance_=0; state_=StringId(0); } // If there's no new state, we're done if (newState.GetString()==0) { return; } // Change current state typedef GameState* (*CreateFunction)(); HashTableIterator<HashTableKey_StringId,CreateFunction> it(gameStates_); CreateFunction createFunction=0; if (it.Find(HashTableKey_StringId(newState))) { createFunction=it.GetCurrent(); } Assert(createFunction,"State not recognized!"); if (!createFunction) { return; } state_=newState; stateInstance_=createFunction(); }
bool CosSimLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { /* Initialize the basic parent class */ Layer::init(layerMap, parameterMap); CHECK_EQ(inputLayers_.size(), 2LU); createFunction(forward_, "CosSimForward", FuncConfig().set("scale", (real)config_.cos_scale())); createFunction(backward_, "CosSimBackward", FuncConfig().set("scale", (real)config_.cos_scale())); return true; }
VarSymbol* Parser :: ParseDirectDeclaration(){ VarSymbol *var_sym = 0; SymbolType *type = 0; while(isEq(scan.Get(), _OPERATION, "*") ) type = new PointerSymbol(type); if(isEq(scan.Get(), _SEPARATION, "(")){ scan.Next(); var_sym = ParseDirectDeclaration(); } else { errorIf(scan.Get()->Type != _IDENTIFIER, "Identifier expected", scan.Get()); errorIf(symStack->find_symbol(scan.Get()->Value), "Redefinition", scan.Get()); var_sym = new VarSymbol(scan.Get()->Value, 0); scan.Next(); } if(isEq(scan.Get(), _SEPARATION, "(")) type = createFunction("", type); else if(isEq(scan.Get(), _SEPARATION, "[")) type = ParseArrayDimension(type); if(!var_sym->type) var_sym->type = type; else { while(var_sym->type->upType()) var_sym->type = var_sym->type->upType(); var_sym->type->initType(type); } if(isEq(scan.Get(), _SEPARATION, ")")) scan.Next(); return var_sym; }
/// Fit the data simultaneously. void MultiDatasetFit::fitSimultaneous() { try { m_uiForm.btnFit->setEnabled(false); auto fun = createFunction(); auto fit = Mantid::API::AlgorithmManager::Instance().create("Fit"); fit->initialize(); fit->setProperty("Function", fun); fit->setPropertyValue("InputWorkspace", getWorkspaceName(0).toStdString()); fit->setProperty("WorkspaceIndex", getWorkspaceIndex(0)); auto range = getFittingRange(0); fit->setProperty("StartX", range.first); fit->setProperty("EndX", range.second); int n = getNumberOfSpectra(); for (int ispec = 1; ispec < n; ++ispec) { std::string suffix = boost::lexical_cast<std::string>(ispec); fit->setPropertyValue("InputWorkspace_" + suffix, getWorkspaceName(ispec).toStdString()); fit->setProperty("WorkspaceIndex_" + suffix, getWorkspaceIndex(ispec)); auto range = getFittingRange(ispec); fit->setProperty("StartX_" + suffix, range.first); fit->setProperty("EndX_" + suffix, range.second); } m_fitOptionsBrowser->copyPropertiesToAlgorithm(*fit); m_outputWorkspaceName = m_fitOptionsBrowser->getProperty("Output"); if (m_outputWorkspaceName.isEmpty()) { m_outputWorkspaceName = "out"; fit->setPropertyValue("Output", m_outputWorkspaceName.toStdString()); m_fitOptionsBrowser->setProperty("Output", "out"); } if (n == 1) { m_outputWorkspaceName += "_Workspace"; } else { m_outputWorkspaceName += "_Workspaces"; } removeOldOutput(); m_fitRunner.reset(new API::AlgorithmRunner()); connect(m_fitRunner.get(), SIGNAL(algorithmComplete(bool)), this, SLOT(finishFit(bool)), Qt::QueuedConnection); m_fitRunner->startAlgorithm(fit); } catch (std::exception &e) { QString mess(e.what()); const int maxSize = 500; if (mess.size() > maxSize) { mess = mess.mid(0, maxSize); mess += "..."; } QMessageBox::critical(this, "MantidPlot - Error", QString("Fit failed:\n\n %1").arg(mess)); m_uiForm.btnFit->setEnabled(true); } }
bool InputOutputMaster::checkMinus (Expression ** peOutput,int cEnd) { Printable ** ppOutput=new Printable *; convertToPrintable (cRead+1,cEnd,ppOutput); *peOutput=static_cast<Expression*> (*ppOutput); *peOutput=createFunction(MINUS,*peOutput); cRead--; return true; }
void executeImpl(struct RuntimeContext *ctx) { // Locate entrypoint and execute it struct FuncHeader *epHdr = ctx->funcTable->table[0]; struct FunctionContext *func = createFunction(epHdr, ctx); executeFunction(func, ctx); #ifdef _DEBUG getchar(); #endif }
bool Predicate::evaluate() const { ASSERT(m_expr != 0); Value result(m_expr->evaluate()); // foo[3] means foo[position()=3] if (result.isNumber()) return EqTestOp(EqTestOp::OP_EQ, createFunction("position"), new Number(result.toNumber())).evaluate().toBoolean(); return result.toBoolean(); }
VarSymbol* Parser :: ParseComplexDeclaration(SymbolType* start_type){ VarSymbol *var_sym = ParseDirectDeclaration(); if(isEq(scan.Get(), _SEPARATION, "(")) start_type = createFunction("", start_type); else if(isEq(scan.Get(), _SEPARATION, "[")) start_type = ParseArrayDimension(start_type); // if(scan.Get() == cl_bracket) // scan.Next(); if(!var_sym->type) var_sym->type = start_type; else { while(var_sym->type->upType()) var_sym->type = var_sym->type->upType(); var_sym->type->initType(start_type); } return var_sym; }
BaseNode* new_node_from_tag(SBinaryTag* tag, bool skipCopy) { const char* tagClass = get_string_from_dict(tag, "class"); nodeFunctionPtr createFunction = NULL; for (int index = 0; index < g_createFunctionsLength; index += 1) { SFuncLookup* entry = &g_createFunctions[index]; if (strcmp(entry->className, tagClass) == 0) { createFunction = entry->createFunction; } } if (createFunction == NULL) { fprintf(stderr, "new_node_from_tag(): Couldn't find a factory function for node class '%s'\n", tagClass); return NULL; } BaseNode* result = createFunction(tag, skipCopy); const char* name = get_string_from_dict(tag, "name"); result->setName(name); return result; }
VarSymbol * Parser :: ParseIdentifier(SymbolType *type, bool param){ VarSymbol *result = 0; Token *token = scan.Get(); bool Const = false; Token* name = token; if(isEq(token, _SEPARATION, "(")) return ParseComplexDeclaration(type); while (isEq(token, _OPERATION, "*") || isEq(token, _OPERATION, "**") || token->Type == _CONST){ if(token->Type == _CONST) Const = true; else type = new PointerSymbol(type); token =scan.GetNext(); } // else{ token = scan.GetNext();} if (token->Type == _IDENTIFIER){ name = token; } errorIf(name->Type != _IDENTIFIER, "Identifier expected", token); token = scan.GetNext(); if(!isEq(token, _SEPARATION, "(")){ errorIf(type->name == "void", "Incomplete type is invalid", token); if(isEq(token, _SEPARATION, "[")) type = ParseArrayDimension(type); } else{ VarSymbol* buf = new VarSymbol(name->Value,type) ; if((symbolBuffer = symStack->tables.back()->find_symbol(name->Value)) != 0 ){ buf = dynamic_cast<VarSymbol*>(symbolBuffer); FuncSymbol* func = dynamic_cast<FuncSymbol*>(buf->type); errorIf(!CheckArgs(func), "Redefinition",token); errorIf(type != func->value, "banned over-the return value :" + func->name ,token ); result = new VarSymbol(name->Value, func); // errorIf(!(isEq(token, _SEPARATION, ",")|| isEq(token, _SEPARATION, ";") || isEq(token, _OPERATION, "=") ||isEq(token, _SEPARATION, "{")), // "Semicolon expected", scan.Get()); return result; } else type = createFunction(name->Value, type,Const); } if(Const) type = new ConstSymbolType(type); result = new VarSymbol(name->Value, type); // token = scan.GetNext(); errorIf(symStack->tables.back()->find_symbol(name->Value) != 0, "Redefinition", scan.Get()); errorIf(!(isEq(scan.Get(), _OPERATION, ",")|| isEq(scan.Get(), _SEPARATION, ";") || isEq(scan.Get(), _OPERATION, "=") ||isEq(scan.Get(), _SEPARATION, "{")), "Semicolon expected", scan.Get()); return result; }
/** * Create a composite function from an expression. * @param expr :: The input expression * @param parentAttributes :: An output map filled with the attribute name & values of the parent function * @return A pointer to the created function */ CompositeFunction_sptr FunctionFactoryImpl::createComposite(const Expression& expr, std::map<std::string,std::string>& parentAttributes)const { if (expr.name() != ";") inputError(expr.str()); if (expr.size() == 0) { return CompositeFunction_sptr(); } const std::vector<Expression>& terms = expr.terms(); std::vector<Expression>::const_iterator it = terms.begin(); const Expression& term = it->bracketsRemoved(); CompositeFunction_sptr cfun; if (term.name() == "=") { if (term.terms()[0].name() == "composite") { cfun = boost::dynamic_pointer_cast<CompositeFunction>(createFunction(term.terms()[1].name())); if (!cfun) inputError(expr.str()); ++it; } else if (term.terms()[0].name() == "name") { cfun = boost::dynamic_pointer_cast<CompositeFunction>(createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } } else if (term.name() == ",") { std::vector<Expression>::const_iterator firstTerm = term.terms().begin(); if (firstTerm->name() == "=") { if (firstTerm->terms()[0].name() == "composite") { cfun = boost::dynamic_pointer_cast<CompositeFunction>(createSimple(term,parentAttributes)); if (!cfun) inputError(expr.str()); ++it; } else if (firstTerm->terms()[0].name() == "name") { cfun = boost::dynamic_pointer_cast<CompositeFunction>(createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } } } else if (term.name() == ";") { cfun = boost::dynamic_pointer_cast<CompositeFunction>(createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } for(;it!=terms.end();++it) { const Expression& term = it->bracketsRemoved(); IFunction_sptr fun; std::map<std::string,std::string> pAttributes; if (term.name() == ";") { fun = createComposite(term,pAttributes); if (!fun) continue; } else { std::string parName = term[0].name(); if (parName.size() >= 10 && parName.substr(0,10) == "constraint") { addConstraints(cfun,term[1]); continue; } else if (parName == "ties") { addTies(cfun,term[1]); continue; } else { fun = createSimple(term,pAttributes); } } cfun->addFunction(fun); size_t i = cfun->nFunctions() - 1; for(auto att = pAttributes.begin(); att != pAttributes.end(); ++att) { cfun->setLocalAttributeValue(i,att->first,att->second); } } cfun->applyTies(); return cfun; }
int Scope::invoke( const char* code , const BSONObj& args, int timeoutMs ){ ScriptingFunction func = createFunction( code ); uassert( 10207 , "compile failed" , func ); return invoke( func , args, timeoutMs ); }
bool Doc::loadWorkspaceAs(QString &fileName) { bool success = false; QString buf; QString s; QString t; QList<QString> list; newDocument(); if (FileHandler::readFileToList(fileName, list) == true) { m_workspaceFileName = QString(fileName); // Create devices and functions from the list for (QString* string = list.first(); string != NULL; string = list.next()) { if (*string == QString("Entry")) { string = list.next(); if (*string == QString("Device")) { DMXDevice* d = createDevice(list); if (d != NULL) { addDevice(d); } } else if (*string == QString("Function")) { // Only create the function but don't care for // its contents yet Function* f = createFunction(list); if (f != NULL) { // Add function to function pool addFunction(f); } } else if (*string == QString("Bus")) { Bus* bus = new Bus(); bus->createContents(list); addBus(bus); _app->virtualConsole()->setDefaultSpeedBus(bus); } else if (*string == QString("Joystick")) { createJoystickContents(list); } else if (*string == QString("Virtual Console")) { // Virtual console wants it all, go to "Entry" list.prev(); list.prev(); _app->virtualConsole()->createContents(list); } else { // Unknown keyword, do nothing } } } // Now put contents to functions // The functions are given their contents after every function // object has been created. Otherwise some functions can not // be created. for (QString* string = list.first(); string != NULL; string = list.next()) { if (*string == QString("Entry")) { string = list.next(); if (*string == QString("Function")) { createFunctionContents(list); } else { // Reel back one step, it might contain the keyword // "Entry" string = list.prev(); } } } success = true; } else { success = false; } setModified(false); return success; }
Function* createFunction(const String& name) { HeapVector<Member<Expression>> args; return createFunction(name, args); }
/** * Create a composite function from an expression. * @param expr :: The input expression * @return A pointer to the created function */ CompositeFunction* FunctionFactoryImpl::createComposite(const Expression& expr)const { if (expr.name() != ";") inputError(expr.str()); if (expr.size() == 0) { return 0; } const std::vector<Expression>& terms = expr.terms(); std::vector<Expression>::const_iterator it = terms.begin(); const Expression& term = it->bracketsRemoved(); CompositeFunction* cfun = 0; std::string wsName,wsParam; if (term.name() == "=") { if (term.terms()[0].name() == "composite") { cfun = dynamic_cast<CompositeFunction*>(createFunction(term.terms()[1].name())); if (!cfun) inputError(expr.str()); ++it; } else if (term.terms()[0].name() == "name") { cfun = dynamic_cast<CompositeFunction*>(createFunction("CompositeFunctionMW")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } } else if (term.name() == ",") { std::vector<Expression>::const_iterator firstTerm = term.terms().begin(); if (firstTerm->name() == "=") { if (firstTerm->terms()[0].name() == "composite") { cfun = dynamic_cast<CompositeFunction*>(createSimple(term)); if (!cfun) inputError(expr.str()); ++it; } else if (firstTerm->terms()[0].name() == "name") { cfun = dynamic_cast<CompositeFunction*>(createFunction("CompositeFunctionMW")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } } } else if (term.name() == ";") { cfun = dynamic_cast<CompositeFunction*>(createFunction("CompositeFunctionMW")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } for(;it!=terms.end();++it) { const Expression& term = it->bracketsRemoved(); IFitFunction* fun = NULL; if (term.name() == ";") { fun = createComposite(term); if (!fun) continue; } else { std::string parName = term[0].name(); std::string parValue = term[1].str(); if (term[0].name().size() >= 10 && term[0].name().substr(0,10) == "constraint") { addConstraints(cfun,term[1]); continue; } else if (term[0].name() == "ties") { addTies(cfun,term[1]); continue; } else if (parName == "Workspace") { wsName = parValue; } else if (parName == "WSParam") { wsParam = parValue; } else { fun = createSimple(term); } } cfun->addFunction(fun); } if (!wsName.empty()) { Workspace_sptr ws = AnalysisDataService::Instance().retrieve(wsName); cfun->setWorkspace(ws,wsParam); } return cfun; }
/** * Create a composite function from an expression. * @param expr :: The input expression * @param parentAttributes :: An output map filled with the attribute name & * values of the parent function * @return A pointer to the created function */ CompositeFunction_sptr FunctionFactoryImpl::createComposite( const Expression &expr, std::map<std::string, std::string> &parentAttributes) const { if (expr.name() != ";") inputError(expr.str()); if (expr.size() == 0) { return CompositeFunction_sptr(); } const std::vector<Expression> &terms = expr.terms(); auto it = terms.cbegin(); const Expression &term = it->bracketsRemoved(); CompositeFunction_sptr cfun; if (term.name() == "=") { if (term.terms()[0].name() == "composite") { cfun = boost::dynamic_pointer_cast<CompositeFunction>( createFunction(term.terms()[1].name())); if (!cfun) inputError(expr.str()); ++it; } else if (term.terms()[0].name() == "name") { cfun = boost::dynamic_pointer_cast<CompositeFunction>( createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } } else if (term.name() == ",") { auto firstTerm = term.terms().cbegin(); if (firstTerm->name() == "=") { if (firstTerm->terms()[0].name() == "composite") { cfun = boost::dynamic_pointer_cast<CompositeFunction>( createSimple(term, parentAttributes)); if (!cfun) inputError(expr.str()); ++it; } else if (firstTerm->terms()[0].name() == "name") { cfun = boost::dynamic_pointer_cast<CompositeFunction>( createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } } } else if (term.name() == ";") { cfun = boost::dynamic_pointer_cast<CompositeFunction>( createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { inputError(expr.str()); } if (!cfun) inputError(expr.str()); for (; it != terms.end(); ++it) { const Expression &term = it->bracketsRemoved(); IFunction_sptr fun; std::map<std::string, std::string> pAttributes; if (term.name() == ";") { fun = createComposite(term, pAttributes); if (!fun) continue; } else { std::string parName = term[0].name(); if (parName.size() >= 10 && parName.substr(0, 10) == "constraint") { addConstraints(cfun, term[1]); continue; } else if (parName == "ties") { addTies(cfun, term[1]); continue; } else { fun = createSimple(term, pAttributes); } } cfun->addFunction(fun); size_t i = cfun->nFunctions() - 1; for (auto &pAttribute : pAttributes) { // Apply parent attributes of the child function to this function. If this // function doesn't have those attributes, they get passed up the chain to // this function's parent. if (cfun->hasLocalAttribute(pAttribute.first)) { cfun->setLocalAttributeValue(i, pAttribute.first, pAttribute.second); } else { parentAttributes[pAttribute.first] = pAttribute.second; } } } if (cfun) { cfun->applyTies(); } return cfun; }
/** * Create a function from an expression. * @param expr :: The input expression * @return A pointer to the created function */ IFitFunction* FunctionFactoryImpl::createSimple(const Expression& expr)const { if (expr.name() == "=" && expr.size() > 1) { return createFunction(expr.terms()[1].name()); } if (expr.name() != "," || expr.size() == 0) { inputError(expr.str()); } const std::vector<Expression>& terms = expr.terms(); std::vector<Expression>::const_iterator term = terms.begin(); if (term->name() != "=") inputError(expr.str()); if (term->terms()[0].name() != "name" && term->terms()[0].name() != "composite") { throw std::invalid_argument("Function name must be defined before its parameters"); } std::string fnName = term->terms()[1].name(); IFitFunction* fun = createFunction(fnName); std::string wsName,wsParam; for(++term;term!=terms.end();++term) {// loop over function's parameters/attributes if (term->name() != "=") inputError(expr.str()); std::string parName = term->terms()[0].name(); std::string parValue = term->terms()[1].str(); if (fun->hasAttribute(parName)) {// set attribute if (parValue.size() > 1 && parValue[0] == '"') {// remove the double quotes parValue = parValue.substr(1,parValue.size()-2); } IFitFunction::Attribute att = fun->getAttribute(parName); att.fromString(parValue); fun->setAttribute(parName,att); } else if (parName.size() >= 10 && parName.substr(0,10) == "constraint") {// or it can be a list of constraints addConstraints(fun,(*term)[1]); } else if (parName == "ties") { addTies(fun,(*term)[1]); } else if (parName == "Workspace") { wsName = parValue; } else if (parName == "WSParam") { wsParam = parValue; } else {// set initial parameter value fun->setParameter(parName,atof(parValue.c_str())); } }// for term if (!wsName.empty()) { Workspace_sptr ws = AnalysisDataService::Instance().retrieve(wsName); fun->setWorkspace(ws,wsParam); } return fun; }
void Global_as::registerClasses() { registerNatives(*this); function_class_init(*this, NSV::CLASS_FUNCTION); initObjectClass(_objectProto, *this, NSV::CLASS_OBJECT); string_class_init(*this, NSV::CLASS_STRING); array_class_init(*this, NSV::CLASS_ARRAY); // No idea why, but it seems there's a NULL _global.o // defined at player startup... // Probably due to the AS-based initialization // Not enumerable but overridable and deletable. // as_value nullVal; nullVal.set_null(); init_member("o", nullVal, PropFlags::dontEnum); VM& vm = getVM(); // _global functions. // These functions are only available in SWF6+, but this is just // because SWF5 or lower did not have a "_global" // reference at all. init_member("ASnative", createFunction(global_asnative)); init_member("ASconstructor", createFunction(global_asconstructor)); init_member("ASSetPropFlags", vm.getNative(1, 0)); init_member("ASSetNative", vm.getNative(4, 0)); init_member("ASSetNativeAccessor", vm.getNative(4, 1)); init_member("AsSetupError", createFunction(global_assetuperror)); init_member("updateAfterEvent", vm.getNative(9, 0)); init_member("trace", vm.getNative(100, 4)); init_member("setInterval", vm.getNative(250, 0)); init_member("clearInterval", vm.getNative(250, 1)); init_member("setTimeout", vm.getNative(250, 2)); // This is an odd function with no properties. There ought to be // a better way of implementing this. See also TextFormat.getTextExtent. as_function* edc = createFunction(global_enableDebugConsole); edc->clearProperties(); init_member("enableDebugConsole", edc); init_member("showRedrawRegions", vm.getNative(1021, 1)); init_member("clearTimeout", getMember(*this, getURI(vm, "clearInterval"))); _classes.declareAll(avm1Classes()); // SWF8 visibility: const ObjectURI& flash = getURI(vm, "flash"); flash_package_init(*this, flash); init_member("escape", vm.getNative(100, 0)); init_member("unescape", vm.getNative(100, 1)); init_member("parseInt", vm.getNative(100, 2)); init_member("parseFloat", vm.getNative(100, 3)); init_member("isNaN", vm.getNative(200, 18)); init_member("isFinite", vm.getNative(200, 19)); init_member("NaN", as_value(NaN)); init_member("Infinity", as_value( std::numeric_limits<double>::infinity())); loadExtensions(); }