TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *main_window) : QTreeView(parent) , main_window(main_window) { setUniformRowHeights(true); // Load settings bool column_loaded = loadSettings(); // Create and apply delegate listDelegate = new TransferListDelegate(this); setItemDelegate(listDelegate); // Create transfer list model listModel = new TorrentModel(this); nameFilterModel = new TransferListSortModel(); nameFilterModel->setDynamicSortFilter(true); nameFilterModel->setSourceModel(listModel); nameFilterModel->setFilterKeyColumn(TorrentModel::TR_NAME); nameFilterModel->setFilterRole(Qt::DisplayRole); nameFilterModel->setSortCaseSensitivity(Qt::CaseInsensitive); setModel(nameFilterModel); // Visual settings setRootIsDecorated(false); setAllColumnsShowFocus(true); setSortingEnabled(true); setSelectionMode(QAbstractItemView::ExtendedSelection); setItemsExpandable(false); setAutoScroll(true); setDragDropMode(QAbstractItemView::DragOnly); #if defined(Q_OS_MAC) setAttribute(Qt::WA_MacShowFocusRect, false); #endif header()->setStretchLastSection(false); // Default hidden columns if (!column_loaded) { setColumnHidden(TorrentModel::TR_ADD_DATE, true); setColumnHidden(TorrentModel::TR_SEED_DATE, true); setColumnHidden(TorrentModel::TR_UPLIMIT, true); setColumnHidden(TorrentModel::TR_DLLIMIT, true); setColumnHidden(TorrentModel::TR_TRACKER, true); setColumnHidden(TorrentModel::TR_AMOUNT_DOWNLOADED, true); setColumnHidden(TorrentModel::TR_AMOUNT_UPLOADED, true); setColumnHidden(TorrentModel::TR_AMOUNT_DOWNLOADED_SESSION, true); setColumnHidden(TorrentModel::TR_AMOUNT_UPLOADED_SESSION, true); setColumnHidden(TorrentModel::TR_AMOUNT_LEFT, true); setColumnHidden(TorrentModel::TR_TIME_ELAPSED, true); setColumnHidden(TorrentModel::TR_SAVE_PATH, true); setColumnHidden(TorrentModel::TR_COMPLETED, true); setColumnHidden(TorrentModel::TR_RATIO_LIMIT, true); setColumnHidden(TorrentModel::TR_SEEN_COMPLETE_DATE, true); setColumnHidden(TorrentModel::TR_LAST_ACTIVITY, true); setColumnHidden(TorrentModel::TR_TOTAL_SIZE, true); } //Ensure that at least one column is visible at all times bool atLeastOne = false; for (unsigned int i = 0; i<TorrentModel::NB_COLUMNS; i++) { if (!isColumnHidden(i)) { atLeastOne = true; break; } } if (!atLeastOne) setColumnHidden(TorrentModel::TR_NAME, false); //When adding/removing columns between versions some may //end up being size 0 when the new version is launched with //a conf file from the previous version. for (unsigned int i = 0; i<TorrentModel::NB_COLUMNS; i++) if (!columnWidth(i)) resizeColumnToContents(i); setContextMenuPolicy(Qt::CustomContextMenu); // Listen for list events connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(torrentDoubleClicked(QModelIndex))); connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(displayListMenu(const QPoint &))); header()->setContextMenuPolicy(Qt::CustomContextMenu); connect(header(), SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(displayDLHoSMenu(const QPoint &))); connect(header(), SIGNAL(sectionMoved(int, int, int)), this, SLOT(saveSettings())); connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(saveSettings())); connect(header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(saveSettings())); editHotkey = new QShortcut(QKeySequence("F2"), this, SLOT(renameSelectedTorrent()), 0, Qt::WidgetShortcut); deleteHotkey = new QShortcut(QKeySequence::Delete, this, SLOT(deleteSelectedTorrents()), 0, Qt::WidgetShortcut); #ifdef QBT_USES_QT5 // This hack fixes reordering of first column with Qt5. // https://github.com/qtproject/qtbase/commit/e0fc088c0c8bc61dbcaf5928b24986cd61a22777 QTableView unused; unused.setVerticalHeader(header()); header()->setParent(this); unused.setVerticalHeader(new QHeaderView(Qt::Horizontal)); #endif }
request_parser::result_type request_parser::consume(request& req, char input) { switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { state_ = method; req.method.push_back(input); return indeterminate; } case method: if (input == ' ') { state_ = uri; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.method.push_back(input); return indeterminate; } case uri: if (input == ' ') { state_ = http_version_h; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.uri.push_back(input); return indeterminate; } case http_version_h: if (input == 'H') { state_ = http_version_t_1; return indeterminate; } else { return bad; } case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return indeterminate; } else { return bad; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return indeterminate; } else { return bad; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return indeterminate; } else { return bad; } case http_version_slash: if (input == '/') { req.http_version_major = 0; req.http_version_minor = 0; state_ = http_version_major_start; return indeterminate; } else { return bad; } case http_version_major_start: if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; state_ = http_version_major; return indeterminate; } else { return bad; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return indeterminate; } else if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; return indeterminate; } else { return bad; } case http_version_minor_start: if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return indeterminate; } else { return bad; } case http_version_minor: if (input == '\r') { state_ = expecting_newline_1; return indeterminate; } else if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; return indeterminate; } else { return bad; } case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return indeterminate; } else if (!req.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.push_back(header()); req.headers.back().name.push_back(input); state_ = header_name; return indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (input == ' ' || input == '\t') { return indeterminate; } else if (is_ctl(input)) { return bad; } else { state_ = header_value; req.headers.back().value.push_back(input); return indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.back().name.push_back(input); return indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return indeterminate; } else { return bad; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.headers.back().value.push_back(input); return indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case expecting_newline_3: return (input == '\n') ? good : bad; default: return bad; } }
static void test_basic(void) { header(); plan(12); /* Create key_def */ uint32_t fields[] = { 0 }; uint32_t types[] = { FIELD_TYPE_UNSIGNED }; struct key_def *key_def = box_key_def_new(fields, types, 1); assert(key_def != NULL); struct vy_mem *mem = create_test_mem(key_def); is(mem->dump_lsn, -1, "mem->dump_lsn on empty mem"); const struct vy_stmt_template stmts[] = { STMT_TEMPLATE(100, REPLACE, 1), STMT_TEMPLATE(101, REPLACE, 1), STMT_TEMPLATE(102, REPLACE, 1), STMT_TEMPLATE(103, REPLACE, 1), STMT_TEMPLATE(104, REPLACE, 1) }; /* Check dump lsn */ struct vy_entry entry = vy_mem_insert_template(mem, &stmts[0]); is(mem->dump_lsn, -1, "mem->dump_lsn after prepare"); vy_mem_commit_stmt(mem, entry); is(mem->dump_lsn, 100, "mem->dump_lsn after commit"); /* Check vy_mem_older_lsn */ struct vy_entry older = entry; entry = vy_mem_insert_template(mem, &stmts[1]); ok(vy_entry_is_equal(vy_mem_older_lsn(mem, entry), older), "vy_mem_older_lsn 1"); ok(vy_entry_is_equal(vy_mem_older_lsn(mem, older), vy_entry_none()), "vy_mem_older_lsn 2"); vy_mem_commit_stmt(mem, entry); /* Check rollback */ struct vy_entry olderolder = entry; older = vy_mem_insert_template(mem, &stmts[2]); entry = vy_mem_insert_template(mem, &stmts[3]); ok(vy_entry_is_equal(vy_mem_older_lsn(mem, entry), older), "vy_mem_rollback 1"); vy_mem_rollback_stmt(mem, older); ok(vy_entry_is_equal(vy_mem_older_lsn(mem, entry), olderolder), "vy_mem_rollback 2"); /* Check version */ entry = vy_mem_insert_template(mem, &stmts[4]); is(mem->version, 8, "vy_mem->version") vy_mem_commit_stmt(mem, entry); is(mem->version, 9, "vy_mem->version") /* Clean up */ vy_mem_delete(mem); key_def_delete(key_def); fiber_gc(); footer(); check_plan(); }
void header1(const std::string& arg) { header(arg, 1); }
void header3(const std::string& arg) { header(arg, 3); }
void TransfersView::slotHideSection(int logicalIndex) { const bool hide = !header()->isSectionHidden(logicalIndex); header()->setSectionHidden(logicalIndex, hide); slotSaveHeader(); }
/** * The thread function in charge receiving and transmitting messages with the radio. * The received messages from RF24Network and NRF24L01 device and enqueued in the rxQueue and forwaded to the TUN/TAP device. * The messages from the TUN/TAP device (in the txQueue) are sent to the RF24Network lib and transmited over the air. * * @note Optimization: Use two thread for rx and tx with the radio, but thread synchronisation and semaphores are needed. * It may increase the throughput. */ void radioRxTxThreadFunction() { while(1) { try { network.update(); //RX section while ( network.available() ) { // Is there anything ready for us? RF24NetworkHeader header; // If so, grab it and print it out Message msg; uint8_t buffer[MAX_PAYLOAD_SIZE]; unsigned int bytesRead = network.read(header,buffer,MAX_PAYLOAD_SIZE); if (bytesRead > 0) { msg.setPayload(buffer,bytesRead); if (PRINT_DEBUG >= 1) { std::cout << "Radio: Received "<< bytesRead << " bytes ... " << std::endl; } if (PRINT_DEBUG >= 3) { printPayload(msg.getPayloadStr(),"radio RX"); } radioRxQueue.push(msg); } else { std::cerr << "Radio: Error reading data from radio. Read '" << bytesRead << "' Bytes." << std::endl; } } //End RX network.update(); // TX section while(!radioTxQueue.empty() && !radio.available() ) { Message msg = radioTxQueue.pop(); if (PRINT_DEBUG >= 1) { std::cout << "Radio: Sending "<< msg.getLength() << " bytes ... "; } if (PRINT_DEBUG >= 3) { std::cout << std::endl; //PrintDebug == 1 does not have an endline. printPayload(msg.getPayloadStr(),"radio TX"); } uint8_t *tmp = msg.getPayload(); /*printf("********WRITING************\n"); for(int i=0; i<8; i++){ //std::cout << std::hex << buffer[i] <<std::endl; //printf("%#x\n",(uint8_t)buffer[i]); //uint32_t tmp2 = 0; //tmp2 |= (uint32_t)tmp; //printf("%01x\n",tmp2); printf("0%#x\n",tmp[i]); //tmp++; }*/ tmp = msg.getPayload(); uint32_t RF24_STR = 0x34324652; //Identifies the mac as an RF24 mac uint32_t ARP_BC = 0xFFFFFFFF; //Broadcast address struct macStruct{ uint16_t rf24_Addr; uint32_t rf24_Verification; }; //struct serialip_state *s = &(uip_conn->appstate);//Creates a pointer to the application state of the current connection, which can be used to terminate it? macStruct macData; //memcpy(&macData,tmp,sizeof(macData)); memcpy(&macData.rf24_Addr,tmp,2); memcpy(&macData.rf24_Verification,tmp+2,4); //const uint16_t other_node = otherNodeAddr; bool ok = 0; if(macData.rf24_Verification == RF24_STR){ const uint16_t other_node = macData.rf24_Addr; RF24NetworkHeader header(/*to node*/ other_node, EXTERNAL_DATA_TYPE); ok = network.write(header,msg.getPayload(),msg.getLength()); printf("*************W1\n"); }else if(macData.rf24_Verification == ARP_BC){ const uint16_t other_node = otherNodeAddr; RF24NetworkHeader header(/*to node*/ 00, EXTERNAL_DATA_TYPE); //Set to master node, will be modified by RF24Network if multi-casting if(thisNodeAddr == 00){ //Master Node ok = network.multicast(header,msg.getPayload(),msg.getLength(),1 ); //Send to Level 1 }else{ ok = network.write(header,msg.getPayload(),msg.getLength()); } printf("*****************W2\n"); } printf("Addr: 0%#x\n",macData.rf24_Addr); printf("Verif: 0%#x\n",macData.rf24_Verification); if (ok) { std::cout << "ok." << std::endl; } else { std::cerr << "failed." << std::endl; } } //End Tx } catch(boost::thread_interrupted&) { std::cerr << "radioRxThreadFunction is stopped" << std::endl; return; } } }
void THttpSocket::readRequest() { T_TRACEFUNC(""); uint limitBodyBytes = Tf::app()->appSettings().value("LimitRequestBody", "0").toUInt(); qint64 bytes = 0; QByteArray buf; while ((bytes = bytesAvailable()) > 0) { buf.resize(bytes); bytes = QTcpSocket::read(buf.data(), bytes); if (bytes < 0) { tSystemError("socket read error"); break; } lastProcessed = Tf::currentDateTimeSec(); if (lengthToRead > 0) { // Writes to buffer if (fileBuffer.isOpen()) { if (fileBuffer.write(buf.data(), bytes) < 0) { throw RuntimeException(QLatin1String("write error: ") + fileBuffer.fileName(), __FILE__, __LINE__); } } else { readBuffer.append(buf.data(), bytes); } lengthToRead = qMax(lengthToRead - bytes, 0LL); } else if (lengthToRead < 0) { readBuffer.append(buf); int idx = readBuffer.indexOf("\r\n\r\n"); if (idx > 0) { THttpRequestHeader header(readBuffer); tSystemDebug("content-length: %d", header.contentLength()); if (limitBodyBytes > 0 && header.contentLength() > limitBodyBytes) { throw ClientErrorException(413); // Request Entity Too Large } lengthToRead = qMax(idx + 4 + (qint64)header.contentLength() - readBuffer.length(), 0LL); if (header.contentType().trimmed().startsWith("multipart/form-data") || header.contentLength() > READ_THRESHOLD_LENGTH) { // Writes to file buffer if (!fileBuffer.open()) { throw RuntimeException(QLatin1String("temporary file open error: ") + fileBuffer.fileTemplate(), __FILE__, __LINE__); } if (readBuffer.length() > idx + 4) { tSystemDebug("fileBuffer name: %s", qPrintable(fileBuffer.fileName())); if (fileBuffer.write(readBuffer.data() + idx + 4, readBuffer.length() - (idx + 4)) < 0) { throw RuntimeException(QLatin1String("write error: ") + fileBuffer.fileName(), __FILE__, __LINE__); } } } } } else { // do nothing break; } if (lengthToRead == 0) { emit newRequest(); } } }
int Logging_Handler::handle_input (ACE_HANDLE) { ACE_Log_Record log_record; // We need to use the old two-read trick here since TCP sockets // don't support framing natively. Allocate a message block for the // payload; initially at least large enough to hold the header, but // needs some room for alignment. ACE_Message_Block *payload_p = 0; ACE_Message_Block *header_p = 0; ACE_NEW_RETURN (header_p, ACE_Message_Block (ACE_DEFAULT_CDR_BUFSIZE), -1); auto_ptr <ACE_Message_Block> header (header_p); // Align the Message Block for a CDR stream ACE_CDR::mb_align (header.get ()); ACE_CDR::Boolean byte_order; ACE_CDR::ULong length; ssize_t count = ACE::recv_n (this->peer ().get_handle (), header->wr_ptr (), 8); switch (count) { // Handle shutdown and error cases. default: case -1: case 0: ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("server logging daemon closing down\n"))); return -1; /* NOTREACHED */ case 8: // Just fall through in this case.. break; } header->wr_ptr (8); // Reflect addition of 8 bytes. // Create a CDR stream to parse the 8-byte header. ACE_InputCDR header_cdr (header.get ()); // Extract the byte-order and use helper methods to disambiguate // octet, booleans, and chars. header_cdr >> ACE_InputCDR::to_boolean (byte_order); // Set the byte-order on the stream... header_cdr.reset_byte_order (byte_order); // Extract the length header_cdr >> length; ACE_NEW_RETURN (payload_p, ACE_Message_Block (length), -1); auto_ptr <ACE_Message_Block> payload (payload_p); // Ensure there's sufficient room for log record payload. ACE_CDR::grow (payload.get (), 8 + ACE_CDR::MAX_ALIGNMENT + length); // Use <recv_n> to obtain the contents. if (ACE::recv_n (this->peer ().get_handle (), payload->wr_ptr (), length) <= 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("recv_n()"))); return -1; } payload->wr_ptr (length); // Reflect additional bytes ACE_InputCDR payload_cdr (payload.get ()); payload_cdr.reset_byte_order (byte_order); payload_cdr >> log_record; // Finally extract the <ACE_log_record>. log_record.length (length); log_record.print (ACE_TEXT_CHAR_TO_TCHAR (this->peer_name_), 1, stderr); return 0; }
void CLevelGraph::draw_nodes () { CGameObject* O = smart_cast<CGameObject*> (Level().CurrentEntity()); Fvector POSITION = O->Position(); POSITION.y += 0.5f; // display Fvector P = POSITION; // CPosition Local; // vertex_position (Local,P); u32 ID = O->ai_location().level_vertex_id(); CGameFont* F = HUD().Font().pFontDI; F->SetHeightI (.02f); F->OutI (0.f,0.5f,"%f,%f,%f",VPUSH(P)); // float x,z; // unpack_xz (Local,x,z); // F->Out (0.f,0.55f,"%3d,%4d,%3d -> %d", iFloor(x),iFloor(Local.y()),iFloor(z),u32(ID)); svector<u32,128> linked; { const_iterator i,e; begin (ID,i,e); for(; i != e; ++i) linked.push_back(value(ID,i)); } // render float sc = header().cell_size()/16; float st = 0.98f*header().cell_size()/2; float tt = 0.01f; Fvector DUP; DUP.set(0,1,0); RCache.set_Shader (sh_debug); F->SetColor (color_rgba(255,255,255,255)); // если включён ai_dbg_frustum раскрасить ноды по light // иначе раскрашивать по cover bool b_light = false; ////////////////////////////////////////////////////////////////////////// Fvector min_position,max_position; max_position = min_position = Device.vCameraPosition; min_position.sub(30.f); max_position.add(30.f); CLevelGraph::const_vertex_iterator I, E; if (valid_vertex_position(min_position)) I = std::lower_bound(begin(),end(),vertex_position(min_position).xz(),&vertex::predicate2); else I = begin(); if (valid_vertex_position(max_position)) { E = std::upper_bound(begin(),end(),vertex_position(max_position).xz(),&vertex::predicate); if (E != end()) ++E; } else E = end(); ////////////////////////////////////////////////////////////////////////// for ( ; I != E; ++I) { const CLevelGraph::CVertex& N = *I; Fvector PC; PC = vertex_position(N); u32 Nid = vertex_id(I); if (Device.vCameraPosition.distance_to(PC)>30) continue; float sr = header().cell_size(); if (::Render->ViewBase.testSphere_dirty(PC,sr)) { u32 LL = ((b_light) ? iFloor(float(N.light())/15.f*255.f) : iFloor(vertex_cover(I)/4*255.f)); u32 CC = D3DCOLOR_XRGB(0,0,255); u32 CT = D3DCOLOR_XRGB(LL,LL,LL); u32 CH = D3DCOLOR_XRGB(0,128,0); BOOL bHL = FALSE; if (Nid==u32(ID)) { bHL = TRUE; CT = D3DCOLOR_XRGB(0,255,0); } else { for (u32 t=0; t<linked.size(); ++t) { if (linked[t]==Nid) { bHL = TRUE; CT = CH; break; } } } // unpack plane Fplane PL; Fvector vNorm; pvDecompress(vNorm,N.plane()); PL.build (PC,vNorm); // create vertices Fvector v,v1,v2,v3,v4; v.set(PC.x-st,PC.y,PC.z-st); PL.intersectRayPoint(v,DUP,v1); v1.mad(v1,PL.n,tt); // minX,minZ v.set(PC.x+st,PC.y,PC.z-st); PL.intersectRayPoint(v,DUP,v2); v2.mad(v2,PL.n,tt); // maxX,minZ v.set(PC.x+st,PC.y,PC.z+st); PL.intersectRayPoint(v,DUP,v3); v3.mad(v3,PL.n,tt); // maxX,maxZ v.set(PC.x-st,PC.y,PC.z+st); PL.intersectRayPoint(v,DUP,v4); v4.mad(v4,PL.n,tt); // minX,maxZ // render quad RCache.dbg_DrawTRI (Fidentity,v3,v2,v1,CT); RCache.dbg_DrawTRI (Fidentity,v1,v4,v3,CT); // render center Level().debug_renderer().draw_aabb (PC,sc,sc,sc,CC); // render id if (bHL) { Fvector T; Fvector4 S; T.set (PC); T.y+=0.3f; Device.mFullTransform.transform (S,T); if (S.z < 0 || S.z < 0) continue; if (S.x < -1.f || S.x > 1.f || S.y<-1.f || S.x>1.f) continue; F->SetHeightI (0.05f/_sqrt(_abs(S.w))); F->SetColor (0xffffffff); F->OutI (S.x,-S.y,"~%d",Nid); } } } }
QString KisColorSelectorSettings::name() { return header(); }
int main(){ char inputFile[24] = ""; char outFile[24] = ""; printf("Please enter the name of input data file (max 20 characters): "); scanf("%s", inputFile); strcat (inputFile,".txt"); checkForFile(inputFile, 0); printf("Please enter name of report file to be generated (max 20 characters): "); scanf("%s", outFile); strcat (outFile,".txt"); checkForFile(outFile, 1); FILE *ficaTxt = fopen("fica.txt", "r"); FILE *inFile = fopen(inputFile, "r"); FILE *reportFile = fopen(outFile, "a"); fclose(reportFile); int PK = 0; int LK = 0; const int Max_Lines = 5; int noOfRecords = 0; double ficaRate; int ficaLimit; char st1[9], st2[8]; int empNo; char givenName[15], surName[15], dept[6]; double ytd, payRate, hours; double totalGross = 0, totalFica = 0, totalNet = 0; while ( fscanf(ficaTxt, "%s %d %s %lf", st1, &ficaLimit, st2, &ficaRate) != EOF ) { }; // Get the current FICA values fclose(ficaTxt); if( PK == 0 ) header(outFile); //Start to Read the file double fica, gross, net; double tFica = 0, tGross = 0, tNet = 0; if(PK == 0) newPage(&PK, LK, outFile); while ( fscanf(inFile, "%d %s %s %s %lf %lf %lf", &empNo, givenName, surName, dept, &ytd, &payRate, &hours) != EOF ) { FILE *reportFile = fopen(outFile, "a"); // gross = calGross(hours, payRate); fica = calFica(ytd, gross, ficaLimit, ficaRate); net = calNet(gross, fica); fprintf(reportFile, "%-5d \t%-12s\t %-12s\t %5s\t %9.2f\t %8.2f\t %6.2f\t %8.2f\n", empNo, givenName, surName, dept, ytd, gross, fica, net); printf("%-5d \t%-12s\t %-12s\t %5s\t %9.2f\t %8.2f\t %6.2f\t %8.2f\n", empNo, givenName, surName, dept, ytd, gross, fica, net); noOfRecords++; totalGross += gross; totalFica += fica; totalNet += net; LK++; fclose(reportFile); // Check the Line counter to see if we need a new header if (LK == Max_Lines){ footer(PK, totalGross, totalFica, totalNet, outFile); newPage(&PK, LK, outFile); header(outFile); LK = 0; tGross += totalGross; totalGross = 0; tFica += totalFica; totalFica = 0; tNet += totalNet; totalNet = 0; } } // print the rest of the report (if theres any unaccounted items) if(LK > 0 && LK < Max_Lines){ footer(PK, totalGross, totalFica, totalNet, outFile); int i; FILE *openFile = fopen(outFile, "a"); for (i = LK; i < Max_Lines; i++){ printf("\n"); fprintf(openFile, "\n"); LK++; } PK++; fclose(openFile); } closingPage(&PK, noOfRecords, tGross, tFica, tNet, outFile); return 0; }
bool KviHttpRequest::processHeader(KviCString &szHeader) { int idx = szHeader.findFirstIdx("\r\n"); KviCString szResponse; if(idx != -1) { szResponse = szHeader.left(idx); szHeader.cutLeft(idx + 2); } else { szResponse = szHeader; szHeader = ""; } szResponse.trim(); bool bValid = false; unsigned int uStatus = 0; // check the response value if(kvi_strEqualCSN(szResponse.ptr(),"HTTP",4)) { KviCString szR = szResponse; szR.cutToFirst(' '); szR.trim(); int idx = szR.findFirstIdx(' '); KviCString szNumber; if(idx != -1)szNumber = szR.left(idx); else szNumber = szR; bool bOk; uStatus = szNumber.toUInt(&bOk); if(bOk)bValid = true; } QString szUniResponse = QString::fromUtf8(szResponse.ptr()); if(!bValid) { // the response is invalid ? resetInternalStatus(); m_szLastError = __tr2qs("Invalid HTTP response: %1").arg(szUniResponse); emit terminated(false); return false; } QString tmp = __tr2qs("Received HTTP response: %1").arg(szUniResponse); emit status(tmp); emit receivedResponse(szUniResponse); KviPointerList<KviCString> hlist; hlist.setAutoDelete(true); idx = szHeader.findFirstIdx("\r\n"); while(idx != -1) { if(idx > 0) { hlist.append(new KviCString(szHeader.ptr(),idx)); szHeader.cutLeft(idx + 2); } idx = szHeader.findFirstIdx("\r\n"); } if(szHeader.hasData())hlist.append(new KviCString(szHeader)); KviPointerHashTable<const char *,KviCString> hdr(11,false,true); hdr.setAutoDelete(true); for(KviCString * s = hlist.first();s;s = hlist.next()) { idx = s->findFirstIdx(":"); if(idx != -1) { KviCString szName = s->left(idx); s->cutLeft(idx + 1); s->trim(); hdr.replace(szName.ptr(),new KviCString(*s)); //qDebug("FOUND HEADER (%s)=(%s)",szName.ptr(),s->ptr()); } } KviCString * size = hdr.find("Content-length"); if(size) { bool bOk; m_uTotalSize = size->toUInt(&bOk); if(!bOk)m_uTotalSize = 0; } KviCString * contentEncoding = hdr.find("Content-encoding"); if(contentEncoding) { m_bGzip = contentEncoding->equalsCI("gzip"); } KviCString * transferEncoding = hdr.find("Transfer-Encoding"); if(transferEncoding) { if(kvi_strEqualCI(transferEncoding->ptr(),"chunked")) { // be prepared to handle the chunked transfer encoding as required by HTTP/1.1 m_bChunkedTransferEncoding = true; m_uRemainingChunkSize = 0; } } emit header(&hdr); // check the status // case 200: // OK // case 206: // Partial content // case 100: // Continue ?? // case 101: // Switching protocols ??? // case 201: // Created // case 202: // Accepted // case 203: // Non-Authoritative Information // case 204: // No content // case 205: // Reset content // case 300: // Multiple choices // case 301: // Moved permanently // case 302: // Found // case 303: // See Other // case 304: // Not modified // case 305: // Use Proxy // case 306: // ??? // case 307: // Temporary Redirect // case 400: // Bad request // case 401: // Unauthorized // case 402: // Payment Required // case 403: // Forbidden // case 404: // Not found // case 405: // Method not allowed // case 406: // Not acceptable // case 407: // Proxy authentication required // case 408: // Request timeout // case 409: // Conflict // case 410: // Gone // case 411: // Length required // case 412: // Precondition failed // case 413: // Request entity too large // case 414: // Request-URI Too Long // case 415: // Unsupported media type // case 416: // Requested range not satisfiable // case 417: // Expectation Failed // case 500: // Internal server error // case 501: // Not implemented // case 502: // Bad gateway // case 503: // Service unavailable // case 504: // Gateway timeout // case 505: // HTTP Version not supported if((uStatus != 200) && (uStatus != 206)) { // this is not "OK" and not "Partial content" // Error, redirect or something confusing // FIXME: Handle 30x codes by re-issuing the request with the new URI ? if(m_eProcessingType != HeadersOnly) { // this is an error then resetInternalStatus(); m_szLastError = szResponse.ptr(); emit terminated(false); return false; } // else the server will terminate (it was a HEAD request) } if((m_uMaxContentLength > 0) && (m_uTotalSize > ((unsigned int)m_uMaxContentLength))) { resetInternalStatus(); m_szLastError=__tr2qs("The amount of received data exceeds the maximum length"); emit terminated(false); return false; } // fixme: could check for data type etc... return true; }
// 'Fl_FileBrowser::load()' - Load a directory into the browser. int // O - Number of files loaded Fl_File_Browser::load(const Fl_String &dir) // I - Directory to load { Fl_String old_dir(directory()); m_dir_ds.directory(dir); clear(); clear_columns(); sort_col(1); m_up_item = 0; if(dir.empty()) { header()->add_column("", 20); // No directory specified: // - For UNIX list all mount points. // - For Win32 list all valid drive letters. //icon = Fl_FileIcon::find("any", Fl_FileIcon::DEVICE); //if (icon == (Fl_FileIcon *)0) // icon = Fl_FileIcon::find("any", Fl_FileIcon::DIR); begin(); char filename[FL_PATH_MAX]; #ifdef _WIN32 header()->add_column(_("File"), 100); header()->add_column(_("Type"), 100); header()->add_column(_("Capacity"), 100); header()->add_column(_("Free Space"), 100); // Drive available bits DWORD drives = GetLogicalDrives(); for(int i = 'A'; i <= 'Z'; i ++, drives >>= 1) { if (drives & 1) { Fl_ListView_Item *item = new Fl_ListView_Item(); item->image(&hd_pix); snprintf(filename, sizeof(filename)-1, "%c:\\", i); item->label(1, filename); Fl_File_Attr *attr = fl_file_attr(filename); if(attr->flags & Fl_File_Attr::DEVICE) { uint type = GetDriveTypeA(filename); const char *typestr=_(types[0]); if (type==DRIVE_CDROM) { typestr=_(types[4]); item->image(&cd_pix); } else if (type==DRIVE_REMOVABLE) { typestr=_(types[5]); item->image(&floppy_pix); } else if (type==DRIVE_FIXED) typestr=_(types[6]); else if (type==DRIVE_REMOTE) typestr=_(types[7]); else if (type==DRIVE_RAMDISK) typestr=_(types[8]); item->label(2, typestr); uint s = 0; Fl_String suffix; if((s = get_dev_size(attr->capacity, suffix))>0) { item->label(3, Fl_String(s)+" "+suffix); } if((s = get_dev_size(attr->free, suffix))>0) { item->label(4, Fl_String(s)+" "+suffix); } /* //TOO SLOW!!! char drivename[255]; if(GetVolumeInformation( filename, drivename, sizeof(drivename)-1, NULL, NULL, NULL, NULL, 0)) { if(drivename[0]) snprintf(fname, sizeof(fname)-1, "%s (%s)", filename, drivename); } */ } } } #else header()->add_column(_("File"), 100); header()->add_column(_("Device"), 100); header()->add_column(_("Type"), 100); FILE *mtab = 0; // /etc/mtab or /etc/mnttab file char line[1024]; // Input line char dev[256]; // Device name char fstype[256]; // Filesystem type // Open the file that contains a list of mounted filesystems... # if defined(__hpux) || defined(__sun) // Fairly standard mtab = fl_fopen("/etc/mnttab", "r"); # elif defined(__sgi) || defined(linux) // More standard mtab = fl_fopen("/etc/mtab", "r"); # endif // Otherwise fallback to full list if(mtab == NULL) mtab = fl_fopen("/etc/fstab", "r"); if(mtab == NULL) mtab = fl_fopen("/etc/vfstab", "r"); if (mtab != NULL) { while (fgets(line, sizeof(line), mtab) != NULL) { if (line[0] == '#' || line[0] == '\n') continue; if (sscanf(line, "%255s%4095s%255s", dev, filename, fstype) != 3) continue; if(!strcasecmp(dev, "none")) continue; Fl_ListView_Item *item = new Fl_ListView_Item(); item->image(&hd_pix); item->label(1, filename); item->label(2, dev); item->label(3, fstype); } fclose(mtab); } #endif // _WIN32 end(); resizable_col(0, false); return children(); } else {
static void set_boot_message() { boot_message = header("U") + TAB + mudname + TAB + (time() - uptime()) + TAB + GENERATION + TAB + comments; }
/********************************************************************************** Description: 玩家的角色基本信息更新 @param [in] info @return int @exception none */ int RobRuleValid::DoICSSetRoleInfoPro(Qhelper_Ics_Complaint& ics_info) { map<string,string> theParamIn; vector < map<string, string> > theGetResult; int iRoleExistFlag = 0; ValidLOG->WriteLog("In Valid Proccess,DoICSSetRoleInfoPro-IcsInfo==|ICSID:%s|iKind:%s|vCommand:%s|iParam_Num:%s\n",ics_info.sICSId.c_str(),ics_info.sKindID.c_str(),ics_info.vCommand.c_str(), ics_info.sParaNum.c_str()); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), "", TLOG_LEVEL_INFO, __FUNCTION__, "In Valid Proccess,DoICSSetRoleInfoPro-IcsInfo==|ICSID:%s|iKind:%s|vCommand:%s|iParam_Num:%s\n",ics_info.sICSId.c_str(),ics_info.sKindID.c_str(),ics_info.vCommand.c_str(), ics_info.sParaNum.c_str() ); //第一步角色基本信息更新:角色名字和等级 //Code From Here Only For dnf2 //解析vCommand字符串 std::map<string, string> dst_opData; std::string src_cmd = ics_info.vCommand; string flag = "&="; SplitToMap(src_cmd, dst_opData, flag, (unsigned int)2); ValidLOG->WriteLog("解析vCommand字符串, 获得用户服务器, 角色ID, src_cmd: %s | dst_opData[type]:%s | dst_opData[area]:%s | dst_opData[role_id]:%s|iParam_Num:%s\n",src_cmd.c_str(),dst_opData["type"].c_str(),dst_opData["area"].c_str(), dst_opData["role_id"].c_str(), ics_info.sParaNum.c_str() ); //ics_get_role_list ValidLOG->WriteLog("In [dnf2] Proccess,前言 准备:角色列表\n"); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["role_id"].c_str(), TLOG_LEVEL_DEBUG, __FUNCTION__, "In [dnf2] Proccess,前言 准备:角色列表\n" ); theParamIn["area"]=dst_opData["area"]; theParamIn["uin"]=""; theParamIn["role_name"]=""; theParamIn["role_id"]= dst_opData["role_id"]; ics_log_header header(ics_info.sICSId,"",ics_info.sServiceID); iRet = valid_parse.GetFunction(header,theParamIn,"ics_get_role_info",theGetResult);//角色id查询信息 if (!iRet) { for ( int i = 0; i < theGetResult.size(); i++) { ValidLOG->WriteLog("填单ID:%s| 获取玩家QQ:%s|角色ID:%s| 角色等级: %s| 工会ID:%s\n",ics_info.sICSId.c_str(),theGetResult[i]["m_id"].c_str(), theGetResult[i]["charac_no"].c_str(), theGetResult[i]["lev"].c_str(), theGetResult[i]["guild_id"].c_str()); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_DEBUG, __FUNCTION__, "填单ID:%s| 获取玩家QQ:%s|角色ID:%s| 角色等级: %s| 工会ID:%s\n",ics_info.sICSId.c_str(),theGetResult[i]["m_id"].c_str(), theGetResult[i]["charac_no"].c_str(), theGetResult[i]["lev"].c_str(), theGetResult[i]["guild_id"].c_str() ); if(theGetResult[i]["charac_no"]==dst_opData["role_id"]) { dst_opData["uin"]=theGetResult[i]["m_id"]; std::string sUin = theGetResult[i]["m_id"]; std::string sRole_Id = theGetResult[i]["charac_no"]; std::string sRole_Name = theGetResult[i]["charac_name"]; std::string sRole_Level = theGetResult[i]["lev"]; std::string sGuild_Id = theGetResult[i]["guild_id"]; //将信息连接到vCommand后 ics_info.vCommand += "&uin="+sUin; ics_info.vCommand += "&role_id="+sRole_Id; ics_info.vCommand += "&role_name="+sRole_Name; ics_info.vCommand += "&role_level="+sRole_Level; ics_info.vCommand += "&guild_id="+sGuild_Id; iRoleExistFlag = 1; ValidLOG->WriteLog("角色id查询信息cmd=%s| 获取玩家等级:%s|角色名字:%s\n",ics_info.vCommand.c_str(),sRole_Level.c_str(),sRole_Name.c_str()); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_DEBUG, __FUNCTION__, "角色id查询获取玩家等级:%s|角色名字:%s\n", sRole_Level.c_str(), sRole_Name.c_str() ); } } } if(iRoleExistFlag == 0) { if(0 <= theGetResult.size()) { string strError = theGetResult[0]["result"]; if("-1999" == strError)//停服 { ValidLOG->WriteLog("当前大区[%s]停服中\n",ics_info.sServiceID); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), "", TLOG_LEVEL_ERROR, __FUNCTION__, "当前大区[%s]停服中\n", ics_info.sServiceID.c_str() ); return -12; }else { ValidLOG->WriteLog("没有找到相关玩家角色信息\n"); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), "", TLOG_LEVEL_WARNING, __FUNCTION__, "没有找到相关玩家角色信息\n" ); return STEP_FLITER_RUN_STAT_ERROR_ROLE_INFO_NEW; } } } //角色基本信息更新:角色VIP信息 theParamIn.clear(); theGetResult.clear(); #ifdef dnf2 ValidLOG->WriteLog("In [dnf2] Proccess,第三步角色基本信息更新:角色VIP信息\n"); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_INFO, __FUNCTION__, "In [dnf2] Proccess,第三步角色基本信息更新:角色VIP信息\n"); ProCheckVIPInfo(ics_info); #endif return 0; }
void halt() { log_info("halting"); send_data(header("D")); }
/** receive_doble天内重复来单不受理; 用户暂定为1天 * params: ics_info * return: int */ int RobRuleValid::ProCheckDobleQuest(Qhelper_Ics_Complaint &ics_info) { map<string,string> theParamIn; theParamIn.clear(); //解析vCommand字符串 std::map<string, string> dst_opData; std::string src_cmd = ics_info.vCommand; string flag = "& = "; SplitToMap(src_cmd, dst_opData, flag, (unsigned int)2); ValidLOG->WriteLog("in Valid Proccess,ProCheckDobleQuest-IcsInfo==|ICSID:%s| dst_opData[area]:%s | dst_opData[role_id]:%s|iParam_Num:%s\n",ics_info.sICSId.c_str(), dst_opData["area"].c_str(), dst_opData["role_id"].c_str(), ics_info.sParaNum.c_str()); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["role_id"].c_str(), TLOG_LEVEL_DEBUG, __FUNCTION__, "in Valid Proccess,ProCheckDobleQuest-IcsInfo\n" ); theParamIn["uin"] = dst_opData["uin"]; theParamIn["apply_day_in"] = CRobConf::getConf()->GetIcsValid()["receve_double"]; //一天内 theParamIn["service_id"] = ics_info.sServiceID; #ifdef dnf2 //调试阶段以role_name代替role_id theParamIn["role_id"] = string(GbkToUtf8((char*)dst_opData["role_name"].c_str())); #endif vector< map<string,string> > base_result; theParamIn["role_id"] = dst_opData["rold_id"]; //ics_log_header header(info.sICSId,info.sUin,info.sServiceID); ics_log_header header(ics_info.sICSId,"",ics_info.sServiceID); if(0 != valid_parse.GetFunction(header,theParamIn,"ics_apply_repeat_uin",base_result)) { ValidLOG->WriteLog("In Valid Proccess, Find Uin 'ics_apply_repeat_uin' happened error,not find info\n"); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_ERROR, __FUNCTION__, "In Valid Proccess, Find Uin 'get_ics_info_by_uin' happened error,not find info\n" ); return STEP_FLITER_RUN_STAT_ERROR_INTERFACE; } //////////////////////////////////added by v_zhtang on 2012-11-20//////////////////////////////////////// int check_flag=0; int check_running_flag=0; int check_false_flag=0; int check_result=0; if(base_result.size()>1){ for(int i=0;i<base_result.size();i++){ ValidLOG->WriteLog("[Info]'ProCheckDobleQuest' Proccessing <%d>&iICSAnaylseResult=<%s>\n",base_result.size(),base_result[i]["sDesc"].c_str()); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_INFO, __FUNCTION__, "[Info]'ProCheckDobleQuest' Proccessing <%d>&iICSAnaylseResult=<%s>\n",base_result.size(),base_result[i]["sDesc"].c_str() ); //a 如果存在处理成功的---:此单据为异常单据《重复单据》 if(StrToInt(base_result[i]["sDesc"])==STEP_FLITER_RUN_STAT_SUCCESS) { ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] Get The Fromer icsID Result<%s>, Process Pass Fliter Ok, So Not Pass It\n",base_result[i]["sDesc"].c_str()); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_ERROR, __FUNCTION__, "[Info] [QhelperRuleValid::ProCheckDobleQuest] Get The Fromer icsID Result<%s>, Process Pass Fliter Ok, So Not Pass It\n",base_result[i]["sDesc"].c_str() ); return (STEP_FLITER_RUN_STAT_ERROR_APPLY_AGAIN); } //a.1 如果存在在阶段的处理的流程中的单据 if(StrToInt(base_result[i]["sDesc"]) ==STEP_FLITER_RUNNING_STAT) { ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] Runing AND False=[%s]\n",base_result[i]["sDesc"].c_str()); { check_result++; ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] Running=%s&check_result=%d\n",base_result[i]["sDesc"].c_str(),check_result); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_WARNING, __FUNCTION__, "[Info] [QhelperRuleValid::ProCheckDobleQuest] Running=%s&check_result=%d\n",base_result[i]["sDesc"].c_str(),check_result ); } } //a.2 如果存在在一次处理多的单据 if(StrToInt(base_result[i]["sICSAnaylseStatus"])==STEP_FLITER_RUNNING_STAT) { check_running_flag++; ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] LOT APPLY=%d",check_running_flag); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_WARNING, __FUNCTION__, "[Info] [QhelperRuleValid::ProCheckDobleQuest] LOT APPLY=%d",check_running_flag ); } } //如果存在各阶段处理中的单据 if(check_result>0){ return STEP_FLITER_RUN_STAT_ERROR_INTERFACE; } //如果所有的单据的都是在第一个阶段的单据 if(check_running_flag>1){ ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] STEP_FLITER_RUN_STAT_ERROR_APPLY_LOT,So Pass Last It ,check_flag=<%d>\n",check_running_flag); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_WARNING, __FUNCTION__, "[Info] [QhelperRuleValid::ProCheckDobleQuest] STEP_FLITER_RUN_STAT_ERROR_APPLY_LOT,So Pass Last It ,check_flag=<%d>\n",check_running_flag ); return STEP_FLITER_RUN_STAT_ERROR_APPLY_LOT; }else if(check_running_flag==1){ ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] STEP_FLITER_RUN_STAT_ERROR_APPLY_LOT,So I am The Last One ,check_flag=<%d>\n",check_running_flag); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_INFO, __FUNCTION__, "[Info] [QhelperRuleValid::ProCheckDobleQuest] STEP_FLITER_RUN_STAT_ERROR_APPLY_LOT,So I am The Last One ,check_flag=<%d>\n",check_running_flag ); return 0; } return 0;//其它情况 返回正常 }else if(base_result.size()==1){ ValidLOG->WriteLog("[Info] [QhelperRuleValid::ProCheckDobleQuest] The Fisrt Processing Only One, So Pass It\n"); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_INFO, __FUNCTION__, "[Info] [QhelperRuleValid::ProCheckDobleQuest] The Fisrt Processing Only One, So Pass It\n" ); return 0; }else{ ValidLOG->WriteLog("[QhelperRuleValid::ProCheckDobleQuest] The <ics_apply_repeat_uin> Processing Interface Error\n"); WriteLogsRUN(TLOG_TYPE_ROBANLYSVALID, ics_info.sICSId.c_str(), dst_opData["uin"].c_str(), TLOG_LEVEL_ERROR, __FUNCTION__, "[QhelperRuleValid::ProCheckDobleQuest] The <ics_apply_repeat_uin> Processing Interface Error" ); return STEP_FLITER_RUN_STAT_ERROR_INTERFACE; } }
void TransfersView::slotSaveHeader() { Settings::setHeaderState(header()->saveState().toBase64()); Settings::self()->writeConfig(); }
//********************************************************* // Callback method. This method gets called via // CTsFileSeek::Seek()->OnRawData2(buffer,dwBytesRead) // tsPacket : pointer to 188 byte Transport Stream packet // // This method checks if the ts packet contains a PCR timestamp // and ifso sets the PCR timestamp in m_pcrFound; void CTsFileSeek::OnTsPacket(byte* tsPacket) { if (m_pcrFound.IsValid) return ; CTsHeader header(tsPacket); CAdaptionField field; field.Decode(header,tsPacket); if (field.Pcr.IsValid) { //got a pcr, is it the correct pid? if ( (m_seekPid>0 && (header.Pid==m_seekPid)) || (m_seekPid<0) ) { // pid is valid // did we have a pcr rollover ?? if (m_duration.FirstStartPcr() > m_duration.EndPcr()) { //pcr rollover occured. //next we need to convert the pcr into filestamp //since we are seeking from 0-duration //but the file can start with any pcr timestamp if (field.Pcr.ToClock() <=m_duration.EndPcr().ToClock()) { // pcr < endpcr (second half of the file) // pcrFound= pcr+(MAXIMUM_PCR - startpcr) // StartPcr------>(0x1ffffffff;0x1ff), (0x0,0x0)--------->EndPcr m_pcrFound=field.Pcr; double d1=m_pcrFound.ToClock(); CPcr pcr2; pcr2.PcrReferenceBase = 0x1ffffffffULL; pcr2.PcrReferenceExtension = 0x1ffULL; double start=pcr2.ToClock()- m_duration.StartPcr().ToClock(); d1+=start; m_pcrFound.FromClock(d1); } else { //PCR > endpcr (first half of the file) // pcrFound= (pcr-startpcr) m_pcrFound=field.Pcr; double d1=m_pcrFound.ToClock(); double start=m_duration.StartPcr().ToClock();//earliest pcr available in the file LogDebug(" found clock %f earliest is %f", d1, start); d1-=start; LogDebug(" after sub %f", d1); m_pcrFound.FromClock(d1); } } else { //no pcr rollover occured. //next we need to convert the pcr into filestamp //since we are seeking from 0-duration //but the file can start with any pcr timestamp // formula: pcrfound = pcr-startpcr; m_pcrFound=field.Pcr; double d1=m_pcrFound.ToClock(); double start=m_duration.StartPcr().ToClock(); //earliest pcr available in the file d1-=start; m_pcrFound.FromClock(d1); } } } }
void header0(const std::string& arg) { header(arg, 0); }
//__________________________________________________________________________________ long DisplayListOfChoices (void) { ReadInTemplateFiles(); if (!availableTemplateFiles.lLength) { return -1; } long choice = -1; char buffer[2048]; _String fileAbbr, *thisLine; _SimpleList categoryDelimiters; _List categoryHeadings; for (choice = 0; choice< availableTemplateFiles.lLength; choice++) { thisLine = (_String*)(*(_List*)availableTemplateFiles(choice))(2); if (thisLine->sData[0]=='!') { categoryDelimiters<<choice; fileAbbr = *thisLine; fileAbbr.Trim (1,-1); categoryHeadings && &fileAbbr; } } choice = -1; if (categoryDelimiters.lLength==0) { while (choice == -1) { for (choice = 0; choice<availableTemplateFiles.lLength; choice++) { printf ("\n\t(%s):%s",((_String*)(*(_List*)availableTemplateFiles(choice))(0))->getStr(), ((_String*)(*(_List*)availableTemplateFiles(choice))(1))->getStr()); } printf ("\n\n Please type in the abbreviation for the file you want to use (or press ENTER to process custom batch file):"); fgets (buffer,2048,stdin); fgets (buffer,2048,stdin); fileAbbr = buffer; if (fileAbbr.FirstNonSpaceIndex()<0) { return -1; } fileAbbr.UpCase(); for (choice = 0; choice<availableTemplateFiles.lLength; choice++) { if (fileAbbr.Equal((_String*)(*(_List*)availableTemplateFiles(choice))(0))) { break; } } if (choice==availableTemplateFiles.lLength) { choice=-1; } } } else { long categNumber = -1; while (choice==-1) { if (categNumber<0) { _String header ("***************** TYPES OF STANDARD ANALYSES *****************"), verString (GetVersionString().getStr()); if (verString.sLength<header.sLength-2) { _String padder (128,true); long poop = (header.sLength-2-verString.sLength)/2; if (!poop) { poop = 1; } for (choice=0; choice<poop; choice++) { padder << ' '; } padder.Finalize(); verString = padder & '/' & verString & "\\" & padder; } printf ("\n\033[2J\033[H%s\n%s\n\n",verString.getStr(), header.getStr()); for (choice = 0; choice<categoryHeadings.lLength; choice++) { printf ("\n\t(%ld) %s",choice+1,((_String*)categoryHeadings(choice))->getStr()); } printf ("\n\n Please select type of analyses you want to list (or press ENTER to process custom batch file):"); fgets (buffer,2048,stdin); fileAbbr = buffer; if (logInputMode) { loggedUserInputs && & fileAbbr; } if (fileAbbr.FirstNonSpaceIndex()<0) { return -1; } choice = fileAbbr.toNum(); if ( choice>0 && choice<=categoryHeadings.lLength) { categNumber = choice-1; } } else { printf ("\n\033[2J\033[H ***************** FILES IN '%s' ***************** \n\n",((_String*)categoryHeadings(categNumber))->getStr()); long start = categoryDelimiters.lData[categNumber]+1, end = categNumber==categoryDelimiters.lLength-1?availableTemplateFiles.lLength:categoryDelimiters.lData[categNumber+1]; for (choice = start; choice<end; choice++) { printf ("\n\t(%ld) %s",choice-start+1,((_String*)(*(_List*)availableTemplateFiles(choice))(1))->getStr()); } printf ("\n\n Please select the file you want to use (or press ENTER to return to the list of analysis types):"); fileAbbr = *StringFromConsole (); if (logInputMode) { loggedUserInputs && & fileAbbr; } if (fileAbbr.FirstNonSpaceIndex()<0) { categNumber = -1; } else { choice = fileAbbr.toNum(); if ((choice>0 && choice<=end-start)) { return start+choice-1; } } } choice = -1; } } return choice; }
void header2(const std::string& arg) { header(arg, 2); }
void MasterPlaylist::add_header(HlsConfigParams & config) { Section header("header"); header.add_tag("M3U"); //header.add_tag("VERSION", 3); playlist.add_section(header); for(auto it = config.variant_streams.begin(), ite= config.variant_streams.end(); it != ite; it++) { std::ostringstream oss; oss << "\""; if(it->vid.codec == h264video) oss << "avc1"; //profile if(it->vid.profile == "baseline") oss << ".4200"; else if(it->vid.profile == "main") oss << ".4d00"; else if(it->vid.profile == "high") oss << ".6400"; //level if(it->vid.level == 3.0) oss << "1e"; else if(it->vid.level == 3.1) oss << "1f"; //audio if(it->aud.codec == mpeg4audio_latm && it->aud.subtype == "aac-lc") oss << ",mp4a.40.2"; else if(it->aud.codec == mpeg2audio_adts && it->aud.subtype == "aac-lc") oss << ",mp4a.20.2"; oss << "\""; { Section node("n1"); Tag t("STREAM-INF"); t.add_property("BANDWIDTH", it->bandwidth); t.add_property("RESOLUTION",it->vid.resolution); t.add_property("CODECS",oss.str()); node.add_tag(t); node.set_path((config.web_server_url + it->id).c_str()); node.set_locator("media.m3u8"); playlist.add_section(node); } { Section node("n1"); Tag t("I-FRAME-STREAM-INF"); t.add_property("BANDWIDTH", it->bandwidth/10); t.add_property("RESOLUTION",it->vid.resolution); t.add_property("CODECS",oss.str()); oss.str(""); oss << "\"" << config.web_server_url ; if(!config.web_server_url.empty() && config.web_server_url.find_last_of("/") != (config.web_server_url.size()-1)) oss << "/" ; oss << it->id << "/iframe.m3u8\""; t.add_property("URI", oss.str()); node.add_tag(t); playlist.add_section(node); } } }
void K3bDataFileView::slotDropped( QDropEvent* e, QListViewItem*, QListViewItem* ) { // remove any highlighting if( m_dropDirItem ) { m_dropDirItem->highlightIcon( false ); m_dropDirItem = 0; } if( !e->isAccepted() ) return; // determine K3bDirItem to add the items to m_addParentDir = currentDir(); if( K3bDataDirViewItem* dirViewItem = dynamic_cast<K3bDataDirViewItem*>( itemAt(contentsToViewport(e->pos())) ) ) { // only add to a dir if we drop directly on the name if( header()->sectionAt( e->pos().x() ) == 0 ) m_addParentDir = dirViewItem->dirItem(); } if( m_addParentDir ) { // check if items have been moved if( e->source() == viewport() ) { // move all selected items QPtrList<QListViewItem> selectedViewItems = selectedItems(); QValueList<K3bDataItem*> selectedDataItems; QPtrListIterator<QListViewItem> it( selectedViewItems ); for( ; it.current(); ++it ) { K3bDataViewItem* dataViewItem = dynamic_cast<K3bDataViewItem*>( it.current() ); if( dataViewItem ) selectedDataItems.append( dataViewItem->dataItem() ); else kdDebug() << "no dataviewitem" << endl; } K3bDataUrlAddingDialog::copyMoveItems( selectedDataItems, m_addParentDir, this, e->action() == QDropEvent::Copy ); } else if( e->source() == m_treeView->viewport() ) { // move the selected dir if( K3bDataDirViewItem* dirItem = dynamic_cast<K3bDataDirViewItem*>( m_treeView->selectedItem() ) ) { QValueList<K3bDataItem*> selectedDataItems; selectedDataItems.append( dirItem->dirItem() ); K3bDataUrlAddingDialog::copyMoveItems( selectedDataItems, m_addParentDir, this, e->action() == QDropEvent::Copy ); } } else { // seems that new items have been dropped m_addUrls.clear(); if( KURLDrag::decode( e, m_addUrls ) ) { // // This is a small (not to ugly) hack to circumvent problems with the // event queues: the url adding dialog will be non-modal regardless of // the settings in case we open it directly. // QTimer::singleShot( 0, this, SLOT(slotAddUrls()) ); } } } // now grab that focus setFocus(); }
void Sync::update(void) { // Pump the network network.update(); // Look for changes to the data uint8_t message[32]; uint8_t *mptr = message; unsigned at = 0; while ( at < len ) { if ( app_data && internal_data && app_data[at] != internal_data[at] ) { // Compose a message with the deltas *mptr++ = at + 1; *mptr++ = app_data[at]; // Update our internal view internal_data[at] = app_data[at]; } ++at; } // Zero out the remainder while ( at++ < sizeof(message) ) *mptr++ = 0; // If changes, send a message if ( *message ) { // TODO handle the case where this has to be broken into // multiple messages RF24NetworkHeader header(/*to node*/ to_node, /*type*/ 'S' /*Sync*/); network.write(header,message,sizeof(message)); } // Look for messages from the network // Is there anything ready for us? if ( network.available() ) { // If so, take a look at it RF24NetworkHeader header; network.peek(header); switch (header.type) { case 'S': IF_SERIAL_DEBUG(printf_P(PSTR("%lu: SYN Received sync message\n\r"),millis())); network.read(header,&message,sizeof(message)); // Parse the message and update the vars mptr = message; at = 0; while ( mptr < message + sizeof(message) ) { // A '0' in the first position means we are done if ( !*mptr ) break; uint8_t pos = (*mptr++) - 1; uint8_t val = *mptr++; IF_SERIAL_DEBUG(printf_P(PSTR("%lu: SYN Updated position %u to value %u\n\r"),millis(),pos,val)); app_data[pos] = val; internal_data[pos] = val; } break; default: // Leave other messages for the app break; }; } }
static size_t headerCallback(void* data, size_t size, size_t nmemb, void* user) { const char* header_line = (const char*)data; size_t header_len = size * nmemb; LLURLRequestComplete* complete = (LLURLRequestComplete*)user; if (!complete || !header_line) { return header_len; } // *TODO: This should be a utility in llstring.h: isascii() for (size_t i = 0; i < header_len; ++i) { if (header_line[i] < 0) { return header_len; } } std::string header(header_line, header_len); // Per HTTP spec the first header line must be the status line. if (header.substr(0,5) == "HTTP/") { std::string::iterator end = header.end(); std::string::iterator pos1 = std::find(header.begin(), end, ' '); if (pos1 != end) ++pos1; std::string::iterator pos2 = std::find(pos1, end, ' '); if (pos2 != end) ++pos2; std::string::iterator pos3 = std::find(pos2, end, '\r'); std::string version(header.begin(), pos1); std::string status(pos1, pos2); std::string reason(pos2, pos3); S32 status_code = atoi(status.c_str()); if (status_code > 0) { complete->httpStatus((U32)status_code, reason); return header_len; } } std::string::iterator sep = std::find(header.begin(),header.end(),':'); if (sep != header.end()) { std::string key(header.begin(), sep); std::string value(sep + 1, header.end()); key = utf8str_tolower(utf8str_trim(key)); value = utf8str_trim(value); complete->header(key, value); } else { LLStringUtil::trim(header); if (!header.empty()) { llwarns << "Unable to parse header: " << header << llendl; } } return header_len; }
void AabbQueryDemo::queryAabbMT() { HK_TIMER_BEGIN_LIST("queryAabbMT", "setup"); hkAabb aabb; // Grab a body from the world, and compute it's AABB + some padding const hkpCollidable* queryCollidable; { queryCollidable = m_collidables[m_collIdx]; hkpRigidBody* rb = hkGetRigidBody(queryCollidable); queryCollidable->getShape()->getAabb(rb->getTransform(), 20.0f, aabb); } hkArray<hkpKdTreeAabbCommand> commands; commands.setSize(numQueries); // // For performance timings, we query the same AABB multiple times and overwrite the results. // When using this, make sure to use different output arrays! // hkArray<hkPrimitiveId> output; output.setSize(50); // // Set up the commands for the job // for (int i=0; i<commands.getSize(); i++) { hkpKdTreeAabbCommand& command = commands[i]; command.m_aabb = aabb; command.m_results = output.begin(); command.m_resultsCapacity = output.getSize(); command.m_numResultsOut = 0; } // // Setup the job // hkArray<hkpRayCastQueryJobHeader> header(1); hkpKdTreeAabbJob aabbJob(header.begin(), commands.begin(), commands.getSize(), &m_semaphore); aabbJob.m_numTrees = 1; aabbJob.m_trees[0] = m_world->m_kdTreeManager->getTree(); m_jobQueue->addJob( *reinterpret_cast<hkJobQueue::JobQueueEntry*>(&aabbJob), hkJobQueue::JOB_HIGH_PRIORITY ); HK_TIMER_SPLIT_LIST("process"); m_jobThreadPool->processAllJobs( m_jobQueue ); m_jobThreadPool->waitForCompletion(); m_semaphore.acquire(); HK_TIMER_END_LIST(); // // Run the same query on the broadphase for comparison purposes // hkArray<hkpBroadPhaseHandlePair> sapHits; { HK_TIME_CODE_BLOCK("BroadphaseQueryAabb", HK_NULL); for (int i=0; i<numQueries; i++) { sapHits.clear(); m_world->getBroadPhase()->querySingleAabb( aabb, sapHits ); } } // // Check results and draw // for (int i=0; i<commands.getSize(); i++) { hkpKdTreeAabbCommand& command = commands[i]; hkBool jobOk = compareHitArrays(command.m_aabb, command.m_results, command.m_numResultsOut, sapHits); for (int j=0; j<command.m_numResultsOut; j++) { HK_SET_OBJECT_COLOR(command.m_results[j], hkColor::YELLOW); } HK_SET_OBJECT_COLOR((hkUlong)queryCollidable, hkColor::LIME); if( !jobOk ) { m_env->m_textDisplay->outputText("MT Hit lits differed!", 20, 250, (hkUint32) hkColor::RED); } } }
static void test_iterator_restore_after_insertion() { header(); plan(1); /* Create key_def */ uint32_t fields[] = { 0 }; uint32_t types[] = { FIELD_TYPE_UNSIGNED }; struct key_def *key_def = box_key_def_new(fields, types, 1); assert(key_def != NULL); /* Create format */ struct tuple_format *format = vy_stmt_format_new(&stmt_env, &key_def, 1, NULL, 0, 0, NULL); assert(format != NULL); tuple_format_ref(format); /* Create lsregion */ struct lsregion lsregion; struct slab_cache *slab_cache = cord_slab_cache(); lsregion_create(&lsregion, slab_cache->arena); struct vy_entry select_key = vy_entry_key_new(stmt_env.key_format, key_def, NULL, 0); struct mempool history_node_pool; mempool_create(&history_node_pool, cord_slab_cache(), sizeof(struct vy_history_node)); uint64_t restore_on_value = 20; uint64_t restore_on_value_reverse = 60; char data[16]; char *end = data; end = mp_encode_array(end, 1); end = mp_encode_uint(end, restore_on_value); struct vy_entry restore_on_key; restore_on_key.stmt = vy_stmt_new_replace(format, data, end); restore_on_key.hint = vy_stmt_hint(restore_on_key.stmt, key_def); vy_stmt_set_lsn(restore_on_key.stmt, 100); end = data; end = mp_encode_array(end, 1); end = mp_encode_uint(end, restore_on_value_reverse); struct vy_entry restore_on_key_reverse; restore_on_key_reverse.stmt = vy_stmt_new_replace(format, data, end); restore_on_key_reverse.hint = vy_stmt_hint(restore_on_key_reverse.stmt, key_def); vy_stmt_set_lsn(restore_on_key_reverse.stmt, 100); bool wrong_output = false; int i_fail = 0; for (uint64_t i = 0; i < ((1000ULL * 3) << 2); i++) { uint64_t v = i; bool direct = !(v & 1); v >>= 1; bool has40_50 = v & 1; v >>= 1; bool has40_150 = v & 1; v >>= 1; const size_t possible_count = 9; uint64_t middle_value = possible_count / 2 * 10; /* 40 */ bool hasX_100[possible_count]; /* X = 0,10,20,30,40,50,60,70,80 */ bool addX_100[possible_count]; /* X = 0,10,20,30,40,50,60,70,80 */ bool add_smth = false; for (size_t j = 0; j < possible_count; j++) { uint64_t trinity = v % 3; v /= 3; hasX_100[j] = trinity == 1; addX_100[j] = trinity == 2; add_smth = add_smth || addX_100[j]; } if (!add_smth) continue; uint64_t expected_count = 0; uint64_t expected_values[possible_count]; int64_t expected_lsns[possible_count]; if (direct) { for (size_t j = 0; j < possible_count; j++) { if (hasX_100[j]) { expected_values[expected_count] = j * 10; expected_lsns[expected_count] = 100; expected_count++; } else if (j == possible_count / 2 && has40_50) { expected_values[expected_count] = middle_value; expected_lsns[expected_count] = 50; expected_count++; } } } else { for (size_t k = possible_count; k > 0; k--) { size_t j = k - 1; if (hasX_100[j]) { expected_values[expected_count] = j * 10; expected_lsns[expected_count] = 100; expected_count++; } else if (j == possible_count / 2 && has40_50) { expected_values[expected_count] = middle_value; expected_lsns[expected_count] = 50; expected_count++; } } } /* Create mem */ struct vy_mem *mem = create_test_mem(key_def); if (has40_50) { const struct vy_stmt_template temp = STMT_TEMPLATE(50, REPLACE, 40); vy_mem_insert_template(mem, &temp); } if (has40_150) { const struct vy_stmt_template temp = STMT_TEMPLATE(150, REPLACE, 40); vy_mem_insert_template(mem, &temp); } for (size_t j = 0; j < possible_count; j++) { if (hasX_100[j]) { const struct vy_stmt_template temp = STMT_TEMPLATE(100, REPLACE, j * 10); vy_mem_insert_template(mem, &temp); } } struct vy_mem_iterator itr; struct vy_mem_iterator_stat stats = {0, {0, 0}}; struct vy_read_view rv; rv.vlsn = 100; const struct vy_read_view *prv = &rv; vy_mem_iterator_open(&itr, &stats, mem, direct ? ITER_GE : ITER_LE, select_key, &prv); struct vy_entry e; struct vy_history history; vy_history_create(&history, &history_node_pool); int rc = vy_mem_iterator_next(&itr, &history); e = vy_history_last_stmt(&history); assert(rc == 0); size_t j = 0; while (e.stmt != NULL) { if (j >= expected_count) { wrong_output = true; break; } uint32_t val = 42; tuple_field_u32(e.stmt, 0, &val); if (val != expected_values[j] || vy_stmt_lsn(e.stmt) != expected_lsns[j]) { wrong_output = true; break; } j++; if (direct && val >= middle_value) break; else if(!direct && val <= middle_value) break; int rc = vy_mem_iterator_next(&itr, &history); e = vy_history_last_stmt(&history); assert(rc == 0); } if (e.stmt == NULL && j != expected_count) wrong_output = true; if (wrong_output) { i_fail = i; break; } for (size_t j = 0; j < possible_count; j++) { if (addX_100[j]) { const struct vy_stmt_template temp = STMT_TEMPLATE(100, REPLACE, j * 10); vy_mem_insert_template(mem, &temp); } } expected_count = 0; if (direct) { for (size_t j = 0; j < possible_count; j++) { if (j * 10 <= restore_on_value) continue; if (hasX_100[j] || addX_100[j]) { expected_values[expected_count] = j * 10; expected_lsns[expected_count] = 100; expected_count++; } else if (j == possible_count / 2 && has40_50) { expected_values[expected_count] = middle_value; expected_lsns[expected_count] = 50; expected_count++; } } } else { for (size_t k = possible_count; k > 0; k--) { size_t j = k - 1; if (j * 10 >= restore_on_value_reverse) continue; if (hasX_100[j] || addX_100[j]) { expected_values[expected_count] = j * 10; expected_lsns[expected_count] = 100; expected_count++; } else if (j == possible_count / 2 && has40_50) { expected_values[expected_count] = middle_value; expected_lsns[expected_count] = 50; expected_count++; } } } if (direct) rc = vy_mem_iterator_restore(&itr, restore_on_key, &history); else rc = vy_mem_iterator_restore(&itr, restore_on_key_reverse, &history); e = vy_history_last_stmt(&history); j = 0; while (e.stmt != NULL) { if (j >= expected_count) { wrong_output = true; break; } uint32_t val = 42; tuple_field_u32(e.stmt, 0, &val); if (val != expected_values[j] || vy_stmt_lsn(e.stmt) != expected_lsns[j]) { wrong_output = true; break; } j++; int rc = vy_mem_iterator_next(&itr, &history); e = vy_history_last_stmt(&history); assert(rc == 0); } if (j != expected_count) wrong_output = true; if (wrong_output) { i_fail = i; break; } vy_history_cleanup(&history); vy_mem_delete(mem); lsregion_gc(&lsregion, 2); } ok(!wrong_output, "check wrong_output %d", i_fail); /* Clean up */ mempool_destroy(&history_node_pool); tuple_unref(select_key.stmt); tuple_unref(restore_on_key.stmt); tuple_unref(restore_on_key_reverse.stmt); tuple_format_unref(format); lsregion_destroy(&lsregion); key_def_delete(key_def); fiber_gc(); check_plan(); footer(); }
template<typename PointT> int pcl::PCDWriter::appendBinary(const std::string &file_name, const pcl::PointCloud<PointT> &cloud) { if(cloud.empty()) { throw pcl::IOException("[pcl::PCDWriter::appendBinary] Input point cloud has no data!"); return -1; } if(!boost::filesystem::exists(file_name)) return writeBinary(file_name, cloud); std::ifstream file_istream; file_istream.open(file_name.c_str(), std::ifstream::binary); if(!file_istream.good()) { throw pcl::IOException("[pcl::PCDWriter::appendBinary] Error opening file for reading"); return -1; } file_istream.seekg(0, std::ios_base::end); size_t file_size = file_istream.tellg(); file_istream.close(); pcl::PCLPointCloud2 tmp_cloud; PCDReader reader; if(reader.readHeader(file_name, tmp_cloud) != 0) { throw pcl::IOException("[pcl::PCDWriter::appendBinary] Failed reading header"); return -1; } if(tmp_cloud.height != 1 || cloud.height != 1) { throw pcl::IOException("[pcl::PCDWriter::appendBinary] can't use appendBinary with a point cloud that " "has height different than 1!"); return -1; } tmp_cloud.width += cloud.width; std::ostringstream oss; pcl::PointCloud<PointT> tmp_cloud2; // copy the header values: tmp_cloud2.header = tmp_cloud.header; tmp_cloud2.width = tmp_cloud.width; tmp_cloud2.height = tmp_cloud.height; tmp_cloud2.is_dense = tmp_cloud.is_dense; oss << PCDWriter::generateHeader(tmp_cloud2, tmp_cloud2.width) << "DATA binary\n"; size_t data_idx = oss.tellp(); #if _WIN32 HANDLE h_native_file = CreateFileA (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h_native_file == INVALID_HANDLE_VALUE) { throw pcl::IOException ("[pcl::PCDWriter::appendBinary] Error during CreateFile!"); return (-1); } #else int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_APPEND, static_cast<mode_t> (0600)); if (fd < 0) { throw pcl::IOException ("[pcl::PCDWriter::appendBinary] Error during open!"); return (-1); } #endif // Mandatory lock file boost::interprocess::file_lock file_lock; setLockingPermissions (file_name, file_lock); std::vector<pcl::PCLPointField> fields; std::vector<int> fields_sizes; size_t fsize = 0; size_t data_size = 0; size_t nri = 0; pcl::getFields (cloud, fields); // Compute the total size of the fields for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].name == "_") continue; int fs = fields[i].count * getFieldSize (fields[i].datatype); fsize += fs; fields_sizes.push_back (fs); fields[nri++] = fields[i]; } fields.resize (nri); data_size = cloud.points.size () * fsize; data_idx += (tmp_cloud.width - cloud.width) * fsize; if (data_idx != file_size) { const char *msg = "[pcl::PCDWriter::appendBinary] The expected data size and the current data size are different!"; PCL_WARN(msg); throw pcl::IOException (msg); return -1; } // Prepare the map #if _WIN32 HANDLE fm = CreateFileMappingA (h_native_file, NULL, PAGE_READWRITE, 0, (DWORD) (data_idx + data_size), NULL); char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + data_size)); CloseHandle (fm); #else // Stretch the file size to the size of the data off_t result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET); if (result < 0) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); PCL_ERROR ("[pcl::PCDWriter::appendBinary] lseek errno: %d strerror: %s\n", errno, strerror (errno)); throw pcl::IOException ("[pcl::PCDWriter::appendBinary] Error during lseek ()!"); return (-1); } // Write a bogus entry so that the new file size comes in effect result = static_cast<int> (::write (fd, "", 1)); if (result != 1) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::appendBinary] Error during write ()!"); return (-1); } char *map = static_cast<char*> (mmap (0, data_idx + data_size, PROT_WRITE, MAP_SHARED, fd, 0)); if (map == reinterpret_cast<char*> (-1)) //MAP_FAILED) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::appendBinary] Error during mmap ()!"); return (-1); } #endif char* out = &map[0] + data_idx; // Copy the data for (size_t i = 0; i < cloud.points.size (); ++i) { int nrj = 0; for (size_t j = 0; j < fields.size (); ++j) { memcpy (out, reinterpret_cast<const char*> (&cloud.points[i]) + fields[j].offset, fields_sizes[nrj]); out += fields_sizes[nrj++]; } } // write the new header: std::string header(oss.str()); memcpy(map, header.c_str(), header.size()); // If the user set the synchronization flag on, call msync #if !_WIN32 if (map_synchronization_) msync (map, data_idx + data_size, MS_SYNC); #endif // Unmap the pages of memory #if _WIN32 UnmapViewOfFile (map); #else if (munmap (map, (data_idx + data_size)) == -1) { pcl_close (fd); resetLockingPermissions (file_name, file_lock); throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during munmap ()!"); return (-1); } #endif // Close file #if _WIN32 CloseHandle (h_native_file); #else pcl_close (fd); #endif resetLockingPermissions (file_name, file_lock); return 0; }