void GLAnalyzer::analyze( const Scope &s ) { //kDebug() << "Scope Size: " << s.size(); /* Scope t(32); if (s.size() != 32) { Analyzer::interpolate(s, t); } else { t = s; }*/ uint offset = 0; static float peak; float mfactor = 0.0; static int drawcount; if (s.size() == 64) { offset=8; } glRotatef(0.25f, 0.0f, 1.0f, 0.5f); //Rotate the scene drawFloor(); drawcount++; if (drawcount > 25) { drawcount = 0; peak = 0.0; } for ( uint i = 0; i < 32; i++ ) { if (s[i] > peak) { peak = s[i]; } } mfactor = 20 / peak; for ( uint i = 0; i < 32; i++ ) { //kDebug() << "Scope item " << i << " value: " << s[i]; // Calculate new horizontal position (x) depending on number of samples x = -16.0f + i; // Calculating new vertical position (y) depending on the data passed by amarok y = float(s[i+offset] * mfactor); //This make it kinda dynamically resize depending on the data //Some basic bounds checking if (y > 30) y = 30; else if (y < 0) y = 0; if((y - m_oldy[i]) < -0.6f) // Going Down Too Much { y = m_oldy[i] - 0.7f; } if (y < 0.0f) { y = 0.0f; } m_oldy[i] = y; //Save value as last value //Peak Code if (m_oldy[i] > m_peaks[i].level) { m_peaks[i].level = m_oldy[i]; m_peaks[i].delay = 30; } if (m_peaks[i].delay > 0) { m_peaks[i].delay--; } if (m_peaks[i].level > 1.0f) { if (m_peaks[i].delay <= 0) { m_peaks[i].level-=0.4f; } } // Draw the bar drawBar(x,y); drawPeak(x, m_peaks[i].level); } updateGL(); }
void Module::importAll(Scope *prevsc) { //printf("+Module::importAll(this = %p, '%s'): parent = %p\n", this, toChars(), parent); if (scope) return; // already done if (isDocFile) { error("is a Ddoc file, cannot import it"); return; } /* Note that modules get their own scope, from scratch. * This is so regardless of where in the syntax a module * gets imported, it is unaffected by context. * Ignore prevsc. */ Scope *sc = Scope::createGlobal(this); // create root scope // Add import of "object", even for the "object" module. // If it isn't there, some compiler rewrites, like // classinst == classinst -> .object.opEquals(classinst, classinst) // would fail inside object.d. if (members->dim == 0 || ((*members)[0])->ident != Id::object) { Import *im = new Import(0, NULL, Id::object, NULL, 0); members->shift(im); } if (!symtab) { // Add all symbols into module's symbol table symtab = new DsymbolTable(); for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (*members)[i]; s->addMember(NULL, sc->scopesym, 1); } } // anything else should be run after addMember, so version/debug symbols are defined /* Set scope for the symbols so that if we forward reference * a symbol, it can possibly be resolved on the spot. * If this works out well, it can be extended to all modules * before any semantic() on any of them. */ setScope(sc); // remember module scope for semantic for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (*members)[i]; s->setScope(sc); } for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (*members)[i]; s->importAll(sc); } sc = sc->pop(); sc->pop(); // 2 pops because Scope::createGlobal() created 2 }
int main( int argc, char ** argv ) { Scope global; EventLoop::setup(); const char * error = 0; bool ok = true; if ( argc != 5 ) { error = "Wrong number of arguments"; ok = false; } uint port = 0; if ( ok ) { port = EString( argv[1] ).number( &ok ); if ( !ok ) error = "Could not parse own port number"; } if ( ok ) { Listener<RecorderServer> * l4 = new Listener<RecorderServer>( Endpoint( "0.0.0.0", port ), "recording relay/4" ); Allocator::addEternal( l4, "recording listener" ); Listener<RecorderServer> * l6 = new Listener<RecorderServer>( Endpoint( "::", port ), "recording relay/6" ); Allocator::addEternal( l6, "recording listener" ); if ( l4->state() != Connection::Listening && l6->state() != Connection::Listening ) error = "Could not listen for connections"; } if ( ok ) { port = EString( argv[3] ).number( &ok ); if ( !ok ) error = "Could not parse server's port number"; } if ( ok ) { EStringList l = Resolver::resolve( argv[2] ); if ( l.isEmpty() ) { ok = false; error = (EString("Cannot resolve ") + argv[2] + ": " + Resolver::errors().join( ", " ) ).cstr(); } else { ep = new Endpoint( *l.first(), port ); Allocator::addEternal( ep, "target server endpoint" ); } if ( ep && !ep->valid() ) { ok = false; error = "Invalid server address"; } } if ( !ok ) { fprintf( stderr, "Error: %s\n" "Usage: recorder port address port filebase\n" " First port: The recorder's own port.\n" " Address: The IP address of the server to forward to.\n" " Second port: The server port to forward to.\n" " Filebase: The filename base (.<blah> is added).\n", error ); exit( 1 ); } ::base = new EString( argv[4] ); Allocator::addEternal( ::base, "base of recorded file names" ); global.setLog( new Log ); EventLoop::global()->start(); }
void EnumDeclaration::semantic(Scope *sc) { //printf("EnumDeclaration::semantic(sd = %p, '%s') %s\n", sc->scopesym, sc->scopesym->toChars(), toChars()); //printf("EnumDeclaration::semantic() %p %s\n", this, toChars()); if (!members && !memtype) // enum ident; return; if (semanticRun >= PASSsemanticdone) return; // semantic() already completed if (semanticRun == PASSsemantic) { assert(memtype); ::error(loc, "circular reference to enum base type %s", memtype->toChars()); errors = true; semanticRun = PASSsemanticdone; return; } semanticRun = PASSsemantic; if (!symtab) symtab = new DsymbolTable(); Scope *scx = NULL; if (scope) { sc = scope; scx = scope; // save so we don't make redundant copies scope = NULL; } unsigned dprogress_save = Module::dprogress; if (sc->stc & STCdeprecated) isdeprecated = true; userAttribDecl = sc->userAttribDecl; parent = sc->parent; protection = sc->protection; /* The separate, and distinct, cases are: * 1. enum { ... } * 2. enum : memtype { ... } * 3. enum ident { ... } * 4. enum ident : memtype { ... } * 5. enum ident : memtype; * 6. enum ident; */ type = type->semantic(loc, sc); if (memtype) { memtype = memtype->semantic(loc, sc); /* Check to see if memtype is forward referenced */ if (memtype->ty == Tenum) { EnumDeclaration *sym = (EnumDeclaration *)memtype->toDsymbol(sc); if (!sym->memtype || !sym->members || !sym->symtab || sym->scope) { // memtype is forward referenced, so try again later scope = scx ? scx : sc->copy(); scope->setNoFree(); scope->module->addDeferredSemantic(this); Module::dprogress = dprogress_save; //printf("\tdeferring %s\n", toChars()); semanticRun = PASSinit; return; } } if (memtype->ty == Tvoid) { error("base type must not be void"); memtype = Type::terror; } if (memtype->ty == Terror) { errors = true; if (members) { for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (*members)[i]; s->errors = true; // poison all the members } } semanticRun = PASSsemanticdone; return; } } semanticRun = PASSsemanticdone; if (!members) // enum ident : memtype; return; if (members->dim == 0) { error("enum %s must have at least one member", toChars()); errors = true; return; } Module::dprogress++; Scope *sce; if (isAnonymous()) sce = sc; else { sce = sc->push(this); sce->parent = this; } sce = sce->startCTFE(); sce->setNoFree(); // needed for getMaxMinValue() /* Each enum member gets the sce scope */ for (size_t i = 0; i < members->dim; i++) { EnumMember *em = (*members)[i]->isEnumMember(); if (em) em->scope = sce; } if (!added) { /* addMember() is not called when the EnumDeclaration appears as a function statement, * so we have to do what addMember() does and install the enum members in the right symbol * table */ ScopeDsymbol *scopesym = NULL; if (isAnonymous()) { /* Anonymous enum members get added to enclosing scope. */ for (Scope *sct = sce; 1; sct = sct->enclosing) { assert(sct); if (sct->scopesym) { scopesym = sct->scopesym; if (!sct->scopesym->symtab) sct->scopesym->symtab = new DsymbolTable(); break; } } } else // Otherwise enum members are in the EnumDeclaration's symbol table scopesym = this; for (size_t i = 0; i < members->dim; i++) { EnumMember *em = (*members)[i]->isEnumMember(); if (em) { em->ed = this; em->addMember(sc, scopesym, 1); } } } for (size_t i = 0; i < members->dim; i++) { EnumMember *em = (*members)[i]->isEnumMember(); if (em) em->semantic(em->scope); } //printf("defaultval = %lld\n", defaultval); //if (defaultval) printf("defaultval: %s %s\n", defaultval->toChars(), defaultval->type->toChars()); //members->print(); }
void EnumDeclaration::semantic(Scope *sc) { int i; uinteger_t number; Type *t; Scope *sce; //printf("EnumDeclaration::semantic(sd = %p, '%s')\n", sc->scopesym, sc->scopesym->toChars()); if (!memtype) memtype = Type::tint32; if (symtab) // if already done { if (isdone || !scope) return; // semantic() already completed } else symtab = new DsymbolTable(); Scope *scx = NULL; if (scope) { sc = scope; scx = scope; // save so we don't make redundant copies scope = NULL; } unsigned dprogress_save = Module::dprogress; if (sc->stc & STCdeprecated) isdeprecated = 1; parent = sc->scopesym; memtype = memtype->semantic(loc, sc); /* Check to see if memtype is forward referenced */ if (memtype->ty == Tenum) { EnumDeclaration *sym = (EnumDeclaration *)memtype->toDsymbol(sc); if (!sym->memtype) { error("base enum %s is forward referenced", sym->toChars()); memtype = Type::tint32; } } if (!memtype->isintegral()) { error("base type must be of integral type, not %s", memtype->toChars()); memtype = Type::tint32; } isdone = 1; Module::dprogress++; t = isAnonymous() ? memtype : type; symtab = new DsymbolTable(); sce = sc->push(this); sce->parent = this; number = 0; if (!members) // enum ident; return; if (members->dim == 0) error("enum %s must have at least one member", toChars()); int first = 1; for (i = 0; i < members->dim; i++) { EnumMember *em = ((Dsymbol *)members->data[i])->isEnumMember(); Expression *e; if (!em) /* The e->semantic(sce) can insert other symbols, such as * template instances and function literals. */ continue; //printf("Enum member '%s'\n",em->toChars()); e = em->value; if (e) { assert(e->dyncast() == DYNCAST_EXPRESSION); e = e->semantic(sce); e = e->optimize(WANTvalue); // Need to copy it because we're going to change the type e = e->copy(); e = e->implicitCastTo(sc, memtype); e = e->optimize(WANTvalue); number = e->toInteger(); e->type = t; } else { // Default is the previous number plus 1 // Check for overflow if (!first) { switch (t->toBasetype()->ty) { case Tbool: if (number == 2) goto Loverflow; break; case Tint8: if (number == 128) goto Loverflow; break; case Tchar: case Tuns8: if (number == 256) goto Loverflow; break; case Tint16: if (number == 0x8000) goto Loverflow; break; case Twchar: case Tuns16: if (number == 0x10000) goto Loverflow; break; case Tint32: if (number == 0x80000000) goto Loverflow; break; case Tdchar: case Tuns32: if (number == 0x100000000LL) goto Loverflow; break; case Tint64: if (number == 0x8000000000000000LL) goto Loverflow; break; case Tuns64: if (number == 0) goto Loverflow; break; Loverflow: error("overflow of enum value"); break; default: assert(0); } } e = new IntegerExp(em->loc, number, t); } em->value = e; // Add to symbol table only after evaluating 'value' if (isAnonymous()) { //sce->enclosing->insert(em); for (Scope *scx = sce->enclosing; scx; scx = scx->enclosing) { if (scx->scopesym) { if (!scx->scopesym->symtab) scx->scopesym->symtab = new DsymbolTable(); em->addMember(sce, scx->scopesym, 1); break; } } } else em->addMember(sc, this, 1); if (first) { first = 0; defaultval = number; minval = number; maxval = number; } else if (memtype->isunsigned()) { if (number < minval) minval = number; if (number > maxval) maxval = number; } else { if ((sinteger_t)number < (sinteger_t)minval) minval = number; if ((sinteger_t)number > (sinteger_t)maxval) maxval = number; } number++; } //printf("defaultval = %lld\n", defaultval); sce->pop(); //members->print(); }
void run(){ Scope * s = globalScriptEngine->newScope(); s->localConnect( "asd" ); const char * foo = "asdas\0asdasd"; const char * base64 = "YXNkYXMAYXNkYXNk"; BSONObj in; { BSONObjBuilder b; b.append( "a" , 7 ); b.appendBinData( "b" , 12 , BinDataGeneral , foo ); in = b.obj(); s->setObject( "x" , in ); } s->invokeSafe( "myb = x.b; print( myb ); printjson( myb );" , BSONObj() ); s->invokeSafe( "y = { c : myb };" , BSONObj() ); BSONObj out = s->getObject( "y" ); ASSERT_EQUALS( BinData , out["c"].type() ); // pp( "in " , in["b"] ); // pp( "out" , out["c"] ); ASSERT_EQUALS( 0 , in["b"].woCompare( out["c"] , false ) ); // check that BinData js class is utilized s->invokeSafe( "q = x.b.toString();", BSONObj() ); stringstream expected; expected << "BinData(" << BinDataGeneral << ",\"" << base64 << "\")"; ASSERT_EQUALS( expected.str(), s->getString( "q" ) ); stringstream scriptBuilder; scriptBuilder << "z = { c : new BinData( " << BinDataGeneral << ", \"" << base64 << "\" ) };"; string script = scriptBuilder.str(); s->invokeSafe( script.c_str(), BSONObj() ); out = s->getObject( "z" ); // pp( "out" , out["c"] ); ASSERT_EQUALS( 0 , in["b"].woCompare( out["c"] , false ) ); s->invokeSafe( "a = { f: new BinData( 128, \"\" ) };", BSONObj() ); out = s->getObject( "a" ); int len = -1; out[ "f" ].binData( len ); ASSERT_EQUALS( 0, len ); ASSERT_EQUALS( 128, out[ "f" ].binDataType() ); delete s; }
/** * Applies the map function to an object, which should internally call emit() */ void JSMapper::map( const BSONObj& o ) { Scope * s = _func.scope(); assert( s ); if ( s->invoke( _func.func() , &_params, &o , 0 , true, false, true ) ) throw UserException( 9014, str::stream() << "map invoke failed: " + s->getError() ); }
void SBStateIndicatorItem::UpdateState() { int quadState = -1; bool cameraOk = true; bool problems = false; bool partials = false; wxString MIAs; switch (type) { case Field_Gear: if (pCamera && pCamera->Connected) { partials = true; } else { MIAs += _("Camera, "); cameraOk = false; problems = true; } if ((pMount && pMount->IsConnected()) || (pSecondaryMount && pSecondaryMount->IsConnected())) partials = true; else { MIAs += _("Mount, "); problems = true; } if (pPointingSource && pPointingSource->IsConnected()) partials = true; else { MIAs += _("Aux Mount, "); problems = true; } if (pMount && pMount->IsStepGuider()) { if (pMount->IsConnected()) partials = true; else { MIAs += _("AO, "); problems = true; } } if (pRotator) { if (pRotator->IsConnected()) partials = true; else { MIAs += _("Rotator, "); problems = true; } } if (partials) { if (!problems) { pic->SetIcon(wxIcon(container->icoGreenLed)); quadState = 1; otherInfo = ""; } else { if (cameraOk) pic->SetIcon(container->icoYellowLed); else pic->SetIcon(container->icoRedLed); // What good are we without a camera quadState = 0; otherInfo = MIAs.Mid(0, MIAs.Length() - 2); pic->SetToolTip(IndicatorToolTip(type, quadState)); } } else { pic->SetIcon(container->icoRedLed); quadState = -1; } break; case Field_Darks: if (pFrame) { if (pFrame->m_useDarksMenuItem->IsChecked() || pFrame->m_useDefectMapMenuItem->IsChecked()) { quadState = 1; wxString lastLabel = ctrl->GetLabelText(); wxString currLabel = (pFrame->m_useDefectMapMenuItem->IsChecked() ? _("BPM") : _("Dark")); if (lastLabel != currLabel) { ctrl->SetLabelText(currLabel); ctrl->SetToolTip(IndicatorToolTip(type, quadState)); } } } break; case Field_Calib: { // For calib: -1 => no cal, 0 => cal but no pointing compensation, 1 => golden bool calibrated = (!pMount || pMount->IsCalibrated()) && (!pSecondaryMount || pSecondaryMount->IsCalibrated()); if (calibrated) { Scope *scope = TheScope(); bool deccomp = scope && scope->DecCompensationActive(); quadState = deccomp ? 1 : 0; } break; } default: break; } // Don't flog the status icons unless something has changed if (lastState != quadState) { if (type != Field_Gear) { switch (quadState) { case -2: ctrl->SetForegroundColour(*wxLIGHT_GREY); break; case -1: ctrl->SetForegroundColour(*wxRED); break; case 0: ctrl->SetForegroundColour(*wxYELLOW); break; case 1: ctrl->SetForegroundColour(*wxGREEN); break; } ctrl->Refresh(); if (quadState != -2) ctrl->SetToolTip(IndicatorToolTip(type, quadState)); } else if (quadState != -2) { pic->SetToolTip(IndicatorToolTip(type, quadState)); } lastState = quadState; } }
void installBenchmarkSystem( Scope& scope ) { scope.injectNative( "benchRun" , benchRun ); }
Scope::Scope(const Scope& orig) { assign(orig.ttl(), orig.publicKey()); }
bool TagAppend::parseStream() { Protocol::CreateTagCommand cmd(m_command); if (!cmd.remoteId().isEmpty() && !connection()->context()->resource().isValid()) { return failureResponse("Only resources can create tags with remote ID"); } TagType tagType; if (!cmd.type().isEmpty()) { const QString typeName = QString::fromUtf8(cmd.type()); tagType = TagType::retrieveByNameOrCreate(typeName); if (!tagType.isValid()) { return failureResponse(QStringLiteral("Unable to create tagtype '") % typeName % QStringLiteral("'")); } } qint64 tagId = -1; const QString gid = QString::fromUtf8(cmd.gid()); if (cmd.merge()) { QueryBuilder qb(Tag::tableName()); qb.addColumn(Tag::idColumn()); qb.addValueCondition(Tag::gidColumn(), Query::Equals, gid); if (!qb.exec()) { return failureResponse("Unable to list tags"); } if (qb.query().next()) { tagId = qb.query().value(0).toLongLong(); } } if (tagId < 0) { Tag insertedTag; insertedTag.setGid(gid); if (cmd.parentId() >= 0) { insertedTag.setParentId(cmd.parentId()); } if (tagType.isValid()) { insertedTag.setTypeId(tagType.id()); } if (!insertedTag.insert(&tagId)) { return failureResponse("Failed to store tag"); } const Protocol::Attributes attrs = cmd.attributes(); for (auto iter = attrs.cbegin(), end = attrs.cend(); iter != end; ++iter) { TagAttribute attribute; attribute.setTagId(tagId); attribute.setType(iter.key()); attribute.setValue(iter.value()); if (!attribute.insert()) { return failureResponse("Failed to store tag attribute"); } } DataStore::self()->notificationCollector()->tagAdded(insertedTag); } if (!cmd.remoteId().isEmpty()) { const qint64 resourceId = connection()->context()->resource().id(); CountQueryBuilder qb(TagRemoteIdResourceRelation::tableName()); qb.addValueCondition(TagRemoteIdResourceRelation::tagIdColumn(), Query::Equals, tagId); qb.addValueCondition(TagRemoteIdResourceRelation::resourceIdColumn(), Query::Equals, resourceId); if (!qb.exec()) { return failureResponse("Failed to query for existing TagRemoteIdResourceRelation entries"); } const bool exists = (qb.result() > 0); //If the relation is already existing simply update it (can happen if a resource simply creates the tag again while enabling merge) bool ret = false; if (exists) { //Simply using update() doesn't work since TagRemoteIdResourceRelation only takes the tagId for identification of the column QueryBuilder qb(TagRemoteIdResourceRelation::tableName(), QueryBuilder::Update); qb.addValueCondition(TagRemoteIdResourceRelation::tagIdColumn(), Query::Equals, tagId); qb.addValueCondition(TagRemoteIdResourceRelation::resourceIdColumn(), Query::Equals, resourceId); qb.setColumnValue(TagRemoteIdResourceRelation::remoteIdColumn(), cmd.remoteId()); ret = qb.exec(); } else { TagRemoteIdResourceRelation rel; rel.setTagId(tagId); rel.setResourceId(resourceId); rel.setRemoteId(QString::fromUtf8(cmd.remoteId())); ret = rel.insert(); } if (!ret) { return failureResponse("Failed to store tag remote ID"); } } // FIXME BIN Scope scope; ImapSet set; set.add(QVector<qint64>() << tagId); scope.setUidSet(set); TagFetchHelper helper(connection(), scope); if (!helper.fetchTags()) { return failureResponse("Failed to fetch the new tag"); } return successResponse<Protocol::CreateTagResponse>(); }
bool StandardAuthorizationServerPolicies::isScopeValid(const Scope &clientScope, const Scope &requestScope) const { return requestScope.isSubscopeOf(clientScope); };
vector<AOMDDFunction*> DDMiniBucket::GenerateMessages() { vector<AOMDDFunction*> messages; if (functions.size() == 0) { // cout << "No functions in bucket, returning empty message vector." << endl; return messages; } if (metric == I_BOUND) { // check function scopes list<LongIntPair> functionAritys; Scope combined; for (unsigned int i = 0; i < functions.size(); ++i) { combined = combined + functions[i]->GetScope(); unsigned int numVars = functions[i]->GetScope().GetNumVars(); if (numVars > bound) { // cout << "Warning: function arity exceeds bound! Increasing i-bound" << endl; bound = numVars; } functionAritys.push_back(LongIntPair(numVars, i)); // cout << "Function " << i << " arity: " << numVars << endl; } functionAritys.sort(CompareLongIntPair); /* cout << "Combined bucket output arity: " << combined.GetNumVars() - 1; cout << ", Bound: " << bound << endl; */ if (bound > 0 && combined.GetNumVars() > bound) { /* list<unsigned int> unassigned; for (unsigned int i = 0; i < functionAritys.size(); ++i) { unassigned.push_back(functionAritys[i].second); } */ vector< vector<int> > partitions; // cout << "Creating new partition" << endl; partitions.push_back(vector<int>()); int curPartition = 0; Scope partScope; while (!functionAritys.empty()) { list<LongIntPair>::iterator it = functionAritys.begin(); for (; it != functionAritys.end(); ++it) { Scope tempScope = partScope + functions[it->second]->GetScope(); // tempScope.Save(cout); if (tempScope.GetNumVars() <= bound + 1) { partScope = tempScope; partitions[curPartition].push_back(it->second); break; } // cout << "...was too large: " << tempScope.GetNumVars() << endl; } if (it != functionAritys.end()) { functionAritys.erase(it); } else { // cout << "Creating new partition" << endl; curPartition++; partitions.push_back(vector<int>()); partScope.Clear(); } } // generate messages for each partition for (unsigned int i = 0; i < partitions.size(); ++i) { messages.push_back(new AOMDDFunction(*functions[partitions[i][0]])); // for each function in the partition for (unsigned int j = 1; j < partitions[i].size(); ++j) { messages[i]->Multiply(*functions[partitions[i][j]]); } } // cerr << "Created " << partitions.size() << " partitions." << endl; } else { // just do the standard apply loop messages.push_back(new AOMDDFunction(*functions[0])); for (unsigned int i = 1; i < functions.size(); ++i) { messages[0]->Multiply(*functions[i]); } } } else if (metric == DIAGRAM_SIZE) { // calculate upper bound on non-partitioned diagram size unsigned long size = 1; double logSize = 0; list<LongIntPair> functionSizes; for (unsigned int i = 0; i < functions.size(); ++i) { int numMeta, numAND; tie(numMeta, numAND) = functions[i]->Size(); functionSizes.push_back(LongIntPair(numMeta+numAND+1, i)); // cout << "Function " << i << " size " << numMeta + numAND + 1<< endl; size *= numMeta + numAND + 1; logSize += log(numMeta+numAND + 1); } functionSizes.sort(CompareLongIntPair); /* cout << "Estimated combined bucket size: " << size << endl; cout << "Estimated combined bucket logsize: " << logSize << endl; cout << "Bound: " << bound << endl; */ // partition if size is > bound if (bound > 0 && size > bound) { // do standard largest first greedy partitioning map<int,unsigned int> partitionSizes; vector< vector<int> > partitions; partitions.push_back(vector<int>()); int curPartition = 0; partitionSizes[curPartition] = 1; while (!functionSizes.empty()) { list<LongIntPair>::iterator it = functionSizes.begin(); if (it == functionSizes.end()) break; int currentSize, idx; bool found = false; // if including this function fits under the bound... do { currentSize = it->first; idx = it->second; if (currentSize * partitionSizes[curPartition] <= bound || partitions[curPartition].empty()) { partitions[curPartition].push_back(idx); partitionSizes[curPartition] *= currentSize; functionSizes.erase(it); found = true; } else { ++it; } } while (!found && it != functionSizes.end()); if (!found) { // cerr << "Creating a new partition." << endl; ++curPartition; partitionSizes[curPartition] = 1; partitions.push_back(vector<int>()); } } /* for (unsigned int i = 0; i < partitions.size(); ++i) { cout << " " << partitionSizes[i]; } cout << endl; */ // generate messages for each partition for (unsigned int i = 0; i < partitions.size(); ++i) { messages.push_back(new AOMDDFunction(*functions[partitions[i][0]])); // for each function in the partition for (unsigned int j = 1; j < partitions[i].size(); ++j) { messages[i]->Multiply(*functions[partitions[i][j]]); } } // cerr << "Created " << partitions.size() << " partitions." << endl; } else { // just do the standard apply loop messages.push_back(new AOMDDFunction(*functions[0])); for (unsigned int i = 1; i < functions.size(); ++i) { messages[0]->Multiply(*functions[i]); } } } else { cout << "No metric set! Exiting..." << endl; exit(0); } return messages; }
void ScopeInfo::SaveScopeInfoForDeferParse(ByteCodeGenerator* byteCodeGenerator, FuncInfo* parentFunc, FuncInfo* funcInfo) { // TODO: Not technically necessary, as we always do scope look up on eval if it is // not found in the scope chain, and block scopes are always objects in eval. // But if we save the global eval block scope for deferred child so that we can look up // let/const in that scope with slot index instead of doing a scope lookup. // We will have to implement encoding block scope info to enable, which will also // enable defer parsing function that are in block scopes. Scope* currentScope = byteCodeGenerator->GetCurrentScope(); Assert(currentScope == funcInfo->GetBodyScope()); if (funcInfo->IsDeferred()) { // Don't need to remember the parent function if we have a global function if (!parentFunc->IsGlobalFunction() || ((byteCodeGenerator->GetFlags() & fscrEvalCode) && parentFunc->HasDeferredChild())) { // TODO: currently we only support defer nested function that is in function scope (no block scope, no with scope, etc.) #if DBG if (funcInfo->GetFuncExprScope() && funcInfo->GetFuncExprScope()->GetIsObject()) { if (funcInfo->paramScope && !funcInfo->paramScope->GetCanMergeWithBodyScope()) { Assert(currentScope->GetEnclosingScope()->GetEnclosingScope() == funcInfo->GetFuncExprScope()); } else { Assert(currentScope->GetEnclosingScope() == funcInfo->GetFuncExprScope() && currentScope->GetEnclosingScope()->GetEnclosingScope() == (parentFunc->IsGlobalFunction() ? parentFunc->GetGlobalEvalBlockScope() : parentFunc->GetBodyScope())); } } else { if (currentScope->GetEnclosingScope() == parentFunc->GetParamScope()) { Assert(!parentFunc->GetParamScope()->GetCanMergeWithBodyScope()); Assert(funcInfo->GetParamScope()->GetCanMergeWithBodyScope()); } else if (currentScope->GetEnclosingScope() == funcInfo->GetParamScope()) { Assert(!funcInfo->GetParamScope()->GetCanMergeWithBodyScope()); } else { Assert(currentScope->GetEnclosingScope() == (parentFunc->IsGlobalFunction() ? parentFunc->GetGlobalEvalBlockScope() : parentFunc->GetBodyScope())); } } #endif Js::ScopeInfo::SaveParentScopeInfo(parentFunc, funcInfo); } } else if (funcInfo->HasDeferredChild() || (!funcInfo->IsGlobalFunction() && funcInfo->byteCodeFunction && funcInfo->byteCodeFunction->IsReparsed() && funcInfo->byteCodeFunction->GetFunctionBody()->HasAllNonLocalReferenced())) { // When we reparse due to attach, we would need to capture all of them, since they were captured before going to debug mode. Js::ScopeInfo::SaveScopeInfo(byteCodeGenerator, parentFunc, funcInfo); } }
void run(){ Scope * s = globalScriptEngine->newScope(); { // date BSONObj o; { BSONObjBuilder b; b.appendDate( "d" , 123456789 ); o = b.obj(); } s->setObject( "x" , o ); s->invoke( "return x.d.getTime() != 12;" , BSONObj() ); ASSERT_EQUALS( true, s->getBoolean( "return" ) ); s->invoke( "z = x.d.getTime();" , BSONObj() ); ASSERT_EQUALS( 123456789 , s->getNumber( "z" ) ); s->invoke( "z = { z : x.d }" , BSONObj() ); BSONObj out = s->getObject( "z" ); ASSERT( out["z"].type() == Date ); } { // regex BSONObj o; { BSONObjBuilder b; b.appendRegex( "r" , "^a" , "i" ); o = b.obj(); } s->setObject( "x" , o ); s->invoke( "z = x.r.test( 'b' );" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "z" ) ); s->invoke( "z = x.r.test( 'a' );" , BSONObj() ); ASSERT_EQUALS( true , s->getBoolean( "z" ) ); s->invoke( "z = x.r.test( 'ba' );" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "z" ) ); s->invoke( "z = { a : x.r };" , BSONObj() ); BSONObj out = s->getObject("z"); ASSERT_EQUALS( (string)"^a" , out["a"].regex() ); ASSERT_EQUALS( (string)"i" , out["a"].regexFlags() ); } // array { BSONObj o = fromjson( "{r:[1,2,3]}" ); s->setObject( "x", o, false ); BSONObj out = s->getObject( "x" ); ASSERT_EQUALS( Array, out.firstElement().type() ); s->setObject( "x", o, true ); out = s->getObject( "x" ); ASSERT_EQUALS( Array, out.firstElement().type() ); } delete s; }
int main( int argc, char *argv[] ) { Scope global; EString sender; UString mailbox; EString recipient; EString filename; int verbose = 0; bool error = false; int n = 1; while ( n < argc ) { if ( argv[n][0] == '-' ) { switch ( argv[n][1] ) { case 'f': if ( argc - n > 1 ) sender = argv[++n]; break; case 't': if ( argc - n > 1 ) { Utf8Codec c; mailbox = c.toUnicode( argv[++n] ); if ( !c.valid() ) error = true; } break; case 'v': { int i = 1; while ( argv[n][i] == 'v' ) { verbose++; i++; } if ( argv[n][i] != '\0' ) error = true; } break; default: error = true; break; } } else if ( recipient.isEmpty() ) { recipient = argv[n]; } else if ( filename.isEmpty() ) { filename = argv[n]; } else { error = true; } n++; } if ( error || recipient.isEmpty() ) { fprintf( stderr, "Syntax: deliver [-v] [-f sender] recipient [filename]\n" ); exit( -1 ); } EString contents; if ( filename.isEmpty() ) { char s[128]; while ( fgets( s, 128, stdin ) != 0 ) contents.append( s ); } else { File message( filename ); if ( !message.valid() ) { fprintf( stderr, "Unable to open message file %s\n", filename.cstr() ); exit( -1 ); } contents = message.contents(); } Configuration::setup( "archiveopteryx.conf" ); Injectee * message = new Injectee; message->parse( contents ); if ( !message->error().isEmpty() ) { fprintf( stderr, "Message parsing failed: %s", message->error().cstr( ) ); exit( EX_DATAERR ); } if ( verbose > 0 ) fprintf( stderr, "Sending to <%s>\n", recipient.cstr() ); EventLoop::setup(); Database::setup( 1 ); Log * l = new Log; Allocator::addEternal( l, "delivery log" ); global.setLog( l ); Allocator::addEternal( new StderrLogger( "deliver", verbose ), "log object" ); Configuration::report(); Mailbox::setup(); Deliverator * d = new Deliverator( message, mailbox, recipient ); EventLoop::global()->start(); if ( !d->i || d->i->failed() ) return EX_UNAVAILABLE; if ( verbose ) fprintf( stderr, "deliver: Stored in %s as UID %d\n", d->mb->name().utf8().cstr(), d->m->uid( d->mb ) ); return 0; }
void run(){ Scope * s = globalScriptEngine->newScope(); // -- A -- BSONObj o; { BSONObjBuilder b ; b.append( "a" , (int)5 ); b.append( "b" , 5.6 ); o = b.obj(); } ASSERT_EQUALS( NumberInt , o["a"].type() ); ASSERT_EQUALS( NumberDouble , o["b"].type() ); s->setObject( "z" , o ); s->invoke( "return z" , BSONObj() ); BSONObj out = s->getObject( "return" ); ASSERT_EQUALS( 5 , out["a"].number() ); ASSERT_EQUALS( 5.6 , out["b"].number() ); ASSERT_EQUALS( NumberDouble , out["b"].type() ); ASSERT_EQUALS( NumberInt , out["a"].type() ); // -- B -- { BSONObjBuilder b ; b.append( "a" , (int)5 ); b.append( "b" , 5.6 ); o = b.obj(); } s->setObject( "z" , o , false ); s->invoke( "return z" , BSONObj() ); out = s->getObject( "return" ); ASSERT_EQUALS( 5 , out["a"].number() ); ASSERT_EQUALS( 5.6 , out["b"].number() ); ASSERT_EQUALS( NumberDouble , out["b"].type() ); ASSERT_EQUALS( NumberInt , out["a"].type() ); // -- C -- { BSONObjBuilder b ; { BSONObjBuilder c; c.append( "0" , 5.5 ); c.append( "1" , 6 ); b.appendArray( "a" , c.obj() ); } o = b.obj(); } ASSERT_EQUALS( NumberDouble , o["a"].embeddedObjectUserCheck()["0"].type() ); ASSERT_EQUALS( NumberInt , o["a"].embeddedObjectUserCheck()["1"].type() ); s->setObject( "z" , o , false ); out = s->getObject( "z" ); ASSERT_EQUALS( NumberDouble , out["a"].embeddedObjectUserCheck()["0"].type() ); ASSERT_EQUALS( NumberInt , out["a"].embeddedObjectUserCheck()["1"].type() ); s->invokeSafe( "z.z = 5;" , BSONObj() ); out = s->getObject( "z" ); ASSERT_EQUALS( 5 , out["z"].number() ); ASSERT_EQUALS( NumberDouble , out["a"].embeddedObjectUserCheck()["0"].type() ); // Commenting so that v8 tests will work // ASSERT_EQUALS( NumberDouble , out["a"].embeddedObjectUserCheck()["1"].type() ); // TODO: this is technically bad, but here to make sure that i understand the behavior // Eliot says I don't have to worry about this case // // -- D -- // // o = fromjson( "{a:3.0,b:4.5}" ); // ASSERT_EQUALS( NumberDouble , o["a"].type() ); // ASSERT_EQUALS( NumberDouble , o["b"].type() ); // // s->setObject( "z" , o , false ); // s->invoke( "return z" , BSONObj() ); // out = s->getObject( "return" ); // ASSERT_EQUALS( 3 , out["a"].number() ); // ASSERT_EQUALS( 4.5 , out["b"].number() ); // // ASSERT_EQUALS( NumberDouble , out["b"].type() ); // ASSERT_EQUALS( NumberDouble , out["a"].type() ); // delete s; }
void installShellUtils( Scope& scope ) { scope.injectNative( "quit", Quit ); scope.injectNative( "getMemInfo" , JSGetMemInfo ); scope.injectNative( "_replMonitorStats" , replMonitorStats ); scope.injectNative( "_srand" , JSSrand ); scope.injectNative( "_rand" , JSRand ); scope.injectNative( "_isWindows" , isWindows ); scope.injectNative( "_isAddressSanitizerActive", isAddressSanitizerActive ); scope.injectNative( "interpreterVersion", interpreterVersion ); scope.injectNative( "getBuildInfo", getBuildInfo ); scope.injectNative( "isKeyTooLarge", isKeyTooLarge ); scope.injectNative( "validateIndexKey", validateIndexKey ); #ifndef MONGO_SAFE_SHELL //can't launch programs installShellUtilsLauncher( scope ); installShellUtilsExtended( scope ); #endif }
/** * actually applies a reduce, to a list of tuples (key, value). * After the call, tuples will hold a single tuple {"0": key, "1": value} */ void JSReducer::_reduce( const BSONList& tuples , BSONObj& key , int& endSizeEstimate ) { uassert( 10074 , "need values" , tuples.size() ); int sizeEstimate = ( tuples.size() * tuples.begin()->getField( "value" ).size() ) + 128; // need to build the reduce args: ( key, [values] ) BSONObjBuilder reduceArgs( sizeEstimate ); boost::scoped_ptr<BSONArrayBuilder> valueBuilder; int sizeSoFar = 0; unsigned n = 0; for ( ; n<tuples.size(); n++ ) { BSONObjIterator j(tuples[n]); BSONElement keyE = j.next(); if ( n == 0 ) { reduceArgs.append( keyE ); key = keyE.wrap(); sizeSoFar = 5 + keyE.size(); valueBuilder.reset(new BSONArrayBuilder( reduceArgs.subarrayStart( "tuples" ) )); } BSONElement ee = j.next(); uassert( 13070 , "value too large to reduce" , ee.size() < ( BSONObjMaxUserSize / 2 ) ); if ( sizeSoFar + ee.size() > BSONObjMaxUserSize ) { assert( n > 1 ); // if not, inf. loop break; } valueBuilder->append( ee ); sizeSoFar += ee.size(); } assert(valueBuilder); valueBuilder->done(); BSONObj args = reduceArgs.obj(); Scope * s = _func.scope(); s->invokeSafe( _func.func() , &args, 0 ); ++numReduces; if ( s->type( "return" ) == Array ) { uasserted( 10075 , "reduce -> multiple not supported yet"); return; } endSizeEstimate = key.objsize() + ( args.objsize() / tuples.size() ); if ( n == tuples.size() ) return; // the input list was too large, add the rest of elmts to new tuples and reduce again // note: would be better to use loop instead of recursion to avoid stack overflow BSONList x; for ( ; n < tuples.size(); n++ ) { x.push_back( tuples[n] ); } BSONObjBuilder temp( endSizeEstimate ); temp.append( key.firstElement() ); s->append( temp , "1" , "return" ); x.push_back( temp.obj() ); _reduce( x , key , endSizeEstimate ); }
void initScope( Scope &scope ) { // Need to define this method before JSFiles::utils is executed. scope.injectNative("_useWriteCommandsDefault", useWriteCommandsDefault); scope.injectNative("_writeMode", writeMode); scope.externalSetup(); mongo::shell_utils::installShellUtils( scope ); scope.execSetup(JSFiles::servers); scope.execSetup(JSFiles::mongodtest); scope.execSetup(JSFiles::shardingtest); scope.execSetup(JSFiles::servers_misc); scope.execSetup(JSFiles::replsettest); scope.execSetup(JSFiles::replsetbridge); scope.injectNative("benchRun", BenchRunner::benchRunSync); scope.injectNative("benchRunSync", BenchRunner::benchRunSync); scope.injectNative("benchStart", BenchRunner::benchStart); scope.injectNative("benchFinish", BenchRunner::benchFinish); if ( !_dbConnect.empty() ) { uassert( 12513, "connect failed", scope.exec( _dbConnect , "(connect)" , false , true , false ) ); } if ( !_dbAuth.empty() ) { uassert( 12514, "login failed", scope.exec( _dbAuth , "(auth)" , true , true , false ) ); } }
void visit(const Let *let) { let->value.accept(this); defined_internally.push(let->name, 0); let->body.accept(this); defined_internally.pop(let->name); }
void visit(const Pipeline *op) { if (op->buffer != func.name()) { IRMutator::visit(op); } else { // We're interested in the case where exactly one of the // mins of the buffer depends on the loop_var, and none of // the extents do. string dim = ""; Expr min, extent; for (size_t i = 0; i < func.args().size(); i++) { string min_name = func.name() + "." + func.args()[i] + ".min"; string extent_name = func.name() + "." + func.args()[i] + ".extent"; assert(scope.contains(min_name) && scope.contains(extent_name)); Expr this_min = scope.get(min_name); Expr this_extent = scope.get(extent_name); if (ExprDependsOnVar(this_extent, loop_var).result) { min = Expr(); extent = Expr(); break; } if (ExprDependsOnVar(this_min, loop_var).result) { if (min.defined()) { min = Expr(); extent = Expr(); break; } else { dim = func.args()[i]; min = this_min; extent = this_extent; } } } if (min.defined()) { // Ok, we've isolated a function, a dimension to slide along, and loop variable to slide over log(2) << "Sliding " << func.name() << " over dimension " << dim << " along loop variable " << loop_var << "\n"; Expr loop_var_expr = new Variable(Int(32), loop_var); Expr steady_state = loop_var_expr > loop_min; Expr initial_min = substitute(loop_var, loop_min, min); // The new min is one beyond the max we reached on the last loop iteration Expr new_min = substitute(loop_var, loop_var_expr - 1, min + extent); // The new extent is the old extent shrunk by how much we trimmed off the min Expr new_extent = extent + min - new_min; new_min = new Select(steady_state, new_min, initial_min); new_extent = new Select(steady_state, new_extent, extent); stmt = new LetStmt(func.name() + "." + dim + ".extent", new_extent, op); stmt = new LetStmt(func.name() + "." + dim + ".min", new_min, stmt); } else { log(2) << "Could not perform sliding window optimization of " << func.name() << " over " << loop_var << "\n"; stmt = op; } } }
void visit(const For *op) { varying.push(op->name, 0); IRMutator::visit(op); varying.pop(op->name); }
void run(){ Scope * s = globalScriptEngine->newScope(); s->invoke( "x=5;" , BSONObj() ); ASSERT( 5 == s->getNumber( "x" ) ); s->invoke( "return 17;" , BSONObj() ); ASSERT( 17 == s->getNumber( "return" ) ); s->invoke( "function(){ return 17; }" , BSONObj() ); ASSERT( 17 == s->getNumber( "return" ) ); s->setNumber( "x" , 1.76 ); s->invoke( "return x == 1.76; " , BSONObj() ); ASSERT( s->getBoolean( "return" ) ); s->setNumber( "x" , 1.76 ); s->invoke( "return x == 1.79; " , BSONObj() ); ASSERT( ! s->getBoolean( "return" ) ); s->invoke( "function( z ){ return 5 + z; }" , BSON( "" << 11 ) ); ASSERT_EQUALS( 16 , s->getNumber( "return" ) ); delete s; }
double FSAOHDist_NECOF::GetXOHProb_relT( const Scope& sfSc, const std::vector<Index>& sfacIndices, const Scope& agSc, const std::vector<Index>& ohIndices ) const { //we use a running example to illustrate the code: // ->we want to compute P(o1o2x1x2) //However, o1 additionally depends on x3 and o2 on x4 //first check if sfSc contains all state factors that can influence //the observation (and thus the OHs) of the agents in agentSc, if //not, we will need to marginalize over the state factors that are not //in sfSc (but are in the SoI). Scope all_relevant_sfacIs(sfSc); for(Index i=0; i < agSc.size(); i++) all_relevant_sfacIs.Insert( _m_puf->GetFDPOMDPD()-> Get2DBN()->GetYSoI_O( agSc[i] ) ); Scope to_marginalize_over_sfacIs(all_relevant_sfacIs); to_marginalize_over_sfacIs.Remove(sfSc); //p(x1x2) = P(x1)*P(x2) double p1 = GetXProb(sfSc, sfacIndices); vector<Index> marg_vec(to_marginalize_over_sfacIs.size(), 0); vector<size_t> marg_nrSFvals( to_marginalize_over_sfacIs.size()); IndexTools::RestrictIndividualIndicesToScope( _m_puf->GetFDPOMDPD()->GetNrValuesPerFactor(), to_marginalize_over_sfacIs, marg_nrSFvals); //this will hold P(o1o2|x1x2) double p_ohIndices_given_sfacIndices = 0.0; do { //the probability of this instantiation of marg_vec //P(x3x4) double p2 = GetXProb(to_marginalize_over_sfacIs, marg_vec); if(p2>0) // optimalization: if p2 is zero the rest will be zero as well { //construct the 'full' state vector (i.e., containing all_relevant_sfacIs) //the vector x1x2x3x4 vector<Index> all_relevant_vals(sfacIndices); all_relevant_vals.insert(all_relevant_vals.end(), marg_vec.begin(), marg_vec.end()); //P(o1o2|x1x2x3x4) double p_ohIndices_given_all_relevant_vals = 1.0; for(Index i=0; i < agSc.size(); i++) { Index agI=agSc.at(i); Index ohI=ohIndices.at(i); vector<Index> sfacIrestr(_m_sfacSoI.at(agI).size()); try{ IndexTools::RestrictIndividualIndicesToNarrowerScope( all_relevant_vals, all_relevant_sfacIs, _m_sfacSoI.at(agI), sfacIrestr); }catch(ENoSubScope& e) { throw ENoSubScope("bah"); } Index x = IndexTools::IndividualToJointIndicesStepSize( sfacIrestr, _m_stepsize.at(agI) ); double p_OHi_given_all_relevant_vals = _m_oHistConditional.at(agI)->Get(ohI, x); //P(o1o2|x1x2x3x4) = P(o1|x1x2x3)P(o2|x1x2x4) p_ohIndices_given_all_relevant_vals *= p_OHi_given_all_relevant_vals; } //P(o1o2x3x4|x1x2) = P(o1o2|x1x2x3x4)P(x3x4) double p_ohIndices_marg_vec_given_sfacIndices = p2 * p_ohIndices_given_all_relevant_vals; //P(o1o2|x1x2) = sum_{x3x4} P(o1o2x3x4|x1x2) p_ohIndices_given_sfacIndices += p_ohIndices_marg_vec_given_sfacIndices; } }while (! IndexTools::Increment( marg_vec, marg_nrSFvals ) ); //finally P(o1o2x1x2): double result = p1 * p_ohIndices_given_sfacIndices; return(result); }
void run(){ Scope * s = globalScriptEngine->newScope(); BSONObj o = BSON( "x" << 17 << "y" << "eliot" << "z" << "sara" ); s->setObject( "blah" , o ); s->invoke( "return blah.x;" , BSONObj() ); ASSERT_EQUALS( 17 , s->getNumber( "return" ) ); s->invoke( "return blah.y;" , BSONObj() ); ASSERT_EQUALS( "eliot" , s->getString( "return" ) ); s->setThis( & o ); s->invoke( "return this.z;" , BSONObj() ); ASSERT_EQUALS( "sara" , s->getString( "return" ) ); s->invoke( "return this.z == 'sara';" , BSONObj() ); ASSERT_EQUALS( true , s->getBoolean( "return" ) ); s->invoke( "this.z == 'sara';" , BSONObj() ); ASSERT_EQUALS( true , s->getBoolean( "return" ) ); s->invoke( "this.z == 'asara';" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "return" ) ); s->invoke( "return this.x == 17;" , BSONObj() ); ASSERT_EQUALS( true , s->getBoolean( "return" ) ); s->invoke( "return this.x == 18;" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "return" ) ); s->invoke( "function(){ return this.x == 17; }" , BSONObj() ); ASSERT_EQUALS( true , s->getBoolean( "return" ) ); s->invoke( "function(){ return this.x == 18; }" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "return" ) ); s->invoke( "function (){ return this.x == 17; }" , BSONObj() ); ASSERT_EQUALS( true , s->getBoolean( "return" ) ); s->invoke( "function z(){ return this.x == 18; }" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "return" ) ); s->invoke( "function (){ this.x == 17; }" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "return" ) ); s->invoke( "function z(){ this.x == 18; }" , BSONObj() ); ASSERT_EQUALS( false , s->getBoolean( "return" ) ); s->invoke( "x = 5; for( ; x <10; x++){ a = 1; }" , BSONObj() ); ASSERT_EQUALS( 10 , s->getNumber( "x" ) ); delete s; }
void Module::semantic() { if (semanticstarted) return; //printf("+Module::semantic(this = %p, '%s'): parent = %p\n", this, toChars(), parent); semanticstarted = 1; // Note that modules get their own scope, from scratch. // This is so regardless of where in the syntax a module // gets imported, it is unaffected by context. Scope *sc = scope; // see if already got one from importAll() if (!sc) { printf("test2\n"); Scope::createGlobal(this); // create root scope } //printf("Module = %p, linkage = %d\n", sc->scopesym, sc->linkage); #if 0 // Add import of "object" if this module isn't "object" if (ident != Id::object) { Import *im = new Import(0, NULL, Id::object, NULL, 0); members->shift(im); } // Add all symbols into module's symbol table symtab = new DsymbolTable(); for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (Dsymbol *)members->data[i]; s->addMember(NULL, sc->scopesym, 1); } /* Set scope for the symbols so that if we forward reference * a symbol, it can possibly be resolved on the spot. * If this works out well, it can be extended to all modules * before any semantic() on any of them. */ for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (Dsymbol *)members->data[i]; s->setScope(sc); } #endif // Do semantic() on members that don't depend on others for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (*members)[i]; //printf("\tModule('%s'): '%s'.semantic0()\n", toChars(), s->toChars()); s->semantic0(sc); } // Pass 1 semantic routines: do public side of the definition for (size_t i = 0; i < members->dim; i++) { Dsymbol *s = (*members)[i]; //printf("\tModule('%s'): '%s'.semantic()\n", toChars(), s->toChars()); s->semantic(sc); runDeferredSemantic(); } if (!scope) { sc = sc->pop(); sc->pop(); // 2 pops because Scope::createGlobal() created 2 } semanticRun = semanticstarted; //printf("-Module::semantic(this = %p, '%s'): parent = %p\n", this, toChars(), parent); }
void run(){ Scope * s = globalScriptEngine->newScope(); BSONObj o = BSON( "x" << 17 << "y" << "eliot" << "z" << "sara" << "zz" << BSONObj() ); s->setObject( "blah" , o , true ); s->invoke( "blah.y = 'e'", BSONObj() ); BSONObj out = s->getObject( "blah" ); ASSERT( strlen( out["y"].valuestr() ) > 1 ); s->invoke( "blah.a = 19;" , BSONObj() ); out = s->getObject( "blah" ); ASSERT( out["a"].eoo() ); s->invoke( "blah.zz.a = 19;" , BSONObj() ); out = s->getObject( "blah" ); ASSERT( out["zz"].embeddedObject()["a"].eoo() ); s->setObject( "blah.zz", BSON( "a" << 19 ) ); out = s->getObject( "blah" ); ASSERT( out["zz"].embeddedObject()["a"].eoo() ); s->invoke( "delete blah['x']" , BSONObj() ); out = s->getObject( "blah" ); ASSERT( !out["x"].eoo() ); // read-only object itself can be overwritten s->invoke( "blah = {}", BSONObj() ); out = s->getObject( "blah" ); ASSERT( out.isEmpty() ); // test array - can't implement this in v8 // o = fromjson( "{a:[1,2,3]}" ); // s->setObject( "blah", o, true ); // out = s->getObject( "blah" ); // s->invoke( "blah.a[ 0 ] = 4;", BSONObj() ); // s->invoke( "delete blah['a'][ 2 ];", BSONObj() ); // out = s->getObject( "blah" ); // ASSERT_EQUALS( 1.0, out[ "a" ].embeddedObject()[ 0 ].number() ); // ASSERT_EQUALS( 3.0, out[ "a" ].embeddedObject()[ 2 ].number() ); delete s; }
ComputeModulusRemainder(const Scope<ModulusRemainder> *s) { scope.set_containing_scope(s); }
void NyanCatAnalyzer::transform(Scope& s) { m_fht->spectrum(&s.front()); }