/* * Check for primitives * Flags, Registers, Numbers, Addresses and parentheses */ Condition* Primitive(const char** str, Condition* c) { if (isFlag(next)) /* Flags */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_FLAG; c->value1 = next; } else { c->type2 = TYPE_FLAG; c->value2 = next; } scan(str); return c; } else if (isRegister(next)) /* Registers */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_REG; c->value1 = next; } else { c->type2 = TYPE_REG; c->value2 = next; } scan(str); return c; } else if (isPCBank(next)) /* PC Bank */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_PC_BANK; c->value1 = next; } else { c->type2 = TYPE_PC_BANK; c->value2 = next; } scan(str); return c; } else if (isDataBank(next)) /* Data Bank */ { if (c->type1 == TYPE_NO) { c->type1 = TYPE_DATA_BANK; c->value1 = next; } else { c->type2 = TYPE_DATA_BANK; c->value2 = next; } scan(str); return c; } else if (next == '#') /* Numbers */ { unsigned int number = 0; if (!getNumber(&number, str)) { return 0; } if (c->type1 == TYPE_NO) { c->type1 = TYPE_NUM; c->value1 = number; } else { c->type2 = TYPE_NUM; c->value2 = number; } return c; } else if (next == '$') /* Addresses */ { if ((**str >= '0' && **str <= '9') || (**str >= 'A' && **str <= 'F')) /* Constant addresses */ { unsigned int number = 0; if (!getNumber(&number, str)) { return 0; } if (c->type1 == TYPE_NO) { c->type1 = TYPE_ADDR; c->value1 = number; } else { c->type2 = TYPE_ADDR; c->value2 = number; } return c; } else if (**str == '[') /* Dynamic addresses */ { scan(str); Parentheses(str, c, '[', ']'); if (c->type1 == TYPE_NO) { c->type1 = TYPE_ADDR; } else { c->type2 = TYPE_ADDR; } return c; } else { return 0; } } else if (next == '(') { return Parentheses(str, c, '(', ')'); } return 0; }
void doSetThickness(FILE *stream) { int t; t = getNumber(stream); gdImageSetThickness(image, t); }
void PhoneDetails::countryChanged(int) { getNumber(); }
/* * Read the first member of the archive file and check whether it * is a special one, and if so, handle it. If the first member is * a normal archive member, then set up to rescan it for the next * readNormalMember call. Returns TRUE on success. */ static BOOL readSpecialMember(Archive * arch) { struct ar_hdr hdr; /* * 1. Read a header H. Fail if impossible. */ if (!readMember(arch, &hdr)) return FALSE; /* * 2. If H is a symbol table, ditch it. * Fail if impossible. */ if ((strncmp(hdr.ar_name, "/ ", 2) == 0) || (strncmp(hdr.ar_name, "__.SYMTAB ", sizeof(hdr.ar_name)) == 0)) { if (!canonicalize(arch, &hdr)) return FALSE; return skipMember(arch); } /* * 3. If H is a SysV longname table, read it into ARCH. */ if (strncmp(hdr.ar_name, "//", 2) == 0) { unsigned long len; ssize_t cc; if (!getNumber(hdr.ar_size, 10, sizeof(hdr.ar_size), &len)) { fprintf(stderr, "Invalid name-table size\n"); return FALSE; } arch->nameTable = malloc(len + 1); if (!arch->nameTable) { fprintf(stderr, "Out of memory\n"); return FALSE; } cc = read(arch->fd, arch->nameTable, len); if (cc == -1) { fprintf(stderr, "Error reading name-table: %s\n", strerror(errno)); return FALSE; } if (cc != (ssize_t) len) { fprintf(stderr, "Unexpected end of file in name-table\n"); return FALSE; } arch->nameTable[len] = 0; return skipPadding(arch->fd, len % 2); } /* * 4. We read a normal header. * Canonicalize it, and mark it as needing rescanning. */ arch->rescan = TRUE; return canonicalize(arch, &hdr); }
void cmd_nfc_mifareclassic_memdump(uint8_t argc, char **argv) { pn532_error_t error; byte_t abtUID[8]; byte_t abtBlock[32]; size_t szUIDLen; int32_t timeout; bool retriesChanged = false; // To dump an NDEF formatted Mifare Classic Card (formatted using NXP TagWriter on Android // for example), you must use the following authentication keys: // // Sector 0: 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5 // Sectors 1..15: 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7 // // For more information on NDEF see the following document: // // AN1305 - MIFARE Classic as NFC Type MIFARE Classic Tag // http://www.nxp.com/documents/application_note/AN1305.pdf // Set this to one for NDEF cards, or 0 for blank factory default cards #define CARDFORMAT_NDEF (0) #if CARDFORMAT_NDEF == 1 byte_t abtAuthKey1[6] = { 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5 }; // Sector 0 of NXP formatter NDEF cards byte_t abtAuthKey2[6] = { 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7 }; // All other sectors use standard key (AN1305 p.20, Table 6) #else byte_t abtAuthKey1[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; byte_t abtAuthKey2[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; #endif // Set a timeout waiting for passive targets (default = 0xFF, wait forever) if (argc > 0) { getNumber (argv[0], &timeout); if (timeout > 0xFF || timeout < 0) { printf("Invalid timeout [0..255]%s", CFG_PRINTF_NEWLINE); return; } else if (timeout > 0 || timeout < 0xFF) { // We can safely ignore errors here since there is a default value anyway pn532_config_SetPassiveActivationRetries(timeout); retriesChanged = true; } } // Use the MIFARE Classic Helper to read/write to the tag's EEPROM storage printf("Please insert a Mifare Classic 1K or 4K card%s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE); // Wait for any ISO14443A card error = pn532_mifareclassic_WaitForPassiveTarget(abtUID, &szUIDLen); if (!error) { // Mifare classic card found ... cycle through each sector uint8_t block; bool authenticated = false; for (block = 0; block < 64; block++) { // Check if this is a new block so that we can reauthenticate if (pn532_mifareclassic_isFirstBlock(block)) authenticated = false; if (!authenticated) { // Start of a new sector ... try to to authenticate printf("-------------------------Sector %02d--------------------------%s", block / 4, CFG_PRINTF_NEWLINE); error = pn532_mifareclassic_AuthenticateBlock (abtUID, szUIDLen, block, PN532_MIFARE_CMD_AUTH_A, block / 4 ? abtAuthKey2 : abtAuthKey1); if (error) { switch(error) { default: printf("Authentication error (0x%02x)%s", error, CFG_PRINTF_NEWLINE); break; } } else { authenticated = true; } } // If we're still not authenticated just skip the block if (!authenticated) { printf("Block %02d: ", block); printf("Unable to authenticate%s", CFG_PRINTF_NEWLINE); } else { // Authenticated ... we should be able to read the block now error = pn532_mifareclassic_ReadDataBlock (block, abtBlock); if (error) { switch(error) { default: printf("Block %02d: ", block); printf("Unable to read this block%s", CFG_PRINTF_NEWLINE); break; } } else { // Read successful printf("Block %02d: ", block); pn532PrintHexChar(abtBlock, 16); } } } } else { switch (error) { case PN532_ERROR_WRONGCARDTYPE: printf("Wrong card type%s", CFG_PRINTF_NEWLINE); break; case PN532_ERROR_TIMEOUTWAITINGFORCARD: printf("Timed out waiting for a card%s", CFG_PRINTF_NEWLINE); break; default: printf("Error establishing passive connection (0x%02x)%s", error, CFG_PRINTF_NEWLINE); break; } } // Set retry count back to infinite if it was changed if (retriesChanged) { pn532_config_SetPassiveActivationRetries(0xFF); } }
void Buttongrid::drawGrid(){ int xPos,yPos,width,height; int btnWidth,btnHeight; xPos = x; yPos = y; width = w; height = h; btnWidth = w / columns; btnHeight = h / rows; //--nums background rectangle Tft.fillRectangle(xPos,yPos,width,height,bgColor); //-- outer border for(byte i=borderWidth; i!=0;i--){ Tft.drawRectangle(xPos++,yPos++,width--,height--,borderColor); width--; height--; } //-- horizontal lines for(byte j=1;j<rows;j++) { // draw # horizontal lines depending on borderWidth for(byte i=0; i<borderWidth;i++){ Tft.drawHorizontalLine(x,y+btnHeight*j+i-vGap,width+borderWidth,borderColor); } //Only draw gaps in between edges if(vGap>0){ //Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK); for(byte i=0; i<borderWidth;i++){ Tft.drawHorizontalLine(x,y+btnHeight*j+i+borderWidth+vGap,width+borderWidth,borderColor); } } } //-- vertical lines for(byte j=1;j<columns;j++) { // draw # of vertical lines depending on borderWidth for(byte i=0; i<borderWidth;i++){ Tft.drawVerticalLine(x+btnWidth*j+i-hGap,y+borderWidth,height+borderWidth,borderColor); } //Only draw gaps in between edges if(hGap>0){ //Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK); for(byte i=0; i<borderWidth;i++){ Tft.drawVerticalLine(x+btnWidth*j+i+borderWidth+hGap,y+borderWidth,height+borderWidth,borderColor); } } } //-- draw contents byte colIndex=0; byte rowIndex=0; for(byte r=1; r<=rows; r++) { for(byte c=1; c<=columns; c++) { //byte num = getNumber(r,c); //c+(r-1)*columns; //Serial.print(" r: "); //Serial.print(r); //Serial.print(" c: "); //Serial.print(c); //Serial.print(" num: "); //Serial.print(num); //Serial.print(" label: "); //Serial.print(labels[r-1][c-1]); //Serial.print(","); //setLabel(getNumber(r,c),labels[r-1][c-1]); printName(getNumber(r,c)); } //Serial.println(); } //-- Gaps fill if(hGap > 0){ for(byte j=1;j<columns;j++){ Tft.fillRectangle(x+j*btnWidth+borderWidth-hGap,y,hGap*2,h,myCanvas->bgColor); } } if(vGap > 0){ for(byte j=1;j<rows;j++){ Tft.fillRectangle(x,y+j*btnHeight+borderWidth-vGap,w,vGap*2,myCanvas->bgColor); } } }
int main(int argc, const char * argv[]) { // Make an instance of BaseList. If you, or anyone, forgets what BaseList, all you do is Cmd-Click // (on Mac) the type and it'll bring you to the definition. Also, here I'll discuss what auto is // doing. If you look at the line below you can read it like mBases is being initialized with a // construction of BaseList. Therefore, there's no doubt as to what type mBases is. It is clearly // an instance of BaseList. 'auto' allows us to use type-inference in C++ which is another great // expressive idea that has been a part of higher-level languages for a long time but unlike many // higher-languages that need to run-time check the type information of an object. The inferring // happens at compile time so there's no penalty for that inference. That is amazing. Also, look // at what we've written, BaseList is a type that we've defined above with our using statement, // our using statement uses a type BaseRef that we defined above that. In essence without these // constructs we'd be writing this line like this. // // std::vector<std::shared_ptr<Base>> mBases = std::vector<std::shared_ptr<Base>>(); // // Could you imagine how awful that'd be? Can you see why C++ has had a bad name for so long? The // below line show just how much more modern C++ has become. It is so much more expressive! auto mBases = BaseList(); // Now I can add instances of Derived Classes that inherit from Base easily into this vector because // shared_ptr's will implicitly cast the underlying pointer, which is of Derived type, to the base // type and it does this safely by checking types at compile-time and throwing errors if you're doing // something you shouldn't be, like trying to convert something you think is derived that isn't actually // So Safety! So Nice! Also notice how nice the type definitions are to write! mBases.push_back( DerivedFloatRef( new DerivedFloat( "Mike", 29.0f ) ) ); mBases.push_back( DerivedArrayRef( new DerivedArray( "Ryan" ) ) ); // Now hopefully you can see what is going on with auto here. Basically because the compiler // knows that mBases is a std::vector of BaseRefs it already knows what type 'basePtr' should // be, BaseRef. After it figures out what type 'basePtr' is, I then tell it that I'd like // to take a reference to that type which means that 'basePtr' is going to point to the // shared_ptr which holds the instance of Base. It seems like I'm saying a lot with just a // couple of letters, which happens to be only good. This is the reason that we've spent // so much time on syntax, because once you understand what's going on, you'll be able to // just express what you mean. for ( auto & basePtr : mBases ) { // Use base like it has been created to be used. std::cout << basePtr->getName() << std::endl; basePtr->print(); // I'd like to do something with DerivedFloat specifically. So, let's check it's run-time // type information. if( basePtr->getDerivedType() == DerivedTypes::DERIVED_FLOAT ) { // Yaaaayyyy auto! std also provides a function called dynamic_pointer_cast for std::shared_ptr's // you put the type of shared pointer (DerivedFloat) you'd like to cast to and provide the // object you'd like to cast (basePtr) and It will return a std::shared_ptr<DerivedFloat>. Now // we can see that auto will work because we've told the compiler all the info it needs to descern // the type of derivedFloatPtr. Simple! auto derivedFloatPtr = std::dynamic_pointer_cast<DerivedFloat>( basePtr ); // Let's check that. std::cout << "I'm a derived float ptr: " << derivedFloatPtr->getNumber() << std::endl; } else { std::cout << basePtr->getName() << " isn't a DERIVED_FLOAT" << std::endl; } } // After this function returns you'll be able to see the way in which order everything is destroyed. // Check the console! And thanks for following me through this windy road. I promise when you understand // what's basically going on in the lessons up to here things about C++ will become much easier. return 0; }
void cmd_rtc_write(uint8_t argc, char **argv) { error_t error; rtcTime_t time; int32_t year, month, day, hour, minute, second; getNumber(argv[0], &year); getNumber(argv[1], &month); getNumber(argv[2], &day); getNumber(argv[3], &hour); getNumber(argv[4], &minute); getNumber(argv[5], &second); /* Make sure values are valid */ if ((year < 2000) || (year > 2038)) { printf("%s%s", "Year must be between 2000 and 2023", CFG_PRINTF_NEWLINE); return; } if ((month < RTC_MONTHS_JANUARY) || (month > RTC_MONTHS_DECEMBER)) { printf("%s%s", "Month must be between 1 and 12", CFG_PRINTF_NEWLINE); return; } if ((day < 1) || (day > 31)) { printf("%s%s", "Day must be between 1 and 31", CFG_PRINTF_NEWLINE); return; } if ((hour < 0) || (hour > 23)) { printf("%s%s", "Hour must be between 0 and 23", CFG_PRINTF_NEWLINE); return; } if ((minute < 0) || (minute > 59)) { printf("%s%s", "Minute must be between 0 and 59", CFG_PRINTF_NEWLINE); return; } if ((second < 0) || (second > 59)) { printf("%s%s", "Second must be between 0 and 59", CFG_PRINTF_NEWLINE); return; } /* Try to create a date */ error = rtcCreateTime(year, month, day, hour, minute, second, 0, &time); if (error) { printf("%s%s", "Invalid timestamp", CFG_PRINTF_NEWLINE); return; } /* Write the time to the RTC */ error = pcf2129SetTime(time); if (error) { printf("%s%s", STRING(LOCALISATION_TEXT_No_response_on_the_I2C_bus), CFG_PRINTF_NEWLINE); return; } }
static void getNumber_StringWithoutNumber_ZeroNum(void ** state) { char str[] = "helloBlaBla"; assert_int_equal(getNumber(str), 0); }
void LapTimeComparisonDialog::updateData() { int scrollBarPosition = ui->tableWidget->verticalScrollBar()->sliderPosition(); QItemSelectionModel * selection = ui->tableWidget->selectionModel(); // for (int i = ui->tableWidget->rowCount()-1; i >= 0; --i) // ui->tableWidget->removeRow(i); QTableWidgetItem *item; int firstLap = 99, lastLap = 0; int index[4]; QString wTitle = "Lap time comparison: "; for (int i = 0; i < 4; ++i) { index[i] = 0; int idx = eventData.getDriverId(getNumber(i)); if (idx > 0) { if (i > 0) wTitle += " - "; wTitle += eventData.getDriversData()[idx-1].getDriverName(); if(!eventData.getDriversData()[idx-1].getLapData().isEmpty()) { if (eventData.getDriversData()[idx-1].getLapData()[0].getLapNumber() < firstLap) firstLap = eventData.getDriversData()[idx-1].getLapData()[0].getLapNumber(); if (eventData.getDriversData()[idx-1].getLapData().last().getLapNumber() > lastLap) lastLap = eventData.getDriversData()[idx-1].getLapData().last().getLapNumber(); } DriverData &dd = eventData.getDriversData()[idx-1]; QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); lab->setPixmap(ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(dd.getNumber(), thumbnailsSize));//eventData.carImages[idx].scaledToWidth(120, Qt::SmoothTransformation)); } else { QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); lab->clear(); } } setWindowTitle(wTitle); // ui->tableWidget->insertRow(0); // ui->tableWidget->setRowHeight(0, 50); int j = 0, k = firstLap; for (; k <= lastLap; ++k, ++j) { int lapNo = lastLap - k + firstLap; LapTime laps[4]; if (ui->tableWidget->rowCount() <= j+1) ui->tableWidget->insertRow(j+1); item = ui->tableWidget->item(j+1, 0); if (!item) { item = new QTableWidgetItem(QString("%1.").arg(lapNo)); // item->setFlags(Qt::ItemIsSelectable); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); ui->tableWidget->setItem(j+1, 0, item); } else item->setText(QString("%1.").arg(lapNo)); for (int i = 0; i < 4; ++i) { int idx = eventData.getDriverId(getNumber(i)); if (idx > 0 && !eventData.getDriversData()[idx-1].getLapData().isEmpty()) { //int lapIndex = (reversedOrder ? eventData.driversData[idx-1].lapData.size() - index[i] - 1 : index[i]); DriverData &dd = eventData.getDriversData()[idx-1]; LapData ld = dd.getLapData(lapNo); // if (j == 0) // { // int idx = (dd.number > 13 ? dd.number-2 : dd.number-1) / 2; // QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); // lab->setPixmap(smallCarImg[idx]);//eventData.carImages[idx].scaledToWidth(120, Qt::SmoothTransformation)); // } if (dd.getLapData().size() > index[i] && ld.getLapNumber() == lapNo && ld.getCarID() != -1) { laps[i] = ld.getTime(); item = ui->tableWidget->item(j+1, i+1); if (!item) { item = new QTableWidgetItem(ld.getTime()); item->setTextAlignment(Qt::AlignCenter); ui->tableWidget->setItem(j+1, i+1, item); } else item->setText(ld.getTime()); if (ld.getTime().toString() == "IN PIT") item->setText(item->text() + " (" + dd.getPitTime(ld.getLapNumber()) + ")"); ++index[i]; } else { item = ui->tableWidget->item(j+1, i+1); if (item) item->setText(""); } } else { if (j == 0) { // QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); // if (lab) // lab->clear(); } item = ui->tableWidget->item(j+1, i+1); if (item) item->setText(""); } } int bestIdx = DriverData::lapDiff(laps); if (bestIdx != -1) { for (int i = 0; i < 4; ++i) { if (i != bestIdx && laps[i].toString() != "" && laps[i].toString() != "IN PIT" && laps[i].toString() != "RETIRED" && !laps[i].toString().contains("LAP")) { item = ui->tableWidget->item(j+1, i+1); if (item) { item->setText(item->text() + " (+"+QString::number(laps[i].toDouble(), 'f', 3)+")"); double msecs[3]; int ji = 0; for (int j = 0; j < 4; ++j) { if (j != bestIdx) { if (laps[j].toString() != "") msecs[ji++] = laps[j].toMsecs(); else msecs[ji++] = 1000000; } } double maxGap = std::max(std::max(msecs[0], msecs[1]), msecs[2]); double minGap = std::min(std::min(msecs[0], msecs[1]), msecs[2]); LTPackets::Colors color = LTPackets::YELLOW; if (laps[i].toMsecs() == minGap) color = LTPackets::WHITE; else if (laps[i].toMsecs() == maxGap) color = LTPackets::RED; item->setTextColor(ColorsManager::getInstance().getColor(color)); } } else if (laps[i].toString() == "IN PIT" || laps[i].toString() == "RETIRED" || laps[i].toString().contains("LAP")) { item = ui->tableWidget->item(j+1, i+1); item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::RED)); } } item = ui->tableWidget->item(j+1, bestIdx+1); if (item && laps[bestIdx].toString() != "IN PIT" && laps[bestIdx].toString() != "RETIRED" && !laps[bestIdx].toString().contains("LAP")) item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::GREEN)); } ui->tableWidget->setRowHeight(j+1, 20); } for (int i = ui->tableWidget->rowCount()-1; i >= j+1; --i) ui->tableWidget->removeRow(i); ui->tableWidget->setSelectionModel(selection); ui->tableWidget->verticalScrollBar()->setSliderPosition(scrollBarPosition); }
//*************************************************************** CInstance *CAutoGroup::getGroupingCandidate() { //H_AUTO(R2_CAutoGroup_getGroupingCandidate) if (!_AutoGroupEnabled) return NULL; // if I'm a bot object, don't auto-group CObject *palEntry = getEditor().getDMC().getPaletteElement(_PaletteEntry); if (!palEntry || !palEntry->isTable()) return NULL; if (getNumber(palEntry, "IsBotObject") == 1) return NULL; // auto-group feature // look in default feature and sort objects by distance CInstance *defaultFeatInst = getEditor().getDefaultFeature(getEditor().getCurrentAct()); CInstance *baseDefaultFeatInst = getEditor().getDefaultFeature(getEditor().getBaseAct()); if (!defaultFeatInst || !baseDefaultFeatInst) { nlwarning("Can't access to Default Features"); // syntax error in lua was making the client crash return NULL; //In this case there is no default features } CObjectTable *defaultFeat = defaultFeatInst->getObjectTable(); CObjectTable *baseDefaultFeat = baseDefaultFeatInst->getObjectTable(); CObject *components = defaultFeat->getAttr("Components"); CObject *baseComponents = baseDefaultFeat->getAttr("Components"); if (!components || !baseComponents || !palEntry->isTable()) return NULL; _SortedComponents.clear(); for (uint k = 0; k < (components->getSize()+baseComponents->getSize()); ++k) { CObject *obj = NULL; if(k<components->getSize()) obj = components->getValue(k); else obj = baseComponents->getValue(k - components->getSize()); CInstance *inst = getEditor().getInstanceFromObject(obj); if (!inst) { nlwarning("Error: can not find create Instance of an object."); continue; } CDisplayerVisual *dv = inst->getDisplayerVisual(); if (!dv) continue; CComponentSort cs; cs.Dist = (_TestPos - dv->getWorldPos()).norm(); if (cs.Dist > CV_AutoGroupMaxDist.get()) continue; cs.Instance = inst; _SortedComponents.push_back(cs); } // iterate through other features CObjectTable *act = getEditor().getCurrentAct()->getObjectTable(); CObjectTable *baseAct = getEditor().getBaseAct()->getObjectTable(); if (!act || !baseAct) return NULL; CObject *features = act->getAttr("Features"); CObject *baseFeatures = baseAct->getAttr("Features"); if (!features || !baseFeatures) return NULL; for (uint k = 0; k < (features->getSize()+baseFeatures->getSize()); ++k) { CObject *obj = NULL; if(k<features->getSize()) obj = features->getValue(k); else obj = baseFeatures->getValue(k - features->getSize()); CInstance *inst = getEditor().getInstanceFromObject(obj); CDisplayerVisual *dv = inst->getDisplayerVisual(); if (!dv) continue; if (inst->isKindOf("NpcGrpFeature")) { if (dv->getNumSons() == 0) continue; CComponentSort cs; cs.Dist = (_TestPos - dv->getSon(0)->getWorldPos()).norm(); if (cs.Dist > CV_AutoGroupMaxDist.get()) continue; cs.Instance = inst; _SortedComponents.push_back(cs); } } std::sort(_SortedComponents.begin(), _SortedComponents.end()); CLuaState &ls = getEditor().getLua(); const CObject *categoryObj = getObject(palEntry, "Category"); if (!categoryObj) { nlwarning("No 'Category' field in palEntry '%s'", _PaletteEntry.c_str()); return NULL; } if (!categoryObj->isString()) return NULL; std::string category = categoryObj->toString(); // const CObject *subCategoryObj = getObject(palEntry, "SubCategory"); std::string subCategory; if (subCategoryObj && subCategoryObj->isString()) { subCategory = subCategoryObj->toString(); } else { //nlwarning("No 'SubCategory' field in palEntry '%s'", paletteEntry.c_str()); } // if (category.empty()) return NULL; for(uint k = 0; k < _SortedComponents.size(); ++k) { CLuaStackRestorer lsr(&ls, 0); if (_SortedComponents[k].Instance->isKindOf("Npc")) { _SortedComponents[k].Instance->getLuaProjection().callMethodByNameNoThrow("isPlant", 0, 1); if (ls.toBoolean(-1) == true) continue; _SortedComponents[k].Instance->getLuaProjection().callMethodByNameNoThrow("isBotObject", 0, 1); if (ls.toBoolean(-1) == true) continue; } else if (!_SortedComponents[k].Instance->isKindOf("NpcGrpFeature")) { continue; } std::string destCategory; if (_SortedComponents[k].Instance->getLuaProjection().callMethodByNameNoThrow("getCategory", 0, 1)) { destCategory = ls.toString(-1); ls.pop(); } if (destCategory != category) continue; // std::string destSubCategory; if (_SortedComponents[k].Instance->getLuaProjection().callMethodByNameNoThrow("getSubCategory", 0, 1)) { if (ls.isString(-1)) { destSubCategory = ls.toString(-1); } ls.pop(); } if (destSubCategory != subCategory) continue; // good candidate return _SortedComponents[k].Instance; } return NULL; }
double DictionaryValue::numberProperty(const String16& name, double defaultValue) const { double result = defaultValue; getNumber(name, &result); return result; }
int DLAPI::Dictionary::getInt(std::string key) { return (int)getNumber(key); }
void ReplicatedMergeTreeBlockOutputStream::commitPart(zkutil::ZooKeeperPtr & zookeeper, MergeTreeData::MutableDataPartPtr & part, const String & block_id) { storage.check(part->columns); assertSessionIsNotExpired(zookeeper); /// Obtain incremental block number and lock it. The lock holds our intention to add the block to the filesystem. /// We remove the lock just after renaming the part. In case of exception, block number will be marked as abandoned. /// Also, make deduplication check. If a duplicate is detected, no nodes are created. /// Allocate new block number and check for duplicates bool deduplicate_block = !block_id.empty(); String block_id_path = deduplicate_block ? storage.zookeeper_path + "/blocks/" + block_id : ""; auto block_number_lock = storage.allocateBlockNumber(part->info.partition_id, zookeeper, block_id_path); if (!block_number_lock) { LOG_INFO(log, "Block with ID " << block_id << " already exists; ignoring it."); part->is_duplicate = true; last_block_is_duplicate = true; ProfileEvents::increment(ProfileEvents::DuplicatedInsertedBlocks); return; } Int64 block_number = block_number_lock->getNumber(); /// Set part attributes according to part_number. Prepare an entry for log. part->info.min_block = block_number; part->info.max_block = block_number; part->info.level = 0; String part_name = part->getNewName(part->info); part->name = part_name; StorageReplicatedMergeTree::LogEntry log_entry; log_entry.type = StorageReplicatedMergeTree::LogEntry::GET_PART; log_entry.create_time = time(nullptr); log_entry.source_replica = storage.replica_name; log_entry.new_part_name = part_name; log_entry.quorum = quorum; log_entry.block_id = block_id; /// Simultaneously add information about the part to all the necessary places in ZooKeeper and remove block_number_lock. /// Information about the part. Coordination::Requests ops; storage.getCommitPartOps(ops, part, block_id_path); /// Replication log. ops.emplace_back(zkutil::makeCreateRequest( storage.zookeeper_path + "/log/log-", log_entry.toString(), zkutil::CreateMode::PersistentSequential)); /// Deletes the information that the block number is used for writing. block_number_lock->getUnlockOps(ops); /** If you need a quorum - create a node in which the quorum is monitored. * (If such a node already exists, then someone has managed to make another quorum record at the same time, but for it the quorum has not yet been reached. * You can not do the next quorum record at this time.) */ if (quorum) { ReplicatedMergeTreeQuorumEntry quorum_entry; quorum_entry.part_name = part_name; quorum_entry.required_number_of_replicas = quorum; quorum_entry.replicas.insert(storage.replica_name); /** At this point, this node will contain information that the current replica received a part. * When other replicas will receive this part (in the usual way, processing the replication log), * they will add themselves to the contents of this node. * When it contains information about `quorum` number of replicas, this node is deleted, * which indicates that the quorum has been reached. */ ops.emplace_back( zkutil::makeCreateRequest( quorum_info.status_path, quorum_entry.toString(), zkutil::CreateMode::Persistent)); /// Make sure that during the insertion time, the replica was not reinitialized or disabled (when the server is finished). ops.emplace_back( zkutil::makeCheckRequest( storage.replica_path + "/is_active", quorum_info.is_active_node_version)); /// Unfortunately, just checking the above is not enough, because `is_active` node can be deleted and reappear with the same version. /// But then the `host` value will change. We will check this. /// It's great that these two nodes change in the same transaction (see MergeTreeRestartingThread). ops.emplace_back( zkutil::makeCheckRequest( storage.replica_path + "/host", quorum_info.host_node_version)); } MergeTreeData::Transaction transaction(storage.data); /// If you can not add a part to ZK, we'll remove it back from the working set. storage.data.renameTempPartAndAdd(part, nullptr, &transaction); Coordination::Responses responses; int32_t multi_code = zookeeper->tryMultiNoThrow(ops, responses); /// 1 RTT if (multi_code == Coordination::ZOK) { transaction.commit(); storage.merge_selecting_task->schedule(); /// Lock nodes have been already deleted, do not delete them in destructor block_number_lock->assumeUnlocked(); } else if (multi_code == Coordination::ZCONNECTIONLOSS || multi_code == Coordination::ZOPERATIONTIMEOUT) { /** If the connection is lost, and we do not know if the changes were applied, we can not delete the local part * if the changes were applied, the inserted block appeared in `/blocks/`, and it can not be inserted again. */ transaction.commit(); storage.enqueuePartForCheck(part->name, MAX_AGE_OF_LOCAL_PART_THAT_WASNT_ADDED_TO_ZOOKEEPER); /// We do not know whether or not data has been inserted. throw Exception("Unknown status, client must retry. Reason: " + String(Coordination::errorMessage(multi_code)), ErrorCodes::UNKNOWN_STATUS_OF_INSERT); } else if (Coordination::isUserError(multi_code)) { String failed_op_path = zkutil::KeeperMultiException(multi_code, ops, responses).getPathForFirstFailedOp(); if (multi_code == Coordination::ZNODEEXISTS && deduplicate_block && failed_op_path == block_id_path) { /// Block with the same id have just appeared in table (or other replica), rollback thee insertion. LOG_INFO(log, "Block with ID " << block_id << " already exists; ignoring it (removing part " << part->name << ")"); part->is_duplicate = true; transaction.rollback(); last_block_is_duplicate = true; ProfileEvents::increment(ProfileEvents::DuplicatedInsertedBlocks); } else if (multi_code == Coordination::ZNODEEXISTS && failed_op_path == quorum_info.status_path) { transaction.rollback(); throw Exception("Another quorum insert has been already started", ErrorCodes::UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE); } else { /// NOTE: We could be here if the node with the quorum existed, but was quickly removed. transaction.rollback(); throw Exception("Unexpected logical error while adding block " + toString(block_number) + " with ID '" + block_id + "': " + zkutil::ZooKeeper::error2string(multi_code) + ", path " + failed_op_path, ErrorCodes::UNEXPECTED_ZOOKEEPER_ERROR); } } else if (Coordination::isHardwareError(multi_code)) { transaction.rollback(); throw Exception("Unrecoverable network error while adding block " + toString(block_number) + " with ID '" + block_id + "': " + zkutil::ZooKeeper::error2string(multi_code), ErrorCodes::UNEXPECTED_ZOOKEEPER_ERROR); } else { transaction.rollback(); throw Exception("Unexpected ZooKeeper error while adding block " + toString(block_number) + " with ID '" + block_id + "': " + zkutil::ZooKeeper::error2string(multi_code), ErrorCodes::UNEXPECTED_ZOOKEEPER_ERROR); } if (quorum) { /// We are waiting for quorum to be satisfied. LOG_TRACE(log, "Waiting for quorum"); String quorum_status_path = storage.zookeeper_path + "/quorum/status"; try { while (true) { zkutil::EventPtr event = std::make_shared<Poco::Event>(); std::string value; /// `get` instead of `exists` so that `watch` does not leak if the node is no longer there. if (!zookeeper->tryGet(quorum_status_path, value, nullptr, event)) break; ReplicatedMergeTreeQuorumEntry quorum_entry(value); /// If the node has time to disappear, and then appear again for the next insert. if (quorum_entry.part_name != part_name) break; if (!event->tryWait(quorum_timeout_ms)) throw Exception("Timeout while waiting for quorum", ErrorCodes::TIMEOUT_EXCEEDED); } /// And what if it is possible that the current replica at this time has ceased to be active and the quorum is marked as failed and deleted? String value; if (!zookeeper->tryGet(storage.replica_path + "/is_active", value, nullptr) || value != quorum_info.is_active_node_value) throw Exception("Replica become inactive while waiting for quorum", ErrorCodes::NO_ACTIVE_REPLICAS); } catch (...) { /// We do not know whether or not data has been inserted /// - whether other replicas have time to download the part and mark the quorum as done. throw Exception("Unknown status, client must retry. Reason: " + getCurrentExceptionMessage(false), ErrorCodes::UNKNOWN_STATUS_OF_INSERT); } LOG_TRACE(log, "Quorum satisfied"); } }
static void menu_long_select_callback(MenuLayer *me, MenuIndex *cell_index, void *data) { if (strlen(getNumber(cell_index->row)) == 0) return; sendpickedEntry(cell_index->row, 1); }
static void getNumber_StringWithIntNumber_ZeroNum(void ** state) { char str[] = "HelloWorld3"; assert_int_equal(getNumber(str), 0); }
//------------------------------------------------------------- // returns the absolute value BigInteger BigInteger::absolute() { return BigInteger( getNumber() ); // +ve by default }
static void getNumber_StringWithNumbers_cnt(void ** state) { char str[] = "BlahBlah2.0h7.2"; assert_int_equal(getNumber(str), 2); }
//MAIN FUNCTION void makeTree(){ //Declare initial variables const int n_variables(11); std::string line; std::string date, clock; std::string dv[n_variables],dne[n_variables],dpe[n_variables]; //Data structure for HV variables struct HVdata{ double value, negError, posError; char severity[20], status[20]; }; //Data structure for time variables struct HVtime{ int year, month, day, hour, minute, second, millisecond, date, clock; }; //Initiate variables HVdata data[n_variables]; HVtime time; //Create TFile, TTree and TBranches TFile *f = new TFile("OutTree.root","RECREATE"); TTree *tree = new TTree("Tree","Tree for data from HV"); tree->Branch("Time",&time.year,"year/I:month:day:hour:minute:second:millisecond:date:clock"); tree->Branch("uB_TPCDrift_HV01_keithleyPickOff_getVoltage",&data[0].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_TPCDrift_HV01_keithleyCurrMon_calcCurrent",&data[1].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_OnDetPower_TPCPS_1_1_0_CURR_READ",&data[2].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_OnDetPower_TPCPS_1_1_2_CURR_READ",&data[3].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_OnDetPower_TPCPS_1_1_4_CURR_READ",&data[4].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_OnDetPower_TPCPS_1_1_6_CURR_READ",&data[5].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_PMTHV_TRPM_M2C0_CURR",&data[6].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_TPCDrift_HV01_keithleyPickOff_voltDiff5s60s",&data[7].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_TPCDrift_HV01_1_0_voltage",&data[8].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_Cryo_IFIX_1_0_LAR_PUMP_1_FORWARD",&data[9].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); tree->Branch("uB_TPCDrift_HV01_keithleyCurrMon_getVoltage",&data[10].value,"value/D:negError:posError:severity[20]/C:status[20]/C"); //Open file and read out the values std::fstream Input; std::string filenameDATA = "HVdata.dat"; //Opening file Input.open(filenameDATA.c_str(), std::ios::in); if(Input.is_open()){ while(std::getline(Input,line,'\n')){ //Read all values as strings provided line is not empty or commented if(line[0] != '#' && line.length()>0){ stringstream(line) >> date >> clock >> dv[0] >> dne[0] >> dpe[0] >> data[0].severity >> data[0].status >> dv[1] >> dne[1] >> dpe[1] >> data[1].severity >> data[1].status >> dv[2] >> dne[2] >> dpe[2] >> data[2].severity >> data[2].status >> dv[3] >> dne[3] >> dpe[3] >> data[3].severity >> data[3].status >> dv[4] >> dne[4] >> dpe[4] >> data[4].severity >> data[4].status >> dv[5] >> dne[5] >> dpe[5] >> data[5].severity >> data[5].status >> dv[6] >> dne[6] >> dpe[6] >> data[6].severity >> data[6].status >> dv[7] >> dne[7] >> dpe[7] >> data[7].severity >> data[7].status >> dv[8] >> dne[8] >> dpe[8] >> data[8].severity >> data[8].status >> dv[9] >> dne[9] >> dpe[9] >> data[9].severity >> data[9].status >> dv[10] >> dne[10] >> dpe[10] >> data[10].severity >> data[10].status; // "value", "negError" and "posError" need to be double, so convert them for(int i=0;i<n_variables;i++){ data[i].value = getNumber(dv[i]); data[i].negError = getNumber(dne[i]); data[i].posError = getNumber(dpe[i]); } //Break down "date" and "clock" strings into time struct values time.year = atoi(date.substr(0,4).c_str()); time.month = atoi(date.substr(5,2).c_str()); time.day = atoi(date.substr(8,2).c_str()); time.hour = atoi(clock.substr(0,2).c_str()); time.minute = atoi(clock.substr(3,2).c_str()); time.second = atoi(clock.substr(6,2).c_str()); time.millisecond = atoi(clock.substr(9,3).c_str()); //Just to have a feeling that the script is running, comment it for faster execution std::cout << date << " " << clock << std::endl; //Save "date" and "clock" as integers (and get rid of '/' and ':' separators) for(int i=0; i<=date.size(); i++){ if(date[i]=='/') { date.erase(i,1); } } for(int i=0; i<=clock.size(); i++){ if(clock[i]==':') { clock.erase(i,1); } } time.date = atoi(date.substr(0,8).c_str()); time.clock = atoi(clock.substr(0,7).c_str()); //Fill TTree tree->Fill(); } } }
static void getNumber_EmptyString_NegatNum(void ** state) { char str[] = ""; assert_int_equal(getNumber(str), -1); }
// Implementation of the inherited pure virtual print function. Notice that I use override // as a nice safety net to make sure I'm actually overriding the function. void print() override { std::cout<< "I'm DerivedFloat: " << getNumber() << " " << mName <<std::endl; }
void GetRexxBlock( ss_block *ss_new, char *start, line *line, linenum line_no ) { line = line; line_no = line_no; if( start[0] == '\0' ) { if( firstNonWS == start ) { // line is empty - // do not flag following line as having anything to do // with an unterminated " or # or // from previous line flags.inString = flags.inPreprocessor = flags.inCPPComment = false; } getBeyondText( ss_new ); return; } if( flags.inCComment ) { getCComment( ss_new, start, 0 ); return; } if( flags.inCPPComment ) { getCPPComment( ss_new, start ); return; } if( flags.inPreprocessor ) { getPreprocessor( ss_new, start ); return; } if( flags.inString ) { getString( ss_new, start, 0 ); return; } if( isspace( start[0] ) ) { getWhiteSpace( ss_new, start ); return; } if( *firstNonWS == '#' && (!EditFlags.PPKeywordOnly || firstNonWS == start) ) { getPreprocessor( ss_new, start ); return; } switch( start[0] ) { case '"': getString( ss_new, start, 1 ); return; case '/': if( start[1] == '*' ) { getCComment( ss_new, start, 2 ); return; } else if( start[1] == '/' ) { getCPPComment( ss_new, start ); return; } break; case '\'': getChar( ss_new, start, 1 ); return; case 'L': if( start[1] == '\'' ) { // wide char constant getChar( ss_new, start, 2 ); return; } break; case '.': if( isdigit( start[1] ) ) { getFloat( ss_new, start, 1, AFTER_DOT ); return; } break; case '0': if( start[1] == 'x' || start[1] == 'X' ) { getHex( ss_new, start ); return; } else { getNumber( ss_new, start, '7' ); return; } break; } if( issymbol( start[0] ) ) { getSymbol( ss_new ); return; } if( isdigit( start[0] ) ) { getNumber( ss_new, start, '9' ); return; } if( isalpha( *start ) || ( *start == '_' ) ) { getText( ss_new, start ); return; } getInvalidChar( ss_new ); }
double DBF::getNumber ( const char *name ) { int nth = field(name) ; return nth < 0 ? -1 : getNumber(nth) ; }
std::vector<unsigned char> ReaderUnit::getNumber(std::shared_ptr<Chip> chip, std::shared_ptr<CardsFormatComposite> composite) { LOG(LogLevel::INFOS) << "Started for chip type {0x" << chip->getCardType() << "(" << chip->getGenericCardType() << ")}"; std::vector<unsigned char> ret; if (composite) { LOG(LogLevel::INFOS) << "Composite used to find the chip identifier {" << std::dynamic_pointer_cast<XmlSerializable>(composite)->serialize() << "}"; composite->setReaderUnit(shared_from_this()); CardTypeList ctList = composite->getConfiguredCardTypes(); if (ctList.size() > 0) { std::string useCardType = chip->getCardType(); CardTypeList::iterator itct = std::find(ctList.begin(), ctList.end(), useCardType); // Try to use the generic card type if (itct == ctList.end()) { useCardType = chip->getGenericCardType(); LOG(LogLevel::INFOS) << "No configuration found for the chip type ! Looking for the generic type (" << useCardType << ") configuration..."; itct = std::find(ctList.begin(), ctList.end(), useCardType); } // Try to use the configuration for all card (= generic tag), because the card type isn't configured if (itct == ctList.end()) { LOG(LogLevel::INFOS) << "No configuration found for the chip type ! Looking for \"GenericTag\" configuration..."; useCardType = "GenericTag"; itct = std::find(ctList.begin(), ctList.end(), useCardType); } // Try to read the number only if a configuration exists (for this card type or default) if (itct != ctList.end()) { LOG(LogLevel::INFOS) << "Configuration found in the composite ! Retrieving format for card..."; std::shared_ptr<AccessInfo> ai; std::shared_ptr<Location> loc; std::shared_ptr<Format> format; composite->retrieveFormatForCard(useCardType, &format, &loc, &ai); if (format) { LOG(LogLevel::INFOS) << "Format retrieved successfully ! Reading the format..."; format = composite->readFormat(chip); // Read format on chip if (format) { LOG(LogLevel::INFOS) << "Format read successfully ! Getting identifier..."; ret = format->getIdentifier(); } else { LOG(LogLevel::ERRORS) << "Unable to read the format !"; } } else { LOG(LogLevel::WARNINGS) << "Cannot retrieve the format for card ! Trying using getNumber directly..."; ret = getNumber(chip); } } else { LOG(LogLevel::ERRORS) << "No configuration found !"; } } else { LOG(LogLevel::INFOS) << "Composite card format is NOT NULL, but no card configuration ! Reader chip identifier directly..."; ret = chip->getChipIdentifier(); } } else { LOG(LogLevel::INFOS) << "Composite card format is NULL ! Reader chip identifier directly..."; ret = chip->getChipIdentifier(); } LOG(LogLevel::INFOS) << "Returns number " << BufferHelper::getHex(ret); return ret; }
void doCreate(FILE *stream) { int x, y; x = getNumber(stream); y = getNumber(stream); image = gdImageCreate(x, y); }
std::vector<unsigned char> ReaderUnit::getNumber(std::shared_ptr<Chip> chip) { // Read encoded format if specified in the license. return getNumber(chip, std::shared_ptr<CardsFormatComposite>()); }
void doGene(FILE *stream) { int i, start, end, rstart, rend, y, strand, nsmall, nlarge, color; int *small, *large; start = getNumber(stream); end = getNumber(stream); y = getNumber(stream); strand = getNumber(stream); /* 0, 1, or -1 */ color = getNumber(stream); rstart = viewx(start); rend = viewx(end); y = viewy(y); // fprintf(stderr, "%d->%d, %d->%d\n", start, rstart, end, rend); gdImageLine(image, rstart, y, rend, y, color); if (strand == 1) { for (i = rstart+2; i < rend-2; i = i+5) { gdImageSetPixel(image, i, y-1, color); gdImageSetPixel(image, i-1, y-2, color); gdImageSetPixel(image, i, y+1, color); gdImageSetPixel(image, i-1, y+2, color); } } else if (strand == -1) { for (i = rstart+2; i < rend-2; i = i+5) { gdImageSetPixel(image, i, y-1, color); gdImageSetPixel(image, i+1, y-2, color); gdImageSetPixel(image, i, y+1, color); gdImageSetPixel(image, i+1, y+2, color); } } nsmall = getNumber(stream); for (i = 0; i < nsmall; i++) { start = getNumber(stream); end = getNumber(stream); gdImageFilledRectangle(image, viewx(start), y-4, viewx(end), y+4, color); } nlarge = getNumber(stream); for (i = 0; i < nlarge; i++) { start = getNumber(stream); end = getNumber(stream); // fprintf(stderr, "%d->%d, %d->%d\n", start, viewx(start), end, viewx(end)); gdImageFilledRectangle(image, viewx(start), y-6, viewx(end), y+6, color); } }
static int16_t menu_get_row_height_callback(MenuLayer *me, MenuIndex *cell_index, void *data) { return (strlen(getNumber(cell_index->row)) == 0 ? 40 : 55); }
void PhoneDetails::textChanged(const QString&) { getNumber(); }
// getFloat is an alias of getNumber to avoid mistakes, // since a lot of the time the floating point is // not explicitly written for integral values, // making json_real_value return 0 double JSON::getFloat(const char *key) { return getNumber(key); }