/* You must call makeInterrupt21() before this function will work. */ void handleInterrupt21(int ax, int bx, int cx, int dx) { switch(ax) { case 0: printString(bx); break; case 1: readString(bx); break; case 2: readSector(bx,cx); break; case 3: readFile(bx,cx,dx); break; case 4: runProgram(bx,cx); break; case 5: stop(); break; case 6: writeSector(bx,cx); break; case 7: deleteFile(bx); break; case 8: writeFile(bx,cx,dx); break; case 11: interrupt(25,0,0,0,0); break; case 12: clearScreen(bx, cx); break; case 13: writeInt(bx); break; case 14: readInt(bx); break; case 15: error(bx); break; default: printString("ERROR: Requested service does not exist."); } }
static void readBytes( gzFile file, std::vector<uint8_t>& bytes ) { int count = readInt( file ); bytes.resize( count ); gzread( file, bytes.begin(), count ); }
wyArcticFileData* wyArcticLoader::load(const char* data, size_t length, float resScale) { wyArcticFileData* afd = wyArcticFileData::make(); s_data = data; s_pos = 0; // set scale afd->m_resScale = resScale; // version afd->m_version = readShort(); // skip id for other editor if(afd->m_version > 0x30) skip(4); // flags afd->m_flags = readInt(); // read all modules if((afd->m_flags & AS_MODULES) != 0) { // module count afd->m_moduleCount = readShort(); if(afd->m_moduleCount > 0) { // allocate memory afd->m_modules = (wyArcticModule*)wyCalloc(afd->m_moduleCount, sizeof(wyArcticModule)); for(int i = 0; i < afd->m_moduleCount; i++) { wyArcticModule* module = afd->m_modules + i; // image index if((afd->m_flags & AS_MODULES_IMG) != 0) { module->imageIndex = readByte(); } // location if((afd->m_flags & AS_MODULES_XY) != 0) { if((afd->m_flags & AS_MODULES_XY_SHORT) != 0) { module->x = readShort(); module->y = readShort(); } else { module->x = readByte(); module->y = readByte(); } } // size if((afd->m_flags & AS_MODULES_WH_SHORT) != 0) { module->w = readShort(); module->h = readShort(); } else { module->w = readByte(); module->h = readByte(); } } } } // read all frames if((afd->m_flags & AS_FRAMES) != 0) { // count of frame modules afd->m_frameModuleCount = readShort(); // read all frame modules if(afd->m_frameModuleCount > 0) { afd->m_frameModules = (wyArcticFrameModule*)wyCalloc(afd->m_frameModuleCount, sizeof(wyArcticFrameModule)); for(int i = 0; i < afd->m_frameModuleCount; i++) { wyArcticFrameModule* fm = afd->m_frameModules + i; fm->index = readByte(); if((afd->m_flags & AS_FM_OFF_SHORT) != 0) { fm->x = readShort(); fm->y = readShort(); } else { fm->x = readByte(); fm->y = readByte(); } fm->flags = readByte(); } } // count of frames afd->m_frameCount = readShort(); // read all frames if(afd->m_frameCount > 0) { afd->m_frames = (wyArcticFrame*)wyCalloc(afd->m_frameCount, sizeof(wyArcticFrame)); for(int i = 0; i < afd->m_frameCount; i++) { wyArcticFrame* f = afd->m_frames + i; f->moduleCount = readByte(); f->firstModuleIndex = readShort(); } } // read collision rect of this frame if((afd->m_flags & AS_FRAME_COL_RC) != 0) { for(int i = 0; i < afd->m_frameCount; i++) { wyArcticFrame* f = afd->m_frames + i; f->collisionRectCount = readByte(); if(f->collisionRectCount > 0) { f->collisionRects = (wyRect*)wyCalloc(f->collisionRectCount, sizeof(wyRect)); wyRect* r = f->collisionRects; for(int j = 0; j < f->collisionRectCount; j++, r++) { r->x = readShort(); r->y = readShort(); r->width = readShort(); r->height = readShort(); } } } } } // read all animations if((afd->m_flags & AS_ANIMS) != 0) { // count of animation frames afd->m_animationFrameCount = readShort(); // read all animation frames if(afd->m_animationFrameCount > 0) { afd->m_animationFrames = (wyArcticAnimationFrame*)wyCalloc(afd->m_animationFrameCount, sizeof(wyArcticAnimationFrame)); for(int i = 0; i < afd->m_animationFrameCount; i++) { wyArcticAnimationFrame* af = afd->m_animationFrames + i; af->index = readByte(); af->delay = readByte(); if((afd->m_flags & AS_AF_OFF_SHORT) != 0) { af->offsetX = readShort(); af->offsetY = readShort(); } else { af->offsetX = readByte(); af->offsetY = readByte(); } af->flags = readByte(); } } // count of animations afd->m_animationCount = readShort(); // read all animations if(afd->m_animationCount > 0) { afd->m_animations = (wyArcticAnimation*)wyCalloc(afd->m_animationCount, sizeof(wyArcticAnimation)); for(int i = 0; i < afd->m_animationCount; i++) { wyArcticAnimation* a = afd->m_animations + i; // number of animation frame if((afd->m_flags & AS_AF_NUM_SHORT) != 0) a->frameCount = readShort(); else a->frameCount = readByte(); // first animation index a->firstFrameIndex = readShort(); } } } return afd; }
void GuitarPro5::read(QFile* fp) { f = fp; readInfo(); readLyrics(); readPageSetup(); previousDynamic = -1; previousTempo = -1; //previousDynamic = new int [staves * VOICES]; // initialise the dynamics to 0 //for (int i = 0; i < staves * VOICES; i++) // previousDynamic[i] = 0; tempo = readInt(); if (version > 500) skip(1); key = readInt(); /* int octave =*/ readChar(); // octave readChannels(); skip(42); measures = readInt(); staves = readInt(); slurs = new Slur*[staves]; for (int i = 0; i < staves; ++i) slurs[i] = 0; int tnumerator = 4; int tdenominator = 4; for (int i = 0; i < measures; ++i) { if (i > 0) skip(1); GpBar bar; uchar barBits = readUChar(); if (barBits & SCORE_TIMESIG_NUMERATOR) tnumerator = readUChar(); if (barBits & SCORE_TIMESIG_DENOMINATOR) tdenominator = readUChar(); if (barBits & SCORE_REPEAT_START) bar.repeatFlags = bar.repeatFlags | Repeat::START; if (barBits & SCORE_REPEAT_END) { // number of repeats bar.repeatFlags = bar.repeatFlags |Repeat::END; bar.repeats = readUChar(); } if (barBits & SCORE_MARKER) { bar.marker = readDelphiString(); // new section? /*int color =*/ readInt(); // color? } if (barBits & SCORE_VOLTA) { // a volta uchar voltaNumber = readUChar(); while (voltaNumber > 0) { // voltas are represented as flags bar.volta.voltaType = GP_VOLTA_FLAGS; bar.volta.voltaInfo.append(voltaNumber & 1); voltaNumber >>= 1; } } if (barBits & SCORE_KEYSIG) { int currentKey = readUChar(); /* key signatures are specified as * 1# = 1, 2# = 2, ..., 7# = 7 * 1b = 255, 2b = 254, ... 7b = 249 */ bar.keysig = currentKey <= 7 ? currentKey : -256+currentKey; readUChar(); // specified major/minor mode } if (barBits & SCORE_DOUBLE_BAR) bar.barLine = BarLineType::DOUBLE; if (barBits & 0x3) skip(4); if ((barBits & 0x10) == 0) skip(1); readChar(); // triple feel (none, 8, 16) bar.timesig = Fraction(tnumerator, tdenominator); bars.append(bar); }
int main(void) { unsigned int bcd_max = BCDCapacity; unsigned framestream = 0; // Números de frames a executar unsigned int dma_t_ok; // Transferência RAM para DMA_VGA finalizado em 0 unsigned int pixel; // pixel lido da RAM unsigned int l, c; // indexadores de linhas e colunas // Divide por 4 pois ponteiro é por palavra (?) img = (int*) dataImgAddressI/4; for (framestream = 0; framestream < frameStream; framestream++){ readInt(&zoomCfg); readInt(&contrastecfg); if (zoomCfg == ZINACTIVE) { // Zoom inativo // escrita em memória sem ZOOM for(l = 0; l < totalPixelImagem; l++){ bcd_max = bcdRSt(); while(bcd_max <= 0){ // pooling? bcd_max = bcdRSt(); } // leitura do buffer pixel = bcdRRd(); // escrita em memória mem = img + l; *mem = (int) pixel; } } else { // Zoom Ativo for(l = 0; l < alturaImagem; l++){ for(c = 0; c < larguraImagem; c++){ bcd_max = bcdRSt(); while(bcd_max <= 0){ // pooling? bcd_max = bcdRSt(); } // leitura do buffer pixel = bcdRRd(); // Replica para posição original mem = img + l*larguraImagem + c; *mem = (int) pixel; // Replica para posição original+1 mem = img + l*larguraImagem + (c+1); *mem = (int) pixel; // Replica para próxima linha na posição original mem = img + (l+1)*larguraImagem + c; *mem = (int) pixel; // Replica para próxima linha na posição original+1 mem = img + (l+1)*larguraImagem + (c+1); *mem = (int) pixel; c++; } l++; } } // if (zoomCfg == ZINACTIVE) else // Envio para VGA // dmaVGA_init(a, w, s); dmaVGA_init(dataImgAddressI, 4, totalPixelImagem); dma_t_ok = dmaVGA_st(); while(dma_t_ok != 0){ dma_t_ok = dmaVGA_st(); } } // for (framestream = 0; framestream < frameStream; framestream++){ dmaVGA_closeFile(); // while(1){ // dumb core // } return 0; }
int Page::getLocalDepth(){ return readInt( 0,3 ); }
int GuitarPro5::readBeat(int tick, int voice, Measure* measure, int staffIdx, Tuplet** tuplets, bool /*mixChange*/) { uchar beatBits = readUChar(); bool dotted = beatBits & BEAT_DOTTED; slide = -1; int track = staffIdx * VOICES + voice; if (slides.contains(track)) slide = slides.take(track); int pause = -1; if (beatBits & BEAT_PAUSE) pause = readUChar(); // readDuration int len = readChar(); int tuple = 0; if (beatBits & BEAT_TUPLET) tuple = readInt(); Segment* segment = measure->getSegment(Segment::Type::ChordRest, tick); if (beatBits & BEAT_CHORD) { int numStrings = score->staff(staffIdx)->part()->instr()->stringData()->strings(); skip(17); QString name = readPascalString(21); skip(4); // no header to be read in the GP5 format - default to true. readChord(segment, staffIdx * VOICES, numStrings, name, true); skip(32); } Lyrics* lyrics = 0; if (beatBits & BEAT_LYRICS) { QString txt = readDelphiString(); lyrics = new Lyrics(score); lyrics->setText(txt); } gpLyrics.beatCounter++; if (gpLyrics.beatCounter >= gpLyrics.fromBeat && gpLyrics.lyricTrack == staffIdx+1) { int index = gpLyrics.beatCounter - gpLyrics.fromBeat; if (index < gpLyrics.lyrics.size()) { lyrics = new Lyrics(score); lyrics->setText(gpLyrics.lyrics[index]); } } int beatEffects = 0; if (beatBits & BEAT_EFFECTS) beatEffects = readBeatEffects(track, segment); if (beatBits & BEAT_MIX_CHANGE) readMixChange(measure); int strings = readUChar(); // used strings mask Fraction l = len2fraction(len); // Some beat effects could add a Chord before this ChordRest* cr = segment->cr(track); if (voice != 0 && pause == 0 && strings == 0) cr = 0; else { if (strings == 0) { if (cr) { segment->remove(cr); delete cr; cr = 0; } cr = new Rest(score); } else { if (!cr) cr = new Chord(score); } cr->setTrack(track); TDuration d(l); d.setDots(dotted ? 1 : 0); if (dotted) l = l + (l/2); if (tuple) { Tuplet* tuplet = tuplets[staffIdx * 2 + voice]; if ((tuplet == 0) || (tuplet->elementsDuration() == tuplet->baseLen().fraction() * tuplet->ratio().numerator())) { tuplet = new Tuplet(score); // int track = staffIdx * 2 + voice; tuplets[staffIdx * 2 + voice] = tuplet; tuplet->setTrack(cr->track()); setTuplet(tuplet, tuple); tuplet->setParent(measure); } tuplet->setTrack(cr->track()); tuplet->setBaseLen(l); tuplet->setDuration(l * tuplet->ratio().denominator()); cr->setTuplet(tuplet); tuplet->add(cr); } cr->setDuration(l); if (cr->type() == Element::Type::REST && (pause == 0 || l == measure->len())) cr->setDurationType(TDuration::DurationType::V_MEASURE); else cr->setDurationType(d); if(!segment->cr(track)) segment->add(cr); Staff* staff = cr->staff(); int numStrings = staff->part()->instr()->stringData()->strings(); bool hasSlur = false; for (int i = 6; i >= 0; --i) { if (strings & (1 << i) && ((6-i) < numStrings)) { Note* note = new Note(score); if (dotted) { // there is at most one dotted note in this guitar pro version NoteDot* dot = new NoteDot(score); dot->setIdx(0); dot->setParent(note); dot->setTrack(track); // needed to know the staff it belongs to (and detect tablature) dot->setVisible(true); note->add(dot); } static_cast<Chord*>(cr)->add(note); hasSlur = readNote(6-i, note); note->setTpcFromPitch(); } } createSlur(hasSlur, staffIdx, cr); if (lyrics) cr->add(lyrics); } int rr = readChar(); if (cr && (cr->type() == Element::Type::CHORD)) { Chord* chord = static_cast<Chord*>(cr); applyBeatEffects(chord, beatEffects); if (rr == ARPEGGIO_DOWN) chord->setStemDirection(MScore::Direction::DOWN); else if (rr == ARPEGGIO_UP) chord->setStemDirection(MScore::Direction::UP); } int r = readChar(); if (r & 0x8) { int rrr = readChar(); qDebug(" 3beat read 0x%02x", rrr); } if (cr && (cr->type() == Element::Type::CHORD) && slide > 0) createSlide(slide, cr, staffIdx); restsForEmptyBeats(segment, measure, cr, l, track, tick); return cr ? cr->actualTicks() : measure->ticks(); }
void ParseOBJ::readFace() { // Ensure that we have a material if (isNull(m_currentMaterial)) { m_currentMaterial = m_currentMaterialLibrary.materialTable["default"]; } // Ensure that we have a group if (isNull(m_currentGroup)) { // Create a group named "default", per the OBJ specification m_currentGroup = Group::create(); m_currentGroup->name = "default"; groupTable.set(m_currentGroup->name, m_currentGroup); // We can't have a mesh without a group, but conservatively reset this anyway m_currentMesh.reset(); } // Ensure that we have a mesh if (isNull(m_currentMesh)) { bool created = false; shared_ptr<Mesh>& m = m_currentGroup->meshTable.getCreate(m_currentMaterial, created); if (created) { m = Mesh::create(); m->material = m_currentMaterial; } m_currentMesh = m; } Face& face = m_currentMesh->faceArray.next(); const int vertexArraySize = vertexArray.size(); const int texCoordArraySize = texCoord0Array.size(); const int normalArraySize = normalArray.size(); // Consume leading whitespace bool done = maybeReadWhitespace(); while (! done) { Index& index = face.next(); // Read index index.vertex = readInt(); if (index.vertex > 0) { // Make 0-based --index.vertex; } else { // Negative; make relative to the current end of the array. // -1 will be the last element, so just add the size of the array. index.vertex += vertexArraySize; } if ((remainingCharacters > 0) && (*nextCharacter == '/')) { // Read the slash consumeCharacter(); if (remainingCharacters > 0) { if (*nextCharacter != '/') { // texcoord index index.texCoord = readInt(); if (index.texCoord > 0) { // Make 0-based --index.texCoord; } else { // Negative; make relative to the current end // of the array. -1 will be the last element, // so just add the size of the array. index.texCoord += texCoordArraySize; } } if ((remainingCharacters > 0) && (*nextCharacter == '/')) { // Consume the slash consumeCharacter(); // normal index index.normal = readInt(); if (index.normal > 0) { // Make 0-based --index.normal; } else { // Negative; make relative to the current // end of the array. -1 will be the last // element, so just add the size of the // array. index.normal += normalArraySize; } } } } // Read remaining whitespace done = maybeReadWhitespace(); } }
void BPlusTree::insertInParent(TreeNode *node, int startKeyInSplitNode, int splitNodeId, TreeNode** trace, int level) { BufferManager *bm = BufferManager::getInstance(dbName); //cout<<endl<<"level: "<<level<<"startKeyInSplitNode: "<<startKeyInSplitNode<<endl; if (level == 0) { //cout<<"parent is root"<<endl; int newId = StorageManager::allocateBlock(dbName); char* newNodeBuff = bm->pinPage(newId); TreeNode *newNode = new TreeNode(newNodeBuff); //copying the content of old root to new node moveBytes(root->getBuffPage(), newNode->getBuffPage(), BLOCK_SIZE); root->setNoPairs(1); root->setIsLeaf(0); writeInt(root->getBuffPage(), 2 * SIZE_INT, newId); writeInt(root->getBuffPage(), 2 * SIZE_INT + PTR_SIZE, startKeyInSplitNode); writeInt(root->getBuffPage(), 2 * SIZE_INT + PAIR_SIZE, splitNodeId); bm->unpinPage(newId, true); delete newNode; cout << "parent is root: done" << endl; } else { //cout<<"else case entered"<<endl; TreeNode *parentNode = trace[level - 1]; int noPairs = parentNode->getNoPairs(); cout << "no of pairs" << noPairs << endl; if (noPairs < maxNoPairs) { //int childId = getDiskBlockId( node->getBuffPage() ); int firstKeyInNode = readInt(node->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); int keyCount; int ithKey = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); for (keyCount = 0; keyCount < noPairs && firstKeyInNode >= ithKey; keyCount++) { ithKey = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE); } cout << " keycount: " << keyCount << " stop Key " << ithKey << endl; if (keyCount < noPairs) { moveBytes(parentNode->getBuffPage() + 2 * SIZE_INT + keyCount * PAIR_SIZE + PTR_SIZE, parentNode->getBuffPage() + 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE, (noPairs - keyCount) * PAIR_SIZE); //writes split key writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + keyCount * PAIR_SIZE + PTR_SIZE, startKeyInSplitNode); //writes split node id just after split key writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE, splitNodeId); } else { //writes split key to k of nth pair(new apir) writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + noPairs * PAIR_SIZE + PTR_SIZE, startKeyInSplitNode); //writes splitNodeId to p(n)( at the end) writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + (noPairs + 1) * PAIR_SIZE, splitNodeId); } parentNode->setNoPairs(noPairs + 1); bm->unpinPage(trace[level]->getBuffPage(), true); delete trace[level]; for (int i = level - 1; i >= 1; i--) { bm->unpinPage(trace[i]->getBuffPage(), false); delete trace[i]; } } else { cout << "parent splitting" << endl; int newNodeId = StorageManager::allocateBlock(dbName); char* newNodeBuff = bm->pinPage(newNodeId); TreeNode *newNode = new TreeNode(newNodeBuff); char temp[BLOCK_SIZE + 1]; moveBytes(parentNode->getBuffPage() + 2 * SIZE_INT, temp, BLOCK_SIZE - 2 * SIZE_INT); int keyCount; int ithKey = readInt(temp, PTR_SIZE); for (keyCount = 0; keyCount < maxNoPairs && startKeyInSplitNode > ithKey; keyCount++) { ithKey = readInt(temp, (keyCount + 1) * PAIR_SIZE + PTR_SIZE); } if (keyCount < maxNoPairs) { moveBytes(temp + keyCount * PAIR_SIZE + PTR_SIZE, temp + (keyCount + 1) * PAIR_SIZE + PTR_SIZE, (maxNoPairs - keyCount) * PAIR_SIZE); writeInt(temp, keyCount * PAIR_SIZE + PTR_SIZE, startKeyInSplitNode); writeInt(temp, (keyCount + 1) * PAIR_SIZE, splitNodeId); } else { writeInt(temp, maxNoPairs * PAIR_SIZE + PTR_SIZE, startKeyInSplitNode); writeInt(temp, (maxNoPairs + 1) * PAIR_SIZE, splitNodeId); } moveBytes(temp, parentNode->getBuffPage() + 2 * SIZE_INT, (maxNoPairs / 2) * PAIR_SIZE + PTR_SIZE); int splitKey = readInt(temp, (maxNoPairs / 2) * PAIR_SIZE + PTR_SIZE); moveBytes(temp + (maxNoPairs / 2 + 1) * PAIR_SIZE, newNode->getBuffPage() + 2 * SIZE_INT, ((maxNoPairs + 1) / 2) * PAIR_SIZE + PTR_SIZE); parentNode->setNoPairs(maxNoPairs / 2); newNode->setNoPairs((maxNoPairs + 1) / 2); newNode->setIsLeaf(0); bm->unpinPage(newNodeId, true); delete newNode; insertInParent(parentNode, splitKey, newNodeId, trace, level - 1); bm->unpinPage(trace[level]->getBuffPage(), true); delete trace[level]; } } cout << "done" << endl; }
void readSubspace (Subspace *s, const char* trainingFile, int quiet) { int i, j, headerSize, rowDim, colDim; char junk[FILE_LINE_LENGTH], text[FILE_LINE_LENGTH]; char** header; float ftemp; FILE* file; headerSize = 255; header = (char**) malloc (sizeof(char*) * headerSize); assert (header); for (i = 0; i < headerSize; i++) { header[i] = (char*) malloc(sizeof(char) * FILE_LINE_LENGTH); assert (header[i]); } file = fopen (trainingFile, "rb"); if (!file) { printf("Error: could not open file <%s>\n", trainingFile); exit(1); } for (i = 0; i < headerSize; i++) fgets(header[i], FILE_LINE_LENGTH, file); if (!quiet) { printf("\nTraining Header File is:\n"); for (i = 0; i < TRAINING_HEADER_ENTRIES; i++) printf(" Line %d: %s", i, header[i]); } sscanf(header[7], "%s%s%d", junk, junk, &s->basisDim); sscanf(header[4], "%s%*s%s", junk, text); if (strcmp(text, "NO") == 0) s->useLDA = 0; else s->useLDA = 1; /*START: Changed by Zeeshan: for LPP*/ sscanf(header[10], "%s%*s%s", junk, text); if (strcmp(text, "NO") == 0) s->useLPP = 0; else s->useLPP = 1; sscanf(header[11], "%s%s%d", junk, junk, &s->neighbourCount); sscanf(header[12], "%s%*s%s", junk, text); s->lppDistance = strdup(text); sscanf(header[13], "%s%s%d", junk, junk, &s->lppKeepNVectors); sscanf(header[14], "%s%s%d", junk, junk, &s->useAdaptiveK); /*END: Changed by Zeeshan: for LPP*/ /*START: Changed by Zeeshan: for ICA*/ sscanf(header[15], "%s%*s%s", junk, text); if (strcmp(text, "NO") == 0) s->useICA = 0; else s->useICA = 1; sscanf(header[16], "%s%s%d", junk, junk, &s->blockSize); sscanf(header[17], "%s%s%e", junk, junk, &ftemp); s->learningRate = (double)ftemp; sscanf(header[18], "%s%s%d", junk, junk, &s->iterations); sscanf(header[19], "%s%s%d", junk, junk, &s->arch); /*END: Changed by Zeeshan: for ICA*/ readInt (file,&rowDim); s->numPixels = rowDim; DEBUG_INT (3, "Vector size", rowDim); s->mean = makeMatrix(rowDim, 1); for (i = 0; i < (s->mean)->row_dim; i++) { readDouble (file, &ME(s->mean,i,0)); } readInt (file,&rowDim); s->values = makeMatrix (rowDim, 1); for (i = 0; i < (s->values)->row_dim; i++) { readDouble (file, &ME(s->values,i,0)); } rowDim = s->numPixels; readInt (file,&colDim); s->basis = makeMatrix (rowDim, colDim); for (i = 0; i < (s->basis)->col_dim; i++) { for (j = 0; j < (s->basis)->row_dim; j++) { readDouble (file, &ME(s->basis, j, i)); } } if(s->useICA) { /*START: Changed by Zeeshan: for ICA*/ readInt (file,&rowDim); readInt (file,&colDim); s->ica2Basis = makeMatrix (rowDim, colDim); for (i = 0; i < (s->ica2Basis)->col_dim; i++) { for (j = 0; j < (s->ica2Basis)->row_dim; j++) { readDouble (file, &ME(s->ica2Basis, j, i)); } } /*END: Changed by Zeeshan: for ICA*/ } fclose(file); }
unsigned int CCBuffer::readUInt() { DO_RETURN_R(TO_UINT(readInt())); }
GLuint Model::loadTexture(const std::string& strFilename) { GLuint pId=0; if(stricmp(strrchr(strFilename.c_str(),'.'),".raw")==0) { // open the texture file std::ifstream file; file.open(strFilename.c_str(), std::ios::in | std::ios::binary); if(!file) { std::cerr << "Texture file '" << strFilename << "' not found." << std::endl; return 0; } // load the dimension of the texture int width = readInt(&file); int height = readInt(&file); int depth = readInt(&file); // allocate a temporary buffer to load the texture to unsigned char *pBuffer; pBuffer = new unsigned char[width * height * depth]; if(pBuffer == 0) { std::cerr << "Memory allocation for texture '" << strFilename << "' failed." << std::endl; return 0; } // load the texture file.read((char *)pBuffer, width * height * depth); // explicitely close the file file.close(); // generate texture glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &pId); glBindTexture(GL_TEXTURE_2D, pId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (depth == 3) ? GL_RGB : GL_RGBA, width, height, 0, (depth == 3) ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE, &pBuffer[0]); // free the allocated memory delete [] pBuffer; } else if (stricmp(strrchr(strFilename.c_str(),'.'),".tga")==0) { CTga *Tga; Tga = new CTga(); //Note: This will always make a 32-bit texture if(Tga->ReadFile(strFilename.c_str())==0) { Tga->Release(); return false; } //Bind texture int width = Tga->GetSizeX(); int height = Tga->GetSizeY(); int depth = Tga->Bpp() / 8; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &pId); glBindTexture(GL_TEXTURE_2D, pId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, ((depth == 3) ? GL_RGB : GL_RGBA), width, height, 0, ((depth == 3) ? GL_RGB : GL_RGBA) , GL_UNSIGNED_BYTE, (char*)Tga->GetPointer() ); Tga->Release(); } return pId; }
int parseBitmapFontGeneratorFile(MAHandle file, int end, Charset *charset) { char ident[4]; // read magic //maReadData(file, ident, filePtr, 4); readChars(ident, 4); int version = ident[3]; if(ident[0] != 'B' || ident[1] != 'M' || ident[2] != 'F' || version < 2 || version > 3) { //PANIC_MESSAGE("Wrong .fnt format!"); //printf("Wrong .fnt format!\n"); return 0; } for(int i = 0; i < 255; i++) { charset->chars[i].x = 0xffff; } while(sFilePos != end) { // read block type and block size unsigned char id = readByte(); unsigned int blockSize = readInt(); unsigned int skipValue = blockSize; if(version == 2) skipValue -= 4; switch(id) { case 1: { int initialFilePos = sFilePos; skipBytes(14); int i = readChars(charset->name, CHARSET_MAX_NAME_LEN); charset->name[i-1] = 0; skipBytes((skipValue+initialFilePos)-sFilePos); } break; case 2: // type common //#pragma pack(1) //struct commonBlock //{ // int blockSize; // WORD lineHeight; // WORD base; // WORD scaleW; // WORD scaleH; // WORD pages; // BYTE packed :1; // BYTE encoded :1; // Added with version 2 // BYTE reserved:6; //}; //int blockSize = readInt(file, &filePtr); { //int filePtrBefore = filePtr; //printf("Reading common block!\n"); charset->lineHeight = readShort(); charset->base = readShort(); charset->width = readShort(); charset->height = readShort(); charset->pages = readShort(); if(version==2) skipBytes(1); else skipBytes(5); //int currentBlockSize = (filePtr-filePtrBefore)+4; //printf("blockSize: %d, currentBlockSize: %d\n", blockSize, currentBlockSize); } break; case 4: // type char //struct charsBlock //{ // int blockSize; // struct charInfo // { // WORD id; // WORD x; // WORD y; // WORD width; // WORD height; // short xoffset; // short yoffset; // short xadvance; // BYTE page; // BYTE chnl; // } chars[1]; //}; //int blockSize = readInt(file, &filePtr); { //int filePtrBefore = filePtr; int numBytesPerChar = 18; if(version == 3) numBytesPerChar = 20; int numTimes = skipValue/numBytesPerChar; while(numTimes--) { //printf("Reading char block! filePtr: %d\n", filePtr); unsigned int c; if(version == 2) c = readShort(); else c = readInt(); if(c>256) { maPanic(1, "Font contains unicode characters! Only ascii is supported."); } //printf("Reading char %c!\n", (char)c); charset->chars[c].x = readShort(); charset->chars[c].y = readShort(); charset->chars[c].width = readShort(); charset->chars[c].height = readShort(); charset->chars[c].xOffset = readShort(); charset->chars[c].yOffset = readShort(); charset->chars[c].xAdvance = readShort(); charset->chars[c].page = readByte(); skipBytes(1); } //int currentBlockSize = (filePtr-filePtrBefore)+4; //printf("blockSize: %d, currentBlockSize: %d\n", blockSize, currentBlockSize); } break; default: //printf("not reading this id\n");; skipBytes(skipValue); break; } } for(int i = 0; i < 255; i++) { if(charset->chars[i].x == 0xffff) { charset->chars[i] = charset->chars[(byte)' ']; } } return 1; }
void* MQTTSPacket_Factory(int sock, char** clientAddr, struct sockaddr* from, int* error) { static MQTTSHeader header; int ptype; void* pack = NULL; /*struct sockaddr_in cliAddr;*/ int n; char* data = &msg[0]; socklen_t len = sizeof(struct sockaddr_in6); FUNC_ENTRY; /* #if !defined(NO_BRIDGE) client = Protocol_getoutboundclient(sock); FUNC_ENTRY; if (client!=NULL) n = recv(sock,msg,512,0); else #endif */ /* max message size from global parameters, as we lose the packet if we don't receive it. Default is * 65535, so the parameter can be used to decrease the memory usage. * The message memory area must be allocated on the heap so that this memory can be not allocated * on reduced-memory systems. */ n = recvfrom(sock, msg, max_packet_size, 0, from, &len); if (n == SOCKET_ERROR) { int en = Socket_error("UDP read error", sock); if (en == EINVAL) Log(LOG_WARNING, 0, "EINVAL"); *error = SOCKET_ERROR; goto exit; } *clientAddr = Socket_getaddrname(from, sock); /* printf("%d bytes of data on socket %d from %s\n",n,sock,*clientAddr); if (n>0) { for (i=0;i<n;i++) { printf("%d ",msg[i]); } printf("\n"); } */ *error = SOCKET_ERROR; // indicate whether an error occurred, or not if (n < 2) goto exit; if (msg[0] == 1) { ++data; header.len = readInt(&data); } else header.len = *(unsigned char*)data++; header.type = *data++; //printf("header.type is %d, header.len is %d, n is %d\n", header.type, header.len, n); if (header.len != n) { *error = UDPSOCKET_INCOMPLETE; goto exit; } else { ptype = header.type; if (ptype < MQTTS_ADVERTISE || ptype > MQTTS_WILLMSGRESP || new_mqtts_packets[ptype] == NULL) Log(TRACE_MAX, 17, NULL, ptype); else if ((pack = (*new_mqtts_packets[ptype])(header, data)) == NULL) *error = BAD_MQTTS_PACKET; } exit: FUNC_EXIT_RC(*error); return pack; }
int Page::getRecordOffset( int index ){ return readInt( CAPACITY - ( index + 1 ) * 8 - 4, CAPACITY - ( index + 1 ) * 8 - 1 ); }
void BPlusTree::insertEntry(int key, int rid) { BufferManager *bm = BufferManager::getInstance(dbName); int height; TreeNode **trace = new TreeNode *[10]; for (int i = 0; i < 10; i++) trace[i] = NULL; TreeNode *leafNode = getLeaf(key, trace, &height); //cout<<endl<<"height of the tree: "<<height<<endl; if (leafNode == NULL) cout << "exception null node" << endl; cout << "lookup " << lookUpWithoutUnpin(key, leafNode) << endl; if (lookUpWithoutUnpin(key, leafNode) != -1) { cout << "key already exists" << endl; for (int i = height; i >= 1; i--) { //cout<<"unpinning trace:"<<endl; bm->unpinPage(trace[i]->getBuffPage(), false); delete trace[i]; } } else { int nofPairs = readInt(leafNode->getBuffPage(), 0); //if num of pairs less than n-1 if (nofPairs < maxNoPairs) { insertInLeaf(leafNode, key, rid); if (height != 0) { bm->unpinPage(leafNode->getBuffPage(), true); //cout<<"unpinning the leaf node which is not a root"<<endl; } //delete leafNode; for (int i = height - 1; i >= 1; i--) { //cout<<"unpinning trace:"<<endl; bm->unpinPage(trace[i]->getBuffPage(), false); delete trace[i]; } } else { int newLeafId = StorageManager::allocateBlock(dbName); char* newLeafNodeBuff = bm->pinPage(newLeafId); TreeNode *newLeafNode = new TreeNode(newLeafNodeBuff); int divideKeyOffset = maxNoPairs / 2; //cout<<"divideKeyOffset: "<<divideKeyOffset<<endl; int divideKey = readInt(leafNode->getBuffPage(), 2 * SIZE_INT + divideKeyOffset * PAIR_SIZE + PTR_SIZE); cout << "divideKey: " << divideKey << endl; if (key < divideKey) { moveBytes(leafNode->getBuffPage() + 2 * SIZE_INT + divideKeyOffset*PAIR_SIZE, newLeafNode->getBuffPage() + 2 * SIZE_INT, (maxNoPairs - divideKeyOffset) * PAIR_SIZE); //writing "nofPairs" into new leaf //writeInt(newLeafNode->getBuffPage(),0,(maxNoPairs+1)/2); newLeafNode->setNoPairs((maxNoPairs + 1) / 2); //writing "isLeaf" into new leaf //writeInt(newLeafNode->getBuffPage(),SIZE_INT,1); newLeafNode->setIsLeaf(1); //copying P(n) of leaf to P(n) of new leaf moveBytes(leafNode->getBuffPage() + BLOCK_SIZE - PTR_SIZE, newLeafNode->getBuffPage() + BLOCK_SIZE - PTR_SIZE, PTR_SIZE); //make p(n) of leaf to point to new leaf writeInt(leafNode->getBuffPage(), BLOCK_SIZE - PTR_SIZE, newLeafId); leafNode->setNoPairs(maxNoPairs / 2); insertInLeaf(leafNode, key, rid); bm->unpinPage(newLeafId, true); insertInParent(leafNode, divideKey, newLeafId, trace, height); } else { moveBytes(leafNode->getBuffPage() + 2 * SIZE_INT + (divideKeyOffset + 1) * PAIR_SIZE, newLeafNode->getBuffPage() + 2 * SIZE_INT, (maxNoPairs - divideKeyOffset - 1) * PAIR_SIZE); //writing "nofPairs" into new leaf //writeInt(newLeafNode->getBuffPage(),0,maxNoPairs-divideKeyOffset-1); newLeafNode->setNoPairs(maxNoPairs - divideKeyOffset - 1); //writing "isLeaf" into new leaf //writeInt(newLeafNode->getBuffPage(),SIZE_INT,1); newLeafNode->setIsLeaf(1); //copying P(n) of leaf to P(n) of new leaf moveBytes(leafNode->getBuffPage() + BLOCK_SIZE - PTR_SIZE, newLeafNode->getBuffPage() + BLOCK_SIZE - PTR_SIZE, PTR_SIZE); //make p(n) of leaf to point to new leaf writeInt(leafNode->getBuffPage(), BLOCK_SIZE - PTR_SIZE, newLeafId); //writing "nofPairs" into leaf leafNode->setNoPairs(divideKeyOffset + 1); insertInLeaf(newLeafNode, key, rid); int startKey = readInt(newLeafNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); bm->unpinPage(newLeafId, true); //cout<<"task completed and unpinnednew leaf id"<<endl; insertInParent(leafNode, startKey, newLeafId, trace, height); } } //bm->unpinPage(leafId,true); cout << endl << key << " inserted" << endl << endl; } //free (trace); //cout<<"no of pairs in root: "<<readInt(root->getBuffPage(), 0)<<endl; }
int Page::getRecordLength ( int index ){ return readInt( CAPACITY - ( index + 1 ) * 8 - 8, CAPACITY - ( index + 1 ) * 8 - 5 ); }
void BPlusTree::recursiveDeleteEntry(TreeNode *node, int key, int pointer, TreeNode** trace, int level) { BufferManager *bm = BufferManager::getInstance(dbName); int noPairsInNode = node->getNoPairs(); int node_diskBlockId; int keyCount; int ithKey; if (node->isLeaf()) { cout << "delete key: " << key << " pointer: " << pointer << " in leaf" << endl; ithKey = readInt(node->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); for (keyCount = 0; keyCount < noPairsInNode && key != ithKey; keyCount++) { ithKey = readInt(node->getBuffPage(), 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE); } moveBytes(node->getBuffPage() + 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE, node->getBuffPage() + 2 * SIZE_INT + keyCount*PAIR_SIZE, (noPairsInNode - keyCount - 1) * PAIR_SIZE); node->setNoPairs(noPairsInNode - 1); } else { cout << "delete key: " << key << " pointer: " << pointer << " in non leaf" << endl; ithKey = readInt(node->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); for (keyCount = 0; keyCount < noPairsInNode && key != ithKey; keyCount++) { //cout<<"ithKey "<<ithKey<<endl; ithKey = readInt(node->getBuffPage(), 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE); } moveBytes(node->getBuffPage() + 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE, node->getBuffPage() + 2 * SIZE_INT + keyCount * PAIR_SIZE + PTR_SIZE, (noPairsInNode - keyCount - 1) * PAIR_SIZE); node->setNoPairs(noPairsInNode - 1); } noPairsInNode = node->getNoPairs(); //node is root and only one pointer in it after deletion if (level == 0) { //root is not a leaf if (node->isLeaf() == 0 && noPairsInNode == 0) { cout << "root is not a leaf(termination condition)" << endl; int rootChildId = readInt(node->getBuffPage(), 2 * SIZE_INT); TreeNode *rootChildNode = new TreeNode(bm->pinPage(rootChildId)); moveBytes(rootChildNode->getBuffPage(), node->getBuffPage(), BLOCK_SIZE); bm->unpinPage(rootChildId, false); StorageManager::freeBlock(dbName, rootChildId); } cout << "terminates" << endl; //no unpin needed here } else if (noPairsInNode < (maxNoPairs + 1) / 2 && level != 0) { TreeNode *parentNode = trace[level - 1]; int noPairsInParent = parentNode->getNoPairs(); int kDash; int searchKey = readInt(node->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); ithKey = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); for (keyCount = 0; keyCount < noPairsInParent && searchKey >= ithKey; keyCount++) { ithKey = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE); } TreeNode *siblingNode; int siblingNodeId; int swapCheck = 0; int noPairsInSibling; int nodeToBeDeleted; //finding N' /** * sibling is the leftmost node wherein swapping * the pointers N and N' is needed */ if (keyCount == 0) { //sibling to unpined using siblingNodeId node_diskBlockId = readInt(parentNode->getBuffPage(), 2 * SIZE_INT); siblingNodeId = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + PAIR_SIZE); siblingNode = new TreeNode(bm->pinPage(siblingNodeId)); kDash = ithKey; swapCheck = 1; nodeToBeDeleted = siblingNodeId; } /** * sibling is not thethe leftmost node */ else { node_diskBlockId = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + keyCount * PAIR_SIZE); siblingNodeId = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount - 1) * PAIR_SIZE); siblingNode = new TreeNode(bm->pinPage(siblingNodeId)); kDash = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount - 1) * PAIR_SIZE + PTR_SIZE); nodeToBeDeleted = readInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount) * PAIR_SIZE); } noPairsInSibling = siblingNode->getNoPairs(); int mergeCheck = 0; if (node->isLeaf()) { if (node->getNoPairs() + noPairsInSibling <= maxNoPairs) { mergeCheck = 1; } } else { if (node->getNoPairs() + noPairsInSibling + 1 <= maxNoPairs) { mergeCheck = 1; } } if (mergeCheck == 1) { cout << "merging case" << endl; /** * swaping the names of the node , sibling we always make * sure that we dump(or merge ) the content of * left node into right node ,but the siblingNodeId is * same(new treenode which is not in trace) */ if (swapCheck == 1) { TreeNode *temp; temp = node; node = siblingNode; siblingNode = temp; } if (node->isLeaf()) { noPairsInNode = node->getNoPairs(); noPairsInSibling = siblingNode->getNoPairs(); moveBytes(node->getBuffPage() + 2 * SIZE_INT, siblingNode->getBuffPage() + 2 * SIZE_INT + (noPairsInSibling) * PAIR_SIZE, noPairsInNode * PAIR_SIZE); moveBytes(node->getBuffPage() + BLOCK_SIZE - PTR_SIZE, siblingNode->getBuffPage() + BLOCK_SIZE - PTR_SIZE, PTR_SIZE); siblingNode->setNoPairs(noPairsInSibling + noPairsInNode); } else { noPairsInNode = node->getNoPairs(); noPairsInSibling = siblingNode->getNoPairs(); writeInt(siblingNode->getBuffPage(), 2 * SIZE_INT + noPairsInSibling * PAIR_SIZE + PTR_SIZE, kDash); moveBytes(node->getBuffPage() + 2 * SIZE_INT, siblingNode->getBuffPage() + 2 * SIZE_INT + (noPairsInSibling + 1) * PAIR_SIZE, noPairsInNode * PAIR_SIZE + PTR_SIZE); siblingNode->setNoPairs(noPairsInSibling + noPairsInNode + 1); } if (swapCheck == 1) { bm->unpinPage(trace[level]->getBuffPage(), true); bm->unpinPage(siblingNodeId, false); StorageManager::freeBlock(dbName, siblingNodeId); delete trace[level]; } else { bm->unpinPage(trace[level]->getBuffPage(), false); bm->unpinPage(siblingNodeId, true); StorageManager::freeBlock(dbName, node_diskBlockId); delete trace[level]; } cout << "kDash: " << kDash << endl; recursiveDeleteEntry(parentNode, kDash, nodeToBeDeleted, trace, level - 1); } //redistribution else { cout << "redistribution "; //if N' is predecessor of N if (swapCheck != 1) { if (node->isLeaf()) { cout << " leaf,middle node" << endl; int lastKeyInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + noPairsInSibling * PAIR_SIZE - PTR_SIZE); int lastRidInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + (noPairsInSibling - 1) * PAIR_SIZE); moveBytes(node->getBuffPage() + 2 * SIZE_INT, node->getBuffPage() + 2 * SIZE_INT + PAIR_SIZE, noPairsInNode * PAIR_SIZE); siblingNode->setNoPairs(noPairsInSibling - 1); noPairsInSibling = siblingNode->getNoPairs(); writeInt(node->getBuffPage(), 2 * SIZE_INT, lastRidInSibling); writeInt(node->getBuffPage(), 2 * SIZE_INT + PTR_SIZE, lastKeyInSibling); node->setNoPairs(noPairsInNode + 1); //node is not the first child of parent node writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount - 1) * PAIR_SIZE + PTR_SIZE, lastKeyInSibling); } else { cout << " non leaf,middle node" << endl; int lastKeyInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + noPairsInSibling * PAIR_SIZE - PTR_SIZE); int lastPtrInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + noPairsInSibling * PAIR_SIZE); moveBytes(node->getBuffPage() + 2 * SIZE_INT, node->getBuffPage() + 2 * SIZE_INT + PAIR_SIZE, noPairsInNode * PAIR_SIZE + PTR_SIZE); siblingNode->setNoPairs(noPairsInSibling - 1); noPairsInSibling = siblingNode->getNoPairs(); writeInt(node->getBuffPage(), 2 * SIZE_INT, lastPtrInSibling); writeInt(node->getBuffPage(), 2 * SIZE_INT + PTR_SIZE, kDash); node->setNoPairs(noPairsInNode + 1); writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + (keyCount - 1) * PAIR_SIZE + PTR_SIZE, lastKeyInSibling); } } else { if (node->isLeaf()) { cout << " leaf,leftmost node" << endl; int firstRidInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT); int firstKeyInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); moveBytes(siblingNode->getBuffPage() + 2 * SIZE_INT + PAIR_SIZE, siblingNode->getBuffPage() + 2 * SIZE_INT, (noPairsInSibling - 1) * PAIR_SIZE); siblingNode->setNoPairs(noPairsInSibling - 1); noPairsInSibling = siblingNode->getNoPairs(); writeInt(node->getBuffPage(), 2 * SIZE_INT + noPairsInNode*PAIR_SIZE, firstRidInSibling); writeInt(node->getBuffPage(), 2 * SIZE_INT + noPairsInNode * PAIR_SIZE + PTR_SIZE, firstKeyInSibling); node->setNoPairs(noPairsInNode + 1); //node is first child of parent node firstKeyInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE, firstKeyInSibling); } else { cout << " non leaf,leftmost node" << endl; int firstPtrInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT); int firstKeyInSibling = readInt( siblingNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE); moveBytes(siblingNode->getBuffPage() + 2 * SIZE_INT + PAIR_SIZE, siblingNode->getBuffPage() + 2 * SIZE_INT, (noPairsInSibling - 1) * PAIR_SIZE + PTR_SIZE); siblingNode->setNoPairs(noPairsInSibling - 1); noPairsInSibling = siblingNode->getNoPairs(); writeInt(node->getBuffPage(), 2 * SIZE_INT + noPairsInNode * PAIR_SIZE + PTR_SIZE, kDash); writeInt(node->getBuffPage(), 2 * SIZE_INT + (noPairsInNode + 1) * PAIR_SIZE, firstPtrInSibling); node->setNoPairs(noPairsInNode + 1); writeInt(parentNode->getBuffPage(), 2 * SIZE_INT + PTR_SIZE, firstKeyInSibling); } } bm->unpinPage(trace[level]->getBuffPage(), true); bm->unpinPage(siblingNodeId, true); delete trace[level]; for (int i = level - 1; i >= 1; i--) { bm->unpinPage(trace[i]->getBuffPage(), false); delete trace[i]; } } } cout << key << "key deleted at level " << level << endl << endl; }
bool Configurator::readConfiguration (const char *filename) { std::ifstream file(filename == 0 ? Configurator::filename : filename); if (!file.good()) return false; int version; if (!readInt(file, version) || (version != 1 && version != 2 && version != 3)) return false; int routerCount; if (!readInt(file, routerCount) || routerCount < 0) return false; for (int i = 0; i != routerCount; ++i) { std::string interface; int vrid; int addressFamily; int priority; int interval; bool accept; bool preempt; bool enabled; int flags; IpAddress primaryIp; int addressCount; IpSubnetSet subnets; std::string masterCommand; std::string backupCommand; int vlanId; // Read data if ( !readString(file, interface) || !readInt(file, vrid) || !readInt(file, addressFamily) || !readInt(file, priority) || !readInt(file, interval) || !readBoolean(file, accept) || !readBoolean(file, preempt) || !readBoolean(file, enabled) || !readInt(file, flags)) { return false; } if (flags & FLAG_HAS_PRIMARY_IP_ADDRESS) { if (!readIp(file, primaryIp)) return false; } if (version > 1) { if (!readString(file, masterCommand) || !readString(file, backupCommand)) return false; } if (version > 2) { if (!readInt(file, vlanId)) return false; } if (!readInt(file, addressCount)) return false; for (int j = 0; j != addressCount; ++j) { IpSubnet subnet; if (!readSubnet(file, subnet)) return false; subnets.insert(subnet); } // Sanitize if (vrid < 1 || vrid > 255) { // TODO - Add to log continue; } if (priority < 1 || priority > 255) { // TODO - Add to log continue; } if (addressFamily != AF_INET && addressFamily != AF_INET6) { // TODO - Add to log continue; } if (interval % 10 != 0 || interval < 10 || interval > 40950) { // TODO - Add to log continue; } int ifIndex = if_nametoindex(interface.c_str()); if (ifIndex <= 0) { // TODO - Add to log continue; } // Create service VrrpService *service = VrrpManager::getService(ifIndex, vrid, vlanId, addressFamily, true); if (service == 0) { // TODO - Add to log continue; } service->setPriority(priority); service->setAdvertisementInterval(interval / 10); service->setAcceptMode(accept); service->setPreemptMode(preempt); if (flags & FLAG_HAS_PRIMARY_IP_ADDRESS) service->setPrimaryIpAddress(primaryIp); service->setMasterCommand(masterCommand); service->setBackupCommand(backupCommand); for (IpSubnetSet::const_iterator subnet = subnets.begin(); subnet != subnets.end(); ++subnet) { service->addIpAddress(*subnet); } if (enabled) service->enable(); else service->disable(); } return true; }
EDLL AoscMessage::AoscMessage(byte *data, int size) { bok=true; memset(pattern, 0, sizeof(pattern)); memset(format, 0, sizeof(format)); { int pos=0; int sz; sz=readString(pattern, data+pos, size-pos); if(sz<0) { bok=false; return; } pos+=sz; sz=readString(format, data+pos, size-pos); if(sz<0) { bok=false; return; } pos+=sz; { char *s=format; while(*s&&bok) { switch(*s) { case 'i': { int i; if(readInt(&i, data+pos, size-pos)==4) this->add(new AoscInteger(i)); else bok=false; } break; case 'f': { float f; if(readFloat(&f, data+pos, size-pos)==4) this->add(new AoscFloat(f)); else bok=false; } break; case 's': { char str[1024]; if(readString(str, data+pos, size-pos)>=0) this->add(new AoscString(str)); else bok=false; } break; case 'r': { int i; if(readInt(&i, data+pos, size-pos)==4) this->add(new AoscColor((dword)i)); else bok=false; } break; case ',': break; default: assert(false); // unknown break; } s++; } } } }
void GuitarPro5::readTracks() { for (int i = 0; i < staves; ++i) { int tuning[GP_MAX_STRING_NUMBER]; Staff* staff = score->staff(i); Part* part = staff->part(); uchar c = readUChar(); // simulations bitmask if (c & 0x2) { // 12 stringed guitar } if (c & 0x4) { // banjo track } if (i == 0 || version == 500) skip(1); QString name = readPascalString(40); int strings = readInt(); if (strings <= 0 || strings > GP_MAX_STRING_NUMBER) throw GuitarProError::GP_BAD_NUMBER_OF_STRINGS ; for (int j = 0; j < strings; ++j) { tuning[j] = readInt(); } for (int j = strings; j < GP_MAX_STRING_NUMBER; ++j) readInt(); /*int midiPort =*/ readInt(); // -1 int midiChannel = readInt() - 1; /*int midiChannel2 =*/ readInt(); // -1 int frets = readInt(); int capo = readInt(); /*int color =*/ readInt(); skip(version > 500 ? 49 : 44); if (version > 500) { // british stack clean / amp tone readDelphiString(); readDelphiString(); } int tuning2[strings]; for (int k = 0; k < strings; ++k) tuning2[strings-k-1] = tuning[k]; StringData stringData(frets, strings, tuning2); Instrument* instr = part->instr(); instr->setStringData(stringData); part->setPartName(name); part->setLongName(name); instr->setTranspose(Interval(capo)); // // determine clef // int patch = channelDefaults[midiChannel].patch; ClefType clefId = ClefType::G; if (midiChannel == GP_DEFAULT_PERCUSSION_CHANNEL) { clefId = ClefType::PERC; // instr->setUseDrumset(DrumsetKind::GUITAR_PRO); instr->setDrumset(gpDrumset); staff->setStaffType(StaffType::preset(StaffTypes::PERC_DEFAULT)); } else if (patch >= 24 && patch < 32) clefId = ClefType::G3; else if (patch >= 32 && patch < 40) clefId = ClefType::F8; Measure* measure = score->firstMeasure(); Clef* clef = new Clef(score); clef->setClefType(clefId); clef->setTrack(i * VOICES); Segment* segment = measure->getSegment(Segment::Type::Clef, 0); segment->add(clef); Channel& ch = instr->channel(0); if (midiChannel == GP_DEFAULT_PERCUSSION_CHANNEL) { ch.program = 0; ch.bank = 128; } else { ch.program = patch; ch.bank = 0; } ch.volume = channelDefaults[midiChannel].volume; ch.pan = channelDefaults[midiChannel].pan; ch.chorus = channelDefaults[midiChannel].chorus; ch.reverb = channelDefaults[midiChannel].reverb; //qDebug("default2: %d", channelDefaults[i].reverb); // missing: phase, tremolo ch.updateInitList(); } skip(version == 500 ? 2 : 1); }
bool IniConfig::readEmulation (ini_fd_t ini) { bool ret = true; (void) ini_locateHeading (ini, "Emulation"); { int clockSpeed = -1; ret &= readInt (ini, "ClockSpeed", clockSpeed); if (clockSpeed != -1) { if (clockSpeed < 0 || clockSpeed > 1) ret = false; emulation_s.clockSpeed = SID2_CLOCK_PAL; if (clockSpeed) emulation_s.clockSpeed = SID2_CLOCK_NTSC; } } ret &= readBool (ini, "ForceSongSpeed", emulation_s.clockForced); { int mos8580 = -1; ret &= readInt (ini, "MOS8580", mos8580); if (mos8580 != -1) { if (mos8580 < 0 || mos8580 > 1) ret = false; emulation_s.sidModel = SID2_MOS6581; if (mos8580) emulation_s.sidModel = SID2_MOS8580; } } ret &= readBool (ini, "UseFilter", emulation_s.filter); ret &= readString (ini, "Filter6581", emulation_s.filter6581); ret &= readString (ini, "Filter8580", emulation_s.filter8580); ret &= readBool (ini, "SidSamples", emulation_s.sidSamples); // These next two change the ini section! if (emulation_s.filter6581) { // Try to load the filter filter6581.read (ini, emulation_s.filter6581); if (!filter6581) { filter6581.read (emulation_s.filter6581); if (!filter6581) ret = false; } } if (emulation_s.filter8580) { // Try to load the filter filter8580.read (ini, emulation_s.filter8580); if (!filter8580) { filter8580.read (emulation_s.filter8580); if (!filter8580) ret = false; } } return ret; }
int main(int argc, char *argv[]) { if (argc < 4) { puts("Argument Exception!"); return 1; } //Load Road Network from File loadData(argv[1]); //载入频繁序列信息 loadFrequency(); long bbb = clock(); //1 读入轨迹文件 FILE* file = fopen(argv[2],"rb"); int tjNumber = readInt(file); //轨迹条数 FILE* result = fopen(argv[3],"wb"); //用街道编号压缩 writeInt(result,tjNumber); int i; for (i = 0; i < tjNumber; ++i) { int spNumber = readInt(file); //路径段数 //-- //printf("%d\n",spNumber); ansSize = 0; int j; for (j = 0; j < spNumber; ++j) path[j] = readInt(file); //路径上的边 tmp_num = 0; int p = fre_last[path[0]]; while (p > -1) { tmp_item[tmp_num][0] = fre_other[p][0]; tmp_item[tmp_num][1] = fre_other[p][1]; tmp_item[tmp_num][2] = fre_other[p][1]; ++tmp_num; p = fre_pre[p]; } //for (j = 0; j < tmp_num; ++j) printf("%d-%d-%d\t",tmp_item[j][0],tmp_item[j][1],tmp_item[j][2]); //puts(""); //if (tmp_num == 0) ansList[ansSize++] = path[0]; int nowEdge; int preEdge = 0; for (nowEdge = 1; nowEdge < spNumber; ++nowEdge) { //后一个的项集合 tmp_num2 = 0; int p = fre_last[path[nowEdge]]; while (p > -1) { tmp_mm[tmp_num2][0] = fre_other[p][0]; tmp_mm[tmp_num2][2] = fre_other[p][1]; ++tmp_num2; p = fre_pre[p]; } //项集合求并 int tp = 0; int l,r; for (r = 0;r < tmp_num2; ++r) for (l = 0; l < tmp_num; ++l) if (tmp_item[l][0] == tmp_mm[r][0] && tmp_item[l][2] + 1 == tmp_mm[r][2]) { tmp_mm[tp][0] = tmp_mm[r][0]; tmp_mm[tp][1] = tmp_item[l][1]; tmp_mm[tp][2] = tmp_mm[r][2]; ++tp; break; } //如果没有继续维系的了,那么输出上一个路段 if (tp == 0) { if (tmp_num == 0 || tmp_item[0][1] == tmp_item[0][2]) { //孤立道路 ansList[ansSize++] = path[preEdge]; //=== //printf("Edge:%d\t",path[preEdge]); //printf("%d ",path[preEdge]); }else { //一条子轨迹 ansList[ansSize++] = (1 << 31) | ((tmp_item[0][0] % 32768) * 65536) + ((tmp_item[0][1] % 256) * 256) + (tmp_item[0][2] % 256); //=== //if (tmp_item[0][1]!=tmp_item[0][2]) //printf("Sub:%d^%d-%d\t",tmp_item[0][0],tmp_item[0][1],tmp_item[0][2]); //int k; //for (k = tmp_item[0][1]; k<= tmp_item[0][2]; ++k) // printf("%d ",fre[tmp_item[0][0]][k]); } tmp_num = 0; int p = fre_last[path[nowEdge]]; while (p > -1) { tmp_item[tmp_num][0] = fre_other[p][0]; tmp_item[tmp_num][1] = fre_other[p][1]; tmp_item[tmp_num][2] = fre_other[p][1]; ++tmp_num; p = fre_pre[p]; } preEdge = nowEdge; }else { //可以继续延长 tmp_num = tp; for (j = 0; j < tmp_num; ++j) { tmp_item[j][0] = tmp_mm[j][0]; tmp_item[j][1] = tmp_mm[j][1]; tmp_item[j][2] = tmp_mm[j][2]; } } } if (tmp_num == 0 || tmp_item[0][1] == tmp_item[0][2]) { //孤立道路 ansList[ansSize++] = path[preEdge]; //=== //printf("Edge:%d\n",path[preEdge]); //printf("%d ",path[preEdge]); }else { //一条子轨迹 ansList[ansSize++] = (1 << 31) | ((tmp_item[0][0] % 32768) * 65536) + ((tmp_item[0][1] % 256) * 256) + (tmp_item[0][2] % 256); //=== //printf("Sub:%d^%d-%d\n",tmp_item[0][0],tmp_item[0][1],tmp_item[0][2]); //int k; //for (k = tmp_item[0][1]; k<= tmp_item[0][2]; ++k) // printf("%d ",fre[tmp_item[0][0]][k]); } //puts(""); for (j = 0; j < ansSize; ++j) writeInt(result,ansList[j]);// printf("%d ",ansList[j]); //调试用 if (i % 100 ==99) printf("+"); if (i % 10000 ==9999) printf("\n"); } fclose(result); fclose(file); FILE* fpp = fopen(argv[4],"a+"); fprintf(fpp,"%ld\n",clock() - bbb); fclose(fpp); return 0; }
void bTrack::readInputTrack(const char *fname, int cage){ char *chrom=0; int fg=-1; int span=1, step=1; long start=0, beg=0, end=0; float score=0; ScoredRange bed; char *inputString, abuf[1000], chBuf[256], *sx; long iLine=0; char strand=0; int nStrand=0; hasCompl=1; trackType=getTrackType(fname); FILE *f=xopen(fname, "rt"); setvbuf ( f , NULL , _IOFBF , 65536 ); strcpy(curFname,fname); inputErrLine=inputErr = 0; // flag: if input track has no errors BufFile input; input.init(fname); for(;(inputString=input.getString())!=0; iLine++){ inputErrLine++; int dataFg=1; //======== remove end-of-line signes if(iLine%100000 ==0) {verb("== %li %s... \r",iLine,curChrom->chrom); } if(*inputString==0) continue; if(strncmp(inputString,"browser" ,7)==0) continue; //========= browser line => skip if(strncmp(inputString,"track" ,5)==0) {trackDef(inputString); continue;} if(strncmp(inputString,"#bedGraph",9)==0) {trackType=BED_GRAPH; continue;} if(*inputString=='#' || *inputString==0) continue; //======== comment line if(trackType==WIG_TRACK) trackType=checkWig(inputString); beg=-1; end=-1; switch(trackType){ case BED_TRACK: //======== BED score=1; //======== default score=1 strand=0; //======== default strand=unknown chrom=readChrom(inputString); //======== find chrom field beg=readInt(); //======== find beg field end=readInt(); //======== find end field sx=strtok(0,"\t\n"); if(sx==0) break; //======== ignore name field sx=strtok(0,"\t\n"); if(sx==0) break; //======== take score field if(*sx!=0 && (isdigit(*sx) || *sx=='-')) { score=atof(sx); if(score==0) score=0.01; } sx=strtok(0,"\t\n"); if(sx==0) break; //======== take strand field if(*sx!=0 && *sx!='.') {strand=*sx; nStrand++;} //======================= read gene structure break; case BED_GRAPH: chrom=readChrom(inputString); //======== find chrom field beg=readInt(); //======== find beg field end=readInt(); //======== find end field score=readFloat(); //======== find score field break; case WIG_TRACK: if(*inputString=='v'){ if(strncmp(inputString,"variableStep", 12)==0){ //======== read parameters for variableStep chrom=getAttr(inputString+12,(char *)"chrom",chBuf); span=1; fg=0; dataFg=0; sx=getAttr(inputString+12,(char *)"span",abuf); if(sx!=0) span=atoi(sx); }} else if(*inputString=='f'){ if(strncmp(inputString,(char *)"fixedStep", 9)==0){ //======== read parameters for fixedStep fg=1; dataFg=0; chrom=getAttr(inputString+10,(char *)"chrom",chBuf); sx=getAttr(inputString+10,(char *)"span",abuf); if(sx!=0) span=atoi(sx); sx=getAttr(inputString+10,(char *)"step",abuf); if(sx!=0) step=atoi(sx); sx=getAttr(inputString+10,(char *)"start",abuf); if(sx!=0) start=atol(sx); }} else{ if(fg==0){ //======== variableStep if((sx=strtok(inputString," \t\n\r"))==0) continue; beg=atoi(sx); end=beg+span; if((sx=strtok(0," \t\n\r"))==0) continue; score=atof(sx); } else if(fg==1){ //======== fixedStep beg=start; end=beg+span; start=beg+step; sx=inputString; if(sx==0) break; score=atof(sx); } else errorExit("wrong WIG format"); } break; case BROAD_PEAK: chrom=readChrom(inputString); //======== find chrom field beg=readInt(); //======== find beg field end=readInt(); //======== find end field strtok(0," \t\n\r"); //======== skip name sx=strtok(0," \t\n\r"); if(sx==0) break; if(bpType==BP_SCORE) score=atof(sx); //======== find score field sx=strtok(0," \t\n"); if(sx==0) break; //======== take strand field if(*sx!=0 && *sx!='.') {strand=*sx; nStrand++;} if(bpType==BP_SCORE) break; sx=strtok(0," \t\n"); if(sx==0) break; //======== take signal field if(bpType==BP_SIGNAL) {score=atof(sx); break;} sx=strtok(0," \t\n"); if(sx==0) break; //======== take pval field if(bpType==BP_LOGPVAL) {score=atof(sx); break;} break; default: errorExit("track type undefined or unknown"); break; } if(dataFg && (chrom==0 || beg < 0 || end < 0)){ if(syntax) errorExit("wrong line in input file <%s> line# <%i>\n",fname,iLine); else{ writeLog("wrong line in input file <%s> line# <%i>\n",fname,iLine); verb("wrong line in input file <%s> line# <%i>\n",fname,iLine); } continue; } bed.chrom=chrom; bed.beg=beg; bed.end=end; bed.score=score; if(cage > 0) bed.end=bed.beg+cage; if(cage < 0) bed.beg=bed.end+cage; if(dataFg) { addSgm(strand, &bed); } } if(nStrand==0) hasCompl=0; fclose(f); verb("\n"); }
char SFE_BMP180::begin() // Initialize library for subsequent pressure measurements { double c3,c4,b1; // Start up the Arduino's "wire" (I2C) library: Wire.begin(); // The BMP180 includes factory calibration data stored on the device. // Each device has different numbers, these must be retrieved and // used in the calculations when taking pressure measurements. // Retrieve calibration data from device: if (readInt(0xAA,AC1) && readInt(0xAC,AC2) && readInt(0xAE,AC3) && readUInt(0xB0,AC4) && readUInt(0xB2,AC5) && readUInt(0xB4,AC6) && readInt(0xB6,VB1) && readInt(0xB8,VB2) && readInt(0xBA,MB) && readInt(0xBC,MC) && readInt(0xBE,MD)) { // All reads completed successfully! // If you need to check your math using known numbers, // you can uncomment one of these examples. // (The correct results are commented in the below functions.) // Example from Bosch datasheet // AC1 = 408; AC2 = -72; AC3 = -14383; AC4 = 32741; AC5 = 32757; AC6 = 23153; // B1 = 6190; B2 = 4; MB = -32768; MC = -8711; MD = 2868; // Example from http://wmrx00.sourceforge.net/Arduino/BMP180-Calcs.pdf // AC1 = 7911; AC2 = -934; AC3 = -14306; AC4 = 31567; AC5 = 25671; AC6 = 18974; // VB1 = 5498; VB2 = 46; MB = -32768; MC = -11075; MD = 2432; /* Serial.print("AC1: "); Serial.println(AC1); Serial.print("AC2: "); Serial.println(AC2); Serial.print("AC3: "); Serial.println(AC3); Serial.print("AC4: "); Serial.println(AC4); Serial.print("AC5: "); Serial.println(AC5); Serial.print("AC6: "); Serial.println(AC6); Serial.print("VB1: "); Serial.println(VB1); Serial.print("VB2: "); Serial.println(VB2); Serial.print("MB: "); Serial.println(MB); Serial.print("MC: "); Serial.println(MC); Serial.print("MD: "); Serial.println(MD); */ // Compute floating-point polynominals: c3 = 160.0 * pow(2,-15) * AC3; c4 = pow(10,-3) * pow(2,-15) * AC4; b1 = pow(160,2) * pow(2,-30) * VB1; c5 = (pow(2,-15) / 160) * AC5; c6 = AC6; mc = (pow(2,11) / pow(160,2)) * MC; md = MD / 160.0; x0 = AC1; x1 = 160.0 * pow(2,-13) * AC2; x2 = pow(160,2) * pow(2,-25) * VB2; y0 = c4 * pow(2,15); y1 = c4 * c3; y2 = c4 * b1; p0 = (3791.0 - 8.0) / 1600.0; p1 = 1.0 - 7357.0 * pow(2,-20); p2 = 3038.0 * 100.0 * pow(2,-36); /* Serial.println(); Serial.print("c3: "); Serial.println(c3); Serial.print("c4: "); Serial.println(c4); Serial.print("c5: "); Serial.println(c5); Serial.print("c6: "); Serial.println(c6); Serial.print("b1: "); Serial.println(b1); Serial.print("mc: "); Serial.println(mc); Serial.print("md: "); Serial.println(md); Serial.print("x0: "); Serial.println(x0); Serial.print("x1: "); Serial.println(x1); Serial.print("x2: "); Serial.println(x2); Serial.print("y0: "); Serial.println(y0); Serial.print("y1: "); Serial.println(y1); Serial.print("y2: "); Serial.println(y2); Serial.print("p0: "); Serial.println(p0); Serial.print("p1: "); Serial.println(p1); Serial.print("p2: "); Serial.println(p2); */ // Success! return(1); } else { // Error reading calibration data; bad component or connection? return(0); } }
int Page::freeOffset(){ return readInt( CAPACITY - 4 , CAPACITY - 1); }
int main( int argc, char* argv[] ) { char cwd[2048]; _getcwd( cwd, sizeof(cwd) ); // zar <opt> <dir> if ( argc != 4 ) { printf( "Usage:\n" "archive: zar -a <name> <dir>\n" "unarchive: zar -x <name> <dir>\n" "remove: zar -d <name> <filelist>\n" ); return 0; } const char* opt = argv[1]; const char* name = argv[2]; const char* dir = argv[3]; if ( std::string(opt) == "-a" ) { // read files std::vector<File> files; if ( -1 != _chdir(dir) ) { printf( "Processing %s...\n", dir ); readFiles( files, "*.*" ); } else { printf( "Path %s not found\n", dir ); } _chdir( cwd ); // check for duplicate file names int i; for ( i = 0 ; i < (int)files.size() ; ++i ) { for ( int j = i+1 ; j < (int)files.size() ; ++j ) { if ( files[i].name == files[j].name ) { printf( "Warning: Two files have identical names (%s). Paths:\n", files[i].name.c_str() ); printf( "%s\n", files[i].path.c_str() ); printf( "%s\n", files[j].path.c_str() ); printf( "Removing %s/%s...\n", files[j].path.c_str(), files[j].name.c_str() ); files.erase( files.begin()+j ); --j; } } } // write zip printf( "Writing %s...\n", name ); gzFile zip = gzopen( name, "wb" ); writeInt( zip, files.size() ); for ( i = 0 ; i < (int)files.size() ; ++i ) { File& file = files[i]; writeString( zip, file.name.c_str() ); writeBytes( zip, file.data.begin(), file.data.size() ); } gzclose( zip ); } else if ( std::string(opt) == "-x" ) { // read zip printf( "Reading %s...\n", name ); gzFile zip = gzopen( name, "rb" ); if ( !zip ) { printf( "Failed to open %s.", name ); return 1; } std::vector<File> files; int count = readInt( zip ); files.resize( count ); for ( int i = 0 ; i < count ; ++i ) { File& file = files[i]; readString( zip, file.name ); readBytes( zip, file.data ); } gzclose( zip ); // write files if ( -1 != _chdir(dir) ) { for ( int i = 0 ; i < (int)files.size() ; ++i ) { File& file = files[i]; printf( "Writing %s...\n", file.name.c_str() ); FILE* fh = fopen( file.name.c_str(), "wb" ); if ( fh ) { fwrite( file.data.begin(), 1, file.data.size(), fh ); fclose( fh ); } else { printf( "Cannot write to file: %s\n", file.name.c_str() ); } } } else { printf( "Path %s not found\n", dir ); } _chdir( cwd ); } else if ( std::string(opt) == "-d" ) { // read zip printf( "Reading %s...\n", name ); gzFile zip = gzopen( name, "rb" ); if ( !zip ) { printf( "Failed to open %s.", name ); return 1; } std::vector<File> files; int count = readInt( zip ); files.resize( count ); for ( int i = 0 ; i < count ; ++i ) { File& file = files[i]; readString( zip, file.name ); readBytes( zip, file.data ); } gzclose( zip ); // read file list printf( "Reading list %s...\n", dir ); FILE* fh = fopen( dir, "rt" ); if ( !fh ) { printf( "File list not found: %s\n", dir ); return 1; } std::vector<std::string> filelist; char buf[2048]; while ( !feof(fh) ) { if ( 1 != fscanf(fh,"%s",buf) ) break; filelist.push_back( buf ); } // remove listed files for ( int i = 0 ; i < (int)filelist.size() ; ++i ) { std::string str = filelist[i]; for ( int j = 0 ; j < (int)files.size() ; ++j ) { if ( files[j].name == str ) { files.erase( files.begin()+j ); --j; } } } // write zip printf( "Writing %s...\n", name ); zip = gzopen( name, "wb" ); writeInt( zip, files.size() ); for ( int i = 0 ; i < (int)files.size() ; ++i ) { File& file = files[i]; writeString( zip, file.name.c_str() ); writeBytes( zip, file.data.begin(), file.data.size() ); } gzclose( zip ); } else { printf( "Invalid option: %s\n", opt ); } return 0; }
int Page::getSlotNumber(){ return readInt( CAPACITY - 8, CAPACITY - 5 ); }
static bool readItemRecursive(WebCore::HistoryItem* newItem, const char** pData, int length) { if (!pData || length < HISTORY_MIN_SIZE) { ALOGW("readItemRecursive() bad params; pData=%p length=%d", pData, length); return false; } const char* data = *pData; const char* end = data + length; String content; // Read the original url if (readString(data, end, content, "Original url")) newItem->setOriginalURLString(content); else return false; // Read the url if (readString(data, end, content, "Url")) newItem->setURLString(content); else return false; // Read the title if (readString(data, end, content, "Title")) newItem->setTitle(content); else return false; // Generate a new ResourceRequest object for populating form information. // Read the form content type WTF::String formContentType; if (!readString(data, end, formContentType, "Content type")) return false; // Read the form data size unsigned formDataSize; if (!readUnsigned(data, end, formDataSize, "Form data size")) return false; // Read the form data WTF::RefPtr<WebCore::FormData> formData; if (formDataSize) { ALOGV("Reading Form data %d %.*s", formDataSize, formDataSize, data); if ((end < data) || ((size_t)(end - data) < formDataSize)) { ALOGW("\tNot enough data to read form data; returning"); return false; } formData = WebCore::FormData::create(data, formDataSize); data += formDataSize; // Read the identifier int64_t id; if (!readInt64(data, end, id, "Form id")) return false; if (id) formData->setIdentifier(id); } // Set up the form info if (formData != NULL) { WebCore::ResourceRequest r; r.setHTTPMethod("POST"); r.setHTTPContentType(formContentType); r.setHTTPBody(formData); newItem->setFormInfoFromRequest(r); } // Read the target if (readString(data, end, content, "Target")) newItem->setTarget(content); else return false; AndroidWebHistoryBridge* bridge = newItem->bridge(); ALOG_ASSERT(bridge, "There should be a bridge object during inflate"); // Read the screen scale float fValue; if (readFloat(data, end, fValue, "Screen scale")) bridge->setScale(fValue); else return false; // Read the text wrap scale if (readFloat(data, end, fValue, "Text wrap scale")) bridge->setTextWrapScale(fValue); else return false; // Read scroll position. int scrollX; if (!readInt(data, end, scrollX, "Scroll pos x")) return false; int scrollY; if (!readInt(data, end, scrollY, "Scroll pos y")) return false; newItem->setScrollPoint(IntPoint(scrollX, scrollY)); // Read the document state unsigned docStateCount; if (!readUnsigned(data, end, docStateCount, "Doc state count")) return false; if (docStateCount) { // Create a new vector and reserve enough space for the document state. WTF::Vector<WTF::String> docState; docState.reserveCapacity(docStateCount); while (docStateCount--) { // Read a document state string if (readString(data, end, content, "Document state")) docState.append(content); else return false; } newItem->setDocumentState(docState); } // Read is target item bool c; if (readBool(data, end, c, "Target item")) newItem->setIsTargetItem(c); else return false; // Read the child count unsigned count; if (!readUnsigned(data, end, count, "Child count")) return false; *pData = data; if (count) { while (count--) { // No need to check the length each time because read_item_recursive // will return null if there isn't enough data left to parse. WTF::RefPtr<WebCore::HistoryItem> child = WebCore::HistoryItem::create(); // Set a bridge that will not call into java. child->setBridge(new WebHistoryItem(static_cast<WebHistoryItem*>(bridge))); // Read the child item. if (!readItemRecursive(child.get(), pData, end - data)) return false; child->bridge()->setActive(); newItem->addChildItem(child); } } return true; }
int read() { int ret; readInt(ret); return ret; }