void OpTransform::ParseLine(const char *buffer) { vector<string> vs; if (buffer[0] == '#') return; if (EQn(buffer,"TRANSFORM",7)) { //Split into TRANSFORM reactantSMARTS ProductSMARTS tokenize(vs, buffer, " >\t\n"); OBChemTsfm tr; if (vs.empty() || vs.size() < 3 || vs[1].empty() || vs[2].empty()) { string mes("Could not parse line:\n"); obErrorLog.ThrowError(__FUNCTION__, mes + buffer, obWarning); } else { if(!tr.Init(vs[1],vs[2])) { string mes("Could not make valid transform from the line:\n"); obErrorLog.ThrowError(__FUNCTION__, mes + buffer, obWarning); } else _transforms.push_back(tr); } } }
//READ---------------------------------------------------------------------------------- void MainThread::Read() { qCritical()<<"READ "; QTcpSocket* sock= ((QTcpSocket*)(this->sender())); QByteArray array=sock->readAll(); QString buffer = array; int id; id=cl->ID(sock); qCritical()<<buffer; if (!buffer.contains("#/")) { sock->disconnectFromHost(); return; } QStringList strList=buffer.split("#/"); if (strList.isEmpty()) return; QStringListIterator iter(strList); while(iter.hasNext()) { QString buf=iter.next(); if( buf.contains(structure.prefix+ structure.key+ structure.separator+structure.login+ structure.prefix) ) { qCritical()<<"RES2"; QSharedPointer<IMessage> mes(new Message(buf)); mes->AddPart(keys.s,QString::number(cl->ID(sock))); emit authentification(mes); return; } if( buf.contains(structure.prefix+structure.key+structure.separator+structure.send+structure.prefix)) { QSharedPointer<IMessage> mes(new Message(buf)); mes->AddPart(keys.s,QString::number(cl->ID(sock))); emit send(mes); return; } if( buf.contains(structure.prefix+structure.key+structure.separator+structure.addfriend+structure.prefix)) { addFriend(sock, id, buf); return; } if( buf.contains(structure.prefix+structure.key+structure.separator+structure.removefriend+structure.prefix)) { removeFriend(sock, id, buf); return; } } }
pointer seld_notes() { amc_found=tst_alive_amc(); if (!amc_found && !find_amc()) return Error_0("STOP! amc not running"); BMessage mes(STORE_SEL), reply; StoredNote *notes; Settings *settings; ssize_t bytes=0; int n, items=0; amc_application.SendMessage(&mes,&reply); puts("amc did reply"); switch (reply.what) { case CONTENTS_SEL: reply.FindData(SELD_NOTES,B_OBJECT_TYPE,(const void**)(¬es),&bytes); items=bytes/sizeof(StoredNote); reply.FindData(SETTINGS,B_OBJECT_TYPE,(const void**)(&settings),&bytes); break; default: return Error_0("seld notes: unknown reply"); } pointer ptr, out=nil_pointer(); for (n=0;n<items;++n) { ptr=cons(mk_integer(notes[n].lnr), cons(mk_integer(notes[n].snr), cons(mk_integer(notes[n].sign), cons(mk_integer(notes[n].dur),nil_pointer())))); out=cons(ptr,out); } ptr=cons(mk_integer(settings->meter),nil_pointer()); ptr=cons(mk_symbol("meter"),ptr); ptr=cons(ptr,nil_pointer()); return cons(ptr,out); }
void secure_session_test(){ std::string mes("the test message"); callback client_callbacks; std::string client_id("client"); std::string server_id("server"); themispp::secure_session_t client(std::vector<uint8_t>(client_id.c_str(), client_id.c_str()+client_id.length()), std::vector<uint8_t>(client_priv, client_priv+sizeof(client_priv)), &client_callbacks); callback server_callbacks; themispp::secure_session_t server(std::vector<uint8_t>(server_id.c_str(), server_id.c_str()+server_id.length()), std::vector<uint8_t>(server_priv, server_priv+sizeof(server_priv)), &server_callbacks); std::vector<uint8_t> control_msg1=client.init(); std::vector<uint8_t> control_msg2=server.unwrap(control_msg1); std::vector<uint8_t> control_msg3=client.unwrap(control_msg2); std::vector<uint8_t> control_msg4=server.unwrap(control_msg3); std::vector<uint8_t> control_msg5=client.unwrap(control_msg4); sput_fail_unless(server.is_established(), "server ready", __LINE__); sput_fail_unless(client.is_established(), "client ready", __LINE__); std::vector<uint8_t> msg1=client.wrap(std::vector<uint8_t>(mes.c_str(), mes.c_str()+mes.length()+1)); std::vector<uint8_t> msg2=server.unwrap(msg1); sput_fail_unless(strcmp(mes.c_str(), (const char*)(&msg2[0]))==0, "server get message", __LINE__); std::vector<uint8_t> msg3=server.wrap(std::vector<uint8_t>(mes.c_str(), mes.c_str()+mes.length()+1)); std::vector<uint8_t> msg4=client.unwrap(msg3); sput_fail_unless(strcmp(mes.c_str(), (const char*)(&msg4[0]))==0, "client get message", __LINE__); }
void UT_CPELogEvent::SendMessage( const MEngineMonitor::TPEMessagesFromPhoneEngine aMessage, const TInt aCallId ) { TInt mes(aMessage); TInt call(aCallId); }
inline CppUnit::Message arrays_not_equal_msg( const T1* A, size_t A_len, const T2* B, size_t B_len ) { CppUnit::Message mes( "Equality Assertion Failed for Arrays" ); std::ostringstream strA; if (A_len == 0) strA << "(empty)"; else { strA << '[' << A[0]; for (size_t i = 1; i < A_len; ++i) strA << ',' << A[i]; strA << ']'; } mes.addDetail( std::string( "Expected: ") + strA.str() ); std::ostringstream strB; if (B_len == 0) strB << "(empty)"; else { strB << '[' << B[0]; for (size_t i = 1; i < B_len; ++i) strB << ',' << B[i]; strB << ']'; } mes.addDetail( std::string( "Actual: ") + strB.str() ); return mes; }
inline CppUnit::Message mat_not_equal_check_msg( const Mesquite::MsqMatrix<R,C>& A, const Mesquite::MsqMatrix<R,C>& B ) { CppUnit::Message mes( "Matrix Inequality Assertion Failed" ); mes.addDetail( std::string( "Expected: ") + msq_mat_str(A) ); mes.addDetail( std::string( "Actual: ") + msq_mat_str(B) ); return mes; }
void counter_task(void){ unsigned int count=0; char s[40]; /* タイマモニタウィンドウ作成 */ struct WINDOW *window2=windowctl.create(750,350,140,40,"Timer Monitor") ; Aqua aqua; // 背景全体 aqua.stripebox(window2, 0, 0, 140, 40, 0xF3F3F3); windowctl.all_refresh(window2) ; for(;;) { if (timerctl.check_count(300)) break ; //タイマカウンタの表示 aqua.stripebox(window2, 25, 5, 80, 15, 0xF3F3F3); sprintf(s, "%010d", timerctl.count); mes(window2,25,5,s); windowctl.refresh(window2, 25, 5, 80, 20) ; } //高速カウンタ for (;;) { //タイマカウンタの表示 /* color(220,220,220) ; boxf(window2,20,5,94,15) ; sprintf(s, "%010d", timerctl.count); mes(window2,20,5,s); shtctl.refresh(window2, 20, 5, 94, 15) ; */ count++ ; if (timerctl.check_count(1000)){ //高速カウンタの表示 aqua.stripebox(window2, 25, 25, 80, 15, 0xF3F3F3); sprintf(s, "%010d", count); mes(window2,25,25,s); windowctl.refresh(window2, 25, 25, 94, 15) ; } } }
// low level interface std::vector<std::vector<unsigned char> > sdOSCResponder::forwardOSCMessage(std::vector<unsigned char> message){ sdOSCMessage mes(message); std::vector<sdOSCMessage> rMesVector = forwardOSCMessage(mes); std::vector<sdOSCMessage>::iterator it = rMesVector.begin(); std::vector<std::vector<unsigned char> > rRawVector; while(it != rMesVector.end()){ sdOSCMessage m = *it; rRawVector.push_back(m.getOSCMessage()); it++; } return rRawVector; }
void GribRequestSetting::OnTimeRangeChange(wxCommandEvent &event) { m_pWModel->Show( IsZYGRIB && m_pWaves->IsChecked()); if( m_pModel->GetCurrentSelection() == 0 ) { //gfs if( m_pTimeRange->GetCurrentSelection() > 6 ) { //time range more than 8 days m_pWaves->SetValue(0); m_pWaves->Enable(false); wxMessageDialog mes(this, _("You request a forecast for more than 8 days horizon.\nThis is conflicting with Wave data which will be removed from your request.\nDon't forget that beyond the first 8 days, the resolution will be only 2.5\u00B0x2.5\u00B0 and the time intervall 12 hours."), _("Warning!"), wxOK); mes.ShowModal(); } else m_pWaves->Enable(true); } if(m_AllowSend) m_MailImage->SetValue( WriteMail() ); SetMailImageSize(); }
bool PainterFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv) { OBMol* pmol = dynamic_cast<OBMol*>(pOb); if(pmol==NULL) return false; ostream& ofs = *pConv->GetOutStream(); OBMol workingmol(*pmol); // Copy the molecule //*** Coordinate generation *** //Generate coordinates only if no existing 2D coordinates if(!workingmol.Has2D(true)) { OBOp* pOp = OBOp::FindType("gen2D"); if(!pOp) { obErrorLog.ThrowError("PainterFormat", "gen2D not found", obError, onceOnly); return false; } if(!pOp->Do(&workingmol)) { obErrorLog.ThrowError("PainterFormat", string(workingmol.GetTitle()) + "- Coordinate generation unsuccessful", obError); return false; } } if(!workingmol.Has2D() && workingmol.NumAtoms()>1) { string mes("Molecule "); mes += workingmol.GetTitle(); mes += " needs 2D coordinates to display in PNG2format"; obErrorLog.ThrowError("PainterFormat", mes, obError); return false; } CommandPainter painter(*pConv->GetOutStream()); OBDepict depictor(&painter); if(pConv->IsOption("M")) depictor.SetOption(OBDepict::noMargin); depictor.DrawMolecule(&workingmol); return true; //or false to stop converting }
/* set settings to the dialog controls */ void GribSettingsDialog::WriteSettings() { if(m_Settings.m_bInterpolate != m_cInterpolate->GetValue()) { m_Settings.m_bInterpolate = m_cInterpolate->GetValue(); if(m_cInterpolate->IsChecked()) { wxMessageDialog mes(this, _("This file contains data for particular times and you have chosen to display data for different times.\nPlease consider that these values will be interpolated."), _("Warning!"), wxOK); mes.ShowModal(); } } m_Settings.m_bLoopMode = m_cLoopMode->GetValue(); m_Settings.m_SlicesPerUpdate = m_sSlicesPerUpdate->GetValue(); m_Settings.m_UpdatesPerSecond = m_sUpdatesPerSecond->GetValue(); m_Settings.m_HourDivider = m_sHourDivider->GetValue(); SetDataTypeSettings(m_lastdatatype); m_extSettings = m_Settings; }
bool MainThread::addFriend(QTcpSocket* sock, int id, QString buf) { QSharedPointer<IMessage> mes(new Message(buf)); mes->Parse(); QString friends=mes->GetPart("addfr"); qCritical()<<"ADD FRIEND friend= "<<friends; mes->deleteLater(); bool res =base->addFriend(id,friends); bool res2 = cl->addFriend(sock,friends); if(res && res2) { qCritical()<<"ADD FRIEND SUCCESSFUL"; return true; } else { qCritical()<<"ADD FRIEND ERROR"; return false; } }
void RecvThread::readFromServer() { qCritical()<<"READ "; QByteArray array=socket->readAll(); QString buffer = array; qCritical()<<buffer; if (!buffer.contains("#/")) { return; } QStringList strList=buffer.split("#/"); if (strList.isEmpty()) return; QStringListIterator iter(strList); while(iter.hasNext()) { QString tmp=iter.next(); QSharedPointer<IMessage> mes(new Message(tmp)); emit readyMessage(mes); } }
score() { int scor, maxsco, obj, i; scor=maxsco=0; for(obj=treasr; obj<=objt; ++obj) { if( place(obj)>0 ) { maxsco=maxsco+20; if( place(obj)==3 && prop(obj)==0 ) { /* сокровище b доме */ scor=scor+20; } else if( (prop(obj)&0377)!=inipro ) { /* сокровище видел */ scor=scor+5; } } } rspeak(32); mscore(scor,maxsco); obj = 1; for(i=1; i<=plcl; ++i) if( cval(i) && scor>=cval(i) ) obj = i; mes(ctext(obj)); }
bool Font::Init(std::string fontname) { std::string mes("Generated Font "); mes += fontname.c_str(); m_engine->GetConsole()->Print(mes); m_base = glGenLists(256); m_font = CreateFont( -12 , 0 , 0 , 0 , FW_NORMAL , FALSE , FALSE , FALSE , ANSI_CHARSET , OUT_TT_PRECIS , CLIP_DEFAULT_PRECIS , ANTIALIASED_QUALITY , FF_DONTCARE | DEFAULT_PITCH , LPCSTR(fontname.c_str()) ); SelectObject(m_engine->m_hDC, m_font); wglUseFontOutlines( m_engine->m_hDC , 0 , 255 , m_base , 0.0f , 0.0f , WGL_FONT_POLYGONS , glyfs ); return true; }
pointer send_notes(pointer a) { amc_found=tst_alive_amc(); if (!amc_found && !find_amc()) return Error_0("STOP! amc not running"); static StoredNote buffer[stored_notes_max]; int n, lst_note=0, list_len=list_length(a); pointer p; if (list_len>=stored_notes_max) return Error_0("send_notes: list too long"); for (n=0,p=a;n<list_len;++n,p=cdr(p)) { buffer[n].lnr=int_value(list_ref(car(p),0)); buffer[n].snr=int_value(list_ref(car(p),1)); buffer[n].sign=int_value(list_ref(car(p),2)); buffer[n].dur=int_value(list_ref(car(p),3)); //printf("n=%d lnr=%d\n",n,buffer[n].lnr); } BMessage mes(SEND_NOTES); mes.AddData(SENT_NOTES,B_OBJECT_TYPE,buffer,n*sizeof(StoredNote)); amc_application.SendMessage(&mes); return mk_extra(); }
int BVCan::read( void *param ){ // IMPORTANT : msg should be a pointer to a string int count=0; #ifdef USE_CAN TPCANMsg canmsg; errno = CAN_Read( h, &canmsg); if (errno){ BV_WARNING("BVCan::read XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); perror("BVCan::read CAN_Read() return ERROR, means that I did not read anything at all"); BV_WARNING("BVCan::read XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxXXXXXXXXX"); BV_ASSERT(0); } else{ if ( (int)(canmsg.MSGTYPE) == MSGTYPE_STATUS){ __u32 status = CAN_Status(h); BV_WARNING("BVCan::read E R R O R : peak insert a ERROR message in Q with messageType=0x80 CAN_Status(h)=[" << status <<"]"); } count = (sizeof( canmsg.ID )) + sizeof( canmsg.MSGTYPE )+ sizeof( canmsg.LEN )+ canmsg.LEN * sizeof( canmsg.DATA[0] ); BVMessageTPCANMsg mes(0,0,canmsg.ID ,canmsg.MSGTYPE,canmsg.LEN, canmsg.DATA[0],canmsg.DATA[1],canmsg.DATA[2], canmsg.DATA[3],canmsg.DATA[4],canmsg.DATA[5], canmsg.DATA[6],canmsg.DATA[7]); *((string*)param) = mes.objectToString(); } #endif return count; }
/*============================================================================*/ double randvar_get_1overa (double x, double mean, double u) { /* Calulates 1/a(x, mean, u), with a = the integral from x til \infty over the Gauss density function */ # define CUR_PROC "randvar_get_1overa" #ifdef DO_WITH_GSL double erfc_value; #else int i; double y, z, phi_z, a; #endif if (u <= 0.0) { mes_prot ("u <= 0.0 not allowed\n"); goto STOP; } #ifdef DO_WITH_GSL /* int gsl_sf_erfc (double x) erfc(x) = 1 - erf(x) = 2/\sqrt(\pi) \int_x^\infty \exp(-t^2) */ erfc_value = gsl_sf_erfc ((x - mean) / sqrt (u * 2)); if (erfc_value <= DBL_MIN) { mes (MES_WIN, "a ~= 0.0 critical! (mue = %.2f, u =%.2f)\n", mean, u); return (erfc_value); } else return (2.0 / erfc_value); #else if (randvar_init_PHI () == -1) { mes_proc (); goto STOP; }; y = 1 / sqrt (u); z = (x - mean) * y; /* Linear interpolation (Alternative: Round off with i=m_int(fabs(z)*X_FAKT)) */ i = (int) (fabs (z) * X_FAKT_PHI); if (i >= PHI_len - 1) { i = PHI_len - 2; /* Originally: i = PHI_len-1; but then, the last value in the table is zero! */ phi_z = PHI[i]; } else phi_z = PHI[i] + (fabs (z) - i * X_STEP_PHI) * (PHI[i + 1] - PHI[i]) / X_STEP_PHI; /* NOTA BENE: PHI is tabulated for negative values! */ if (z > 0.0) { if (phi_z == 0) { mes_proc (); goto STOP; } else a = 1 / phi_z; /* PHI between 0.5 and 1 */ /* ??? between 0.5 and 0 ! */ } else { a = 1 - phi_z; if (a > DBL_MIN) a = 1 / a; else { a = 0.0; mes (MES_WIN, "a ~= 0.0 critical! (mue = %.2f, u =%.2f)\n", mean, u); /* goto STOP; */ } } return a; #endif STOP: return (-1.0); # undef CUR_PROC } /* randvar_get_1overa */
void UT_CPELogEvent::SendMessage( const MEngineMonitor::TPEMessagesFromPhoneEngine aMessage ) { TInt mes(aMessage); }
void UT_CPELogEvent::HandleInternalMessage( const TInt aMessage ) { TInt mes( aMessage ); }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { ACE_SOCK_Stream connection_stream; int c; printf("HZ = %d\n", HZ); if (argc < 2) goto usage; while ((c = getopt (argc, argv, "drstU:uvBDTb:f:l:n:p:A:O:L:xh:")) != -1) { switch (c) { case 'h': host = optarg; break; case 'x': new_line = 1; break; case 'L': title = optarg; break; case 'B': b_flag = 1; break; case 't': trans = 1; break; case 'r': trans = 0; break; case 'd': options |= SO_DEBUG; break; case 'D': #ifdef TCP_NODELAY nodelay = 1; #else fprintf (stderr, "ttcp: -D option ignored: TCP_NODELAY socket option not supported\n"); #endif break; case 'n': nbuf = atoi (optarg); break; case 'l': data_buf_len = atoi (optarg); break; case 's': sinkmode = !sinkmode; break; case 'p': port = atoi (optarg); break; case 'U': domain = PF_UNIX; domainname = optarg; break; case 'u': udp = 1; break; case 'v': verbose = 1; break; case 'A': bufalign = atoi (optarg); break; case 'O': bufoffset = atoi (optarg); break; case 'b': #if defined(SO_SNDBUF) || defined(SO_RCVBUF) sockbufsize = atoi (optarg); #else fprintf (stderr, "ttcp: -b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported\n"); #endif break; case 'f': fmt = *optarg; break; case 'T': touchdata = 1; break; default: goto usage; } } /* if transmitter, create remote address to transmit to. */ if (trans) { if (address.set (port, host) == -1) perror ("address.set"), exit (1); } /* else, receiver create address to listen on */ else { address.set (port); } total_msg_len = sizeof (long) + data_buf_len; // allocate the buffer message_buf = (Data_Control_Message *) malloc (total_msg_len); if (message_buf == 0) err ("malloc"); // if (bufalign != 0) // message_buf += (bufalign - ((int) message_buf % bufalign) + bufoffset) % bufalign; // let's go ahead and set the control message for every send right now message_buf->size_ = data_buf_len; session_control_buf.nbuf_ = nbuf; session_control_buf.size_ = data_buf_len; // // print out option values for trans and receiver // if (trans) { fprintf (stdout, "ttcp-t: data_buf_len=%d, nbuf=%d, align=%d/%d, port=%d", data_buf_len, nbuf, bufalign, bufoffset, port); if (sockbufsize) fprintf (stdout, ", sockbufsize=%d", sockbufsize); fprintf (stdout, " %s -> %s\n", domain == PF_INET ? (udp ? "udp" : "tcp") : "unix", host == 0 ? domainname : host); } else // receiver { fprintf (stdout, "ttcp-r: data_buf_len=%d, nbuf=%d, align=%d/%d, port=%d", data_buf_len, nbuf, bufalign, bufoffset, port); if (sockbufsize) fprintf (stdout, ", sockbufsize=%d", sockbufsize); fprintf (stdout, " %s\n", domain == PF_INET ? (udp ? "udp" : "tcp") : "unix"); } mes ("socket"); // // connect and accept // if (!udp) { signal (SIGPIPE, (SIG_TYP) sigpipe); /* the transmitter will set options and connect to receiver */ if (trans) { // turn off weird ack things if (nodelay) { struct protoent *p = getprotobyname ("tcp"); if (p && connection_stream.set_option (p->p_proto, TCP_NODELAY, (char *)& one, sizeof (one))) err ("setsockopt: nodelay"); mes ("nodelay"); } if (connector_factory.connect (connection_stream, address) == -1) perror ("connection failed"), exit (1); fprintf (stdout, "ttcp-t: data_buf_len=%d, nbuf=%d, align=%d/%d, port=%d", data_buf_len, nbuf, bufalign, bufoffset, port); if (sockbufsize) { if (connection_stream.set_option (SOL_SOCKET, SO_SNDBUF, (char *) &sockbufsize, sizeof sockbufsize) == -1) err ("acceptor_factory.set_option"); mes ("sndbuf"); } } /* receiver will listen for connections from the transmitter */ else { if (acceptor_factory.open (address, 1) == -1) perror ("acceptor open"), exit (1); if (sockbufsize) { if (connection_stream.set_option (SOL_SOCKET, SO_RCVBUF, (char *) &sockbufsize, sizeof sockbufsize) == -1) err ("acceptor_factory.set_option"); mes ("rcvbuf"); } ACE_INET_Addr remote_address; if (acceptor_factory.accept (connection_stream, (ACE_Addr *) &remote_address) == -1) perror ("acceptor accept"), exit (1); // set the window size fprintf (stderr, "ttcp-r: accept from %s\n", remote_address.get_host_name()); } } // // start timer // errno = 0; if (trans) { pattern (& (message_buf->data_), data_buf_len); prep_timer (); ACE_DEBUG ((LM_DEBUG, "Sending session control message" " nbuf %d, size %d\n", session_control_buf.nbuf_, session_control_buf.size_)); if (connection_stream.send_n ((char *) &session_control_buf, sizeof (Session_Control_Message)) != sizeof (Session_Control_Message)) ACE_ERROR_RETURN ((LM_ERROR, "%p send session control failed\n", "ttcp"), -1); long ack; int send_result; while (nbuf--) { send_result = connection_stream.send_n ((char *) message_buf, total_msg_len); if (send_result != total_msg_len) ACE_ERROR_RETURN ((LM_ERROR, "%p only sent %d of %d bytes on call %d\n", "ttcp", send_result, total_msg_len, numCalls + 1), -1); numCalls++; nbytes += data_buf_len; if (connection_stream.recv_n ((char *) &ack, sizeof ack) != sizeof ack) ACE_ERROR_RETURN ((LM_ERROR, "%p recv of ack failed\n", "ttcp"), -1); if (ack != data_buf_len) ACE_DEBUG ((LM_DEBUG, "received ack for only %d bytes\n", ack)); } printf("Client finished.\n"); } else { prep_timer (); if (connection_stream.recv_n ((char *) &session_control_buf, sizeof (Session_Control_Message)) != sizeof (Session_Control_Message)) ACE_ERROR_RETURN ((LM_ERROR, "%p recv session control failed\n", "ttcp"), -1); ACE_DEBUG ((LM_DEBUG, "received session control message" " nbuf %d, size %d\n", session_control_buf.nbuf_, session_control_buf.size_)); nbuf = session_control_buf.nbuf_; // ignore session_control_buf.size_ for now long cnt; while (nbuf--) { if (connection_stream.recv_n ((char *) message_buf, sizeof (long)) != sizeof (long)) ACE_ERROR_RETURN ((LM_ERROR, "%p recv data control failed\n", "ttcp"), -1); cnt = connection_stream.recv_n (& (message_buf->data_), message_buf->size_); if (cnt != message_buf->size_) ACE_ERROR_RETURN ((LM_ERROR, "recv data failed\n"), -1); numCalls++; nbytes += cnt; if (connection_stream.send_n ((char *) &cnt, sizeof cnt) != sizeof cnt) ACE_ERROR_RETURN ((LM_ERROR, "%p send ack failed\n", "ttcp"), -1); } printf("Server finished.\n"); } /* if (errno) err ("IO"); */ // // stop the timer // (void) read_timer (stats, sizeof (stats)); if (udp && trans) { (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */ (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */ (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */ (void) Nwrite (connection_stream, message_buf, 4); /* rcvr end */ } if (cput <= 0.0) cput = 0.001; if (realt <= 0.0) realt = 0.001; #if defined (LM_RESULTS) if (trans && (title != 0)) { double tmp; FILE *fd; char filename[BUFSIZ]; ACE_OS::sprintf (filename, "%s.results", title); fd = fopen(filename,"a+"); if (new_line) fprintf(fd,"\n -l %ldk \t", data_buf_len/1024); tmp = ((double) nbytes) / realt; fprintf(fd,"%.2f ", tmp * 8.0 / 1024.0 / 1024.0); fclose(fd); } #endif fprintf (stdout, "ttcp%s: %ld bytes in %.2f real seconds = %s/sec +++\n", trans ? "-t" : "-r", nbytes, realt, outfmt (((double) nbytes) / realt)); if (verbose) { fprintf (stdout, "ttcp%s: %ld bytes in %.2f CPU seconds = %s/cpu sec\n", trans ? "-t" : "-r", nbytes, cput, outfmt (((double) nbytes) / cput)); } fprintf (stdout, "ttcp%s: %d I/O calls, msec/call = %.2f, calls/sec = %.2f\n", trans ? "-t" : "-r", numCalls, 1024.0 * realt / ((double) numCalls), ((double) numCalls) / realt); fprintf (stdout, "ttcp%s: %s\n", trans ? "-t" : "-r", stats); if (verbose) { fprintf (stdout, "ttcp%s: buffer address %#x\n", trans ? "-t" : "-r", message_buf); } exit (0); usage: fprintf (stderr, Usage); return 1; }
bool FastSearchFormat::WriteChemObject(OBConversion* pConv) { //Prepares or updates an index file. Called for each molecule indexed bool update = pConv->IsOption("u")!=NULL; static ostream* pOs; static bool NewOstreamUsed; if(fsi==NULL) { //First pass sets up FastSearchIndexer object pOs = pConv->GetOutStream();// with named index it is already open NewOstreamUsed=false; string mes("prepare an"); if(update) mes = "update the"; clog << "This will " << mes << " index of " << pConv->GetInFilename() << " and may take some time..." << flush; if(!pConv->IsLastFile()) { obErrorLog.ThrowError(__FUNCTION__, "There should not be multiple input files. A .fs file is an index of a single datafile.", obError); return false; } std::string auditMsg = "OpenBabel::Write fastsearch index "; std::string description(Description()); auditMsg += description.substr( 0, description.find('\n') ); obErrorLog.ThrowError(__FUNCTION__,auditMsg,obAuditMsg); FptIndex* pidx=NULL; //used with update //if(pOs==&cout) did not work with GUI if(!dynamic_cast<ofstream*>(pOs)) { //No index filename specified //Derive index name from datafile name string indexname=pConv->GetInFilename(); string::size_type pos=indexname.find_last_of('.'); if(pos!=string::npos) indexname.erase(pos); indexname += ".fs"; bool idxok=true; if(update) { LastSeekpos = 0; //Read in existing index idxok=false; ifstream ifs(indexname.c_str(),ifstream::binary); if(ifs.good()) { pidx = new FptIndex; idxok = pidx->Read(&ifs); } }//ifs closed here pOs = new ofstream(indexname.c_str(),ofstream::binary); if(!pOs->good() || !idxok) { stringstream errorMsg; errorMsg << "Trouble opening or reading " << indexname << endl; obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError); static_cast<ofstream *>(pOs)->close(); // close the file before quitting delete pOs; delete pidx; // remove possible memory leak return false; } NewOstreamUsed=true; } else // not cout { if(update) { obErrorLog.ThrowError(__FUNCTION__, "Currently, updating is only done on index files that" "have the same name as the datafile.\n" "Do not specify an output file; use the form:\n" " babel datafile.xxx -ofs -xu", obError); return false; } } int nbits = 0; const char* p = pConv->IsOption("N"); if(p) nbits = atoi(p); string fpid; //fingerprint type p=pConv->IsOption("f"); if(p) fpid=p; //Prepare name without path string datafilename = pConv->GetInFilename(); if(datafilename.empty()) { obErrorLog.ThrowError(__FUNCTION__, "No datafile!", obError); return false; } string::size_type pos = datafilename.find_last_of("/\\"); if(pos!=string::npos) datafilename=datafilename.substr(pos+1); nmols = pConv->NumInputObjects(); if(nmols>0) clog << "\nIt contains " << nmols << " molecules" << flush; if(nmols>500000) { istream* is = pConv->GetInStream(); streampos origpos = is->tellg(); is->seekg(0,ios_base::end); long long filesize = is->tellg(); if(filesize > 4294967295u) { obErrorLog.ThrowError(__FUNCTION__, "The datafile must not be larger than 4GB", obError); return false; } is->seekg(origpos); } sw.Start(); if(update) { fsi = new FastSearchIndexer(pidx, pOs, nmols);//using existing index //Seek to position in datafile of last of old objects LastSeekpos = *(pidx->seekdata.end()-1); pConv->GetInStream()->seekg(LastSeekpos); } else fsi = new FastSearchIndexer(datafilename, pOs, fpid, nbits, nmols); obErrorLog.StopLogging(); } //All passes provide an object for indexing OBBase* pOb = pConv->GetChemObject(); OBMol* pmol = dynamic_cast<OBMol*> (pOb); if(pmol) pmol->ConvertDativeBonds();//use standard form for dative bonds streampos seekpos = pConv->GetInPos(); if(!update || seekpos>LastSeekpos) { fsi->Add(pOb, seekpos ); if(pConv->GetOutputIndex()==400 && nmols>1000) { clog << " Estimated completion time "; double secs = sw.Elapsed() * nmols / 400; // streamsize op = clog.precision(0); if(secs>150) clog << secs/60 << " minutes" << endl; else clog << secs << " seconds" << endl; clog.precision(op); } } else //Don't index old objects during update. Don't increment pConv->Index. pConv->SetOutputIndex(pConv->GetOutputIndex()-1); if(pConv->IsLast()) { //Last pass delete fsi; //saves index file if(NewOstreamUsed) delete pOs; //return to starting conditions fsi=NULL; obErrorLog.StartLogging(); double secs = sw.Elapsed(); if(secs>150) clog << "\n It took " << secs/60 << " minutes" << endl; else clog << "\n It took " << secs << " seconds" << endl; } delete pOb; return true; }
/** MAIN */ int main(int argc, char** argv) { OptionManager om; TestWrapperStressClient wc; pid_t clientPid = getpid(); Uint32 validArg = 0; Boolean verboseTest; // // Varriables needed for loging and status checking. // String clientId; String pidFile; String clientLog, stopClient; char pid_str[15]; int status = CLIENT_UNKNOWN; // // Number of times the client command succeeded. // Uint32 successCount = 0; // // Number of iterations after which logErrorPercentage() is called. // Uint32 iteration = 0; // // Total number of times the client command was executed. // Uint32 totalCount = 0; // // Variables needed for Command operation. // String command; String options; String help; try { struct OptionRow *newOptionsTable = 0; Uint32 newOptionsCount; struct OptionRow cOptionTable[] = { {"clientname", "", true, Option::STRING, 0, 0, "clientname", "Client name" }, {"options", "", true, Option::STRING, 0, 0, "options", "Corresponding Client program's options" } }; Uint32 cOptionCount = sizeof(cOptionTable) / sizeof(cOptionTable[0]); newOptionsCount = cOptionCount; try { // // Generate new option table for this client using OptionManager // newOptionsTable = wc.generateClientOptions( cOptionTable, cOptionCount, newOptionsCount); validArg = wc.GetOptions( om, argc, argv, newOptionsTable, newOptionsCount); } catch (Exception& e) { cerr << argv[0] << ": " << e.getMessage() << endl; exit(1); } catch (...) { cerr << argv[0] << ": Error in Options operations "<< endl; exit(1); } verboseTest = om.isTrue("verbose"); om.lookupValue("clientid", clientId); om.lookupValue("pidfile", pidFile); om.lookupValue("clientlog", clientLog); om.lookupValue("clientname", command); om.lookupValue("options", options); om.lookupValue("help", help); } /** end of option Try block. */ catch (Exception& e) { cerr << argv[0] << ": " << e.getMessage() <<endl; exit(1); } catch (...) { cerr << argv[0] << ": Unknown Error gathering options " << "in Wrapper Client " << endl; exit(1); } /** Checking whether the user asked for HELP Info... if (om.valueEquals("help", "true")) { String header = "Usage "; header.append(argv[0]); header.append(" -parameters -clientName [clientName] header.append(" -options [options] -clientid [clientId] "); header.append(" -pidfile [pidFile] -clientlog [clientLog]"); String trailer = "Assumes localhost:5988 if host not specified"; trailer.append("\nHost may be of the form name or name:port"); trailer.append("\nPort 5988 assumed if port number missing."); om.printOptionsHelpTxt(header, trailer); exit(0); } */ try { if (options.getCString()) { command.append(" " + options); } if (verboseTest) { errorInfo.append("client command : "); errorInfo.append(command); wc.errorLog(clientPid, clientLog, errorInfo); errorInfo.clear(); } // // Signal Handling - SIGINT. // signal(SIGINT, endTest); // // Timer Start. // wc.startTime(); wc.logInfo(clientId, clientPid, status, pidFile); sprintf(pid_str, "%d", clientPid); stopClient = String::EMPTY; stopClient.append(FileSystem::extractFilePath(pidFile)); stopClient.append("STOP_"); stopClient.append(pid_str); // // This loop executes till the client gets stop signal from // controller. // while (!quit) { if (FileSystem::exists(stopClient)) { if (verboseTest) { String mes("Ending client. "); wc.errorLog(clientPid, clientLog, mes); } break; } if (!verboseTest) { #ifdef PEGASUS_OS_TYPE_WINDOWS freopen("nul","w",stdout); #else FILE * file = freopen("/dev/null","w",stdout); if (0 == file) { // ignore possible error, not having stdout redirected // to /dev/null doesn't hurt the test continue; } #endif } int i = system(command.getCString()); iteration++; totalCount++; switch (i) { case 0: if (status != CLIENT_PASS) { status = CLIENT_PASS; wc.logInfo(clientId, clientPid, status, pidFile); } successCount++; break; case 1: status = CLIENT_UNKNOWN; wc.logInfo(clientId, clientPid, status, pidFile); break; default: status = CLIENT_FAIL; wc.logInfo(clientId, clientPid, status, pidFile); break; } nextCheck = wc.checkTime(); if (nextCheck) { wc.logInfo(clientId, clientPid, status, pidFile); nextCheck = false; } // // If verbose is set, log success percentage for every 100 // iterations. If verbose is not set, log success percentage // for every 1000 iterations. // if (verboseTest) { if (iteration == 100) { wc.logErrorPercentage( successCount, totalCount, clientPid, clientLog, thisClient); iteration = 0; } } else { if (iteration == 1000) { wc.logErrorPercentage( successCount, totalCount, clientPid, clientLog, thisClient); iteration = 0; } } } /** end of while(!quit). */ } /** end of command execution try block. */ catch (Exception &exp) { String expStr("Exception in WrapperClient causing it to exit: "); expStr.append(exp.getMessage()); wc.errorLog(clientPid, clientLog, expStr); if (verboseTest) { cerr << expStr.getCString() << endl; } } catch (...) { String expStr("General Exception in WrapperClient causing it to exit"); wc.errorLog(clientPid, clientLog, expStr); if (verboseTest) { cerr << expStr.getCString() << endl; } } // // second delay before shutdown. // #ifndef PEGASUS_OS_TYPE_WINDOWS sleep(1); #else Sleep(1000); #endif if(FileSystem::exists(stopClient)) { // // Remove STOP file here. // FileSystem::removeFile(stopClient); } if (verboseTest) { errorInfo.append( "++++ TestWrapperStressClient Terminated Normally +++++"); wc.errorLog(clientPid, clientLog, errorInfo); errorInfo.clear(); } return 0; }
BOOL WINAPI DllMain ( HANDLE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {mes();}
bool SVGFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv) { OBMol* pmol = dynamic_cast<OBMol*>(pOb); if(!pmol) return false; ostream &ofs = *pConv->GetOutStream(); //Check for option for single mol in fixed size image const char* fixedpx = pConv->IsOption("P"); if(!fixedpx) fixedpx= pConv->IsOption("px", OBConversion::GENOPTIONS); //If WriteMolecule called directly, e.g. from OBConversion::Write() //the default mode is a fixed image size of 200px square if(!fixedpx && !pConv->IsOption("svgwritechemobject")) fixedpx = "200"; if(fixedpx) { _nmax = _nrows = _ncols = 1; pConv->AddOption("j"); pConv->SetLast(true); pConv->SetOutputIndex(1); } //*** Coordinate generation *** //Generate coordinates only if no existing 2D coordinates if( (pConv->IsOption("y") || !pmol->Has2D(true)) && !pConv->IsOption("n") ) { OBOp* pOp = OBOp::FindType("gen2D"); if(!pOp) { obErrorLog.ThrowError("SVGFormat", "gen2D not found", obError, onceOnly); return false; } if(!pOp->Do(pmol)) { obErrorLog.ThrowError("SVGFormat", string(pmol->GetTitle()) + "- Coordinate generation unsuccessful", obError); return false; } } if(!pmol->Has2D() && pmol->NumAtoms()>1)//allows 3D coordinates (if passed by -xn above) { string mes("Molecule "); mes += pmol->GetTitle(); mes += " needs 2D coordinates to display in SVGformat"; obErrorLog.ThrowError("SVGFormat", mes, obError); return false; } bool hasTable = (_nrows || _ncols); bool transparent=false; string background, bondcolor; const char* bg = pConv->IsOption("b"); background = bg ? "black" : "white"; bondcolor = bg ? "white" : "black"; if(bg && (!strcmp(bg, "none") || bg[0]=='0')) { transparent = true; bondcolor = "gray"; } const char* bcol = pConv->IsOption("B"); if(bcol && *bcol) bondcolor = bcol; if(bg && *bg) background = bg; if(pConv->GetOutputIndex()==1 || fixedpx) { //For the first molecule... if(hasTable) { //multiple molecules - use a table //Outer svg has viewbox for 0 0 100 100 or adjusted for table shape, //and no width or height - it uses the whole of its containing element. //Inner svg with width, height, x, y of table cell, //and viewbox to match molecule min and max x and y if(!pConv->IsOption("x")) ofs << "<?xml version=\"1.0\"?>\n"; ofs << "<svg version=\"1.1\" id=\"topsvg\"\n" "xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" "xmlns:cml=\"http://www.xml-cml.org/schema\" "; //*** Outer viewbox *** double vbwidth=100, vbheight=100; if (_nrows>_ncols) vbwidth = (100*_ncols)/_nrows; else if(_ncols>_nrows) vbheight = (100*_nrows)/_ncols; if(fixedpx)//fixed size image ofs << "x=\"0\" y=\"0\" width=\"" << fixedpx << "px\" height=\"" << fixedpx <<"px\" "; else ofs << "x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" "; ofs << "viewBox=\"0 0 " << vbwidth << ' ' << vbheight << "\">\n"; ofs << "<title>OBDepict</title>\n"; // Draw the background unless transparent if(!transparent) ofs << "<rect x=\"0\" y=\"0\" width=\"" << vbwidth << "\" height=\"" << vbheight << "\" fill=\"" << background << "\"/>\n"; } } //All mols double cellsize; if(hasTable) { //*** Parameter for inner svg *** int nc = _ncols ? _ncols : 1; int nr = (_nrows ? _nrows : 1); cellsize = 100. / std::max(nc, nr); int indx = pConv->GetOutputIndex() - 1; double innerX = (indx % nc) * cellsize; double innerY = (indx / nc) * cellsize; // Change the background in this cell if the condition in the first // parameter of the -xh option is met. Use a default color if // the highlight color is not specified in the second parameter. const char* htxt = pConv->IsOption("h"); if(htxt) { vector<string> vec; tokenize(vec, htxt); string highlight(vec.size()>1 ? vec[1] : "#f4f0ff"); std::istringstream conditionText(vec[0]); if(OBDescriptor::FilterCompare(pOb, conditionText, false)) //Still in outer <svg>, unfortunately ofs << "<rect x=\"" << innerX << "\" y=\"" << innerY << "\" width=\"" << cellsize << "\" height=\"" << cellsize << "\" fill=\"" << highlight << "\"/>\n"; } //*** Write molecule name *** if(!pConv->IsOption("d")) ofs << "<text text-anchor=\"middle\" font-size=\"" << 0.06*cellsize << "\"" << " fill =\"" << bondcolor << "\" font-family=\"sans-serif\"\n" << "x=\"" << innerX + cellsize * 0.5 << "\" y=\"" << innerY + cellsize - 2.0/nr << "\" >" << pmol->GetTitle() << "</text>\n"; SVGPainter painter(*pConv->GetOutStream(), true, cellsize,cellsize,innerX,innerY); OBDepict depictor(&painter); if(!pConv->IsOption("C")) depictor.SetOption(OBDepict::drawTermC);// on by default if(pConv->IsOption("a")) depictor.SetOption(OBDepict::drawAllC); if(pConv->IsOption("A")) { AliasData::RevertToAliasForm(*pmol); depictor.SetAliasMode(); } painter.SetFontFamily("sans-serif"); painter.SetPenColor(OBColor(bondcolor)); depictor.SetBondColor(bondcolor); if(pConv->IsOption("t")) painter.SetPenWidth(4); else painter.SetPenWidth(2); //No element-specific atom coloring if requested if(pConv->IsOption("u")) depictor.SetOption(OBDepict::bwAtoms); if(!pConv->IsOption("U")) depictor.SetOption(OBDepict::internalColor); if(pConv->IsOption("s")) depictor.SetOption(OBDepict::asymmetricDoubleBond); depictor.DrawMolecule(pmol); //Draw atom indices if requested if(pConv->IsOption("i")) depictor.AddAtomLabels(OBDepict::AtomIndex); //Embed CML of molecule if requested if(pConv->IsOption("e")) EmbedCML(pmol,pConv); } else //single molecule { //Nothing written until DrawMolecule call //Final </svg> written at the end of this block (painter destructor) //This leads to some code duplication. double factor = 1.0; SVGPainter painter(*pConv->GetOutStream(), false); OBDepict depictor(&painter); //Scale image by specifying the average bond length in pixels. const char* ppx = pConv->IsOption("p"); if(!ppx) ppx= pConv->IsOption("px", OBConversion::GENOPTIONS); if(ppx) { double oldblen = depictor.GetBondLength(); double newblen = atof(ppx); depictor.SetBondLength(newblen); factor = newblen / oldblen; //Scale bondspacing and font size by same factor depictor.SetBondSpacing(depictor.GetBondSpacing() * factor); depictor.SetFontSize((int)(depictor.GetFontSize() * factor)); } if(pConv->IsOption("W")) depictor.SetOption(OBDepict::noWedgeHashGen); if(!pConv->IsOption("C")) depictor.SetOption(OBDepict::drawTermC);// on by default if(pConv->IsOption("a")) depictor.SetOption(OBDepict::drawAllC); if(pConv->IsOption("A")) { AliasData::RevertToAliasForm(*pmol); depictor.SetAliasMode(); } painter.SetFontFamily("sans-serif"); painter.SetPenColor(OBColor(bondcolor)); depictor.SetBondColor(bondcolor); painter.SetFillColor(OBColor(background)); if(pConv->IsOption("t")) painter.SetPenWidth(4); else painter.SetPenWidth(1); //No element-specific atom coloring if requested if(pConv->IsOption("u")) depictor.SetOption(OBDepict::bwAtoms); if(!pConv->IsOption("U")) depictor.SetOption(OBDepict::internalColor); if(pConv->IsOption("s")) depictor.SetOption(OBDepict::asymmetricDoubleBond); depictor.DrawMolecule(pmol); //Draw atom indices if requested if(pConv->IsOption("i")) depictor.AddAtomLabels(OBDepict::AtomIndex); //*** Write molecule name *** if(!pConv->IsOption("d")) ofs << "<text font-size=\"" << 18 * factor << "\"" << " fill =\"" << bondcolor << "\" font-family=\"sans-serif\"\n" << "x=\"" << 10 * factor << "\" y=\"" << 20 * factor << "\" >" << pmol->GetTitle() << "</text>\n"; //*** Write page title name *** ofs << "<title>" << pmol->GetTitle() << " - OBDepict</title>\n"; //Embed CML of molecule if requested if(pConv->IsOption("e")) EmbedCML(pmol,pConv); } if(hasTable && pConv->IsLast()) { //Draw grid lines if(_nrows && _ncols && pConv->IsOption("l")) { for(int i=1; i<_nrows; ++i) ofs << " <line stroke=\"gray\" stroke-width=\"0.1\" x1=\"0\" x2=\"100\"" << " y1=\"" << i*cellsize << "\" y2=\"" << i*cellsize << "\"/>\n"; for(int i=1; i<_ncols; ++i) ofs << " <line stroke=\"gray\" stroke-width=\"0.1\" y1=\"0\" y2=\"100\"" << " x1=\"" << i*cellsize << "\" x2=\"" << i*cellsize << "\"/>\n"; } //Insert javascript for zooming and panning if(!pConv->IsOption("j")) EmbedScript(ofs); ofs << "</svg>\n" << endl;//Outer svg } return !fixedpx; // return false with fixed size image because only 1 mol }
inline CppUnit::Message ident_check_msg( const Mesquite::MsqMatrix<R,C>& m ) { CppUnit::Message mes( "Identity Assertion Failed" ); mes.addDetail( std::string("Actual: ") + msq_mat_str(m) ); return mes; }
void CResourceManager::SetResourceLocation(const nstring & path) { nstring mes("Set resource location: "); LOG_MESSAGE(mes + path); mResourceLocation = path; }
bool tst_alive_amc() { BMessage mes(ALIVE); if (B_OK==amc_application.SendMessage(&mes,(BHandler*)0,1000)) // delivery timeout 1 msec return true; return false; }
/* *=========================================================================== * ipcom_cmd_ttcp *=========================================================================== */ int ipcom_cmd_ttcp(int argc, char **argv) { /* Uninitialized variables. */ union Ip_sockaddr_union addrme; char *host = IP_NULL; /* ptr to name of host */ int c; Ip_u32 msec0, msec1, msecd, bpermsec, kbpersec; Ip_fd sockfd = -1; char *buf; /* ptr to dynamic buffer */ char *orgbuf = 0; /* the buffer to free. */ struct Ipcom_cmd_ttcp_data context; /* misc initialized variables. */ #ifdef IPCOM_USE_TCP union Ip_sockaddr_union frominet; Ip_socklen_t fromlen; int one = 1; /* for 4.3 BSD style setsockopt() */ Ip_fd oldfd; /* fd of network socket */ #endif Ip_u32 nbytes = 0; /* bytes on net */ int trans = 1; /* 0=receive, !0=transmit mode. Default transmit! */ /* Configuration variables. */ #if defined(IP_SO_X_VR) int vr = 0; #endif int buflen = 8 * 1024; /* length of buffer */ int nbuf = 2 * 1024; /* number of buffers to send in sinkmode */ int bufoffset = 0; /* align buffer to this */ int bufalign = 16; /* modulo this */ int options = 0; /* socket options */ unsigned short port = DEFAULT_PORT; /* TCP port number */ unsigned short meport = 0; /* local port, default 0. */ int sinkmode = 1; /* 0=normal I/O, !0=sink/source mode */ int verbose = 0; /* 0=print basic info, 1=print cpu rate, proc resource usage. */ int sockbufsize = -1; /* Default socket buffer size to use. */ #ifdef IP_TCP_NODELAY int nodelay = 0; /* set TCP_NODELAY socket option. */ #endif int enable = 1; #ifdef TCP_OSERFC2385 char *md5opt = IP_NULL; #endif #ifdef IP_SO_REUSEPORT int reuse_port = 0; #endif #ifdef IPCOM_TTCP_REENTRANT union Ip_sockaddr_union addrhim; #endif int sock_error; int mev = 0; /* Use event logging */ int nend = 5; /* Number of UDP end packets */ #ifdef IPCOM_CMD_TTCP_USE_ZEROCOPY_API int zerocopy = 0; #endif int cpu = -1; #ifdef IPSCTP Ip_bool sctp_type_conflict = IP_FALSE; #endif /* Initialize some static data, default configuration. */ #ifdef IPCOM_USE_TCP int proto = IP_IPPROTO_TCP; int sock_type = IP_SOCK_STREAM; const char *proto_as_str = "TCP"; context.udp = 0; /* Default is TCP. */ #else int proto = IP_IPPROTO_UDP; int sock_type = IP_SOCK_DGRAM; const char *proto_as_str = "UDP"; context.udp = 1; /* Only UDP. */ #endif context.b_flag = 0; context.touchdata = 0; context.numCalls = 0; context.err_no = 0; #ifdef IPCOM_USE_INET context.family = IP_AF_INET; /* default IPv4 */ #else context.family = IP_AF_INET6; /* default IPv6 */ #endif context.addrsize = sizeof(struct Ip_sockaddr_in); (void)ipcom_proc_self(); /* when called from vxworks shell, this prevents a crash */ (void)options; /* Init some more. */ ipcom_memset(&addrhim, 0, sizeof (addrhim)); IPCOM_SA_LEN_SET(&addrhim.sin, sizeof(struct Ip_sockaddr_in)); addrhim.sin.sin_family = IP_AF_INET; ipcom_memset(&addrme, 0, sizeof(addrme)); IPCOM_SA_LEN_SET(&addrme.sin, sizeof(struct Ip_sockaddr_in)); addrme.sin.sin_family = IP_AF_INET; #ifdef IP_PORT_INTEGRITY ipcom_init_libsocket(); #endif if (argc < 2) goto usage; ipcom_getopt_clear(); while ((c = ipcom_getopt(argc, argv, "M:xdrstUuvBDTb:f:l:n:p:A:O:V:RP:me:a:cS")) != -1) { switch (c) { #ifdef TCP_OSERFC2385 case 'M': /* MD5 signature option */ md5opt = ip_optarg; break; #endif #ifdef IPCOM_USE_INET6 case 'x': context.family = IP_AF_INET6; break; #endif case 'm': mev = 1; break; case 'e': nend = ipcom_atoi(ip_optarg); break; case 'B': context.b_flag = 1; break; case 't': trans = 1; break; case 'r': trans = 0; break; #ifdef IP_SO_DEBUG case 'd': options |= IP_SO_DEBUG; break; #endif case 'D': #ifdef IP_TCP_NODELAY nodelay = 1; #else ipcom_fprintf(ip_stderr, "ttcp: -D option ignored: IP_TCP_NODELAY socket option not supported"IP_LF); #endif break; case 'n': nbuf = ipcom_atoi(ip_optarg); break; case 'l': buflen = ipcom_atoi(ip_optarg); break; case 's': #ifdef IPCOM_TTCP_USE_STDIOMODE sinkmode = !sinkmode; #endif break; case 'p': port = (unsigned short)ipcom_atoi(ip_optarg); break; case 'P': meport = (unsigned short)ipcom_atoi(ip_optarg); break; #ifdef IPCOM_CMD_TTCP_USE_ZEROCOPY_API case 'U': zerocopy = 1; /* fall through */ #endif case 'u': proto = IP_IPPROTO_UDP; sock_type = IP_SOCK_DGRAM; proto_as_str = "UDP"; context.udp = 1; break; case 'v': verbose = 1; break; case 'A': bufalign = ipcom_atoi(ip_optarg); break; case 'O': bufoffset = ipcom_atoi(ip_optarg); break; case 'b': #if defined(IP_SO_SNDBUF) || defined(IP_SO_RCVBUF) sockbufsize = ipcom_atoi(ip_optarg); #else ipcom_fprintf(ip_stderr, "ttcp: -b option ignored: IP_SO_SNDBUF/IP_SO_RCVBUF socket options not supported"IP_LF); #endif break; #ifdef IP_SO_REUSEPORT case 'R': reuse_port = 1; break; #endif case 'T': context.touchdata = 1; break; #if defined(IP_SO_X_VR) case 'V': vr = ipcom_atoi(ip_optarg); break; #endif case 'a': cpu = ipcom_atoi(ip_optarg); break; #ifdef IPSCTP case 'c': proto = IP_IPPROTO_SCTP; sock_type = IP_SOCK_STREAM; proto_as_str = "SCTP"; if (IP_TRUE == sctp_type_conflict) { ipcom_fprintf(ip_stderr, "ttcp: c/S conflict in command."IP_LF); goto errorout; } sctp_type_conflict = IP_TRUE; break; case 'S': proto = IP_IPPROTO_SCTP; sock_type = IP_SOCK_SEQPACKET; proto_as_str = "SCTP"; if (IP_TRUE == sctp_type_conflict) { ipcom_fprintf(ip_stderr, "ttcp: c/S conflict in command."IP_LF); goto errorout; } sctp_type_conflict = IP_TRUE; break; #endif default: goto usage; } } #ifndef IP_PORT_LAS if (cpu >= 0) { Ip_cpu_set_t cpuset; if (cpu < 0 || cpu >= IP_CPU_SETSIZE) { ipcom_fprintf(ip_stderr, "ttcp: CPU must be between #0 and #%d"IP_LF, IP_CPU_SETSIZE-1); return -1; } IP_CPU_ZERO(&cpuset); IP_CPU_SET(cpu, &cpuset); if (ipcom_proc_cpu_affinity_set(0, &cpuset) != IPCOM_SUCCESS) { ipcom_fprintf(ip_stderr, "ttcp: Failed to set affinity to CPU #%d"IP_LF, cpu); return -1; } } #endif /* IP_PORT_LAS */ if(trans) { host = argv[ip_optind]; if (host == 0) goto usage; sock_error = ipcom_getsockaddrbyaddrname(context.family, IP_FALSE, host, (struct Ip_sockaddr *)&addrhim); if(sock_error != 0) { ipcom_fprintf(ip_stderr, "ttcp error: ipcom_getsockaddrbyaddrname failed, errno = %d."IP_LF, sock_error); ttcperror(&context, "unknown host"); } addrme.sin.sin_port = ip_htons(meport); addrhim.sin.sin_port = ip_htons(port); /* same port offset for IPv4 and IPv6 */ } else { /* rcvr */ addrme.sin.sin_port = ip_htons(port); } #ifdef IPCOM_USE_INET6 if(context.family == IP_AF_INET6) { context.addrsize = sizeof(struct Ip_sockaddr_in6); IPCOM_SA_LEN_SET(&addrme.sin6, sizeof(struct Ip_sockaddr_in6)); addrme.sin6.sin6_family = IP_AF_INET6; IPCOM_SA_LEN_SET(&addrhim.sin6, sizeof(struct Ip_sockaddr_in6)); addrhim.sin6.sin6_family = IP_AF_INET6; } #endif /* Send more than the sentinel size - UDPMINLEN. */ if(context.udp && buflen <= UDPMINLEN) buflen = UDPMINLEN + 1; /* Align buffer. */ if ((buf = (char *) ipcom_malloc(buflen + bufalign)) == (char *) IP_NULL) ttcperror(&context, "malloc"); else orgbuf = buf; if (bufalign != 0) buf += (bufalign - ((Ip_ptrdiff_t) buf % bufalign) + bufoffset) % bufalign; /* Get a socket. */ if ((sockfd = ipcom_socket(context.family, sock_type, proto)) == ERR) ttcperror(&context,"socket"); if (trans) { if(sockbufsize < 0) { if(context.udp) sockbufsize = DEFAULT_UDP_SNDBUF; else sockbufsize = DEFAULT_TCP_SNDBUF; } ipcom_fprintf(ip_stdout, "ttcp-t: fd=%d, buflen=%d, nbuf=%d, align=%d/%d, port=%d", sockfd, buflen, nbuf, bufalign, bufoffset, (int)port); if (sockbufsize) ipcom_fprintf(ip_stdout, ", sockbufsize=%d", sockbufsize); ipcom_fprintf(ip_stdout, " %s -> %s"IP_LF, proto_as_str, host); } else { if(sockbufsize < 0) { if(context.udp) sockbufsize = DEFAULT_UDP_RCVBUF; else sockbufsize = DEFAULT_TCP_RCVBUF; } ipcom_fprintf(ip_stdout, "ttcp-r: fd=%d, buflen=%d, nbuf=%d, align=%d/%d, port=%d", sockfd, buflen, nbuf, bufalign, bufoffset, (int)port); if (sockbufsize) ipcom_fprintf(ip_stdout, ", sockbufsize=%d", sockbufsize); ipcom_fprintf(ip_stdout, " %s"IP_LF, proto_as_str); } /* Code to open socket is moved to before the printf to get 'sockfd' right. */ mes(trans, "socket"); /* Set REUSE addr */ if(ipcom_setsockopt(sockfd, IP_SOL_SOCKET, IP_SO_REUSEADDR, (char *)&enable, sizeof (int)) == ERR) ttcperror(&context, "setsockopt(IP_SO_REUSEADDR)"); else mes(trans, "setsockopt(IP_SO_REUSEADDR)"); #ifdef IP_SO_REUSEPORT /* Set REUSE port */ if(reuse_port) { if(ipcom_setsockopt(sockfd, IP_SOL_SOCKET, IP_SO_REUSEPORT, (char *)&reuse_port, sizeof (int)) == ERR) ttcperror(&context, "setsockopt(IP_SO_REUSEPORT)"); else mes(trans, "setsockopt(IP_SO_REUSEPORT)"); } #endif #ifdef IPCOM_USE_TCP #ifdef TCP_OSERFC2385 if (!udp && md5opt) { if (ipcom_setsockopt(sockfd, IPPROTO_TCP, TCP_OSERFC2385, md5opt, strlen(md5opt)) == ERR) { ttcperror(&context, "setsockopt(IP_SO_REUSEADDR)"); } else { mes(trans, "setsockopt(IP_SO_REUSEADDR)"); } } #endif #endif /* Set routing table index in socket. */ #if defined(IP_SO_X_VR) if(vr != 0) { if (ipcom_setsockopt(sockfd, IP_SOL_SOCKET, IP_SO_X_VR, (char *)&vr, 4) == ERR) ttcperror(&context, "setsockopt: vr"); else mes(trans, "setsockopt(vr)"); } #endif /* Bind the socket. */ if(ipcom_bind(sockfd, (struct Ip_sockaddr *)&addrme, context.addrsize) == ERR) ttcperror(&context, "bind"); else #ifdef IPCOM_USE_INET6 ipcom_fprintf(ip_stderr, "ttcp%s: bind %s %d"IP_LF, trans ? "-t" : "-r", context.family == IP_AF_INET ? "IPv4" : "IPv6", (int)ip_ntohs(addrme.sin.sin_port)); #else { char tmpbuf[32]; ipcom_sprintf(tmpbuf, "bind %d", ip_ntohs(addrme.sin.sin_port)); mes(trans, tmpbuf); } #endif /* Adjust socker buffer size. */ #if defined(IP_SO_SNDBUF) || defined(IP_SO_RCVBUF) if(sockbufsize) { if (trans) { if (ipcom_setsockopt(sockfd, IP_SOL_SOCKET, IP_SO_SNDBUF, (char *)&sockbufsize, sizeof sockbufsize) == ERR) ttcperror(&context,"setsockopt: sndbuf"); else mes(trans, "setsockopt(sndbuf)"); } else { if (ipcom_setsockopt(sockfd, IP_SOL_SOCKET, IP_SO_RCVBUF, (char *)&sockbufsize, sizeof sockbufsize) == ERR) ttcperror(&context,"setsockopt: rcvbuf"); else mes(trans, "setsockopt(rcvbuf)"); } } #endif /* If TCP we need to connect else accept to remote side. */ #ifdef IPCOM_USE_TCP if (context.udp) { mes(trans, "opened"); } else { /* We are the client if transmitting */ if(trans) { if(options) { if(ipcom_setsockopt(sockfd, IP_SOL_SOCKET, options, (char *)&one, sizeof (one)) == ERR) ttcperror(&context,"setsockopt"); } #ifdef IP_TCP_NODELAY if(nodelay) { if(ipcom_setsockopt(sockfd, IP_IPPROTO_TCP, IP_TCP_NODELAY, (char *)&one, sizeof (one)) == ERR) ttcperror(&context,"setsockopt: nodelay"); mes(trans, "nodelay"); } #endif if(ipcom_connect(sockfd, (struct Ip_sockaddr *)&addrhim, context.addrsize) == ERR) ttcperror(&context,"connect"); else mes(trans, "connect"); } /* Otherwise, we are the TCP server and should listen for the connections. */ else { if(ipcom_listen(sockfd, 0) == ERR) ttcperror(&context,"listen"); else mes(trans, "listen"); if(options) { if(ipcom_setsockopt(sockfd, IP_SOL_SOCKET, options, (char *)&one, sizeof (one)) == ERR) ttcperror(&context,"setsockopt"); } fromlen = context.addrsize; oldfd = sockfd; #ifdef IPSCTP if ((IP_SOCK_SEQPACKET == sock_type) && (IP_IPPROTO_SCTP == proto)) { #define TTCP_SCTP_RCV_BUF_LEN 128 struct Ipsctp_event_subscribe events; union Ip_sockaddr_union local_addr; struct Ipsctp_sndrcvinfo sinfo; Ip_u32 len = 0; char pbuf[TTCP_SCTP_RCV_BUF_LEN]; int flags = 0; int ret = 0; /* set data I/O event flag */ ipcom_memset(&events, 0, sizeof(events)); events.Ipsctp_data_io_event = 1; ret = ipcom_setsockopt(sockfd, IP_IPPROTO_SCTP, IPSCTP_EVENTS, (void *)&events, sizeof(events)); if (ERR == ret) ttcperror(&context, "setsockopt events"); /* get the association identifier */ ipcom_memset(pbuf, 0, TTCP_SCTP_RCV_BUF_LEN); len = sizeof(local_addr); /* Wait for connections */ ret = ipsctp_recvmsg(sockfd, pbuf, TTCP_SCTP_RCV_BUF_LEN, &local_addr.sa, &len, &sinfo, &flags); sockfd = ipsctp_peeloff(sockfd, sinfo.sinfo_assoc_id); if (IP_SOCKERR == sockfd) ttcperror(&context,"peeloff"); } else #endif { if((sockfd = ipcom_accept(sockfd, (struct Ip_sockaddr *)&frominet, &fromlen)) == ERR) ttcperror(&context,"accept"); } { union Ip_sockaddr_union peer; Ip_socklen_t peerlen = context.addrsize; /* Close the mother socket. */ if(ipcom_socketclose(oldfd) == ERR) ttcperror(&context,"close of oldfd."); #if defined(IP_SO_RCVBUF) /* Had to add this code in addition to the above because some stacks don't inherit * the receive buffer size from the server socket. /Lennart Bang Enea Ose Systems 980116. */ if(sockbufsize) { if(ipcom_setsockopt(sockfd, IP_SOL_SOCKET, IP_SO_RCVBUF, (char *)&sockbufsize, sizeof sockbufsize) == ERR) ttcperror(&context,"setsockopt: rcvbuf"); else mes(trans, "setsockopt(rcvbuf)"); } #endif if(ipcom_getpeername(sockfd, (struct Ip_sockaddr *) &peer, &peerlen) == ERR) ttcperror(&context, "getpeername"); #ifdef IPCOM_USE_INET if(context.family == IP_AF_INET) { char addr[16]; ipcom_fprintf(ip_stderr, "ttcp-r: accept from %s"IP_LF, ipcom_inet_ntop(IP_AF_INET, &peer.sin.sin_addr, addr, sizeof(addr))); } #endif #ifdef IPCOM_USE_INET6 if(context.family == IP_AF_INET6) { char addr[40]; ipcom_fprintf(ip_stderr, "ttcp-r: accept from %s"IP_LF, ipcom_inet_ntop(IP_AF_INET6, &peer.sin6.sin6_addr, addr, sizeof(addr))); } #endif } } } #endif /* Begin the TTCP performance test. */ msec0 = get_millisec(); if (mev) { #if defined (IP_PORT_INTEGRITY) #include "ipcom_integrity.h" extern void EventLogOn(void); #if IP_VER < 500 extern void EventLogMask(unsigned int newmask); EventLogMask(~0); #endif EventLogOn(); #endif } if(sinkmode) { register int cnt; /* Transmit side. */ if(trans) { pattern(buf, buflen); if(context.udp) { (void) NWRITE(sockfd, buf, UDPMINLEN, &context); /* rcvr start */ ipcom_millisleep(500); /* arp time */ /* Renew the start time to not include the 500 msec sleep */ msec0 = get_millisec(); } #ifdef IPCOM_CMD_TTCP_USE_ZEROCOPY_API if (zerocopy) { while (nbuf-- && ZERONWRITE(sockfd, buflen, &context) == buflen) nbytes += buflen; } else #endif { while (nbuf-- && NWRITE(sockfd, buf, buflen, &context) == buflen) nbytes += buflen; } if(context.udp) (void) NWRITE(sockfd, buf, UDPMINLEN, &context); /* rcvr end */ } /* Receive side. */ else { if(context.udp) { int going = 0; #ifdef IPCOM_CMD_TTCP_USE_ZEROCOPY_API if (zerocopy) { while ((cnt = ZeroNread(sockfd, &context)) > 0) { if(cnt <= UDPMINLEN) { if(going) break; /* "EOF" */ going = 1; msec0 = get_millisec(); } else { nbytes += cnt; } } } else #endif { while ((cnt = Nread(sockfd, buf, buflen, &context)) > 0) { if(cnt <= UDPMINLEN) { if(going) break; /* "EOF" */ going = 1; msec0 = get_millisec(); } else { nbytes += cnt; } } } } #ifdef IPCOM_USE_TCP else { while ((cnt = Nread(sockfd, buf, buflen, &context)) > 0) { nbytes += cnt; } } #endif } } #ifdef IPCOM_TTCP_USE_STDIOMODE /* non sinkmode. */ else { register int cnt; if(trans) { /* Read from standard input and send to other side. */ while ((cnt = ipcom_fread(buf, buflen, 1, ip_stdin)) > 0 && NWRITE(sockfd, buf, cnt) == cnt) nbytes += cnt; } else { /* Read from network and print on stdout. */ while ((cnt = Nread(sockfd, buf, buflen, &context)) > 0) { ipcom_fwrite(buf, cnt, 1, ip_stdout); nbytes += cnt; } } } #endif if (mev) { #if defined (IP_PORT_INTEGRITY) extern void EventLogOff(void); EventLogOff(); #elif defined (IP_PORT_RTCORE) extern void ip_trace(char *what, char *file, int line, int id, void *data); extern void ip_tracedump(void); ip_trace("[ASSERT]", __FILE__, __LINE__, ipcom_getpid(), IP_NULL); ip_tracedump(); #endif } /* Read the final time and calculate some statistics. */ msec1 = get_millisec(); msecd = msec1 - msec0; if (msecd == 0) msecd = 1; bpermsec = nbytes / msecd; /* Bytes per millisecond. */ kbpersec = nbytes / 128; kbpersec = kbpersec * 125 / msecd; /* kilobyte per sec. */ /* End of test assemble statistice. */ if(context.err_no) { ipcom_fprintf(ip_stdout, "ttcp%s: socket errno: %d."IP_LF, trans ? "-t" : "-r", context.err_no); } if(context.udp && trans) { int j; for (j = 0; j < nend; j++) { ipcom_millisleep(100); /* Let the reading side catch up. */ (void) NWRITE(sockfd, buf, UDPMINLEN, &context); /* rcvr end */ } } /* Print the statistics. */ ipcom_fprintf(ip_stdout, "ttcp%s: %lu bytes in %lu milliseconds = %lu KB/sec, %lu B/msec +++"IP_LF, trans ? "-t" : "-r", nbytes, msecd, kbpersec, bpermsec); ipcom_fprintf(ip_stdout, "ttcp%s: %lu I/O calls, msec/call = %lu, calls/sec = %lu"IP_LF, trans ? "-t" : "-r", context.numCalls, msecd / context.numCalls, 1000 * context.numCalls / msecd); if (verbose) ipcom_fprintf(ip_stdout, "ttcp%s: buffer address %p"IP_LF, trans ? "-t" : "-r", buf); /* Test succeeded, goto errorout to cleanup. */ goto errorout; /* Usage. */ usage: ipcom_fprintf(ip_stderr, "Usage: ttcp -t [-options] host [ < in ]"IP_LF "ttcp -r [-options > out]"IP_LF "Common options:"IP_LF "-x use IPv6 instead of IPv4"IP_LF "-l ## length of bufs read from or written to network (default 8192)"IP_LF #ifdef IPCOM_CMD_TTCP_USE_ZEROCOPY_API "-U use UDP and interpeak zero copy API instead of TCP"IP_LF #endif "-u use UDP (default is TCP)"IP_LF #ifdef IPSCTP "-c use SCTP STREAM type(default is TCP)"IP_LF "-S use SCTP SEQPACKET type(default is TCP)"IP_LF #endif "-p ## port number to send to or listen at (default DEFAULT_PORT)"IP_LF); ipcom_fprintf(ip_stderr, "-s -t: source a pattern to network"IP_LF "-r sink (discard) all data from network"IP_LF "-e ## number of packets to end UDP transmission"IP_LF "-m use event logging (not supported on all platforms)"IP_LF "-A align the start of buffers to this modulus (default 16384)"IP_LF "-O start buffers at this offset from the modulus (default 0)"IP_LF "-v verbose: print more statistics"IP_LF "-d set SO_DEBUG socket option (if supported)"IP_LF); ipcom_fprintf(ip_stderr, "-b ## set socket buffer size (if supported)"IP_LF "Options specific to -t:"IP_LF "-n## number of source bufs written to network (default 2048)"IP_LF "-D don't buffer TCP writes (sets TCP_NODELAY socket option)"IP_LF "Options specific to -r:"IP_LF "-B for -s, only output full blocks as specified by -l (for TAR)"IP_LF "-T \"touch\": access each byte as it's read"IP_LF #if defined(IP_SO_X_VR) "-V virtual router index (if supported)"IP_LF); #endif /* fall through to cleanup...*/ /* Free buffer and close socket if any error. */ errorout: #ifndef IP_PORT_LAS if (cpu >= 0) ipcom_proc_cpu_affinity_clr(0); #endif /* IP_PORT_LAS */ if(orgbuf) ipcom_free(orgbuf); if(sockfd != -1) { if(ipcom_socketclose(sockfd) == ERR) ipcom_fprintf(ip_stderr, "ttcp error: close of sockfd. (line %d, errno %d)."IP_LF, __LINE__, ipcom_errno); } #ifdef IP_PORT_INTEGRITY ipcom_shutdown_libsocket(); #endif return 0; }