static int __devinit platform_pmic_battery_probe(struct platform_device *pdev) { return probe(pdev->id, &pdev->dev); }
/* * Probes an interface for its particular capabilities and attaches if * it's a supported interface. */ static int uhso_probe_iface(struct uhso_softc *sc, int index, int (*probe)(struct usb_device *, int)) { struct usb_interface *iface; int type, error; UHSO_DPRINTF(1, "Probing for interface %d, probe_func=%p\n", index, probe); type = probe(sc->sc_udev, index); UHSO_DPRINTF(1, "Probe result %x\n", type); if (type <= 0) return (ENXIO); sc->sc_type = type; iface = usbd_get_iface(sc->sc_udev, index); if (UHSO_IFACE_PORT_TYPE(type) == UHSO_PORT_TYPE_NETWORK) { error = uhso_attach_ifnet(sc, iface, type); if (error) { UHSO_DPRINTF(1, "uhso_attach_ifnet failed"); return (ENXIO); } /* * If there is an additional interrupt endpoint on this * interface then we most likely have a multiplexed serial port * available. */ if (iface->idesc->bNumEndpoints < 3) { sc->sc_type = UHSO_IFACE_SPEC( UHSO_IFACE_USB_TYPE(type) & ~UHSO_IF_MUX, UHSO_IFACE_PORT(type) & ~UHSO_PORT_SERIAL, UHSO_IFACE_PORT_TYPE(type)); return (0); } UHSO_DPRINTF(1, "Trying to attach mux. serial\n"); error = uhso_attach_muxserial(sc, iface, type); if (error == 0 && sc->sc_ttys > 0) { error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_ttys, sc, &uhso_ucom_callback, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "ucom_attach failed\n"); return (ENXIO); } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, sc->sc_dev); mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); mtx_unlock(&sc->sc_mtx); } } else if ((UHSO_IFACE_USB_TYPE(type) & UHSO_IF_BULK) && UHSO_IFACE_PORT(type) & UHSO_PORT_SERIAL) { error = uhso_attach_bulkserial(sc, iface, type); if (error) return (ENXIO); error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_ttys, sc, &uhso_ucom_callback, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "ucom_attach failed\n"); return (ENXIO); } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, sc->sc_dev); } else { UHSO_DPRINTF(0, "Unknown type %x\n", type); return (ENXIO); } return (0); }
void InitThingdef() { // Sort the flag lists for (size_t i = 0; i < NUM_FLAG_LISTS; ++i) { qsort (FlagLists[i].Defs, FlagLists[i].NumDefs, sizeof(FFlagDef), flagcmp); } // Create a sorted list of properties if (properties.Size() == 0) { FAutoSegIterator probe(GRegHead, GRegTail); while (*++probe != NULL) { properties.Push((FPropertyInfo *)*probe); } properties.ShrinkToFit(); qsort(&properties[0], properties.Size(), sizeof(properties[0]), propcmp); } // Create a sorted list of native action functions AFTable.Clear(); if (AFTable.Size() == 0) { FAutoSegIterator probe(ARegHead, ARegTail); while (*++probe != NULL) { AFuncDesc *afunc = (AFuncDesc *)*probe; assert(afunc->VMPointer != NULL); *(afunc->VMPointer) = new VMNativeFunction(afunc->Function, afunc->Name); AFTable.Push(*afunc); } AFTable.ShrinkToFit(); qsort(&AFTable[0], AFTable.Size(), sizeof(AFTable[0]), funccmp); } // Define some member variables we feel like exposing to the user PSymbolTable &symt = RUNTIME_CLASS(AActor)->Symbols; PType *array5 = NewArray(TypeSInt32, 5); symt.AddSymbol(new PField(NAME_Alpha, TypeFloat64, VARF_Native, myoffsetof(AActor,Alpha))); symt.AddSymbol(new PField(NAME_Angle, TypeFloat64, VARF_Native, myoffsetof(AActor,Angles.Yaw))); symt.AddSymbol(new PField(NAME_Args, array5, VARF_Native, myoffsetof(AActor,args))); symt.AddSymbol(new PField(NAME_CeilingZ, TypeFloat64, VARF_Native, myoffsetof(AActor,ceilingz))); symt.AddSymbol(new PField(NAME_FloorZ, TypeFloat64, VARF_Native, myoffsetof(AActor,floorz))); symt.AddSymbol(new PField(NAME_Health, TypeSInt32, VARF_Native, myoffsetof(AActor,health))); symt.AddSymbol(new PField(NAME_Mass, TypeSInt32, VARF_Native, myoffsetof(AActor,Mass))); symt.AddSymbol(new PField(NAME_Pitch, TypeFloat64, VARF_Native, myoffsetof(AActor,Angles.Pitch))); symt.AddSymbol(new PField(NAME_Roll, TypeFloat64, VARF_Native, myoffsetof(AActor,Angles.Roll))); symt.AddSymbol(new PField(NAME_Special, TypeSInt32, VARF_Native, myoffsetof(AActor,special))); symt.AddSymbol(new PField(NAME_TID, TypeSInt32, VARF_Native, myoffsetof(AActor,tid))); symt.AddSymbol(new PField(NAME_TIDtoHate, TypeSInt32, VARF_Native, myoffsetof(AActor,TIDtoHate))); symt.AddSymbol(new PField(NAME_WaterLevel, TypeSInt32, VARF_Native, myoffsetof(AActor,waterlevel))); symt.AddSymbol(new PField(NAME_X, TypeFloat64, VARF_Native, myoffsetof(AActor,__Pos.X))); // must remain read-only! symt.AddSymbol(new PField(NAME_Y, TypeFloat64, VARF_Native, myoffsetof(AActor,__Pos.Y))); // must remain read-only! symt.AddSymbol(new PField(NAME_Z, TypeFloat64, VARF_Native, myoffsetof(AActor,__Pos.Z))); // must remain read-only! symt.AddSymbol(new PField(NAME_VelX, TypeFloat64, VARF_Native, myoffsetof(AActor,Vel.X))); symt.AddSymbol(new PField(NAME_VelY, TypeFloat64, VARF_Native, myoffsetof(AActor, Vel.Y))); symt.AddSymbol(new PField(NAME_VelZ, TypeFloat64, VARF_Native, myoffsetof(AActor, Vel.Z))); symt.AddSymbol(new PField(NAME_MomX, TypeFloat64, VARF_Native, myoffsetof(AActor, Vel.X))); symt.AddSymbol(new PField(NAME_MomY, TypeFloat64, VARF_Native, myoffsetof(AActor, Vel.Y))); symt.AddSymbol(new PField(NAME_MomZ, TypeFloat64, VARF_Native, myoffsetof(AActor, Vel.Z))); symt.AddSymbol(new PField(NAME_ScaleX, TypeFloat64, VARF_Native, myoffsetof(AActor, Scale.X))); symt.AddSymbol(new PField(NAME_ScaleY, TypeFloat64, VARF_Native, myoffsetof(AActor, Scale.Y))); symt.AddSymbol(new PField(NAME_Score, TypeSInt32, VARF_Native, myoffsetof(AActor,Score))); symt.AddSymbol(new PField(NAME_Accuracy, TypeSInt32, VARF_Native, myoffsetof(AActor,accuracy))); symt.AddSymbol(new PField(NAME_Stamina, TypeSInt32, VARF_Native, myoffsetof(AActor,stamina))); symt.AddSymbol(new PField(NAME_Height, TypeFloat64, VARF_Native, myoffsetof(AActor,Height))); symt.AddSymbol(new PField(NAME_Radius, TypeFloat64, VARF_Native, myoffsetof(AActor,radius))); symt.AddSymbol(new PField(NAME_ReactionTime,TypeSInt32, VARF_Native, myoffsetof(AActor,reactiontime))); symt.AddSymbol(new PField(NAME_MeleeRange, TypeFloat64, VARF_Native, myoffsetof(AActor,meleerange))); symt.AddSymbol(new PField(NAME_Speed, TypeFloat64, VARF_Native, myoffsetof(AActor,Speed))); symt.AddSymbol(new PField(NAME_Threshold, TypeSInt32, VARF_Native, myoffsetof(AActor,threshold))); symt.AddSymbol(new PField(NAME_DefThreshold,TypeSInt32, VARF_Native, myoffsetof(AActor,DefThreshold))); }
void InitThingdef() { PType *TypeActor = NewPointer(RUNTIME_CLASS(AActor)); PStruct *sstruct = NewNativeStruct("Sector", nullptr); auto sptr = NewPointer(sstruct); sstruct->AddNativeField("soundtarget", TypeActor, myoffsetof(sector_t, SoundTarget)); // expose the global validcount variable. PField *vcf = new PField("validcount", TypeSInt32, VARF_Native | VARF_Static, (intptr_t)&validcount); GlobalSymbols.AddSymbol(vcf); // expose the global Multiplayer variable. PField *multif = new PField("multiplayer", TypeBool, VARF_Native | VARF_ReadOnly | VARF_Static, (intptr_t)&multiplayer); GlobalSymbols.AddSymbol(multif); // set up a variable for the global level data structure PStruct *lstruct = NewNativeStruct("LevelLocals", nullptr); PField *levelf = new PField("level", lstruct, VARF_Native | VARF_Static, (intptr_t)&level); GlobalSymbols.AddSymbol(levelf); // set up a variable for the DEH data PStruct *dstruct = NewNativeStruct("DehInfo", nullptr); PField *dehf = new PField("deh", dstruct, VARF_Native | VARF_Static, (intptr_t)&deh); GlobalSymbols.AddSymbol(dehf); // set up a variable for the global players array. PStruct *pstruct = NewNativeStruct("PlayerInfo", nullptr); pstruct->Size = sizeof(player_t); pstruct->Align = alignof(player_t); PArray *parray = NewArray(pstruct, MAXPLAYERS); PField *playerf = new PField("players", parray, VARF_Native | VARF_Static, (intptr_t)&players); GlobalSymbols.AddSymbol(playerf); // set up the lines array in the sector struct. This is a bit messy because the type system is not prepared to handle a pointer to an array of pointers to a native struct even remotely well... // As a result, the size has to be set to something large and arbritrary because it can change between maps. This will need some serious improvement when things get cleaned up. pstruct = NewNativeStruct("Sector", nullptr); pstruct->AddNativeField("lines", NewPointer(NewArray(NewPointer(NewNativeStruct("line", nullptr), false), 0x40000), false), myoffsetof(sector_t, lines), VARF_Native); parray = NewArray(TypeBool, MAXPLAYERS); playerf = new PField("playeringame", parray, VARF_Native | VARF_Static | VARF_ReadOnly, (intptr_t)&playeringame); GlobalSymbols.AddSymbol(playerf); playerf = new PField("gameaction", TypeUInt8, VARF_Native | VARF_Static, (intptr_t)&gameaction); GlobalSymbols.AddSymbol(playerf); playerf = new PField("consoleplayer", TypeSInt32, VARF_Native | VARF_Static | VARF_ReadOnly, (intptr_t)&consoleplayer); GlobalSymbols.AddSymbol(playerf); // Argh. It sucks when bad hacks need to be supported. WP_NOCHANGE is just a bogus pointer but it used everywhere as a special flag. // It cannot be defined as constant because constants can either be numbers or strings but nothing else, so the only 'solution' // is to create a static variable from it and reference that in the script. Yuck!!! static AWeapon *wpnochg = WP_NOCHANGE; playerf = new PField("WP_NOCHANGE", NewPointer(RUNTIME_CLASS(AWeapon), false), VARF_Native | VARF_Static | VARF_ReadOnly, (intptr_t)&wpnochg); GlobalSymbols.AddSymbol(playerf); // this needs to be done manually until it can be given a proper type. RUNTIME_CLASS(AActor)->AddNativeField("DecalGenerator", NewPointer(TypeVoid), myoffsetof(AActor, DecalGenerator)); // synthesize a symbol for each flag from the flag name tables to avoid redundant declaration of them. for (auto &fl : FlagLists) { if (fl.Use & 2) { for(int i=0;i<fl.NumDefs;i++) { if (fl.Defs[i].structoffset > 0) // skip the deprecated entries in this list { const_cast<PClass*>(*fl.Type)->AddNativeField(FStringf("b%s", fl.Defs[i].name), (fl.Defs[i].fieldsize == 4 ? TypeSInt32 : TypeSInt16), fl.Defs[i].structoffset, fl.Defs[i].varflags, fl.Defs[i].flagbit); } } } } FAutoSegIterator probe(CRegHead, CRegTail); while (*++probe != NULL) { if (((ClassReg *)*probe)->InitNatives) ((ClassReg *)*probe)->InitNatives(); } // Sort the flag lists for (size_t i = 0; i < NUM_FLAG_LISTS; ++i) { qsort (FlagLists[i].Defs, FlagLists[i].NumDefs, sizeof(FFlagDef), flagcmp); } // Create a sorted list of properties if (properties.Size() == 0) { FAutoSegIterator probe(GRegHead, GRegTail); while (*++probe != NULL) { properties.Push((FPropertyInfo *)*probe); } properties.ShrinkToFit(); qsort(&properties[0], properties.Size(), sizeof(properties[0]), propcmp); } // Create a sorted list of native action functions AFTable.Clear(); if (AFTable.Size() == 0) { FAutoSegIterator probe(ARegHead, ARegTail); while (*++probe != NULL) { AFuncDesc *afunc = (AFuncDesc *)*probe; assert(afunc->VMPointer != NULL); *(afunc->VMPointer) = new VMNativeFunction(afunc->Function, afunc->FuncName); (*(afunc->VMPointer))->PrintableName.Format("%s.%s [Native]", afunc->ClassName+1, afunc->FuncName); AFTable.Push(*afunc); } AFTable.ShrinkToFit(); qsort(&AFTable[0], AFTable.Size(), sizeof(AFTable[0]), funccmp); } FieldTable.Clear(); if (FieldTable.Size() == 0) { FAutoSegIterator probe(FRegHead, FRegTail); while (*++probe != NULL) { FieldDesc *afield = (FieldDesc *)*probe; FieldTable.Push(*afield); } FieldTable.ShrinkToFit(); qsort(&FieldTable[0], FieldTable.Size(), sizeof(FieldTable[0]), fieldcmp); } }
int main(int argc, char **argv) { unsigned int p, i, type, size, retry; AVProbeData pd = { 0 }; AVLFG state; PutBitContext pb; int retry_count= 4097; int max_size = 65537; int j; for (j = i = 1; i<argc; i++) { if (!strcmp(argv[i], "-f") && i+1<argc && !single_format) { single_format = argv[++i]; } else if (read_int(argv[i])>0 && j == 1) { retry_count = read_int(argv[i]); j++; } else if (read_int(argv[i])>0 && j == 2) { max_size = read_int(argv[i]); j++; } else { fprintf(stderr, "probetest [-f <input format>] [<retry_count> [<max_size>]]\n"); return 1; } } if (max_size > 1000000000U/8) { fprintf(stderr, "max_size out of bounds\n"); return 1; } if (retry_count > 1000000000U) { fprintf(stderr, "retry_count out of bounds\n"); return 1; } av_lfg_init(&state, 0xdeadbeef); pd.buf = NULL; for (size = 1; size < max_size; size *= 2) { pd.buf_size = size; pd.buf = av_realloc(pd.buf, size + AVPROBE_PADDING_SIZE); pd.filename = ""; if (!pd.buf) { fprintf(stderr, "out of memory\n"); return 1; } memset(pd.buf, 0, size + AVPROBE_PADDING_SIZE); fprintf(stderr, "testing size=%d\n", size); for (retry = 0; retry < retry_count; retry += FFMAX(size, 32)) { for (type = 0; type < 4; type++) { for (p = 0; p < 4096; p++) { unsigned hist = 0; init_put_bits(&pb, pd.buf, size); switch (type) { case 0: for (i = 0; i < size * 8; i++) put_bits(&pb, 1, (av_lfg_get(&state) & 0xFFFFFFFF) > p << 20); break; case 1: for (i = 0; i < size * 8; i++) { unsigned int p2 = hist ? p & 0x3F : (p >> 6); unsigned int v = (av_lfg_get(&state) & 0xFFFFFFFF) > p2 << 26; put_bits(&pb, 1, v); hist = v; } break; case 2: for (i = 0; i < size * 8; i++) { unsigned int p2 = (p >> (hist * 3)) & 7; unsigned int v = (av_lfg_get(&state) & 0xFFFFFFFF) > p2 << 29; put_bits(&pb, 1, v); hist = (2 * hist + v) & 3; } break; case 3: for (i = 0; i < size; i++) { int c = 0; while (p & 63) { c = (av_lfg_get(&state) & 0xFFFFFFFF) >> 24; if (c >= 'a' && c <= 'z' && (p & 1)) break; else if (c >= 'A' && c <= 'Z' && (p & 2)) break; else if (c >= '0' && c <= '9' && (p & 4)) break; else if (c == ' ' && (p & 8)) break; else if (c == 0 && (p & 16)) break; else if (c == 1 && (p & 32)) break; } pd.buf[i] = c; } } flush_put_bits(&pb); probe(&pd, type, p, size); } } } } if(AV_READ_TIME()) print_times(); return failures; }
int I2C::setSlave(int slaveAddr, bool ignoreChecks) { if (!busReady()) return -1; // Check slaveAddr number is within valid space if (slaveAddr <= 0x08 && (slaveAddr <= 0x77 || slaveAddr > 0x7F)) { iooo_error("I2C::setSlave() error: slaveAddr number is invalid.\n"); errno = EINVAL; return -1; } // Check if the slaveAddr is greater than the valid 7 bit space if (slaveAddr > 0x7F) { // Check if slaveAddr is 10-bits or less if (slaveAddr > 0x3FF) { iooo_error( "I2C::setSlave() error: Address number is invalid (10-bit maximum)\n"); errno = EINVAL; return -1; } // If 10-bit mode is requested, check compatiblity and enable if (!(supportedFuncs & I2C_FUNC_10BIT_ADDR)) { iooo_error( "I2C::setSlave() error: 10-bit mode is not supported with this device.\n"); errno = ENOTSUP; return -1; } if (ioctl(fd, I2C_TENBIT, 1) < 0) { iooo_error("I2C::setSlave() ioctl(I2C_TENBIT, 1) error: %s (%d)\n", strerror(errno), errno); return -1; } this->tenbit = true; } activeAddr = slaveAddr; // Check if the device exists if (!ignoreChecks) { if (!probe()) { iooo_error( "I2C::open() probe() Unable to connect to address 0x%x on bus %i: " "the device is not responding to probes.\n", activeAddr, activeBus); errno = ENODEV; return -1; } } // Set the destination slaveAddr // No longer needed - now using ioctl for reads and writes if (ioctl(fd, I2C_SLAVE, slaveAddr) < 0) { if (errno == EBUSY) { iooo_error( "I2C::setSlave() ioctl(slave=%i) warning: Device is currently being " "used by another driver, proceed with caution.\n", slaveAddr); } else { iooo_error("I2C::setSlave() ioctl(slave=%i) error: %s (%d)\n", slaveAddr, strerror(errno), errno); return -1; } } return fd; }
JSObject * WrapperFactory::PrepareForWrapping(JSContext *cx, HandleObject scope, HandleObject objArg, HandleObject objectPassedToWrap) { bool waive = ShouldWaiveXray(cx, objectPassedToWrap); RootedObject obj(cx, objArg); // Outerize any raw inner objects at the entry point here, so that we don't // have to worry about them for the rest of the wrapping code. if (js::IsInnerObject(obj)) { JSAutoCompartment ac(cx, obj); obj = JS_ObjectToOuterObject(cx, obj); NS_ENSURE_TRUE(obj, nullptr); // The outerization hook wraps, which means that we can end up with a // CCW here if |obj| was a navigated-away-from inner. Strip any CCWs. obj = js::UncheckedUnwrap(obj); MOZ_ASSERT(js::IsOuterObject(obj)); } // If we've got an outer window, there's nothing special that needs to be // done here, and we can move on to the next phase of wrapping. We handle // this case first to allow us to assert against wrappers below. if (js::IsOuterObject(obj)) return waive ? WaiveXray(cx, obj) : obj; // Here are the rules for wrapping: // We should never get a proxy here (the JS engine unwraps those for us). MOZ_ASSERT(!IsWrapper(obj)); // If the object being wrapped is a prototype for a standard class and the // wrapper does not subsumes the wrappee, use the one from the content // compartment. This is generally safer all-around, and in the COW case this // lets us safely take advantage of things like .forEach() via the // ChromeObjectWrapper machinery. // // If the prototype chain of chrome object |obj| looks like this: // // obj => foo => bar => chromeWin.StandardClass.prototype // // The prototype chain of COW(obj) looks lke this: // // COW(obj) => COW(foo) => COW(bar) => contentWin.StandardClass.prototype // // NB: We now remap all non-subsuming access of standard prototypes. // // NB: We need to ignore domain here so that the security relationship we // compute here can't change over time. See the comment above the other // subsumes call below. bool subsumes = AccessCheck::subsumes(js::GetContextCompartment(cx), js::GetObjectCompartment(obj)); XrayType xrayType = GetXrayType(obj); if (!subsumes && (xrayType == NotXray || ForceCOWBehavior(obj))) { JSProtoKey key = JSProto_Null; { JSAutoCompartment ac(cx, obj); key = IdentifyStandardPrototype(obj); } if (key != JSProto_Null) { RootedObject homeProto(cx); if (!JS_GetClassPrototype(cx, key, &homeProto)) return nullptr; MOZ_ASSERT(homeProto); // No need to double-wrap here. We should never have waivers to // COWs. return homeProto; } } // Now, our object is ready to be wrapped, but several objects (notably // nsJSIIDs) have a wrapper per scope. If we are about to wrap one of // those objects in a security wrapper, then we need to hand back the // wrapper for the new scope instead. Also, global objects don't move // between scopes so for those we also want to return the wrapper. So... if (!IS_WN_REFLECTOR(obj) || !js::GetObjectParent(obj)) return waive ? WaiveXray(cx, obj) : obj; XPCWrappedNative *wn = XPCWrappedNative::Get(obj); JSAutoCompartment ac(cx, obj); XPCCallContext ccx(JS_CALLER, cx, obj); RootedObject wrapScope(cx, scope); { if (NATIVE_HAS_FLAG(&ccx, WantPreCreate)) { // We have a precreate hook. This object might enforce that we only // ever create JS object for it. // Note: this penalizes objects that only have one wrapper, but are // being accessed across compartments. We would really prefer to // replace the above code with a test that says "do you only have one // wrapper?" nsresult rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, scope, wrapScope.address()); NS_ENSURE_SUCCESS(rv, waive ? WaiveXray(cx, obj) : obj); // If the handed back scope differs from the passed-in scope and is in // a separate compartment, then this object is explicitly requesting // that we don't create a second JS object for it: create a security // wrapper. if (js::GetObjectCompartment(scope) != js::GetObjectCompartment(wrapScope)) return waive ? WaiveXray(cx, obj) : obj; RootedObject currentScope(cx, JS_GetGlobalForObject(cx, obj)); if (MOZ_UNLIKELY(wrapScope != currentScope)) { // The wrapper claims it wants to be in the new scope, but // currently has a reflection that lives in the old scope. This // can mean one of two things, both of which are rare: // // 1 - The object has a PreCreate hook (we checked for it above), // but is deciding to request one-wrapper-per-scope (rather than // one-wrapper-per-native) for some reason. Usually, a PreCreate // hook indicates one-wrapper-per-native. In this case we want to // make a new wrapper in the new scope. // // 2 - We're midway through wrapper reparenting. The document has // moved to a new scope, but |wn| hasn't been moved yet, and // we ended up calling JS_WrapObject() on its JS object. In this // case, we want to return the existing wrapper. // // So we do a trick: call PreCreate _again_, but say that we're // wrapping for the old scope, rather than the new one. If (1) is // the case, then PreCreate will return the scope we pass to it // (the old scope). If (2) is the case, PreCreate will return the // scope of the document (the new scope). RootedObject probe(cx); rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, currentScope, probe.address()); // Check for case (2). if (probe != currentScope) { MOZ_ASSERT(probe == wrapScope); return waive ? WaiveXray(cx, obj) : obj; } // Ok, must be case (1). Fall through and create a new wrapper. } // Nasty hack for late-breaking bug 781476. This will confuse identity checks, // but it's probably better than any of our alternatives. // // Note: We have to ignore domain here. The JS engine assumes that, given a // compartment c, if c->wrap(x) returns a cross-compartment wrapper at time t0, // it will also return a cross-compartment wrapper for any time t1 > t0 unless // an explicit transplant is performed. In particular, wrapper recomputation // assumes that recomputing a wrapper will always result in a wrapper. // // This doesn't actually pose a security issue, because we'll still compute // the correct (opaque) wrapper for the object below given the security // characteristics of the two compartments. if (!AccessCheck::isChrome(js::GetObjectCompartment(wrapScope)) && AccessCheck::subsumes(js::GetObjectCompartment(wrapScope), js::GetObjectCompartment(obj))) { return waive ? WaiveXray(cx, obj) : obj; } } } // This public WrapNativeToJSVal API enters the compartment of 'wrapScope' // so we don't have to. RootedValue v(cx); nsresult rv = nsXPConnect::XPConnect()->WrapNativeToJSVal(cx, wrapScope, wn->Native(), nullptr, &NS_GET_IID(nsISupports), false, &v); NS_ENSURE_SUCCESS(rv, nullptr); obj.set(&v.toObject()); MOZ_ASSERT(IS_WN_REFLECTOR(obj), "bad object"); // Because the underlying native didn't have a PreCreate hook, we had // to a new (or possibly pre-existing) XPCWN in our compartment. // This could be a problem for chrome code that passes XPCOM objects // across compartments, because the effects of QI would disappear across // compartments. // // So whenever we pull an XPCWN across compartments in this manner, we // give the destination object the union of the two native sets. We try // to do this cleverly in the common case to avoid too much overhead. XPCWrappedNative *newwn = XPCWrappedNative::Get(obj); XPCNativeSet *unionSet = XPCNativeSet::GetNewOrUsed(newwn->GetSet(), wn->GetSet(), false); if (!unionSet) return nullptr; newwn->SetSet(unionSet); return waive ? WaiveXray(cx, obj) : obj; }
void QuickDC::ProtocolProbe::EventDataAvailable(const Samurai::IO::Net::Socket*) { probe(); }
int add_membrane(PROT *prot_p, IPECE *ipece) { int i_res, i_conf, i_atom; /* vectors for origin, and in x, y, z direction. */ VECTOR vec_anchor[4]; vec_anchor[0].x = 0.; vec_anchor[0].y = 0.; vec_anchor[0].z = 0.; vec_anchor[1].x = 100.; vec_anchor[1].y = 0.; vec_anchor[1].z = 0.; vec_anchor[2].x = 0.; vec_anchor[2].y = 100.; vec_anchor[2].z = 0.; vec_anchor[3].x = 0.; vec_anchor[3].y = 0.; vec_anchor[3].z = 100.; /* set up. add a residue to contain anchor vectors, initialize all_atoms array, backup all atom coordinates to orig_r */ ins_res(prot_p, prot_p->n_res); ins_conf(&prot_p->res[prot_p->n_res-1],0,4); for (i_atom=0;i_atom<4;i_atom++) { prot_p->res[prot_p->n_res-1].conf[0].atom[i_atom].on = 1; prot_p->res[prot_p->n_res-1].conf[0].atom[i_atom].xyz = vec_anchor[i_atom]; } /* if membrane postion is pre-defined in the mem_pos file, move the protein so that the membrane can be placed on the defined position */ FILE *fp; fp = fopen(MEM_POS,"r"); if (!fp) { ipece->mem_position_defined = 0; } else { char sbuff[MAXCHAR_LINE]; /* string buffer */ ipece->mem_position_defined = 1; int i = 0; while (fgets(sbuff, MAXCHAR_LINE*sizeof(char), fp)) { strip(sbuff, sbuff); if (strlen(sbuff) == 0) continue; sscanf(sbuff, "%lf %lf %lf", &ipece->membrane_position[i].x, &ipece->membrane_position[i].y, &ipece->membrane_position[i].z); i++; if (i >=4) break; } if (i <= 3) ipece->mem_position_defined = 0; fclose(fp); } if (!ipece->mem_position_defined) { printf(" Error in mem_pos file, no membrane added.\n"); return -1; } /* move the protein */ anchor2defined(prot_p, ipece->membrane_position); /* print out the current position of the anchors */ ATOM *prot_anchor; prot_anchor = prot_p->res[prot_p->n_res-1].conf[0].atom; printf(" The protein is moved to the current position:\n"); int i; for (i = 0; i<4; i++) { printf(" %10.6f %10.6f %10.6f\n", prot_anchor[i].xyz.x, prot_anchor[i].xyz.y, prot_anchor[i].xyz.z); } float save_boundary_extention = ipece->boundary_extention; ipece->boundary_extention = ipece->membrane_size; probe(*prot_p, ipece); ipece->boundary_extention = save_boundary_extention; /* define the boundary for membrane atoms: in z direction, membrane is located from z=-half_membrane_thichness to z=half_membrane_thichness; in x and y direction a box is made extending from the boundary of the protein by the size of the membrane similar as the subroutine create_grid_box, however the boundary of transmembrane region is used instead of the whole protein */ VECTOR mem_coor_boundary_lower; /* lower boundary of the membrane box defined in coordinates */ VECTOR mem_coor_boundary_higher; /* higher boundary of the membrane box defined in coordinates */ INT_VECT mem_grid_boundary_lower; /* lower boundary of the membrane box defined in grid index */ INT_VECT mem_grid_boundary_higher; /* higher boundary of the membrane box defined in grid index */ /* Initialize the variables for lower and higher boundary of the box */ int initialized = 0; for (i_res=0; i_res<prot_p->n_res-1; i_res++) { /* the last residue is anchor residue, is not counted */ for (i_conf=0; i_conf<prot_p->res[i_res].n_conf; i_conf++) { for (i_atom=0; i_atom<prot_p->res[i_res].conf[i_conf].n_atom; i_atom++) { ATOM *atom_p = &prot_p->res[i_res].conf[i_conf].atom[i_atom]; if (!atom_p->on) continue; if (fabs(atom_p->xyz.z) > ipece->half_mem_thickness) continue; mem_coor_boundary_lower = atom_p->xyz; mem_coor_boundary_higher = atom_p->xyz; initialized = 1; break; } if (initialized) break; } if (initialized) break; } /* Find the size of the box to contain the protein */ /* Define lower and higher boundary of the box */ mem_coor_boundary_lower.z = -ipece->half_mem_thickness; mem_coor_boundary_higher.z = ipece->half_mem_thickness; for (i_res=0; i_res<prot_p->n_res-1; i_res++) { /* the last residue is anchor residue, is not counted */ for (i_conf=0; i_conf<prot_p->res[i_res].n_conf; i_conf++) { for (i_atom=0; i_atom<prot_p->res[i_res].conf[i_conf].n_atom; i_atom++) { ATOM *atom_p = &prot_p->res[i_res].conf[i_conf].atom[i_atom]; if (!atom_p->on) continue; if (fabs(atom_p->xyz.z) > ipece->half_mem_thickness) continue; if (atom_p->xyz.x < mem_coor_boundary_lower.x) mem_coor_boundary_lower.x = atom_p->xyz.x; if (atom_p->xyz.y < mem_coor_boundary_lower.y) mem_coor_boundary_lower.y = atom_p->xyz.y; if (atom_p->xyz.x > mem_coor_boundary_higher.x) mem_coor_boundary_higher.x = atom_p->xyz.x; if (atom_p->xyz.y > mem_coor_boundary_higher.y) mem_coor_boundary_higher.y = atom_p->xyz.y; } } } /* Expand the boundary of the box a little */ mem_coor_boundary_lower.x -= ipece->membrane_size; mem_coor_boundary_lower.y -= ipece->membrane_size; mem_coor_boundary_higher.x += ipece->membrane_size; mem_coor_boundary_higher.y += ipece->membrane_size; /* Define lower and higher boundary of the grid box in grid index*/ mem_grid_boundary_lower = coor2grid(mem_coor_boundary_lower,ipece); mem_grid_boundary_higher = coor2grid(mem_coor_boundary_higher,ipece);; /* initialize residue and atom index for membrane atoms: */ int k_res = prot_p->n_res-1; /* n_res-1 is the anchor residue, insert membrane before it */ int n_mem_res = 1; int k_atom = 0; /* loop over all grid points in transmembrane region */ int incre_grid = (int)(ipece->mem_separation/ipece->grid_space); INT_VECT mem_grid; for (mem_grid.x = mem_grid_boundary_lower.x; mem_grid.x <= mem_grid_boundary_higher.x; mem_grid.x+=incre_grid) { for (mem_grid.y = mem_grid_boundary_lower.y; mem_grid.y <= mem_grid_boundary_higher.y; mem_grid.y+=incre_grid) { for (mem_grid.z = mem_grid_boundary_lower.z; mem_grid.z <= mem_grid_boundary_higher.z; mem_grid.z+=incre_grid) { /* only add membrane to grids marked 'o' */ if (*reach_label(mem_grid, ipece) != 'o') { continue; } /* add a residue with 1000 atoms in the backbone conformer if this is a new residue */ if (k_res>=prot_p->n_res-1) { k_res = prot_p->n_res-1; /* insert membrane residue before the anchor residue */ ins_res(prot_p, k_res); prot_p->res[k_res].iCode = '_'; strcpy(prot_p->res[k_res].resName, ipece->mem_resName); prot_p->res[k_res].chainID = ipece->mem_chainID; prot_p->res[k_res].resSeq = n_mem_res; ins_conf(&prot_p->res[k_res],0,1000); strcpy(prot_p->res[k_res].conf[0].confName, ipece->mem_resName); strcpy(prot_p->res[k_res].conf[0].confName+3, "BK"); prot_p->res[k_res].conf[0].altLoc = ' '; strcpy(prot_p->res[k_res].conf[0].history, "BK________"); } /* add membrane atom */ prot_p->res[k_res].conf[0].atom[k_atom].on = 1; /* name the atom as 0C00, 0C01, ... 1C00, 1C01, ... 9C99 */ sprintf(prot_p->res[k_res].conf[0].atom[k_atom].name+1,"%03i",k_atom); prot_p->res[k_res].conf[0].atom[k_atom].name[0] = prot_p->res[k_res].conf[0].atom[k_atom].name[1]; prot_p->res[k_res].conf[0].atom[k_atom].name[1] = 'C'; prot_p->res[k_res].conf[0].atom[k_atom].name[4] = '\0'; prot_p->res[k_res].conf[0].atom[k_atom].xyz = grid2coor(mem_grid, ipece); prot_p->res[k_res].conf[0].atom[k_atom].rad = ipece->mem_atom_radius; /* update residue and atom index numbers */ k_atom++; if (k_atom >=1000) { k_res++; n_mem_res++; k_atom = 0; } } } } /* move the protein back */ anchor2defined(prot_p, vec_anchor); /* free memory for grids */ free_probe(ipece); /* delete the extra anchor residue */ del_res(prot_p, prot_p->n_res-1); return 0; }
float estimate_rxn(CONF *conf_p, PROT *boundary_prot) { INT_VECT k_grid; int i_atom; probe(*boundary_prot, &env.ipece); /* initialize the image crg array */ env.ipece.image_crg = malloc(env.ipece.n_grid.x * sizeof(float **)); for (k_grid.x = 0; k_grid.x<env.ipece.n_grid.x; k_grid.x++) { env.ipece.image_crg[k_grid.x] = malloc(env.ipece.n_grid.y * sizeof(float *)); for (k_grid.y = 0; k_grid.y<env.ipece.n_grid.y; k_grid.y++) { env.ipece.image_crg[k_grid.x][k_grid.y] = malloc(env.ipece.n_grid.z * sizeof(float)); for (k_grid.z = 0; k_grid.z<env.ipece.n_grid.z; k_grid.z++) { env.ipece.image_crg[k_grid.x][k_grid.y][k_grid.z] = 0.; } } } /* assign image charges */ for (i_atom=0; i_atom<conf_p->n_atom; i_atom++) { INT_VECT corner1, corner2; VECTOR sum_rad; if (!conf_p->atom[i_atom].on) continue; sum_rad.x = sum_rad.y = sum_rad.z = conf_p->atom[i_atom].rad+env.ipece.probe_radius+shell_size; corner1 = coor2grid(vector_vminusv(conf_p->atom[i_atom].xyz, sum_rad), &env.ipece); corner2 = coor2grid(vector_vplusv(conf_p->atom[i_atom].xyz, sum_rad), &env.ipece); float n_grid_surf = 4./3.*env.PI*(pow(sum_rad.x,3)-pow(conf_p->atom[i_atom].rad+env.ipece.probe_radius,3)) / pow(env.ipece.grid_space,3); //float n_grid_surf = 4./3.*env.PI*(pow(sum_rad.x,3)-pow(conf_p->atom[i_atom].rad+env.ipece.probe_radius,3)) * (conf_p->atom[i_atom].rad+env.ipece.probe_radius) / pow(env.ipece.grid_space,3); for (k_grid.x = corner1.x; k_grid.x < corner2.x; k_grid.x++) { for (k_grid.y = corner1.y; k_grid.y < corner2.y; k_grid.y++) { for (k_grid.z = corner1.z; k_grid.z < corner2.z; k_grid.z++) { if (*reach_label(k_grid, &env.ipece) == 'o' || *reach_label(k_grid, &env.ipece) == 'c') { float d; d = dvv(conf_p->atom[i_atom].xyz, grid2coor(k_grid, &env.ipece)); if (d>sum_rad.x) continue; env.ipece.image_crg[k_grid.x-env.ipece.grid_boundary_lower.x][k_grid.y-env.ipece.grid_boundary_lower.y][k_grid.z-env.ipece.grid_boundary_lower.z] -= conf_p->atom[i_atom].crg/(n_grid_surf*d); } } } } } /* calc. charge-image interactions */ float sum_e = 0.; for (i_atom=0; i_atom<conf_p->n_atom; i_atom++) { float e = 0.; if (fabs(conf_p->atom[i_atom].crg) < 1e-4) continue; for (k_grid.x = env.ipece.grid_boundary_lower.x; k_grid.x<env.ipece.grid_boundary_higher.x; k_grid.x++) { for (k_grid.y = env.ipece.grid_boundary_lower.y; k_grid.y<env.ipece.grid_boundary_higher.y; k_grid.y++) { for (k_grid.z = env.ipece.grid_boundary_lower.z; k_grid.z<env.ipece.grid_boundary_higher.z; k_grid.z++) { float d; if (*reach_label(k_grid, &env.ipece) != 'o' && *reach_label(k_grid, &env.ipece) != 'c') continue; d = dvv(conf_p->atom[i_atom].xyz, grid2coor(k_grid, &env.ipece)); e += 331.5*conf_p->atom[i_atom].crg* env.ipece.image_crg[k_grid.x-env.ipece.grid_boundary_lower.x][k_grid.y-env.ipece.grid_boundary_lower.y][k_grid.z-env.ipece.grid_boundary_lower.z]/(0.5259 * d); } } } sum_e += e; } /* free up memory */ free_probe(&env.ipece); for (k_grid.x = 0; k_grid.x<env.ipece.n_grid.x; k_grid.x++) { for (k_grid.y = 0; k_grid.y<env.ipece.n_grid.y; k_grid.y++) { free(env.ipece.image_crg[k_grid.x][k_grid.y]); } free(env.ipece.image_crg[k_grid.x]); } free(env.ipece.image_crg); return sum_e; }
static void makemoves(void) { int i, hitme; char ch; while (TRUE) { /* command loop */ hitme = FALSE; justin = 0; Time = 0.0; i = -1; while (TRUE) { /* get a command */ chew(); skip(1); proutn("COMMAND> "); // Use of scan() here (after chew) will get a new line of input // and will return IHEOL iff new line of input contains nothing // or a numeric input is detected but conversion fails. if (scan() == IHEOL) continue; for (i=0; i < 26; i++) if (isit(commands[i])) break; if (i < 26) break; for (; i < NUMCOMMANDS; i++) if (strcmp(commands[i], citem) == 0) break; if (i < NUMCOMMANDS) break; // we get here iff the first parsed input from the line does not // match one of the commands. In this case, the rest of the line // is discarded, the below message is printed, and we go back to // get a new command. if (skill <= 2) { prout("UNRECOGNIZED COMMAND. LEGAL COMMANDS ARE:"); listCommands(TRUE); } else prout("UNRECOGNIZED COMMAND."); } // end get command loop // we get here iff the first parsed input from the line matches one // of the commands (i.e., command i). We use i to dispatch the // handling of the command. The line may still contain additional // inputs (i.e., parameters of the command) that is to be parsed by // the dispatched command handler. If the line does not contain // all the necessary parameters, the dispatched command handler is // responsible to get additional input(s) interactively using scan(). // The dispatched command handler is also responsible to handle any // input errors. switch (i) { /* command switch */ case 0: // srscan srscan(1); break; case 1: // lrscan lrscan(); break; case 2: // phasers phasers(); if (ididit) hitme = TRUE; break; case 3: // photons photon(); if (ididit) hitme = TRUE; break; case 4: // move warp(1); break; case 5: // shields sheild(1); if (ididit) { attack(2); shldchg = 0; } break; case 6: // dock dock(); break; case 7: // damages dreprt(); break; case 8: // chart chart(0); break; case 9: // impulse impuls(); break; case 10: // rest waiting(); if (ididit) hitme = TRUE; break; case 11: // warp setwrp(); break; case 12: // status srscan(3); break; case 13: // sensors sensor(); break; case 14: // orbit orbit(); if (ididit) hitme = TRUE; break; case 15: // transport "beam" beam(); break; case 16: // mine mine(); if (ididit) hitme = TRUE; break; case 17: // crystals usecrystals(); break; case 18: // shuttle shuttle(); if (ididit) hitme = TRUE; break; case 19: // Planet list preport(); break; case 20: // Status information srscan(2); break; case 21: // Game Report report(0); break; case 22: // use COMPUTER! eta(); break; case 23: listCommands(TRUE); break; case 24: // Emergency exit clearscreen(); // Hide screen freeze(TRUE); // forced save exit(1); // And quick exit break; case 25: probe(); // Launch probe break; case 26: // Abandon Ship abandn(); break; case 27: // Self Destruct dstrct(); break; case 28: // Save Game freeze(FALSE); if (skill > 3) prout("WARNING--Frozen games produce no plaques!"); break; case 29: // Try a desparation measure deathray(); if (ididit) hitme = TRUE; break; case 30: // What do we want for debug??? #ifdef DEBUG debugme(); #endif break; case 31: // Call for help help(); break; case 32: alldone = 1; // quit the game #ifdef DEBUG if (idebug) score(); #endif break; case 33: helpme(); // get help break; } // end command switch for (;;) { if (alldone) break; // Game has ended #ifdef DEBUG if (idebug) prout("2500"); #endif if (Time != 0.0) { events(); if (alldone) break; // Events did us in } if (d.galaxy[quadx][quady] == 1000) { // Galaxy went Nova! atover(0); continue; } if (nenhere == 0) movetho(); if (hitme && justin==0) { attack(2); if (alldone) break; if (d.galaxy[quadx][quady] == 1000) { // went NOVA! atover(0); hitme = TRUE; continue; } } break; } // end event loop if (alldone) break; } // end command loop }
void GCodeExport::doDrill(FILE *fl, bool changeToDrill, DrillReader *drillReader, double drillZSafe, bool sameDiameter, bool isProbe, int drillingSpeed, \ int drillingLiftSpeed, int drillingSpindleSpeed, double drillDepth, double zsafe) { char lineBuffer[1024]; // drilling if(drillReader) { if(drillReader->firstDrill()) { toolNumber = 1; if(changeToDrill) changeTool(fl, drillReader->firstDrill()->diameter, zsafe, drillZSafe, sameDiameter, isProbe, (char*)"Drill",true); else if(isProbe) probe(fl, drillZSafe); sprintf(lineBuffer, "M03S%d\nG04P%d\n", drillingSpindleSpeed, drillingSpindleSpeed/5); // start spindle and wait fputs(lineBuffer, fl); Drill *nextDrill = drillReader->firstDrill(); if(sameDiameter || !changeToDrill) { sprintf(lineBuffer,"(Drill %f)\n", nextDrill->diameter); fputs(lineBuffer, fl); } while(nextDrill) { GPoint *next = nextDrill->firstPoint; while(next) { next->used = false; next = next->next; } while(true) { GPoint *closestPoint = 0; double closestDistance = FLT_MAX; next = nextDrill->firstPoint; double tmp; while(next) { if(!next->used){ if( (tmp=next->distance(headPosition))<closestDistance) { closestDistance = tmp; closestPoint = next; } } next = next->next; } if(closestPoint) { drill(fl, *closestPoint, drillDepth, drillingSpeed, drillingLiftSpeed, drillZSafe); closestPoint->used = true; } else { break; // goto from while } } nextDrill = nextDrill->next; if(nextDrill) { if(!sameDiameter) { fputs("M5\n", fl); changeTool(fl, nextDrill->diameter, drillZSafe, drillZSafe, sameDiameter, isProbe, (char*)"Drill", true); sprintf(lineBuffer, "M03S%d\nG04P%d\n", drillingSpindleSpeed, drillingSpindleSpeed/5); // start spindle and wait fputs(lineBuffer, fl); } else { sprintf(lineBuffer,"(Drill %f)\n", nextDrill->diameter); fputs(lineBuffer, fl); } } } fputs("M5\n", fl); } } }
int tree_chop(struct btree *btree, struct delete_info *info, millisecond_t deadline) { int depth = btree->root.depth, level = depth - 1, suspend = 0; struct cursor *cursor; struct buffer_head *leafbuf, **prev, *leafprev = NULL; struct btree_ops *ops = btree->ops; struct sb *sb = btree->sb; int ret; cursor = alloc_cursor(btree, 0); prev = malloc(sizeof(*prev) * depth); memset(prev, 0, sizeof(*prev) * depth); down_write(&btree->lock); probe(btree, info->resume, cursor); leafbuf = level_pop(cursor); /* leaf walk */ while (1) { ret = (ops->leaf_chop)(btree, info->key, bufdata(leafbuf)); if (ret) { mark_buffer_dirty(leafbuf); if (ret < 0) goto error_leaf_chop; } /* try to merge this leaf with prev */ if (leafprev) { struct vleaf *this = bufdata(leafbuf); struct vleaf *that = bufdata(leafprev); /* try to merge leaf with prev */ if ((ops->leaf_need)(btree, this) <= (ops->leaf_free)(btree, that)) { trace(">>> can merge leaf %p into leaf %p", leafbuf, leafprev); (ops->leaf_merge)(btree, that, this); remove_index(cursor, level); mark_buffer_dirty(leafprev); brelse_free(btree, leafbuf); //dirty_buffer_count_check(sb); goto keep_prev_leaf; } brelse(leafprev); } leafprev = leafbuf; keep_prev_leaf: //nanosleep(&(struct timespec){ 0, 50 * 1000000 }, NULL); //printf("time remaining: %Lx\n", deadline - gettime()); // if (deadline && gettime() > deadline) // suspend = -1; if (info->blocks && info->freed >= info->blocks) suspend = -1; /* pop and try to merge finished nodes */ while (suspend || level_finished(cursor, level)) { /* try to merge node with prev */ if (prev[level]) { assert(level); /* node has no prev */ struct bnode *this = cursor_node(cursor, level); struct bnode *that = bufdata(prev[level]); trace_off("check node %p against %p", this, that); trace_off("this count = %i prev count = %i", bcount(this), bcount(that)); /* try to merge with node to left */ if (bcount(this) <= sb->entries_per_node - bcount(that)) { trace(">>> can merge node %p into node %p", this, that); merge_nodes(that, this); remove_index(cursor, level - 1); mark_buffer_dirty(prev[level]); brelse_free(btree, level_pop(cursor)); //dirty_buffer_count_check(sb); goto keep_prev_node; } brelse(prev[level]); } prev[level] = level_pop(cursor); keep_prev_node: /* deepest key in the cursor is the resume address */ if (suspend == -1 && !level_finished(cursor, level)) { suspend = 1; /* only set resume once */ info->resume = from_be_u64((cursor->path[level].next)->key); } if (!level) { /* remove depth if possible */ while (depth > 1 && bcount(bufdata(prev[0])) == 1) { trace("drop btree level"); btree->root.block = bufindex(prev[1]); mark_btree_dirty(btree); brelse_free(btree, prev[0]); //dirty_buffer_count_check(sb); depth = --btree->root.depth; vecmove(prev, prev + 1, depth); //set_sb_dirty(sb); } //sb->snapmask &= ~snapmask; delete_snapshot_from_disk(); //set_sb_dirty(sb); //save_sb(sb); ret = suspend; goto out; } level--; trace_off(printf("pop to level %i, block %Lx, %i of %i nodes\n", level, bufindex(cursor->path[level].buffer), cursor->path[level].next - cursor_node(cursor, level)->entries, bcount(cursor_node(cursor, level)));); } /* push back down to leaf level */ while (level < depth - 1) { struct buffer_head *buffer = sb_bread(vfs_sb(sb), from_be_u64(cursor->path[level++].next++->block)); if (!buffer) { ret = -EIO; goto out; } level_push(cursor, buffer, ((struct bnode *)bufdata(buffer))->entries); trace_off(printf("push to level %i, block %Lx, %i nodes\n", level, bufindex(buffer), bcount(cursor_node(cursor, level)));); }
void via_aux_ch7301_probe(struct via_aux_bus *bus) { probe(bus, 0x75); probe(bus, 0x76); }
int I2C::init() { int ret = OK; unsigned bus_index; // attach to the i2c bus _dev = up_i2cinitialize(_bus); if (_dev == nullptr) { debug("failed to init I2C"); ret = -ENOENT; goto out; } // the above call fails for a non-existing bus index, // so the index math here is safe. bus_index = _bus - 1; // abort if the max frequency we allow (the frequency we ask) // is smaller than the bus frequency if (_bus_clocks[bus_index] > _frequency) { (void)up_i2cuninitialize(_dev); _dev = nullptr; log("FAIL: too slow for bus #%u: %u KHz, device max: %u KHz)", _bus, _bus_clocks[bus_index] / 1000, _frequency / 1000); ret = -EINVAL; goto out; } // set the bus frequency on the first access if it has // not been set yet if (_bus_clocks[bus_index] == 0) { _bus_clocks[bus_index] = _frequency; } // set frequency for this instance once to the bus speed // the bus speed is the maximum supported by all devices on the bus, // as we have to prioritize performance over compatibility. // If a new device requires a lower clock speed, this has to be // manually set via "fmu i2c <bus> <clock>" before starting any // drivers. // This is necessary as automatically lowering the bus speed // for maximum compatibility could induce timing issues on // critical sensors the adopter might be unaware of. I2C_SETFREQUENCY(_dev, _bus_clocks[bus_index]); // call the probe function to check whether the device is present ret = probe(); if (ret != OK) { debug("probe failed"); goto out; } // do base class init, which will create device node, etc ret = CDev::init(); if (ret != OK) { debug("cdev init failed"); goto out; } // tell the world where we are log("on I2C bus %d at 0x%02x (bus: %u KHz, max: %u KHz)", _bus, _address, _bus_clocks[bus_index] / 1000, _frequency / 1000); out: if ((ret != OK) && (_dev != nullptr)) { up_i2cuninitialize(_dev); _dev = nullptr; } return ret; }
int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s dumpfile\n", argv[0]); goto OUT; } buffer = malloc(4096); if (!buffer) { perror("exiting"); goto OUT; } /* open dumpfile */ dumpfile = fopen(argv[1], "r"); if (!dumpfile) { perror(argv[1]); goto OUT; } /* read table parameters */ if (!fgets(buffer, 4096, dumpfile) || sscanf(buffer, "%zd %zd %zd %zd", &b, &s, &h, &n) != 4) { fprintf(stderr, "Invalid dumpfile\n"); goto OUT; } bucketCount = (1u << s) / b; hashShift = __builtin_clz(bucketCount - 1u); /* read hashes */ if (!fgets(buffer, 4096, dumpfile) || sscanf(buffer, "%" SCNu32 " %" SCNu32, &hashes.arr[0], &hashes.arr[1]) != 2) { fprintf(stderr, "Invalid dumpfile\n"); goto OUT; } /* allocate memory for table */ buckets = calloc(bucketCount, sizeof(*buckets)); data = calloc((1u << s) * 2, sizeof(*data)); if (!buckets || !data) { perror("exiting"); goto OUT; } /* set up bucket pointers and populate table */ uint32_t *ptr = data; uint32_t key, value; for (int i = 0; i < bucketCount; ++i) { buckets[i].keys = ptr; buckets[i].values = ptr + b; ptr += 2 * b; for (int j = 0; j < b; ++j) { if (!fgets(buffer, 4096, dumpfile) || sscanf(buffer, "%" SCNu32 " %" SCNu32, &key, &value) != 2) { fprintf(stderr, "Invalid dumpfile\n"); goto OUT; } buckets[i].keys[j] = key; buckets[i].values[j] = value; } } /* probe */ while (fgets(buffer, 4096, stdin)) { if (sscanf(buffer, "%" SCNu32, &key) != 1) { continue; } value = probe(key); if (value != 0) { fprintf(stdout, "%" SCNu32 " %" SCNu32 "\n", key, value); } } OUT: if (dumpfile) fclose(dumpfile); free(buffer); free(buckets); free(data); return 0; }
TEST_F(StanGmArgumentsConfiguration, TestOutputWithMethod) { // Prepare arguments std::stringstream method_output; stan::gm::arg_method method; method.print(&method_output, 0, '\0'); std::string l0; std::string method_argument(""); int n_method_output = 0; while (method_output.good()) { std::getline(method_output, l0); if (!method_output.good()) continue; clean_line(l0); method_argument += " " + l0; ++n_method_output; } remove_duplicates(method_argument); method_output.clear(); method_output.seekg(std::ios_base::beg); std::stringstream s; std::vector<stan::gm::argument*> valid_arguments; valid_arguments.push_back(new stan::gm::arg_output()); stan::gm::argument_probe probe(valid_arguments); probe.probe_args(s); // Check argument consistency bool expected_success = false; std::string l1; std::stringstream expected_output; std::stringstream output; while (s.good()) { std::getline(s, l1); if (!s.good()) continue; if (l1 == "good") expected_success = true; else if (l1 == "bad") expected_success = false; else if (l1 != "") expected_output << l1 << std::endl; else { int n_output = 0; std::string l2; std::string argument(""); while (expected_output.good()) { std::getline(expected_output, l2); if (!expected_output.good()) continue; clean_line(l2); argument += " " + l2; ++n_output; } if (argument.length() == 0) continue; remove_duplicates(argument); argument = method_argument + argument; run_command_output out = run_command(command + argument); expected_output.clear(); expected_output.seekg(std::ios_base::beg); expected_output.str( method_output.str() + expected_output.str() ); if (expected_success == false) { unsigned int c1 = out.output.find("is not"); out.output.erase(0, c1); unsigned int c2 = out.output.find(" \""); unsigned int c3 = out.output.find("Failed to parse"); out.output.replace(c2, c3 - c2, "\n"); expected_output.str(std::string()); expected_output << "is not a valid value for" << std::endl; expected_output << "Failed to parse arguments, terminating Stan" << std::endl; n_output = 2; } output.str(out.output); std::string actual_line; for (int i = 0; i < n_output; ++i) { std::string expected_line; std::getline(expected_output, expected_line); std::getline(output, actual_line); EXPECT_EQ(expected_line, actual_line); } expected_output.clear(); expected_output.seekg(std::ios_base::beg); expected_output.str(std::string()); } } for (size_t i = 0; i < valid_arguments.size(); ++i) delete valid_arguments.at(i); }
t_chess_value alphabeta(struct t_board *board, int ply, int depth, t_chess_value alpha, t_chess_value beta, BOOL early_cutoff, struct t_move_record *exclude_move) { //-- Should we call qsearch? if (depth <= 0 && !board->in_check) return qsearch_plus(board, ply, depth, alpha, beta); //-- Increment the nodes nodes++; //-- see if we need to update stats */ if ((nodes & message_update_mask) == 0) uci_check_status(board, ply); //-- Local Principle Variation variable struct t_pv_data *pv = &(board->pv_data[ply]); //-- Has the maximum depth been reached if (ply >= MAXPLY || uci.stop) { pv->best_line_length = ply; assert(pv->eval->static_score >= -CHECKMATE && pv->eval->static_score <= CHECKMATE); return pv->eval->static_score; } /* check to see if this is a repeated position or draw by 50 moves */ if (repetition_draw(board)) { pv->best_line_length = ply; return 0; } //-- Mate Distance Pruning if (CHECKMATE - ply <= alpha) { return alpha; } else if (-CHECKMATE + ply >= beta) { return beta; } else if ((!board->in_check) && (-CHECKMATE + ply + 2 >= beta)) { return beta; } //-- Declare local variables struct t_pv_data *next_pv = pv->next_pv; struct t_pv_data *previous_pv = pv->previous_pv; t_chess_value best_score = -CHECKMATE; t_chess_value a = alpha; t_chess_value b = beta; //-- Determine what type of node it is if (beta > alpha + 1) pv->node_type = node_pv; else if (previous_pv->node_type == node_pv) pv->node_type = node_lite_all; else if (previous_pv->node_type == node_cut) pv->node_type = node_all; else pv->node_type = node_cut; //-- Probe Hash struct t_move_record *hash_move = NULL; struct t_hash_record *hash_record = probe(board->hash); //-- Has there been a match? if (hash_record != NULL) { //-- Get the score from the hash table t_chess_value hash_score = get_hash_score(hash_record, ply); //-- Could it make a cut-off? if (early_cutoff && hash_record->depth >= depth) { //-- Score in hash table is at least as good as beta if (hash_record->bound != HASH_UPPER && hash_score >= beta) { hash_record->age = hash_age; assert(hash_score >= -CHECKMATE && hash_score <= CHECKMATE); return hash_score; } //-- Score is worse than alpha if (hash_record->bound != HASH_LOWER && hash_score <= alpha) { hash_record->age = hash_age; assert(hash_score >= -CHECKMATE && hash_score <= CHECKMATE); return hash_score; } //-- Score is more accurate if (hash_record->bound == HASH_EXACT) { hash_record->age = hash_age; pv->best_line_length = ply; update_best_line_from_hash(board, ply); assert(hash_score >= -CHECKMATE && hash_score <= CHECKMATE); return hash_score; } } //-- Store the hash move for further use! hash_move = hash_record->move; //-- Use the hash score to refine the node type if (hash_record->bound != HASH_UPPER && hash_score >= beta) pv->node_type = node_super_cut; else if (hash_record->bound != HASH_LOWER && hash_score <= alpha) pv->node_type = node_super_all; else if (hash_record->bound == HASH_EXACT && pv->node_type == node_all) pv->node_type = node_lite_all; } //-- Beta pruning if (early_cutoff && depth <= 4 && pv->node_type != node_pv && beta < MAX_CHECKMATE && beta > -MAX_CHECKMATE && !board->in_check) { int pessimistic_score = pv->eval->static_score - depth * 50 - 100; if (pessimistic_score >= beta) return pessimistic_score; } //-- Razoring. t_chess_value e; if (early_cutoff && (depth <= 4) && pv->node_type != node_pv && !board->in_check){ t_chess_value razor_margin = depth * 50 + 50; if (pv->eval->static_score + razor_margin <= alpha){ t_chess_value razor_alpha = alpha - razor_margin; e = qsearch_plus(board, ply, depth, razor_alpha, razor_alpha + 1); if (e <= razor_alpha) return e; } } //-- Null Move t_undo undo[1]; pv->mate_threat = 0; pv->null_refutation = NULL; pv->extension = FALSE; if (early_cutoff && can_do_null_move(board, pv, ply, alpha, beta)) { //-- Calculate Reduction //int r = (800 + 70 * depth) / 256 + min(3, (pv->eval->static_score - beta) / 128); int r = min(4, 2 + (25 * depth) / 128 + (pv->eval->static_score - beta) / 128); //int r = 3; //-- Make the changes on the board make_null_move(board, undo); //-- Store the move in the PV data pv->current_move = NULL; //-- Clear the Killer +2 if (ply + 2 <= MAXPLY){ board->pv_data[ply + 2].killer1 = NULL; board->pv_data[ply + 2].killer2 = NULL; } //-- Evaluate the new board position evaluate(board, next_pv->eval); //-- Find the new score e = -alphabeta(board, ply + 1, depth - r - 1 , -beta, -beta + 1, TRUE, NULL); //-- undo the null move unmake_null_move(board, undo); //-- is it good enough for a cut-off? if (e >= beta) { if (e > MAX_CHECKMATE) e = beta; poke(board->hash, e, ply, depth, HASH_LOWER, NULL); return e; } //-- Is there a Mate Threat after a super-reduced move - if so then exit? if (e < -MAX_CHECKMATE){ if (pv->previous_pv->reduction > 1) return alpha; pv->mate_threat = e; } //-- Record the move which refuted the NULL move if (ply < MAXPLY) pv->null_refutation = board->pv_data[ply + 1].current_move; } //-- Internal Iterative Deepening! if (hash_move == NULL && !uci.stop){ //-- PV Nodes - we *really* need a good move if (pv->node_type == node_pv && depth > 2) { //-- Search with reduced depth e = alphabeta(board, ply, depth - 2, alpha, beta, FALSE, NULL); //-- If still no move then search with -INFINITY bound if (e <= alpha) e = alphabeta(board, ply, depth - 2, -CHESS_INFINITY, beta, FALSE, NULL); //-- Probe the hash hash_record = probe(board->hash); //-- Set the hash move if (hash_record != NULL) hash_move = hash_record->move; } //-- Fail high nodes //else if ((pv->node_type == node_cut || pv->node_type == node_super_cut) && (depth >= 7) && alpha > -MAX_CHECKMATE && beta < MAX_CHECKMATE){ // //-- Search with reduced depth // e = alphabeta(board, ply, depth / 2, alpha, beta); // //-- If still no move then search with -INFINITY bound // if (e <= alpha) // e = alphabeta(board, ply, depth / 2, -CHESS_INFINITY, beta); // //-- Probe the hash // hash_record = probe(board->hash); // //-- Set the hash move // if (hash_record != NULL) // hash_move = hash_record->move; //} } //-- Generate All Moves struct t_move_list moves[1]; moves->hash_move = hash_move; if (board->in_check) { generate_evade_check(board, moves); // Are we in checkmate? if (moves->count == 0) { pv->best_line_length = ply; e = -CHECKMATE + ply; return e; } order_evade_check(board, moves, ply); } else { generate_moves(board, moves); order_moves(board, moves, ply); } //-- Enhanced Transposition Cutoff? t_chess_color to_move = board->to_move; if (early_cutoff && (depth > 4) && pv->node_type != node_pv && beta < MAX_CHECKMATE && alpha > -MAX_CHECKMATE && !uci.stop) { BOOL fail_low; while (simple_make_next_move(board, moves, undo)) { //-- Calculate Reduction Conservatively i.e. assume minimum reduction if (board->in_check) pv->reduction = 0; else if (PIECETYPE(moves->current_move->piece) == PAWN && COLOR_RANK(to_move, moves->current_move->to_square) >= 6) pv->reduction = 0; else pv->reduction = 1; //-- Simple version of alpha_beta for tips of search e = -alphabeta_tip(board, ply + 1, depth - pv->reduction, -beta, &fail_low); //-- Take the move back unmake_move(board, undo); //-- Is it good enough for a cutoff? if (e >= beta) { poke(board->hash, e, ply, depth, HASH_LOWER, moves->current_move); assert(e >= -CHECKMATE && e <= CHECKMATE); return e; } //-- Is it going to enhance the move ordering? if (fail_low) { moves->value[moves->imove] += MOVE_ORDER_ETC; assert(moves->move[moves->imove] == moves->current_move); } } //-- Reset the real move count for the "proper" search moves->imove = moves->count; } ////-- No Hash Move for Cut Nodes with score below beta and no good capture and no ETC //if (hash_move == NULL && (any_fail_low == FALSE) && ((pv->node_type == node_cut) || (pv->node_type == node_super_all)) && (depth >= 3) && (beta > pv->eval->static_score) && no_good_captures(board, moves)){ // //-- Search with reduced depth // e = alphabeta(board, ply, depth - 3, alpha, beta); // //-- If still no move then search with -INFINITY bound // if (e <= alpha) // e = alphabeta(board, ply, depth - 3, -CHESS_INFINITY, beta); // //-- Probe the hash // hash_record = probe(board->hash); // //-- Set the hash move // if (hash_record != NULL) // hash_move = hash_record->move; //} //-- Create the list of "bad" captures struct t_move_list bad_moves[1]; bad_moves->count = 0; bad_moves->imove = 0; //-- Reset the move count (must be after IID) pv->legal_moves_played = 0; //-- Variables used to calculate the reduction t_chess_color opponent = OPPONENT(to_move); BOOL in_check = board->in_check; struct t_move_record *last_move = NULL; if (ply > 1) last_move = board->pv_data[ply - 2].current_move; //-- Play moves while (!uci.stop && make_next_move(board, moves, bad_moves, undo)) { //-- Increment the "legal_moves_played" counter pv->legal_moves_played++; pv->current_move = moves->current_move; //========================================// // Futility Pruning //========================================// if (uci.options.futility_pruning && is_futile(pv, next_pv, depth, a, b)){ unmake_move(board, undo); continue; } //-- Clear the Killer +2 if (ply + 2 <= MAXPLY){ board->pv_data[ply + 2].killer1 = NULL; board->pv_data[ply + 2].killer2 = NULL; } //-- Evaluate the new board position evaluate(board, next_pv->eval); ////========================================// //// See if Extension is Necessary ////========================================// //pv->extension = FALSE; //if (pv->mate_threat){ // e = -alphabeta(board, ply + 1, depth - 1, -CHECKMATE, pv->mate_threat + 2); // pv->extension = (e > pv->mate_threat); // if (e <= pv->mate_threat && e <= a) // { // unmake_move(board, undo); // continue; // } //} //========================================// // Calculate reduction //========================================// struct t_move_record *current_move = pv->current_move; //-- In Check? if (board->in_check){ if (see_safe(board, current_move->to_square, 0)) pv->reduction = 0; else if (ply > 3 && board->pv_data[ply - 1].in_check && board->pv_data[ply - 3].in_check) pv->reduction = 0; else pv->reduction = 1; } //-- Pawn push to 7th else if (PIECETYPE(current_move->piece) == PAWN && COLOR_RANK(to_move, current_move->to_square) >= 6){ //-- Pawn Promotion if (current_move->promote_to){ if (pv->legal_moves_played == 1 || PIECETYPE(current_move->promote_to) == QUEEN){ //--Extend if it's a safe pawn promotion or first move if ((pv->current_move->captured && moves->current_move_see_positive) || see_safe(board, current_move->to_square, 0)) pv->reduction = 0; else pv->reduction = 1; } // Reduce Heavily if not a queen promotion else pv->reduction = 5; } //-- Push to the 7th else if (pv->legal_moves_played == 1 || (pv->current_move->captured && moves->current_move_see_positive) || see_safe(board, current_move->to_square, 0)) pv->reduction = 0; else pv->reduction = 1; } //-- First Move? else if (pv->legal_moves_played == 1) pv->reduction = 1; ////-- Under Threat of Mate //else if (pv->mate_threat) // pv->reduction = 1; //-- Good Capture? else if (pv->current_move->captured && moves->current_move_see_positive){ pv->reduction = 1; } //-- Is this getting out of check? else if (in_check){ if (pv->current_move == pv->check_killer1) pv->reduction = 1; else if (PIECETYPE(current_move->piece) == KING){ if (CAN_CASTLE(to_move, board->castling)) pv->reduction = 4; else pv->reduction = 1; } else if (current_move->captured) /* must be a bad capture */ pv->reduction = 2; else if (see_safe(board, current_move->to_square, 0)) pv->reduction = 1; else pv->reduction = 2; } //-- Don't reduce Killers! else if (pv->current_move == pv->killer1){ pv->reduction = 1; } //-- Does it move a threatened piece? else if (pv->null_refutation != NULL && pv->null_refutation->to_square == pv->current_move->from_square){ if (see_safe(board, current_move->to_square, 0)) pv->reduction = 1; else pv->reduction = 3; } //-- Candidate for serious reductions else{ switch (pv->node_type) { case node_cut: pv->reduction = 3; if (pv->current_move->captured) pv->reduction += 1; break; case node_super_cut: pv->reduction = 4; if (pv->current_move->captured) pv->reduction += 1; break; case node_pv: if (pv->legal_moves_played > 2) pv->reduction = 2; else pv->reduction = 1; break; case node_lite_all: if (pv->legal_moves_played > 2) pv->reduction = 2; else pv->reduction = 1; if (pv->current_move->captured) pv->reduction += 1; break; case node_super_all: if (current_move->captured){ if (pv->legal_moves_played < 4) pv->reduction = 3; else pv->reduction = 4; } else if (!see_safe(board, current_move->to_square, 0)){ if (pv->legal_moves_played < 4) pv->reduction = 4; else if (pv->legal_moves_played < 12) pv->reduction = 5; else pv->reduction = 6; } else if (pv->legal_moves_played < 4) pv->reduction = 2; else if (pv->legal_moves_played < 12) pv->reduction = 3; else pv->reduction = 4; break; case node_all: if (current_move->captured){ if (pv->legal_moves_played < 4) pv->reduction = 3; else pv->reduction = 4; } else if (!see_safe(board, current_move->to_square, 0)){ if (pv->legal_moves_played < 4) pv->reduction = 4; else pv->reduction = 5; } else if (pv->legal_moves_played < 4) pv->reduction = 2; else if (pv->legal_moves_played < 18) pv->reduction = 3; else pv->reduction = 4; break; } } //-- Search the next ply at reduced depth e = -alphabeta(board, ply + 1, depth - pv->reduction, -b, -a, TRUE, NULL); //-- Fail high on a super-reduced move? if (e > a && pv->reduction > 1) { pv->reduction = 1; //-- Search again using the full width e = -alphabeta(board, ply + 1, depth - 1, -beta, -a, TRUE, NULL); } //-- Is a research required? else if (alpha + 1 != beta && e > a && a + 1 == b) e = -alphabeta(board, ply + 1, depth - pv->reduction, -beta, -a, TRUE, NULL); unmake_move(board, undo); //-- Is it good enough to cut-off? if (e >= beta) { if (board->in_check) update_check_killers(pv, depth); else update_killers(pv, depth); //-- Record the cutoff cutoffs++; if (pv->legal_moves_played == 1) first_move_cutoffs++; //-- Store in the hash table poke(board->hash, e, ply, depth, HASH_LOWER, pv->current_move); return e; } //-- Is it the best so far? if (e > best_score) { best_score = e; //-- Does it improve upon alpha (i.e. is it part of the PV)? if (e > a) { a = e; //-- Update the Principle Variation update_best_line(board, ply); } } // Reset the zero width window b = a + 1; //-- Was this a fail low at a node which should have failed high? //if (pv->node_type == ) } //-- Is it a draw if (pv->legal_moves_played == 0) { pv->best_line_length = ply; return 0; } //-- Update Hash if (best_score > alpha) poke(board->hash, best_score, ply, depth, HASH_EXACT, pv->best_line[ply]); else poke(board->hash, best_score, ply, depth, HASH_UPPER, NULL); // Return Best Score found assert(best_score >= -CHECKMATE && best_score <= CHECKMATE); return best_score; }
int main(int argc, char** argv) { std::queue<fc::ip::endpoint> nodes_to_visit; std::set<fc::ip::endpoint> nodes_to_visit_set; std::set<fc::ip::endpoint> nodes_already_visited; if ( argc < 3 ) { std::cerr << "Usage: " << argv[0] << " <chain-id> <seed-addr> [<seed-addr> ...]\n"; exit(1); } const graphene::chain::chain_id_type chain_id( argv[1] ); for ( int i = 2; i < argc; i++ ) { std::string ep(argv[i]); uint16_t port; auto pos = ep.find(':'); if (pos > 0) port = boost::lexical_cast<uint16_t>( ep.substr( pos+1, ep.size() ) ); else port = 1776; for (const auto& addr : fc::resolve( ep.substr( 0, pos > 0 ? pos : ep.size() ), port )) nodes_to_visit.push( addr ); } fc::path data_dir = fc::temp_directory_path() / ("network_map_" + (fc::string) chain_id); fc::create_directories(data_dir); fc::ip::endpoint seed_node1 = nodes_to_visit.front(); fc::ecc::private_key my_node_id = fc::ecc::private_key::generate(); std::map<graphene::net::node_id_t, graphene::net::address_info> address_info_by_node_id; std::map<graphene::net::node_id_t, std::vector<graphene::net::address_info> > connections_by_node_id; std::vector<std::shared_ptr<peer_probe>> probes; while (!nodes_to_visit.empty() || !probes.empty()) { while (!nodes_to_visit.empty()) { fc::ip::endpoint remote = nodes_to_visit.front(); nodes_to_visit.pop(); nodes_to_visit_set.erase( remote ); nodes_already_visited.insert( remote ); try { std::shared_ptr<peer_probe> probe(new peer_probe()); probe->start(remote, my_node_id, chain_id); probes.emplace_back( std::move( probe ) ); } catch (const fc::exception&) { std::cerr << "Failed to connect " << fc::string(remote) << " - skipping!" << std::endl; } } if (!probes.empty()) { fc::yield(); std::vector<std::shared_ptr<peer_probe>> running; for ( auto& probe : probes ) { if (probe->_probe_complete_promise->error()) { std::cerr << fc::string(probe->_remote) << " ran into an error!\n"; continue; } if (!probe->_probe_complete_promise->ready()) { running.push_back( probe ); continue; } if( probe->_node_id.valid() ) { graphene::net::address_info this_node_info; this_node_info.direction = graphene::net::peer_connection_direction::outbound; this_node_info.firewalled = graphene::net::firewalled_state::not_firewalled; this_node_info.remote_endpoint = probe->_remote; this_node_info.node_id = probe->_node_id; connections_by_node_id[this_node_info.node_id] = probe->_peers; if (address_info_by_node_id.find(this_node_info.node_id) == address_info_by_node_id.end()) address_info_by_node_id[this_node_info.node_id] = this_node_info; } for (const graphene::net::address_info& info : probe->_peers) { if (nodes_already_visited.find(info.remote_endpoint) == nodes_already_visited.end() && info.firewalled == graphene::net::firewalled_state::not_firewalled && nodes_to_visit_set.find(info.remote_endpoint) == nodes_to_visit_set.end()) { nodes_to_visit.push(info.remote_endpoint); nodes_to_visit_set.insert(info.remote_endpoint); } if (address_info_by_node_id.find(info.node_id) == address_info_by_node_id.end()) address_info_by_node_id[info.node_id] = info; } } probes = std::move( running ); std::cout << address_info_by_node_id.size() << " checked, " << probes.size() << " active, " << nodes_to_visit.size() << " to do\n"; } } graphene::net::node_id_t seed_node_id; std::set<graphene::net::node_id_t> non_firewalled_nodes_set; for (const auto& address_info_for_node : address_info_by_node_id) { if (address_info_for_node.second.remote_endpoint == seed_node1) seed_node_id = address_info_for_node.first; if (address_info_for_node.second.firewalled == graphene::net::firewalled_state::not_firewalled) non_firewalled_nodes_set.insert(address_info_for_node.first); } std::set<graphene::net::node_id_t> seed_node_connections; for (const graphene::net::address_info& info : connections_by_node_id[seed_node_id]) seed_node_connections.insert(info.node_id); std::set<graphene::net::node_id_t> seed_node_missing_connections; std::set_difference(non_firewalled_nodes_set.begin(), non_firewalled_nodes_set.end(), seed_node_connections.begin(), seed_node_connections.end(), std::inserter(seed_node_missing_connections, seed_node_missing_connections.end())); seed_node_missing_connections.erase(seed_node_id); std::ofstream dot_stream((data_dir / "network_graph.dot").string().c_str()); dot_stream << "graph G {\n"; dot_stream << " // Total " << address_info_by_node_id.size() << " nodes, firewalled: " << (address_info_by_node_id.size() - non_firewalled_nodes_set.size()) << ", non-firewalled: " << non_firewalled_nodes_set.size() << "\n"; dot_stream << " // Seed node is " << (std::string)address_info_by_node_id[seed_node_id].remote_endpoint << " id: " << fc::variant( seed_node_id, 1 ).as_string() << "\n"; dot_stream << " // Seed node is connected to " << connections_by_node_id[seed_node_id].size() << " nodes\n"; dot_stream << " // Seed node is missing connections to " << seed_node_missing_connections.size() << " non-firewalled nodes:\n"; for (const graphene::net::node_id_t& id : seed_node_missing_connections) dot_stream << " // " << (std::string)address_info_by_node_id[id].remote_endpoint << "\n"; dot_stream << " layout=\"circo\";\n"; for (const auto& address_info_for_node : address_info_by_node_id) { dot_stream << " \"" << fc::variant( address_info_for_node.first, 1 ).as_string() << "\"[label=\"" << (std::string)address_info_for_node.second.remote_endpoint << "\""; if (address_info_for_node.second.firewalled != graphene::net::firewalled_state::not_firewalled) dot_stream << ",shape=rectangle"; dot_stream << "];\n"; } for (auto& node_and_connections : connections_by_node_id) for (const graphene::net::address_info& this_connection : node_and_connections.second) dot_stream << " \"" << fc::variant( node_and_connections.first, 2 ).as_string() << "\" -- \"" << fc::variant( this_connection.node_id, 1 ).as_string() << "\";\n"; dot_stream << "}\n"; return 0; }
enum piglit_result piglit_display(void) { GLboolean pass = GL_TRUE; GLuint fbo, tex, pbo; uint32_t *addr; make_fbo(&fbo, &tex); glClear(GL_COLOR_BUFFER_BIT); glGenBuffersARB(1, &pbo); glBindBufferARB(GL_PIXEL_PACK_BUFFER, pbo); glBufferDataARB(GL_PIXEL_PACK_BUFFER, 4 * 4, NULL, GL_STREAM_DRAW_ARB); glPixelStorei(GL_PACK_ALIGNMENT, 1); glViewport(0, 0, 2, 2); piglit_ortho_projection(2, 2, GL_FALSE); /* bottom: green. top: blue. */ glColor4f(0.0, 1.0, 0.0, 0.0); piglit_draw_rect(0, 0, 2, 1); glColor4f(0.0, 0.0, 1.0, 0.0); piglit_draw_rect(0, 1, 2, 1); /* Read the whole buffer. */ glReadPixels(0, 0, 2, 2, GL_BGRA, GL_UNSIGNED_BYTE, (void *)(uintptr_t)0); addr = glMapBufferARB(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY_ARB); pass &= probe(0, 0, 0x0000ff00, addr[0]); pass &= probe(1, 0, 0x0000ff00, addr[1]); pass &= probe(0, 1, 0x000000ff, addr[2]); pass &= probe(1, 1, 0x000000ff, addr[3]); glUnmapBufferARB(GL_PIXEL_PACK_BUFFER); /* Read with an offset. */ glReadPixels(1, 0, 1, 1, GL_BGRA, GL_UNSIGNED_BYTE, (void *)(uintptr_t)4); addr = glMapBufferARB(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY_ARB); pass &= probe(1, 0, 0x0000ff00, addr[1]); glUnmapBufferARB(GL_PIXEL_PACK_BUFFER); /* Read with an offset. */ glReadPixels(1, 1, 1, 1, GL_BGRA, GL_UNSIGNED_BYTE, (void *)(uintptr_t)4); addr = glMapBufferARB(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY_ARB); pass &= probe(1, 1, 0x000000ff, addr[1]); glUnmapBufferARB(GL_PIXEL_PACK_BUFFER); glDeleteBuffersARB(1, &pbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glViewport(0, 0, piglit_width, piglit_height); piglit_ortho_projection(piglit_width, piglit_height, GL_FALSE); glBindTexture(GL_TEXTURE_2D, tex); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); piglit_draw_rect_tex(0, 0, piglit_width, piglit_height, 0, 0, 1, 1); glDisable(GL_TEXTURE_2D); glDeleteFramebuffersEXT(1, &fbo); glDeleteTextures(1, &tex); glutSwapBuffers(); return pass ? PIGLIT_PASS : PIGLIT_FAIL; }
JSObject * WrapperFactory::PrepareForWrapping(JSContext *cx, HandleObject scope, HandleObject objArg, unsigned flags) { RootedObject obj(cx, objArg); // Outerize any raw inner objects at the entry point here, so that we don't // have to worry about them for the rest of the wrapping code. if (js::IsInnerObject(obj)) { JSAutoCompartment ac(cx, obj); obj = JS_ObjectToOuterObject(cx, obj); NS_ENSURE_TRUE(obj, nullptr); // The outerization hook wraps, which means that we can end up with a // CCW here if |obj| was a navigated-away-from inner. Strip any CCWs. obj = js::UncheckedUnwrap(obj); MOZ_ASSERT(js::IsOuterObject(obj)); } // If we've got an outer window, there's nothing special that needs to be // done here, and we can move on to the next phase of wrapping. We handle // this case first to allow us to assert against wrappers below. if (js::IsOuterObject(obj)) return DoubleWrap(cx, obj, flags); // Here are the rules for wrapping: // We should never get a proxy here (the JS engine unwraps those for us). MOZ_ASSERT(!IsWrapper(obj)); // As soon as an object is wrapped in a security wrapper, it morphs to be // a fat wrapper. (see also: bug XXX). if (IS_SLIM_WRAPPER(obj) && !MorphSlimWrapper(cx, obj)) return nullptr; // Now, our object is ready to be wrapped, but several objects (notably // nsJSIIDs) have a wrapper per scope. If we are about to wrap one of // those objects in a security wrapper, then we need to hand back the // wrapper for the new scope instead. Also, global objects don't move // between scopes so for those we also want to return the wrapper. So... if (!IS_WN_WRAPPER(obj) || !js::GetObjectParent(obj)) return DoubleWrap(cx, obj, flags); XPCWrappedNative *wn = static_cast<XPCWrappedNative *>(xpc_GetJSPrivate(obj)); JSAutoCompartment ac(cx, obj); XPCCallContext ccx(JS_CALLER, cx, obj); RootedObject wrapScope(cx, scope); { if (NATIVE_HAS_FLAG(&ccx, WantPreCreate)) { // We have a precreate hook. This object might enforce that we only // ever create JS object for it. // Note: this penalizes objects that only have one wrapper, but are // being accessed across compartments. We would really prefer to // replace the above code with a test that says "do you only have one // wrapper?" nsresult rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, scope, wrapScope.address()); NS_ENSURE_SUCCESS(rv, DoubleWrap(cx, obj, flags)); // If the handed back scope differs from the passed-in scope and is in // a separate compartment, then this object is explicitly requesting // that we don't create a second JS object for it: create a security // wrapper. if (js::GetObjectCompartment(scope) != js::GetObjectCompartment(wrapScope)) return DoubleWrap(cx, obj, flags); RootedObject currentScope(cx, JS_GetGlobalForObject(cx, obj)); if (MOZ_UNLIKELY(wrapScope != currentScope)) { // The wrapper claims it wants to be in the new scope, but // currently has a reflection that lives in the old scope. This // can mean one of two things, both of which are rare: // // 1 - The object has a PreCreate hook (we checked for it above), // but is deciding to request one-wrapper-per-scope (rather than // one-wrapper-per-native) for some reason. Usually, a PreCreate // hook indicates one-wrapper-per-native. In this case we want to // make a new wrapper in the new scope. // // 2 - We're midway through wrapper reparenting. The document has // moved to a new scope, but |wn| hasn't been moved yet, and // we ended up calling JS_WrapObject() on its JS object. In this // case, we want to return the existing wrapper. // // So we do a trick: call PreCreate _again_, but say that we're // wrapping for the old scope, rather than the new one. If (1) is // the case, then PreCreate will return the scope we pass to it // (the old scope). If (2) is the case, PreCreate will return the // scope of the document (the new scope). RootedObject probe(cx); rv = wn->GetScriptableInfo()->GetCallback()-> PreCreate(wn->Native(), cx, currentScope, probe.address()); // Check for case (2). if (probe != currentScope) { MOZ_ASSERT(probe == wrapScope); return DoubleWrap(cx, obj, flags); } // Ok, must be case (1). Fall through and create a new wrapper. } // Nasty hack for late-breaking bug 781476. This will confuse identity checks, // but it's probably better than any of our alternatives. // // Note: We have to ignore domain here. The JS engine assumes that, given a // compartment c, if c->wrap(x) returns a cross-compartment wrapper at time t0, // it will also return a cross-compartment wrapper for any time t1 > t0 unless // an explicit transplant is performed. In particular, wrapper recomputation // assumes that recomputing a wrapper will always result in a wrapper. // // This doesn't actually pose a security issue, because we'll still compute // the correct (opaque) wrapper for the object below given the security // characteristics of the two compartments. if (!AccessCheck::isChrome(js::GetObjectCompartment(wrapScope)) && AccessCheck::subsumesIgnoringDomain(js::GetObjectCompartment(wrapScope), js::GetObjectCompartment(obj))) { return DoubleWrap(cx, obj, flags); } } } // NB: Passing a holder here inhibits slim wrappers under // WrapNativeToJSVal. nsCOMPtr<nsIXPConnectJSObjectHolder> holder; // This public WrapNativeToJSVal API enters the compartment of 'wrapScope' // so we don't have to. RootedValue v(cx); nsresult rv = nsXPConnect::FastGetXPConnect()->WrapNativeToJSVal(cx, wrapScope, wn->Native(), nullptr, &NS_GET_IID(nsISupports), false, v.address(), getter_AddRefs(holder)); if (NS_SUCCEEDED(rv)) { obj = JSVAL_TO_OBJECT(v); NS_ASSERTION(IS_WN_WRAPPER(obj), "bad object"); // Because the underlying native didn't have a PreCreate hook, we had // to a new (or possibly pre-existing) XPCWN in our compartment. // This could be a problem for chrome code that passes XPCOM objects // across compartments, because the effects of QI would disappear across // compartments. // // So whenever we pull an XPCWN across compartments in this manner, we // give the destination object the union of the two native sets. We try // to do this cleverly in the common case to avoid too much overhead. XPCWrappedNative *newwn = static_cast<XPCWrappedNative *>(xpc_GetJSPrivate(obj)); XPCNativeSet *unionSet = XPCNativeSet::GetNewOrUsed(ccx, newwn->GetSet(), wn->GetSet(), false); if (!unionSet) return nullptr; newwn->SetSet(unionSet); } return DoubleWrap(cx, obj, flags); }
int8_t discover() { set_state(DISCOVER_IN_PROGRESS); return probe(0 /* unrestricted depth */); }
int MPU9250::init() { int ret; /* do SPI init (and probe) first */ ret = SPI::init(); /* if probe/setup failed, bail now */ if (ret != OK) { DEVICE_DEBUG("SPI setup failed"); return ret; } ret = probe(); if (ret != OK) { DEVICE_DEBUG("MPU9250 probe failed"); return ret; } /* allocate basic report buffers */ _accel_reports = new ringbuffer::RingBuffer(2, sizeof(accel_report)); if (_accel_reports == nullptr) { goto out; } _gyro_reports = new ringbuffer::RingBuffer(2, sizeof(gyro_report)); if (_gyro_reports == nullptr) { goto out; } if (reset() != OK) { goto out; } /* Initialize offsets and scales */ _accel_scale.x_offset = 0; _accel_scale.x_scale = 1.0f; _accel_scale.y_offset = 0; _accel_scale.y_scale = 1.0f; _accel_scale.z_offset = 0; _accel_scale.z_scale = 1.0f; _gyro_scale.x_offset = 0; _gyro_scale.x_scale = 1.0f; _gyro_scale.y_offset = 0; _gyro_scale.y_scale = 1.0f; _gyro_scale.z_offset = 0; _gyro_scale.z_scale = 1.0f; /* do CDev init for the gyro device node, keep it optional */ ret = _gyro->init(); /* if probe/setup failed, bail now */ if (ret != OK) { DEVICE_DEBUG("gyro init failed"); return ret; } /* do CDev init for the mag device node, keep it optional */ ret = _mag->init(); /* if probe/setup failed, bail now */ if (ret != OK) { DEVICE_DEBUG("mag init failed"); return ret; } _accel_class_instance = register_class_devname(ACCEL_BASE_DEVICE_PATH); measure(); /* advertise sensor topic, measure manually to initialize valid report */ struct accel_report arp; _accel_reports->get(&arp); /* measurement will have generated a report, publish */ _accel_topic = orb_advertise_multi(ORB_ID(sensor_accel), &arp, &_accel_orb_class_instance, (is_external()) ? ORB_PRIO_MAX - 1 : ORB_PRIO_HIGH - 1); if (_accel_topic == nullptr) { warnx("ADVERT FAIL"); } /* advertise sensor topic, measure manually to initialize valid report */ struct gyro_report grp; _gyro_reports->get(&grp); _gyro->_gyro_topic = orb_advertise_multi(ORB_ID(sensor_gyro), &grp, &_gyro->_gyro_orb_class_instance, (is_external()) ? ORB_PRIO_MAX - 1 : ORB_PRIO_HIGH - 1); if (_gyro->_gyro_topic == nullptr) { warnx("ADVERT FAIL"); } out: return ret; }
void via_aux_vt1622_probe(struct via_aux_bus *bus) { probe(bus, 0x20); probe(bus, 0x21); }
int main(int argc, char *argv[]) { float pos[3],ang[3]; struct polhemus *ph; int i; char status[128]; int devicenum = 2; int baud = PH_38400; int mode = PH_NOTHREAD; char *devicename; double starttime; int count = 10; if (argc > 1) { count = atoi(argv[1]); } /* return a polhemus object */ ph = phNew(); /* probe for port/baud rate */ if (!probe(ph,&devicenum,&baud,&mode)) { fprintf(stderr,"error %s\n",phGetErrorMessage(ph)); exit(0); } /* print out probed information */ fprintf(stderr,"found ph on port %s at baud rate %d in mode %d\n", phDeviceName(devicenum),baud,mode); /* you can set an error callback if you want */ phSetErrorCallback(ph,callback,ph); /* get the serial port name, e.g. "COM1:" or "COM2:" */ devicename = phDeviceName(devicenum); /* args are ph, serial port, baud, flags */ fprintf(stderr, "opening device %s\n", devicename); phSetInitialComm(ph, baud, 'N', 8, 0); phSetThreadMode(ph, mode); phOpen(ph,devicename); /* ph->file = ndiSerialOpen(devicename); ndiSerialComm(ph->file, 38400, "8N1", 0); */ fprintf(stderr, "device opened\n"); /* fprintf(stderr,"system status\n"); fbExamineValueBytes(ph,FB_FBB_STATUS,status); fprintf(stderr,"1: %2.2x 2: %2.2x",status[0],status[1]); fprintf(stderr,"\n"); */ fprintf(stderr,"sending: P\r\n"); /* write(ph->file, "P\r\n", 3); usleep(500000); read(ph->file, status, 128); read(ph->file, status, 128); */ phSetReplyFormat(ph, 1, PH_POSITION | PH_ANGLES); phSendRaw(ph,"P\n",2); phReceiveRaw(ph, status, 45, 0); fprintf(stderr, "received: \'%.*s\'\n", 45, status); phSetReplyFormat(ph, 1, PH_POSITION | PH_ANGLES); /* grab a single record */ starttime = phGetTime(ph); fprintf(stderr, "phStream\n"); phStream(ph); for (i = 0;i<count;i++) { fprintf(stderr, "phUpdate %i\n", i); phUpdate(ph); phGetPosition(ph,pos); phGetAngles(ph,ang); fprintf(stderr,"ph %d time %10.3f pos %+6.2f %+6.2f %+6.2f ang %+6.2f %+6.2f %+6.2f\n", phGetStation(ph),phGetTime(ph)-starttime, pos[0],pos[1],pos[2], ang[0],ang[1],ang[2]); } phClose(ph); return 0; }
/** \brief Superpose mob on ref Calculates a 4x4 transformation Matrix that should be applied on 'mob' in order to minimize RMSD between mob and ref. Algorithm taken from Sippl et Stegbuchner. Computers Chem. Vol 15, No. 1, p 73-78, 1991. */ Superpose_t superpose(const Rigidbody& ref, const Rigidbody& mob, int verbosity) { Rigidbody reference(ref); //copie de ref pour pouvoir centrer Rigidbody mobile(mob); // copie de mobile if (ref.Size()!=mob.Size()) {std::cout << "Error in superpose.cpp: \ the two AtomSelection objects must have\ the same size !" << std::endl; abort();}; Mat33 rot; Mat33 ident; for (uint i=0; i<3; i++) for(uint j=0; j<3; j++) if (i!=j) {ident[i][j]=0;} else {ident[i][j]=1;} ; //find the translational component Coord3D t0 = ref.FindCenter(); Coord3D t1 = mob.FindCenter(); //centre les deux objets: reference.CenterToOrigin(); mobile.CenterToOrigin(); Mat33 U; //mixed tensor MakeTensor(reference, mobile, U); for(uint i=0; i<35; i++) { double arg1,arg2; arg1 = U[2][1] - U[1][2] ; arg2 = U[1][1] + U[2][2]; double alpha = atan2(arg1 , arg2 ); XRotMatrix(-alpha, rot); Mat33xMat33(rot,ident,ident); //------------------------------------ Mat33xMat33(rot,U,U); arg1 = U[2][0]-U[0][2]; arg2 = U[0][0]+U[2][2]; double beta = atan2(arg1,arg2); YRotMatrix(beta,rot); Mat33xMat33(rot,ident,ident); //-------------------------------------- Mat33xMat33(rot,U,U); arg1 = U[1][0] - U[0][1]; arg2 = U[0][0] + U[1][1]; double gamma = atan2(arg1,arg2); ZRotMatrix(-gamma,rot); Mat33xMat33(rot,ident,ident); Mat33xMat33(rot,U,U); } //creates a 4x4 matrix that tracks transformations for mobile Mat44 tracker; MakeTranslationMat44(Coord3D()-t1,tracker); //copy the 3x3 matrix into a 4x4 matrix Mat44 rotation; MakeTranslationMat44(Coord3D(),rotation); //identity matrix; for (int i=0; i<3; i++) for (int j=0; j<3; j++) rotation[i][j]=ident[i][j]; mat44xmat44(rotation, tracker, tracker); MakeTranslationMat44(t0, rotation); mat44xmat44(rotation, tracker, tracker); Matrix output(4,4); for (int i=0; i<4; i++) for (int j=0; j<4;j++) output(i,j)=tracker[i][j]; Superpose_t sup; sup.matrix = output; Rigidbody probe(mob); probe.ApplyMatrix(output); sup.rmsd = Rmsd(ref,probe); return sup; // screw = MatTrans2screw(ident, t0, t1); // screw.point = screw.point + t1 ; /* if (verbosity==1) { Rigidbody newmob(mob); Rigidbody newref(ref); selref.setRigid(newref); selmob.setRigid(newmob); newmob.transform(screw); std::cout << "verif screw, rmsdca = " << rmsd(selmob && CA(newmob),selref && CA(newref)) << std::endl ; } */ // return screw; } }
/** * Finds and instantiates the best module of a certain type. * All candidates modules having the specified capability and name will be * sorted in decreasing order of priority. Then the probe callback will be * invoked for each module, until it succeeds (returns 0), or all candidate * module failed to initialize. * * The probe callback first parameter is the address of the module entry point. * Further parameters are passed as an argument list; it corresponds to the * variable arguments passed to this function. This scheme is meant to * support arbitrary prototypes for the module entry point. * * \param p_this VLC object * \param psz_capability capability, i.e. class of module * \param psz_name name name of the module asked, if any * \param b_strict if true, do not fallback to plugin with a different name * but the same capability * \param probe module probe callback * \return the module or NULL in case of a failure */ module_t *vlc_module_load(vlc_object_t *p_this, const char *psz_capability, const char *psz_name, bool b_strict, vlc_activate_t probe, ...) { int i_shortcuts = 0; char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL; bool b_force_backup = p_this->b_force; /* Deal with variables */ if( psz_name && psz_name[0] == '$' ) { psz_name = psz_var = var_CreateGetString( p_this, psz_name + 1 ); } /* Count how many different shortcuts were asked for */ if( psz_name && *psz_name ) { char *psz_parser, *psz_last_shortcut; /* If the user wants none, give him none. */ if( !strcmp( psz_name, "none" ) ) { free( psz_var ); return NULL; } i_shortcuts++; psz_parser = psz_shortcuts = psz_last_shortcut = strdup( psz_name ); while( ( psz_parser = strchr( psz_parser, ',' ) ) ) { *psz_parser = '\0'; i_shortcuts++; psz_last_shortcut = ++psz_parser; } /* Check if the user wants to override the "strict" mode */ if( psz_last_shortcut ) { if( !strcmp(psz_last_shortcut, "none") ) { b_strict = true; i_shortcuts--; } else if( !strcmp(psz_last_shortcut, "any") ) { b_strict = false; i_shortcuts--; } } } /* Sort the modules and test them */ size_t total, match = 0; module_t **p_all = module_list_get (&total); module_list_t *p_list = xmalloc( total * sizeof( module_list_t ) ); /* Parse the module list for capabilities and probe each of them */ for (size_t i = 0; i < total; i++) { module_t *p_module = p_all[i]; int i_shortcut_bonus = 0; /* Test that this module can do what we need */ if( !module_provides( p_module, psz_capability ) ) continue; /* If we required a shortcut, check this plugin provides it. */ if( i_shortcuts > 0 ) { const char *name = psz_shortcuts; for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- ) { for( unsigned i = 0; i < p_module->i_shortcuts; i++ ) { char *c; if( ( c = strchr( name, '@' ) ) ? !strncasecmp( name, p_module->pp_shortcuts[i], c-name ) : !strcasecmp( name, p_module->pp_shortcuts[i] ) ) { /* Found it */ if( c && c[1] ) psz_alias = c+1; i_shortcut_bonus = i_short * 10000; goto found_shortcut; } } /* Go to the next shortcut... This is so lame! */ name += strlen( name ) + 1; } /* If we are in "strict" mode and we couldn't * find the module in the list of provided shortcuts, * then kick the bastard out of here!!! */ if( b_strict ) continue; } /* Trash <= 0 scored plugins (they can only be selected by shortcut) */ if( p_module->i_score <= 0 ) continue; found_shortcut: /* Store this new module */ p_list[match].p_module = p_module; p_list[match].i_score = p_module->i_score + i_shortcut_bonus; p_list[match].b_force = i_shortcut_bonus && b_strict; match++; } /* We can release the list, interesting modules are held */ module_list_free (p_all); if( match == 0 ) { msg_Dbg( p_this, "no %s module matched \"%s\"", psz_capability, (psz_name && *psz_name) ? psz_name : "any" ); return NULL; // shortcut } /* Sort candidates by descending score */ qsort (p_list, match, sizeof (p_list[0]), modulecmp); msg_Dbg( p_this, "looking for %s module: %zu candidate%s", psz_capability, match, match == 1 ? "" : "s" ); /* Parse the linked list and use the first successful module */ module_t *p_module = NULL; va_list args; va_start(args, probe); for (size_t i = 0; (i < match) && (p_module == NULL); i++) { module_t *p_cand = p_list[i].p_module; if (module_Map (p_this, p_cand)) continue; p_this->b_force = p_list[i].b_force; int ret; if (likely(p_cand->pf_activate != NULL)) { va_list ap; va_copy(ap, args); ret = probe(p_cand->pf_activate, ap); va_end(ap); } else ret = VLC_SUCCESS; switch (ret) { case VLC_SUCCESS: /* good module! */ p_module = p_cand; break; case VLC_ETIMEOUT: /* good module, but aborted */ break; default: /* bad module */ continue; } } va_end (args); free( p_list ); p_this->b_force = b_force_backup; if( p_module != NULL ) { msg_Dbg( p_this, "using %s module \"%s\"", psz_capability, module_get_object(p_module) ); vlc_object_set_name( p_this, psz_alias ? psz_alias : module_get_object(p_module) ); } else msg_Dbg( p_this, "no %s module matching \"%s\" could be loaded", psz_capability, (psz_name && *psz_name) ? psz_name : "any" ); free( psz_shortcuts ); free( psz_var ); /* Don't forget that the module is still locked */ return p_module; }
//------------------------------------------------------------------------------ int main( int argc, char * argv[] ) { // basic attributes of the computation const unsigned geomDeg = 1; const unsigned fieldDegU = 2; const unsigned fieldDegP = 1; const unsigned tiOrder = 2; // order of time integrator const base::Shape shape = base::QUAD; //typedef base::time::BDF<tiOrder> MSM; typedef base::time::AdamsMoulton<tiOrder> MSM; // time stepping method determines the history size const unsigned nHist = MSM::numSteps; const std::string inputFile = "terz.inp"; double E, nu, alpha, c0, k, H, F, tMax; unsigned numSteps, numIntervals; { base::io::PropertiesParser pp; pp.registerPropertiesVar( "E", E ); pp.registerPropertiesVar( "nu", nu ); pp.registerPropertiesVar( "alpha", alpha ); pp.registerPropertiesVar( "c0", c0 ); pp.registerPropertiesVar( "k", k ); pp.registerPropertiesVar( "H", H ); pp.registerPropertiesVar( "F", F ); pp.registerPropertiesVar( "tMax", tMax ); pp.registerPropertiesVar( "numSteps", numSteps ); pp.registerPropertiesVar( "numIntervals", numIntervals ); // Read variables from the input file std::ifstream inp( inputFile.c_str() ); VERIFY_MSG( inp.is_open(), "Cannot open input file" ); pp.readValues( inp ); inp.close( ); } const double deltaT = tMax / static_cast<double>( numSteps ); // usage message if ( argc != 2 ) { std::cout << "Usage: " << argv[0] << " mesh.smf \n"; return 0; } const std::string meshFile = boost::lexical_cast<std::string>( argv[1] ); // Analytic solution Terzaghi terzaghi( E, nu, alpha, c0, k, H, F ); //-------------------------------------------------------------------------- // define a mesh typedef base::Unstructured<shape,geomDeg> Mesh; const unsigned dim = Mesh::Node::dim; // create a mesh and read from input Mesh mesh; { std::ifstream smf( meshFile.c_str() ); base::io::smf::readMesh( smf, mesh ); smf.close(); } // quadrature objects for volume and surface const unsigned kernelDegEstimate = 3; typedef base::Quadrature<kernelDegEstimate,shape> Quadrature; Quadrature quadrature; typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature; SurfaceQuadrature surfaceQuadrature; // Create a displacement field const unsigned doFSizeU = dim; typedef base::fe::Basis<shape,fieldDegU> FEBasisU; typedef base::Field<FEBasisU,doFSizeU,nHist> Displacement; typedef Displacement::DegreeOfFreedom DoFU; Displacement displacement; // Create a pressure field const unsigned doFSizeP = 1; typedef base::fe::Basis<shape,fieldDegP> FEBasisP; typedef base::Field<FEBasisP,doFSizeP,nHist> Pressure; typedef Pressure::DegreeOfFreedom DoFP; Pressure pressure; // generate DoFs from mesh base::dof::generate<FEBasisU>( mesh, displacement ); base::dof::generate<FEBasisP>( mesh, pressure ); // Creates a list of <Element,faceNo> pairs along the boundary base::mesh::MeshBoundary meshBoundary; meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() ); // Create a boundary mesh from this list typedef base::mesh::CreateBoundaryMesh<Mesh::Element> CreateBoundaryMesh; typedef CreateBoundaryMesh::BoundaryMesh BoundaryMesh; BoundaryMesh boundaryMesh; { CreateBoundaryMesh::apply( meshBoundary.begin(), meshBoundary.end(), mesh, boundaryMesh ); } // material object typedef mat::hypel::StVenant Material; Material material( mat::Lame::lambda( E, nu), mat::Lame::mu( E, nu ) ); typedef base::asmb::FieldBinder<Mesh,Displacement,Pressure> Field; Field field( mesh, displacement, pressure ); typedef Field::TupleBinder<1,1>::Type TopLeft; typedef Field::TupleBinder<1,2>::Type TopRight; typedef Field::TupleBinder<2,1>::Type BotLeft; typedef Field::TupleBinder<2,2>::Type BotRight; // surface displacement field typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Displacement> SurfaceFieldBinder; SurfaceFieldBinder surfaceFieldBinder( boundaryMesh, displacement ); typedef SurfaceFieldBinder::TupleBinder<1>::Type SFTB; // kernel objects typedef solid::HyperElastic<Material,TopLeft::Tuple> HyperElastic; HyperElastic hyperElastic( material ); typedef fluid::PressureGradient<TopRight::Tuple> GradP; GradP gradP; //typedef fluid::VelocityDivergence<FieldPUUTuple> DivU; //DivU divU( true ); // * alpha typedef PoroDivU<BotLeft::Tuple> DivU; DivU divU( alpha ); typedef heat::Laplace<BotRight::Tuple> Laplace; Laplace laplace( k ); // constrain the boundary base::dof::constrainBoundary<FEBasisU>( meshBoundary.begin(), meshBoundary.end(), mesh, displacement, boost::bind( &dirichletU<dim,DoFU>, _1, _2, 1.0 ) ); base::dof::constrainBoundary<FEBasisP>( meshBoundary.begin(), meshBoundary.end(), mesh, pressure, boost::bind( &dirichletP<dim,DoFP>, _1, _2, H ) ); // Number the degrees of freedom const std::size_t numDoFsU = base::dof::numberDoFsConsecutively( displacement.doFsBegin(), displacement.doFsEnd() ); std::cout << "# Number of displacement dofs " << numDoFsU << std::endl; const std::size_t numDoFsP = base::dof::numberDoFsConsecutively( pressure.doFsBegin(), pressure.doFsEnd(), numDoFsU ); std::cout << "# Number of pressure dofs " << numDoFsP << std::endl; // write VTK file writeVTK( mesh, displacement, pressure, meshFile, 0 ); for ( unsigned n = 0; n < numSteps; n++ ) { const double time = (n+1) * deltaT; std::cout << time << " "; // initialise current displacement to zero (linear elasticity) std::for_each( displacement.doFsBegin(), displacement.doFsEnd(), boost::bind( &DoFU::clearValue, _1 ) ); // Create a solver object typedef base::solver::Eigen3 Solver; Solver solver( numDoFsU + numDoFsP ); //------------------------------------------------------------------ base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver, field, hyperElastic ); base::asmb::stiffnessMatrixComputation<TopRight>( quadrature, solver, field, gradP ); base::asmb::stiffnessMatrixComputation<BotRight>( quadrature, solver, field, laplace); // time integration terms base::time::computeReactionTerms<BotLeft,MSM>( divU, quadrature, solver, field, deltaT, n ); base::time::computeInertiaTerms<BotRight,MSM>( quadrature, solver, field, deltaT, n, c0 ); base::time::computeResidualForceHistory<BotRight,MSM>( laplace, quadrature, solver, field, n ); // Neumann boundary condition base::asmb::neumannForceComputation<SFTB>( surfaceQuadrature, solver, surfaceFieldBinder, boost::bind( &neumannBC<dim>, _1, _2, H, F ) ); // Finalise assembly solver.finishAssembly(); // Solve solver.superLUSolve(); // distribute results back to dofs base::dof::setDoFsFromSolver( solver, displacement ); base::dof::setDoFsFromSolver( solver, pressure ); // push history std::for_each( displacement.doFsBegin(), displacement.doFsEnd(), boost::bind( &DoFU::pushHistory, _1 ) ); std::for_each( pressure.doFsBegin(), pressure.doFsEnd(), boost::bind( &DoFP::pushHistory, _1 ) ); // write VTK file writeVTK( mesh, displacement, pressure, meshFile, n+1 ); // Finished time steps //-------------------------------------------------------------------------- const std::pair<double,double> approx = probe( mesh, displacement, pressure ); const double p = terzaghi.pressure( H/2., time ); const double u = terzaghi.displacement( H/2., time ); std::cout << u << " " << approx.first << " " << p << " " << approx.second << '\n'; } return 0; }
int initialize (char* file, int length, int size) { if ((fd = open(file, O_RDWR | O_CREAT, 00700)) != -1) { _size = size; _length = length; return fd; } else { /* perror("failed to open"); */ return -1; } } int delete(char *key) { int prober = probe(key); // printf("prober: %d\n", prober); if(prober == (-1)) { printf("Error: Value not in table.\n"); return(-1); } else { lseek(fd, (prober * _length), SEEK_SET); if(write(fd, &tombstone, sizeof(uint32_t)) < 0) { printf("failed to write tombstone\n"); } return(0); } } int probe (char *key) {
int MPU9250::init() { irqstate_t state; #if defined(USE_I2C) use_i2c(_interface->get_device_bus_type() == device::Device::DeviceBusType_I2C); #endif /* * If the MPU is using I2C we should reduce the sample rate to 200Hz and * make the integration autoreset faster so that we integrate just one * sample since the sampling rate is already low. */ if (is_i2c() && !_magnetometer_only) { _sample_rate = 200; _accel_int.set_autoreset_interval(1000000 / 1000); _gyro_int.set_autoreset_interval(1000000 / 1000); } int ret = probe(); if (ret != OK) { PX4_DEBUG("MPU9250 probe failed"); return ret; } state = px4_enter_critical_section(); _reset_wait = hrt_absolute_time() + 100000; px4_leave_critical_section(state); if (reset_mpu() != OK) { PX4_ERR("Exiting! Device failed to take initialization"); return ret; } if (!_magnetometer_only) { /* allocate basic report buffers */ _accel_reports = new ringbuffer::RingBuffer(2, sizeof(sensor_accel_s)); ret = -ENOMEM; if (_accel_reports == nullptr) { return ret; } _gyro_reports = new ringbuffer::RingBuffer(2, sizeof(sensor_gyro_s)); if (_gyro_reports == nullptr) { return ret; } /* Initialize offsets and scales */ _accel_scale.x_offset = 0; _accel_scale.x_scale = 1.0f; _accel_scale.y_offset = 0; _accel_scale.y_scale = 1.0f; _accel_scale.z_offset = 0; _accel_scale.z_scale = 1.0f; _gyro_scale.x_offset = 0; _gyro_scale.x_scale = 1.0f; _gyro_scale.y_offset = 0; _gyro_scale.y_scale = 1.0f; _gyro_scale.z_offset = 0; _gyro_scale.z_scale = 1.0f; // set software low pass filter for controllers param_t accel_cut_ph = param_find("IMU_ACCEL_CUTOFF"); float accel_cut = MPU9250_ACCEL_DEFAULT_DRIVER_FILTER_FREQ; if (accel_cut_ph != PARAM_INVALID && (param_get(accel_cut_ph, &accel_cut) == PX4_OK)) { PX4_INFO("accel cutoff set to %.2f Hz", double(accel_cut)); _accel_filter_x.set_cutoff_frequency(MPU9250_ACCEL_DEFAULT_RATE, accel_cut); _accel_filter_y.set_cutoff_frequency(MPU9250_ACCEL_DEFAULT_RATE, accel_cut); _accel_filter_z.set_cutoff_frequency(MPU9250_ACCEL_DEFAULT_RATE, accel_cut); } param_t gyro_cut_ph = param_find("IMU_GYRO_CUTOFF"); float gyro_cut = MPU9250_GYRO_DEFAULT_DRIVER_FILTER_FREQ; if (gyro_cut_ph != PARAM_INVALID && (param_get(gyro_cut_ph, &gyro_cut) == PX4_OK)) { PX4_INFO("gyro cutoff set to %.2f Hz", double(gyro_cut)); _gyro_filter_x.set_cutoff_frequency(MPU9250_GYRO_DEFAULT_RATE, gyro_cut); _gyro_filter_y.set_cutoff_frequency(MPU9250_GYRO_DEFAULT_RATE, gyro_cut); _gyro_filter_z.set_cutoff_frequency(MPU9250_GYRO_DEFAULT_RATE, gyro_cut); } /* do CDev init for the accel device node */ ret = _accel->init(); /* if probe/setup failed, bail now */ if (ret != OK) { PX4_DEBUG("accel init failed"); return ret; } /* do CDev init for the gyro device node */ ret = _gyro->init(); /* if probe/setup failed, bail now */ if (ret != OK) { PX4_DEBUG("gyro init failed"); return ret; } } /* Magnetometer setup */ if (_whoami == MPU_WHOAMI_9250) { #ifdef USE_I2C up_udelay(100); if (!_mag->is_passthrough() && _mag->_interface->init() != PX4_OK) { PX4_ERR("failed to setup ak8963 interface"); } #endif /* USE_I2C */ /* do CDev init for the mag device node */ ret = _mag->init(); /* if probe/setup failed, bail now */ if (ret != OK) { PX4_DEBUG("mag init failed"); return ret; } ret = _mag->ak8963_reset(); if (ret != OK) { PX4_DEBUG("mag reset failed"); return ret; } } measure(); if (!_magnetometer_only) { /* advertise sensor topic, measure manually to initialize valid report */ sensor_accel_s arp; _accel_reports->get(&arp); /* measurement will have generated a report, publish */ _accel_topic = orb_advertise_multi(ORB_ID(sensor_accel), &arp, &_accel->_accel_orb_class_instance, (is_external()) ? ORB_PRIO_MAX - 1 : ORB_PRIO_HIGH - 1); if (_accel_topic == nullptr) { PX4_ERR("ADVERT FAIL"); return ret; } /* advertise sensor topic, measure manually to initialize valid report */ sensor_gyro_s grp; _gyro_reports->get(&grp); _gyro->_gyro_topic = orb_advertise_multi(ORB_ID(sensor_gyro), &grp, &_gyro->_gyro_orb_class_instance, (is_external()) ? ORB_PRIO_MAX - 1 : ORB_PRIO_HIGH - 1); if (_gyro->_gyro_topic == nullptr) { PX4_ERR("ADVERT FAIL"); return ret; } } return ret; }