Beispiel #1
0
bool Validate(int alg, bool thorough, const char *seed)
{
	bool result;

	std::string timeSeed;
	if (!seed)
	{
		timeSeed = IntToString(time(NULL));
		seed = timeSeed.c_str();
	}

	cout << "Using seed: " << seed << endl << endl;
	GlobalRNG().Put((const byte *)seed, strlen(seed));

	switch (alg)
	{
	case 1: result = TestSettings(); break;
	case 2: result = TestOS_RNG(); break;
	case 3: result = ValidateMD5(); break;
	case 4: result = ValidateSHA(); break;
	case 5: result = ValidateDES(); break;
	case 6: result = ValidateIDEA(); break;
	case 7: result = ValidateARC4(); break;
	case 8: result = ValidateRC5(); break;
	case 9: result = ValidateBlowfish(); break;
	case 10: result = ValidateDiamond2(); break;
	case 11: result = ValidateThreeWay(); break;
	case 12: result = ValidateBBS(); break;
	case 13: result = ValidateDH(); break;
	case 14: result = ValidateRSA(); break;
	case 15: result = ValidateElGamal(); break;
	case 16: result = ValidateDSA(thorough); break;
	case 17: result = ValidateHAVAL(); break;
	case 18: result = ValidateSAFER(); break;
	case 19: result = ValidateLUC(); break;
	case 20: result = ValidateRabin(); break;
//	case 21: result = ValidateBlumGoldwasser(); break;
	case 22: result = ValidateECP(); break;
	case 23: result = ValidateEC2N(); break;
	case 24: result = ValidateMD5MAC(); break;
	case 25: result = ValidateGOST(); break;
	case 26: result = ValidateTiger(); break;
	case 27: result = ValidateRIPEMD(); break;
	case 28: result = ValidateHMAC(); break;
	case 29: result = ValidateXMACC(); break;
	case 30: result = ValidateSHARK(); break;
	case 32: result = ValidateLUC_DH(); break;
	case 33: result = ValidateLUC_DL(); break;
	case 34: result = ValidateSEAL(); break;
	case 35: result = ValidateCAST(); break;
	case 36: result = ValidateSquare(); break;
	case 37: result = ValidateRC2(); break;
	case 38: result = ValidateRC6(); break;
	case 39: result = ValidateMARS(); break;
	case 40: result = ValidateRW(); break;
	case 41: result = ValidateMD2(); break;
	case 42: result = ValidateNR(); break;
	case 43: result = ValidateMQV(); break;
	case 44: result = ValidateRijndael(); break;
	case 45: result = ValidateTwofish(); break;
	case 46: result = ValidateSerpent(); break;
	case 47: result = ValidateCipherModes(); break;
	case 48: result = ValidateCRC32(); break;
	case 49: result = ValidateECDSA(); break;
	case 50: result = ValidateXTR_DH(); break;
	case 51: result = ValidateSKIPJACK(); break;
	case 52: result = ValidateSHA2(); break;
	case 53: result = ValidatePanama(); break;
	case 54: result = ValidateAdler32(); break;
	case 55: result = ValidateMD4(); break;
	case 56: result = ValidatePBKDF(); break;
	case 57: result = ValidateESIGN(); break;
	case 58: result = ValidateDLIES(); break;
	default: result = ValidateAll(thorough); break;
	}

	time_t endTime = time(NULL);
	cout << "\nTest ended at " << asctime(localtime(&endTime));
	cout << "Seed used was: " << seed << endl;

	return result;
}
Beispiel #2
0
int main(int argc, char *argv[])
{
    char hostname[1024];
    hostname[1023] = '\0';
    gethostname(hostname, 1023);
    std::cout << "Hostname: " << hostname << std::endl;

    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
    std::cout << "Current local time and date: " << asctime (timeinfo) << std::endl;

    char *expPath1 = const_cast<char*>(".");
    char *expPath2 = const_cast<char*>(".");
    char *destPath = const_cast<char*>("./converted");
    int dont_retry = 0;
    int ignoreChecksumErrors = 1;
    if (argc <= 6) {
        usage();
    }
    int argcc = 1;
    while (argcc < argc) {
        switch (argv[argcc][1]) {

        case 's':
            argcc++;
            expPath1 = argv[argcc];
            break;

        case 't':
            argcc++;
            expPath2 = argv[argcc];
            break;

        case 'o':
            argcc++;
            destPath = argv[argcc];
            break;

        case 'c':
            ignoreChecksumErrors = 0;
            break;

        case 'z':
            dont_retry = 1;
            break;

        case 'v':
            fprintf (stdout, "%s", IonVersion::GetFullVersion("MergeDats").c_str());
            exit (0);
            break;
        case 'H':
            usage();
            break;

        default:
            argcc++;
            fprintf (stdout, "\n");

        }
        argcc++;
    }

    MergeAcq merger;
    Image top;
    Image bottom;
    Image combo;
    Acq acq;
    top.SetImgLoadImmediate(false);
    bottom.SetImgLoadImmediate(false);

    char name1[MAX_PATH_LENGTH];
    char name2[MAX_PATH_LENGTH];
    char destName[MAX_PATH_LENGTH];
    int i = 0;
    int k = 0;
    int mode = 0;
    bool allocate = true;

    const char *postNameList[] = {
        "beadfind_post_0000.dat", "beadfind_post_0001.dat",
        "beadfind_post_0002.dat", "beadfind_post_0003.dat"
    };


    // Specify if checksum errors should be ignored
    top.SetIgnoreChecksumErrors(ignoreChecksumErrors);
    bottom.SetIgnoreChecksumErrors(ignoreChecksumErrors);

    // if requested...do not bother waiting for the files to show up
    if (dont_retry) {
        top.SetTimeout(1,1);
        bottom.SetTimeout(1,1);
    }

    int postNameListLen = sizeof(postNameList)/sizeof(postNameList[0]);

    // Create results folder
    umask (0);  // make permissive permissions so its easy to delete.
    if (mkdir (destPath, 0777)) {
        if (errno == EEXIST) {
            //already exists? well okay...
        }
        else {
            perror (destPath);
            exit (1);
        }
    }

    // waiting for first acquisition
    sprintf(name1, "%s/acq_%04d.dat", expPath1, 0);
    sprintf(name2, "%s/acq_%04d.dat", expPath2, 0);
    struct stat info1;
    struct stat info2;
    int limit_seconds = 60*60*12;
    int passed_seconds = 0;
    int delta = 3;
    while ((stat(name1, &info1) || stat(name2, &info2)) && passed_seconds < limit_seconds) {
        passed_seconds += delta;
        sleep(delta);
    }  
    std::cout << "continue with merging beadfind files" << std::endl << std::endl;
   
    // merge beadfinds as soon as acq_0000.dat is available

    // beadfind 
    k = 0;
    while (true)
    {
        sprintf(name1, "%s/beadfind_pre_%04d.dat", expPath1, k);
        sprintf(name2, "%s/beadfind_pre_%04d.dat", expPath2, k);
        sprintf(destName, "%s/beadfind_pre_%04d.dat", destPath, k);
        if (stat(name1, &info1) || stat(name2, &info2)) {
            std::cout << "continue with merging prerun files" << std::endl << std::endl;
            break;
        }
        if (! top.LoadRaw(name1, 0, allocate, false)) {
            std::cout << "cannot merge into file: " << destName << std::endl;
            continue;
        }
        if (! bottom.LoadRaw(name2, 0, allocate, false)) {
            std::cout << "cannot merge into file: " << destName << std::endl;
            continue;
        }
        merge(&merger,&acq,&combo,&top,&bottom,destName);
        k++;
    }

    // prerun
    k = 0;
    while (true)
    {
        sprintf(name1, "%s/prerun_%04d.dat", expPath1, k);
        sprintf(name2, "%s/prerun_%04d.dat", expPath2, k);
        sprintf(destName, "%s/prerun_%04d.dat", destPath, k);
        if (stat(name1, &info1) || stat(name2, &info2)) {
            std::cout << "continue with merging acq files" << std::endl << std::endl;
            break;
        }
        if (! top.LoadRaw(name1, 0, allocate, false)) {
            std::cout << "cannot merge into file: " << destName << std::endl;
            continue;
        }
        if (! bottom.LoadRaw(name2, 0, allocate, false)) {
            std::cout << "cannot merge into file: " << destName << std::endl;
            continue;
        }
        merge(&merger,&acq,&combo,&top,&bottom,destName);
        k++;
    }

    while (mode < 2) {
        if (mode == 0) {
            sprintf(name1, "%s/acq_%04d.dat", expPath1, i);
            sprintf(name2, "%s/acq_%04d.dat", expPath2, i);
            sprintf(destName, "%s/acq_%04d.dat", destPath, i);
        } else if (mode == 1) {
            if(i >= postNameListLen)
                break;
            sprintf(name1, "%s/%s", expPath1, postNameList[i]);
            sprintf(name2, "%s/%s", expPath2, postNameList[i]);
            sprintf(destName, "%s/%s", destPath, postNameList[i]);
        } else
            break;

        std::cout << "Loading images." << std::endl;
        if (top.LoadRaw(name1, 0, allocate, false) && bottom.LoadRaw(name2, 0, allocate, false)) {
            allocate = false;

            merge(&merger,&acq,&combo,&top,&bottom,destName);

            fflush (stdout);
            i++;
        }
        else {
            if ((mode == 1 && i >= 12) || (mode == 0)) {
                mode++;
                i = 0;
                allocate = true;
            }
            else
                i++;
        }
    }
    return EXIT_SUCCESS;
}
Beispiel #3
0
/// @brief Cell output function
///
/// @details Outputs formatted data snapshot for visualisation
///
///   #------------------------------------------------------
///   # Cell configuration file for vampire
///   #------------------------------------------------------
///   # Date: xx/xx/xxxx xx.xx.xx
///   #------------------------------------------------------
///   Number of cells: $n_cells
///   System dimensions: $max_x $max_y $max_z
///   Coordinates-file: $coord_file
///   Time: $t
///   Field: $H
///   Temperature: $T
///   Magnetisation: $mx $my $mz
///   Number of Materials: $n_mat
///   Material Properties 1:  $mu_s $mmx $mmy $mmz $mm
///   Material Properties 2:  $mu_s $mmx $mmy $mmz ...
///   #------------------------------------------------------
///
/// @section License
/// Use of this code, either in source or compiled form, is subject to license from the authors.
/// Copyright \htmlonly &copy \endhtmlonly Richard Evans, 2009-2011. All Rights Reserved.
///
/// @section Information
/// @author  Richard Evans, [email protected]
/// @version 1.0
/// @date    26/04/2013
///
/// @internal
///   Created:    26/04/2013
///   Revision:     ---
///=====================================================================================
///
void legacy_cells()
{

   // wait for all processes
   vmpi::barrier();

   // instantiate timer
   vutil::vtimer_t timer;

   // Set local output filename
   std::stringstream file_sstr;
   file_sstr << "cells-";
   file_sstr << std::setfill('0') << std::setw(8) << sim::output_cells_file_counter;
   file_sstr << ".cfg";
   std::string cfg_file = file_sstr.str();
   const char *cfg_filec = cfg_file.c_str();

   #ifdef MPICF
      // if flag to print cells field is active, all cpus send cells field to root proc
      if(dipole::activated) dipole::send_cells_field(cells::cell_id_array,
                                                     dipole::cells_field_array_x,
                                                     dipole::cells_field_array_y,
                                                     dipole::cells_field_array_z,
                                                     cells::num_local_cells);
   #endif

   // start timer
   timer.start();

   // Output masterfile header on root process
   if (vmpi::my_rank == 0)
   {

      zlog << zTs() << "Outputting cell configuration " << sim::output_cells_file_counter << " to disk" << std::flush;

      // Declare and open output file
      std::ofstream cfg_file_ofstr;
      cfg_file_ofstr.open(cfg_filec);

      // Get system date
      time_t rawtime = time(NULL);
      struct tm *timeinfo = localtime(&rawtime);

      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Cell configuration file for vampire" << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Date: " << asctime(timeinfo);
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Number of spins: " << cells::num_cells << std::endl;
      cfg_file_ofstr << "# System dimensions:" << cs::system_dimensions[0] << "\t" << cs::system_dimensions[1] << "\t" << cs::system_dimensions[2] << std::endl;
      cfg_file_ofstr << "# Coordinates-file: cells-coord.cfg" << std::endl;
      cfg_file_ofstr << "# Time: " << double(sim::time) * mp::dt_SI << std::endl;
      cfg_file_ofstr << "# Field: " << sim::H_applied << std::endl;
      cfg_file_ofstr << "# Temperature: " << sim::temperature << std::endl;
      cfg_file_ofstr << "# Magnetisation: " << stats::system_magnetization.output_normalized_magnetization() << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;

      // Root process now outputs the cell magnetisations
      for (int cell = 0; cell < cells::num_cells; cell++){
         if (cells::num_atoms_in_cell_global[cell] > 0){
            cfg_file_ofstr << cells::mag_array_x[cell] << "\t" << cells::mag_array_y[cell] << "\t" << cells::mag_array_z[cell] << "\t";
            if(dipole::activated) cfg_file_ofstr << dipole::cells_field_array_x[cell] << "\t" << dipole::cells_field_array_y[cell] << "\t" << dipole::cells_field_array_z[cell] << "\n";
            else cfg_file_ofstr << "\n";
         }

      }

      cfg_file_ofstr.close();
   }

   // stop the timer
   timer.stop();

   double data_size = double(config::internal::total_output_cells) * 3.0 * sizeof(double);
   if(dipole::activated) data_size = data_size * 2.0;
   const double io_time = timer.elapsed_time();

   zlog << " of size " << data_size*1.0e-6 << " MB [ " << data_size*1.0e-9/timer.elapsed_time() << " GB/s in " << io_time << " s ]" << std::endl;

   sim::output_cells_file_counter++;

   // wait for all processes
   vmpi::barrier();

   return;
}
Beispiel #4
0
int main()
{
    int listenSock, connSock, ret;
    struct sockaddr_in servaddr;
    struct sctp_initmsg initmsg;
    char buffer[MAX_BUFFER+1];
    time_t currentTime;

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);

    // Create SCTP TCP-Style Socket
    listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);

    // Accept connections from any interface
    bzero((void *)&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(MY_PORT_NUM);

    ret = bind(listenSock, (struct sockaddr *)&servaddr, sizeof(servaddr));

    // Specify that a maximum of 5 streams will be available per socket
    memset(&initmsg, 0, sizeof(initmsg));
    initmsg.sinit_num_ostreams = 5;
    initmsg.sinit_max_instreams = 5;
    initmsg.sinit_max_attempts = 4;
    ret = setsockopt(listenSock, IPPROTO_SCTP, SCTP_INITMSG,
                      &initmsg, sizeof(initmsg));

    // Place the server socket into the listening state
    listen(listenSock, 5);
    printf("Listening on 0.0.0.0:%d ...\n", MY_PORT_NUM);

    while(1) {
        connSock = accept(listenSock, (struct sockaddr *)NULL, (socklen_t *)NULL);
        printf("Accepted a new connection: %d\n", connSock);

        // Grab the current time
        currentTime = time(NULL);

        // Send local time on stream LOCALTIME_STREAM
        snprintf(buffer, MAX_BUFFER, "%s", ctime(&currentTime));
        ret = sctp_sendmsg(connSock, (void *)buffer, (size_t)strlen(buffer),
                            NULL, 0, 0, 0, LOCALTIME_STREAM, 0, 0);
        if(ret == -1) {
            printf("sctp_sendmsg error: %s\n", strerror(errno));
            close(connSock);
            continue;
        }

        // Send GMT on stream GMT_STREAM
        snprintf(buffer, MAX_BUFFER, "%s", asctime(gmtime(&currentTime)));
        ret = sctp_sendmsg(connSock, (void *)buffer, (size_t)strlen(buffer),
                            NULL, 0, 0, 0, GMT_STREAM, 0, 0);
        if(ret == -1) {
            printf("sctp_sendmsg error: %s\n", strerror(errno));
            close(connSock);
            continue;
        }

        close(connSock);
    }

    return 0;
}
Beispiel #5
0
char*
ctime(const time_t *t)
{
	return asctime(localtime(t));
}
Beispiel #6
0
void CAirPlayServer::CTCPClient::PushBuffer(CAirPlayServer *host, const char *buffer,
                                            int length, CStdString &sessionId, std::map<CStdString,
                                            int> &reverseSockets)
{
  HttpParser::status_t status = m_httpParser->addBytes(buffer, length);

  if (status == HttpParser::Done)
  {
    // Parse the request
    CStdString responseHeader;
    CStdString responseBody;
    CStdString reverseHeader;
    CStdString reverseBody;
    int status = ProcessRequest(responseHeader, responseBody, reverseHeader, reverseBody, sessionId);
    CStdString statusMsg = "OK";
    int reverseSocket = INVALID_SOCKET;

    switch(status)
    {
      case AIRPLAY_STATUS_NOT_IMPLEMENTED:
        statusMsg = "Not Implemented";
        break;
      case AIRPLAY_STATUS_SWITCHING_PROTOCOLS:
        statusMsg = "Switching Protocols";
        reverseSockets[sessionId] = m_socket;//save this socket as reverse http socket for this sessionid
        break;
      case AIRPLAY_STATUS_NEED_AUTH:
        statusMsg = "Unauthorized";
        break;
    }

    // Prepare the response
    CStdString response;
    const time_t ltime = time(NULL);
    char *date = asctime(gmtime(&ltime)); //Fri, 17 Dec 2010 11:18:01 GMT;
    date[strlen(date) - 1] = '\0'; // remove \n
    response.Format("HTTP/1.1 %d %s\nDate: %s\r\n", status, statusMsg.c_str(), date);
    if (responseHeader.size() > 0)
    {
      response += responseHeader;
    }

    if (responseBody.size() > 0)
    {
      response.Format("%sContent-Length: %d\r\n", response.c_str(), responseBody.size());
    }
    response += "\r\n";

    if (responseBody.size() > 0)
    {
      response += responseBody;
    }

    // Send the response
    //don't send response on AIRPLAY_STATUS_NO_RESPONSE_NEEDED
    if (status != AIRPLAY_STATUS_NO_RESPONSE_NEEDED)
    {
      send(m_socket, response.c_str(), response.size(), 0);
    }

    // Send event status per reverse http socket (play, loading, paused)
    // if we have a reverse header and a reverse socket
    if (reverseHeader.size() > 0 && reverseSockets.find(sessionId) != reverseSockets.end())
    {
      //search the reverse socket to this sessionid
      response.Format("POST /event HTTP/1.1\r\n");
      reverseSocket = reverseSockets[sessionId]; //that is our reverse socket
      response += reverseHeader;
    }
    response += "\r\n";

    if (reverseBody.size() > 0)
    {
      response += reverseBody;
    }

    if (reverseSocket != INVALID_SOCKET)
    {
      send(reverseSocket, response.c_str(), response.size(), 0);//send the event status on the eventSocket
    }

    // We need a new parser...
    delete m_httpParser;
    m_httpParser = new HttpParser;
  }
}
Beispiel #7
0
        if (tt == (time_t)-1 && PyErr_Occurred())
            return NULL;
    }
    timeptr = localtime(&tt);
    if (timeptr == NULL) {
        PyErr_SetString(PyExc_ValueError, "unconvertible time");
        return NULL;
    }
    return _asctime(timeptr);
}

PyDoc_STRVAR(ctime_doc,
"ctime(seconds) -> string\n\
\n\
Convert a time in seconds since the Epoch to a string in local time.\n\
This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
not present, current time as returned by localtime() is used.");

#ifdef HAVE_MKTIME
static PyObject *
time_mktime(PyObject *self, PyObject *tup)
{
    struct tm buf;
    time_t tt;
    if (!gettmarg(tup, &buf))
        return NULL;
    buf.tm_wday = -1;  /* sentinel; original value ignored */
    tt = mktime(&buf);
    /* Return value of -1 does not necessarily mean an error, but tm_wday
     * cannot remain set to -1 if mktime succeeded. */
    if (tt == (time_t)(-1) && buf.tm_wday == -1) {
int main(int argc, char *argv[])
{
  Test::Output *pout;
  TestType tt(testTypeCompiler);
  int rtn(EXIT_SUCCESS);

  // if user passed command line argument then parse it
  if (argc==1)
  {
    tt=testTypeCompiler;
  }
  else if (argc==2)
  {
    size_t lenargv(strlen(argv[1]));

    // using short codes
    if (lenargv==2)
    {
      if (argv[1][0]=='-')
      {
        switch(argv[1][1])
        {
          case('t'):
            tt=testTypeText;
            break;
          case('c'):
            tt=testTypeCompiler;
            break;
          case('h'):
            tt=testTypeHTML;
            break;
          default:
            std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
            rtn=EXIT_FAILURE;
            break;
        }
      }
      else
      {
        std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
        rtn=EXIT_FAILURE;
      }
    }
    else
    {
      if (lenargv==6)
      {
        if (std::strncmp(argv[1], "--text", lenargv)==0)
          tt=testTypeText;
        else if (std::strncmp(argv[1], "--html", lenargv)==0)
          tt=testTypeHTML;
        else if (std::strncmp(argv[1], "--help", lenargv)==0)
          rtn=EXIT_FAILURE;
        else
        {
          std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
          rtn=EXIT_FAILURE;
        }
      }
      else if (lenargv==10)
      {
        if (std::strncmp(argv[1], "--compiler", lenargv)==0)
          tt=testTypeCompiler;
        else
        {
          std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
          rtn=EXIT_FAILURE;
        }
      }
    }
  }
  else
  {
    std::cerr << "Can only pass one argument." << std::endl;
    rtn=EXIT_FAILURE;
  }
  if (rtn==EXIT_FAILURE)
  {
    std::cerr << "  Usage: " << argv[0] << " [--text|-t|--compiler|-c|--html|-h]" << std::endl;
    return rtn;
  }

  // allocate the correct output type
  switch (tt)
  {
    case(testTypeText):
    {
      Test::TextOutput *po = new Test::TextOutput(Test::TextOutput::Verbose);
      pout = static_cast<Test::Output *>(po);
      break;
    }
    case(testTypeCompiler):
    {
      Test::CompilerOutput *po = new Test::CompilerOutput(Test::CompilerOutput::GCC);
      pout = static_cast<Test::Output *>(po);
      break;
    }
    case(testTypeHTML):
    {
      Test::HtmlOutput *po = new Test::HtmlOutput;
      pout = static_cast<Test::Output *>(po);
      break;
    }
    default:
    {
      rtn=EXIT_FAILURE;
      break;
    }
  }

  if (rtn == EXIT_SUCCESS)
  {
    // get the current time information
    time_t rawtime;
    struct tm * timeinfo;
    std::string datetime;
    time (&rawtime);
    timeinfo = localtime(&rawtime);
    datetime = asctime(timeinfo);

    // add the test suites to the test runner
    // NOTE: This is where changes should be needed
    //
    Test::Suite ts;
    std::string ostr_filename("piecewise_airfoil_test_results.html");

    // add the cppack test suites
    ts.add(std::auto_ptr<Test::Suite>(new piecewise_four_digit_creator_test_suite<float>()));
    ts.add(std::auto_ptr<Test::Suite>(new piecewise_four_digit_creator_test_suite<double>()));
    ts.add(std::auto_ptr<Test::Suite>(new piecewise_four_digit_creator_test_suite<long double>()));

    //
    // NOTE: End of section that should be changed

    // run the test
    rtn = (ts.run(*pout)) ? EXIT_SUCCESS : EXIT_FAILURE;

    // generate the html data if requested
    if (tt==testTypeHTML)
    {
      std::ofstream ostr(ostr_filename.c_str());
      Test::HtmlOutput *phtmlout=dynamic_cast<Test::HtmlOutput *>(pout);

      phtmlout->generate(ostr, true, datetime);

      ostr.close();
    }

    delete pout;
  }

  return rtn;
}
Beispiel #9
0
static void exception_hook(ap_exception_info_t *ei)
{
    int msg_len;
    int logfd;
    char msg_prefix[60];
    time_t now;
    char *newline;
    int using_errorlog = 1;

    time(&now);
    ap_snprintf(msg_prefix, sizeof msg_prefix,
                "[%s pid %ld mod_whatkilledus",
                asctime(localtime(&now)),
                (long)getpid());
    newline = strchr(msg_prefix, '\n'); /* dang asctime() */
    if (newline) {                      /* silly we are */
        *newline = ']';
    }

    if (log_fname) {
        logfd = open(log_fname, O_WRONLY|O_APPEND|O_CREAT, 0644);
        if (logfd == -1) {
            logfd = 2; /* unix, so fd 2 is the web server error log */
            ap_snprintf(buffer, sizeof buffer,
                        "%s error %d opening %s\n",
                        msg_prefix, errno, log_fname);
            write(logfd, buffer, strlen(buffer));
        }
        else {
            using_errorlog = 0;
        }
    }
    else {
        logfd = 2;
    }

    msg_len = ap_snprintf(buffer, sizeof buffer,
                          "%s sig %d crash\n",
                          msg_prefix, ei->sig);
    write(logfd, buffer, msg_len);

    if (local_addr) {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s active connection: %s->%s\n",
                              msg_prefix, remote_addr, local_addr);
    }
    else {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s no active connection at crash\n",
                              msg_prefix);
    }

    write(logfd, buffer, msg_len);

    if (request_plus_headers) {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s active request:\n",
                              msg_prefix);
        write(logfd, buffer, msg_len);
        write(logfd, request_plus_headers, strlen(request_plus_headers));
    }
    else {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s no request active at crash\n",
                              msg_prefix);
        write(logfd, buffer, msg_len);
    }
    msg_len = ap_snprintf(buffer, sizeof buffer,
                          "%s end of report\n",
                          msg_prefix);
    write(logfd, buffer, msg_len);
    if (!using_errorlog) {
        close(logfd);
    }
}
Beispiel #10
0
char *Time_printtime(void) {
	/* =================================================== */
	return (asctime(&_tym));
}
//! \brief Write a log of the simulation to a text file
void writeOutput(const Params& p, Opm::time::StopWatch& watch, int cells,
                 const std::vector<double>& volume, 
                 const Dune::FieldMatrix<double,6,6>& C)
{
  // get current time
  time_t rawtime;
  struct tm* timeinfo;
  time(&rawtime);
  timeinfo = localtime(&rawtime);

  // get hostname
  char hostname[1024];
  gethostname(hostname,1024);

  std::string method = "mortar";
  if (p.method == UPSCALE_MPC)
    method = "mpc";
  if (p.method == UPSCALE_NONE)
    method = "none";

  // write log
  std::ofstream f;
  f.open(p.output.c_str());
  f << "######################################################################" << std::endl
    << "# Results from upscaling elastic moduli." << std::endl
    << "#" << std::endl
    << "# Finished: " << asctime(timeinfo)
    << "# Hostname: " << hostname << std::endl
    << "#" << std::endl
    << "# Upscaling time: " << watch.secsSinceStart() << " secs" << std::endl
    << "#" << std::endl;
  if (p.file == "uniform") {
    f << "# Uniform grid used" << std::endl
      << "#\t cells: " << p.cellsx*p.cellsy*p.cellsz << std::endl;
  }
  else {
    f  << "# Eclipse file: " << p.file << std::endl
       << "#\t cells: " << cells << std::endl;
  }
  f << "#" << std::endl;
  if (!p.rocklist.empty()) {
    f << "# Rock list: " << p.rocklist << std::endl
      << "#" << std::endl;
  }
  f << "# Options used:" << std::endl
    << "#\t         method: " << method << std::endl
    << "#\t linsolver_type: " << (p.linsolver.type==Opm::Elasticity::DIRECT?"direct":"iterative")
                              << std::endl;
  if (p.linsolver.type == Opm::Elasticity::ITERATIVE)
    f << "#\t           ltol: " << p.linsolver.tol << std::endl;
  if (p.file == "uniform") {
    f << "#\t          cellsx: " << p.cellsx << std::endl
      << "#\t          cellsy: " << p.cellsy << std::endl
      << "#\t          cellsz: " << p.cellsz << std::endl;
  }
  f << "#" << std::endl
    <<"# Materials: " << volume.size() << std::endl;
  for (size_t i=0;i<volume.size();++i)
    f << "#\t Material" << i+1 << ": " << volume[i]*100 << "%" << std::endl;
  f << "#" << std::endl
    << "######################################################################" << std::endl
    << C << std::endl;
}
Beispiel #12
0
void
AslCompilerFileHeader (
    UINT32                  FileId)
{
    struct tm               *NewTime;
    time_t                  Aclock;
    char                    *Prefix = "";


    /* Set line prefix depending on the destination file type */

    switch (FileId)
    {
    case ASL_FILE_ASM_SOURCE_OUTPUT:
    case ASL_FILE_ASM_INCLUDE_OUTPUT:

        Prefix = "; ";
        break;

    case ASL_FILE_HEX_OUTPUT:

        if (Gbl_HexOutputFlag == HEX_OUTPUT_ASM)
        {
            Prefix = "; ";
        }
        else if ((Gbl_HexOutputFlag == HEX_OUTPUT_C) ||
                 (Gbl_HexOutputFlag == HEX_OUTPUT_ASL))
        {
            Prefix = " * ";
        }
        break;

    case ASL_FILE_C_SOURCE_OUTPUT:
    case ASL_FILE_C_OFFSET_OUTPUT:
    case ASL_FILE_C_INCLUDE_OUTPUT:

        Prefix = " * ";
        break;

    default:

        /* No other output types supported */

        break;
    }

    /* Compilation header with timestamp */

    (void) time (&Aclock);
    NewTime = localtime (&Aclock);

    FlPrintFile (FileId,
        "%sCompilation of \"%s\" - %s%s\n",
        Prefix, Gbl_Files[ASL_FILE_INPUT].Filename, asctime (NewTime),
        Prefix);

    switch (FileId)
    {
    case ASL_FILE_C_SOURCE_OUTPUT:
    case ASL_FILE_C_OFFSET_OUTPUT:
    case ASL_FILE_C_INCLUDE_OUTPUT:

        FlPrintFile (FileId, " */\n");
        break;

    default:

        /* Nothing to do for other output types */

        break;
    }
}
/** Output the results to file
 *
 * We choose to output all results from a specific analysis to a single file
 *
 */
int XLALOpenSemiCoherentResultsFile(FILE **fp,                  /**< [in] filepointer to output file */
				    CHAR *outputdir,            /**< [in] the output directory name */
				    ParameterSpace *pspace,     /**< [in] the parameter space */
				    CHAR *clargs,               /**< [in] the command line args */
				    UserInput_t *uvar		/**< UNDOCUMENTED */
				    )
{
  CHAR outputfile[LONGSTRINGLENGTH];    /* the output filename */
  time_t curtime = time(NULL);          /* get the current time */
  CHAR *time_string = NULL;             /* stores the current time */
  CHAR *version_string = NULL;          /* pointer to a string containing the git version information */

  /* validate input */
  if (outputdir == NULL) {
    LogPrintf(LOG_CRITICAL,"%s: Invalid input, output directory string == NULL.\n",__func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  if (pspace == NULL) {
    LogPrintf(LOG_CRITICAL,"%s: Invalid input, ParameterSpace structure == NULL.\n",__func__);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* define the output filename */
  /* the format we adopt is the following SemiCoherentResults-<SOURCE>-<START>_<END>-<MIN_FREQ_INT>_<MIN_FREQ_mHZ>_ <MAX_FREQ_INT>_<MAX_FREQ_mHZ>.txt */
  {
    UINT4 min_freq_int = floor(pspace->space->data[0].min);
    UINT4 max_freq_int = floor(pspace->space->data[0].max);
    UINT4 min_freq_mhz = (UINT4)floor(0.5 + (pspace->space->data[0].min - (REAL8)min_freq_int)*1e3);
    UINT4 max_freq_mhz = (UINT4)floor(0.5 + (pspace->space->data[0].max - (REAL8)max_freq_int)*1e3);
    UINT4 end = (UINT4)ceil(XLALGPSGetREAL8(&(pspace->epoch)) + pspace->span);
    /* if (coherent) snprintf(outputfile,LONGSTRINGLENGTH,"%s/CoherentResults-%s-%d_%d-%04d_%03d_%04d_%03d.txt",
			   outputdir,(CHAR*)uvar->comment,pspace->epoch.gpsSeconds,end,min_freq_int,min_freq_mhz,max_freq_int,max_freq_mhz);
    else */
    snprintf(outputfile,LONGSTRINGLENGTH,"%s/SemiCoherentResults-%s-%d_%d-%04d_%03d_%04d_%03d.txt",
		  outputdir,(CHAR*)uvar->comment,pspace->epoch.gpsSeconds,end,min_freq_int,min_freq_mhz,max_freq_int,max_freq_mhz);
  }
  LogPrintf(LOG_DEBUG,"%s : output %s\n",__func__,outputfile);

  /* open the output file */
  if (((*fp) = fopen(outputfile,"w")) == NULL) {
    LogPrintf(LOG_CRITICAL,"%s: Error, failed to open file %s for writing.  Exiting.\n",__func__,outputfile);
    XLAL_ERROR(XLAL_EINVAL);
  }

  /* Convert time to local time representation */
  {
    struct tm *loctime = localtime(&curtime);
    CHAR *temp_time = asctime(loctime);
    UINT4 n = strlen(temp_time);
    time_string = XLALCalloc(n,sizeof(CHAR));
    snprintf(time_string,n-1,"%s",temp_time);
  }

  /* get GIT version information */
  {
    CHAR *temp_version = XLALGetVersionString(0);
    UINT4 n = strlen(temp_version);
    version_string = XLALCalloc(n,sizeof(CHAR));
    snprintf(version_string,n-1,"%s",temp_version);
    XLALFree(temp_version);
  }

  /* output header information */
  fprintf((*fp),"%s \n",version_string);
  fprintf((*fp),"%%%% command line args\t\t= %s\n",clargs);
  fprintf((*fp),"%%%% filename\t\t\t\t= %s\n",outputfile);
  fprintf((*fp),"%%%% date\t\t\t\t\t= %s\n",time_string);
  fprintf((*fp),"%%%% start time (GPS sec)\t\t= %d\n",pspace->epoch.gpsSeconds);
  fprintf((*fp),"%%%% observation span (sec)\t= %d\n",(UINT4)pspace->span);
  fprintf((*fp),"%%%% coherent time (sec)\t\t= %d\n",(UINT4)pspace->tseg);
 /*  fprintf(fp,"%%%% number of segments\t\t= %d\n",Bayes->nsegments); */
/*   fprintf(fp,"%%%% number of dimensions\t= %d\n",Bayes->gridparams->ndim); */
/*   if (pspace->ampspace) fprintf(fp,"%%%% amplitude dimension\t\t\t= 1\n"); */
/*   else fprintf(fp,"%%%% amplitude dimension\t\t\t= 0\n"); */
/*   fprintf(fp,"%%%% mismatch\t\t\t\t= %6.12f\n",Bayes->gridparams->mismatch); */
  fprintf((*fp),"%%%%\n");

  /* free memory */
  XLALFree(time_string);
  XLALFree(version_string);

  LogPrintf(LOG_DEBUG,"%s : leaving.\n",__func__);
  return XLAL_SUCCESS;

}
Beispiel #14
0
//static
void Logger::ExitLogger() {
  time_t t = time(nullptr);
  Logger() << exit_filename << " exiting at " << asctime(localtime(&t));
}
Beispiel #15
0
	operator const char*()
		{ return asctime(false); }
Beispiel #16
0
string daten_to_humantime(uint32_t daten) {
  time_t t = static_cast<time_t>(daten);
  string human_date = string(asctime(localtime(&t)));
  wwiv::strings::StringTrimEnd(&human_date);
  return human_date;
}
Beispiel #17
0
/*
 * char *read_delete(long #1)
 * #1 - The id number of the person we're checking mail for.
 * Returns the message text of the mail received.
 *
 * Retrieves one messsage for a player. The mail is then discarded from
 * the file and the mail index.
 */
char *
read_delete (long recipient)
{
	header_block_type header;
	data_block_type data;
	mail_index_type *mail_pointer, *prev_mail;
	position_list_type *position_pointer;
	long mail_address, following_block;
	char *message, *tmstr, buf[200];
	char *from, *to;
	size_t string_size;

	if (recipient < 0)
	{
		log ("SYSERR: Mail system -- non-fatal error #6. (recipient: %ld)",
			 recipient);
		return (NULL);
	}
	if (!(mail_pointer = find_char_in_index (recipient)))
	{
		log
			("SYSERR: Mail system -- post office spec_proc error?  Error #7. (invalid character in index)");
		return (NULL);
	}
	if (!(position_pointer = mail_pointer->list_start))
	{
		log
			("SYSERR: Mail system -- non-fatal error #8. (invalid position pointer %p)",
			 position_pointer);
		return (NULL);
	}
	if (!(position_pointer->next))
	{							/* just 1 entry in list. */
		mail_address = position_pointer->position;
		free (position_pointer);

		/* now free up the actual name entry */
		if (mail_index == mail_pointer)
		{						/* name is 1st in list */
			mail_index = mail_pointer->next;
			free (mail_pointer);
		}
		else
		{
			/* find entry before the one we're going to del */
			for (prev_mail = mail_index;
				 prev_mail->next != mail_pointer;
				 prev_mail = prev_mail->next);
			prev_mail->next = mail_pointer->next;
			free (mail_pointer);
		}
	}
	else
	{
		/* move to next-to-last record */
		while (position_pointer->next->next)
			position_pointer = position_pointer->next;
		mail_address = position_pointer->next->position;
		free (position_pointer->next);
		position_pointer->next = NULL;
	}

	/* ok, now lets do some readin'! */
	read_from_file (&header, BLOCK_SIZE, mail_address);

	if (header.block_type != HEADER_BLOCK)
	{
		log ("SYSERR: Oh dear. (Header block %ld != %d)", header.block_type,
			 HEADER_BLOCK);
		no_mail = TRUE;
		log
			("SYSERR: Mail system disabled!  -- Error #9. (Invalid header block.)");
		return (NULL);
	}
	tmstr = asctime (localtime (&header.header_data.mail_time));
	*(tmstr + strlen (tmstr) - 1) = '\0';

	from = get_name_by_id (header.header_data.from);
	to = get_name_by_id (recipient);

	sprintf (buf, " ---==* McLandia Email Service *==--- \r\n"
			 "Date: %s\r\n"
			 "  To: %s\r\n"
			 "From: %s\r\n\r\n", tmstr, to ? to : "Unknown",
			 from ? from : "Unknown");

	string_size = (sizeof (char) * (strlen (buf) + strlen (header.txt) + 1));
	CREATE (message, char, string_size);
	strcpy (message, buf);
	strcat (message, header.txt);
	message[string_size - 1] = '\0';
	following_block = header.header_data.next_block;

	/* mark the block as deleted */
	header.block_type = DELETED_BLOCK;
	write_to_file (&header, BLOCK_SIZE, mail_address);
	push_free_list (mail_address);

	while (following_block != LAST_BLOCK)
	{
		read_from_file (&data, BLOCK_SIZE, following_block);

		string_size =
			(sizeof (char) * (strlen (message) + strlen (data.txt) + 1));
		RECREATE (message, char, string_size);
		strcat (message, data.txt);
		message[string_size - 1] = '\0';
		mail_address = following_block;
		following_block = data.block_type;
		data.block_type = DELETED_BLOCK;
		write_to_file (&data, BLOCK_SIZE, mail_address);
		push_free_list (mail_address);
	}

	return (message);
}
/* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
   failure. */
gboolean network_instruments_dump_open(wtap_dumper *wdh, int *err)
{
    observer_dump_private_state * private_state = NULL;
    capture_file_header file_header;

    tlv_header comment_header;
    tlv_time_info time_header;
    char comment[64];
    size_t comment_length;
    struct tm * current_time;
    time_t system_time;

    /* initialize the private state */
    private_state = (observer_dump_private_state *) g_malloc(sizeof(observer_dump_private_state));
    private_state->packet_count = 0;
    private_state->network_type = wtap_to_observer_encap(wdh->encap);
    private_state->time_format = TIME_INFO_GMT;

    /* populate the fields of wdh */
    wdh->priv = (void *) private_state;
    wdh->subtype_write = observer_dump;

    /* initialize the file header */
    memset(&file_header, 0x00, sizeof(file_header));
    g_strlcpy(file_header.observer_version, network_instruments_magic, 31);
    file_header.offset_to_first_packet = (guint16)sizeof(file_header);
    file_header.offset_to_first_packet_high_byte = 0;

    /* create the file comment TLV */
    {
        time(&system_time);
        current_time = localtime(&system_time);
        memset(&comment, 0x00, sizeof(comment));
        g_snprintf(comment, 64, "This capture was saved from Wireshark on %s", asctime(current_time));
        comment_length = strlen(comment);

        comment_header.type = INFORMATION_TYPE_COMMENT;
        comment_header.length = (guint16) (sizeof(comment_header) + comment_length);

        /* update the file header to account for the comment TLV */
        file_header.number_of_information_elements++;
        file_header.offset_to_first_packet += comment_header.length;
    }

    /* create the timestamp encoding TLV */
    {
        time_header.type = INFORMATION_TYPE_TIME_INFO;
        time_header.length = (guint16) (sizeof(time_header));
        time_header.time_format = TIME_INFO_GMT;

        /* update the file header to account for the timestamp encoding TLV */
        file_header.number_of_information_elements++;
        file_header.offset_to_first_packet += time_header.length;
    }

    /* write the file header, swapping any multibyte fields first */
    CAPTURE_FILE_HEADER_TO_LE_IN_PLACE(file_header);
    if (!wtap_dump_file_write(wdh, &file_header, sizeof(file_header), err)) {
        return FALSE;
    }
    wdh->bytes_dumped += sizeof(file_header);

    /* write the comment TLV */
    {
        TLV_HEADER_TO_LE_IN_PLACE(comment_header);
        if (!wtap_dump_file_write(wdh, &comment_header, sizeof(comment_header), err)) {
            return FALSE;
        }
        wdh->bytes_dumped += sizeof(comment_header);

        if (!wtap_dump_file_write(wdh, &comment, comment_length, err)) {
            return FALSE;
        }
        wdh->bytes_dumped += comment_length;
    }

    /* write the time info TLV */
    {
        TLV_TIME_INFO_TO_LE_IN_PLACE(time_header);
        if (!wtap_dump_file_write(wdh, &time_header, sizeof(time_header), err)) {
            return FALSE;
        }
        wdh->bytes_dumped += sizeof(time_header);
    }

    init_gmt_to_localtime_offset();

    return TRUE;
}
void CLogger::Log(const _eLogLevel level, const char* logline, ...)
{
	boost::unique_lock< boost::mutex > lock(m_mutex);

	bool bDoLog = false;
	if (m_verbose_level == VBL_ALL)
		bDoLog = true;
	else if ((m_verbose_level == VBL_STATUS_ERROR) && ((level == LOG_STATUS) || (level == LOG_ERROR)))
		bDoLog = true;
	else if ((m_verbose_level == VBL_ERROR) && (level == LOG_ERROR))
		bDoLog = true;

	if (!bDoLog)
		return;

	va_list argList;
	char cbuffer[1024];
	va_start(argList, logline);
	vsnprintf(cbuffer, 1024, logline, argList);
	va_end(argList);

	time_t now = time(0);
	char *szDate = asctime(localtime(&now));
	szDate[strlen(szDate)-1]=0;

	std::stringstream sstr;
	
	if ((level==LOG_NORM)||(level==LOG_STATUS))
	{
		sstr << szDate << " " << cbuffer;
	}
	else {
		sstr << szDate << " Error: " << cbuffer;
	}

	if (m_lastlog.size()>=MAX_LOG_LINE_BUFFER)
		m_lastlog.erase(m_lastlog.begin());
	m_lastlog.push_back(_tLogLineStruct(level,sstr.str()));

	if (!g_bRunAsDaemon)
	{
		//output to console
		std::cout << sstr.str() << std::endl;
	}
#ifndef WIN32
	if (g_bUseSyslog)
	{
		int sLogLevel = LOG_INFO;
		if (level == LOG_ERROR)
			sLogLevel =  LOG_ERR;
		else if (level == LOG_STATUS)
			sLogLevel = LOG_NOTICE;
		syslog(sLogLevel, "%s", sstr.str().c_str());
	}
#endif
	if (!m_outputfile.is_open())
		return;

	//output to file

	m_outputfile << sstr.str() << std::endl;
	m_outputfile.flush();
}
Beispiel #20
0
int main(int argc, char *argv[])
{
	int i,j,k;
	int fa,nfa;				/* current argument we're looking at */
	int verb = 0;
	static char inname[200] = { 0 };		/* Input cgats file base name */
	static char outname[200] = { 0 };		/* Output cgats file base name */
	cgats *icg;			/* input cgats structure */
	cgats *ocg;			/* output cgats structure */
	time_t clk = time(0);
	struct tm *tsp = localtime(&clk);
	char *atm = asctime(tsp); /* Ascii time */
	int ti;				/* Temporary index */
	edatas ed;			/* Optimising function data structure */
	double resid[4];
	double presid,dresid;
	double sarea;

	error_program = argv[0];
	if (argc <= 1)
		usage();

	/* Process the arguments */
	for(fa = 1;fa < argc;fa++)
		{
		nfa = fa;					/* skip to nfa if next argument is used */
		if (argv[fa][0] == '-')		/* Look for any flags */
			{
			char *na = NULL;		/* next argument after flag, null if none */

			if (argv[fa][2] != '\000')
				na = &argv[fa][2];		/* next is directly after flag */
			else
				{
				if ((fa+1) < argc)
					{
					if (argv[fa+1][0] != '-')
						{
						nfa = fa + 1;
						na = argv[nfa];		/* next is seperate non-flag argument */
						}
					}
				}

			if (argv[fa][1] == '?')
				usage();

			else if (argv[fa][1] == 'v' || argv[fa][1] == 'V')
				verb = 1;
			else 
				usage();
			}
		else
			break;
		}

	/* Get the file name argument */
	if (fa >= argc || argv[fa][0] == '-') usage();
	strcpy(inname,argv[fa]);
	strcat(inname,".ti3");
	strcpy(outname,argv[fa]);
	strcat(outname,".pr1");

	icg = new_cgats();			/* Create a CGATS structure */
	icg->add_other(icg, "CTI3"); 	/* our special input type is Calibration Target Information 3 */

	if (icg->read_name(icg, inname))
		error("CGATS file read error : %s",icg->err);

	if (icg->ntables == 0 || icg->t[0].tt != tt_other || icg->t[0].oi != 0)
		error ("Input file isn't a CTI3 format file");
	if (icg->ntables != 1)
		error ("Input file doesn't contain exactly one table");

	if ((ed.npat = icg->t[0].nsets) <= 0)
		error ("No sets of data");

	if (verb) {
		printf("No of test patches = %d\n",ed.npat);
	}

	if ((ed.cols = (col *)malloc(sizeof(col) * ed.npat)) == NULL)
		error("Malloc failed!");

	/* Setup output cgats file */
	/* This is a simple interpolation CMYK -> XYZ device profile */
	ocg = new_cgats();	/* Create a CGATS structure */
	ocg->add_other(ocg, "PROF1"); 		/* our special type is Profile type 1 */
	ocg->add_table(ocg, tt_other, 0);	/* Start the first table */

	ocg->add_kword(ocg, 0, "DESCRIPTOR", "Argyll Calibration Device Profile Type 1",NULL);
	ocg->add_kword(ocg, 0, "ORIGINATOR", "Argyll sprof", NULL);
	atm[strlen(atm)-1] = '\000';	/* Remove \n from end */
	ocg->add_kword(ocg, 0, "CREATED",atm, NULL);

	/* Figure out the color space */
	if ((ti = icg->find_kword(icg, 0, "COLOR_REP")) < 0)
		error ("Input file doesn't contain keyword COLOR_REPS");
	if (strcmp(icg->t[0].kdata[ti],"CMYK_XYZ") == 0) {
		int ci, mi, yi, ki;
		int Xi, Yi, Zi;
		if ((ci = icg->find_field(icg, 0, "CMYK_C")) < 0)
			error ("Input file doesn't contain field CMYK_C");
		if (icg->t[0].ftype[ci] != r_t)
			error ("Field CMYK_C is wrong type");
		if ((mi = icg->find_field(icg, 0, "CMYK_M")) < 0)
			error ("Input file doesn't contain field CMYK_M");
		if (icg->t[0].ftype[mi] != r_t)
			error ("Field CMYK_M is wrong type");
		if ((yi = icg->find_field(icg, 0, "CMYK_Y")) < 0)
			error ("Input file doesn't contain field CMYK_Y");
		if (icg->t[0].ftype[yi] != r_t)
			error ("Field CMYK_Y is wrong type");
		if ((ki = icg->find_field(icg, 0, "CMYK_K")) < 0)
			error ("Input file doesn't contain field CMYK_K");
		if (icg->t[0].ftype[ki] != r_t)
			error ("Field CMYK_K is wrong type");
		if ((Xi = icg->find_field(icg, 0, "XYZ_X")) < 0)
			error ("Input file doesn't contain field XYZ_X");
		if (icg->t[0].ftype[Xi] != r_t)
			error ("Field XYZ_X is wrong type");
		if ((Yi = icg->find_field(icg, 0, "XYZ_Y")) < 0)
			error ("Input file doesn't contain field XYZ_Y");
		if (icg->t[0].ftype[Yi] != r_t)
			error ("Field XYZ_Y is wrong type");
		if ((Zi = icg->find_field(icg, 0, "XYZ_Z")) < 0)
			error ("Input file doesn't contain field XYZ_Z");
		if (icg->t[0].ftype[Zi] != r_t)
			error ("Field XYZ_Z is wrong type");
		for (i = 0; i < ed.npat; i++) {
			double XYZ[3];
			ed.cols[i].c = *((double *)icg->t[0].fdata[i][ci]) / 100.0;
			ed.cols[i].m = *((double *)icg->t[0].fdata[i][mi]) / 100.0;
			ed.cols[i].y = *((double *)icg->t[0].fdata[i][yi]) / 100.0;
			ed.cols[i].k = *((double *)icg->t[0].fdata[i][ki]) / 100.0;
			XYZ[0] = *((double *)icg->t[0].fdata[i][Xi]) / 100.0;
			XYZ[1] = *((double *)icg->t[0].fdata[i][Yi]) / 100.0;
			XYZ[2] = *((double *)icg->t[0].fdata[i][Zi]) / 100.0;
			icmXYZ2Lab(&icmD50, ed.cols[i].Lab, XYZ);
		}

		/* Initialise the model */
		ed.gam[0] = 1.0;		/* First four are CMYK gamma values */
		ed.gam[1] = 1.0;
		ed.gam[2] = 1.0;
		ed.gam[3] = 1.0;

		/* Initialise interpolation end points for each combination of primary, */
		/* with all combinations close to black being represented by param[7]. */
		ed.k[0][0] = .82; ed.k[1][0] = .83; ed.k[2][0] = .75;		/* White */
		ed.k[0][1] = .66; ed.k[1][1] = .72; ed.k[2][1] = .05;		/*   Y  */
		ed.k[0][2] = .27; ed.k[1][2] = .12; ed.k[2][2] = .06;		/*  M   */
		ed.k[0][3] = .27; ed.k[1][3] = .12; ed.k[2][3] = .00;		/*  MY  */
		ed.k[0][4] = .09; ed.k[1][4] = .13; ed.k[2][4] = .44;		/* C    */
		ed.k[0][5] = .03; ed.k[1][5] = .10; ed.k[2][5] = .04;		/* C Y  */
		ed.k[0][6] = .02; ed.k[1][6] = .01; ed.k[2][6] = .05;		/* CM   */
		ed.k[0][7] = .01; ed.k[1][7] = .01; ed.k[2][7] = .01;		/* Black */

		sarea = 0.3;
		presid = dresid = 100.0;
		for (k=0; /* dresid > 0.0001 && */ k < 40; k++) {	/* Untill we're done */
			double sresid;
			double sr[8];
			double p[8];

			/* Adjust the gamma */
			for (i = 0; i < 4; i++)
				sr[i] = 0.1;			/* Device space search radius */
			if (powell(&resid[3], 4, &ed.gam[0], sr,  0.1, 1000, efunc1, (void *)&ed, NULL, NULL) != 0)
				error ("Powell failed");

			/* Adjust the primaries */
			calc_bc(&ed);		/* Calculate blend coefficients */
			for (i = 0; i < 8; i++)
				sr[i] = 0.2;			/* Device space search radius */
			sresid = 99.0;
			for (j = 0; j < 3; j++) {	/* For each of X, Y and Z */
				ed.xyzi = j;

				for (i = 0; i < 8; i++)
					p[i] = ed.k[j][i];
printf("##############\n");
printf("XYZ = %d\n",j);
				if (powell(&resid[j], 8, p, sr,  0.1, 1000, efunc2, (void *)&ed, NULL, NULL) != 0)
					error ("Powell failed");

				for (i = 0; i < 8; i++)
					ed.k[j][i] = p[i];

				if (sresid > resid[j])
					sresid = resid[j];
			}
			dresid = presid - sresid;
			if (dresid < 0.0)
				dresid = 100.0;
			presid = sresid;
printf("~1 presid = %f, sresid = %f, dresid = %f\n",presid, sresid, dresid);
		}

		/* Fields we want */
		ocg->add_kword(ocg, 0, "DSPACE","CMYK", NULL);
		ocg->add_kword(ocg, 0, "DTYPE","PRINTER", NULL);
		ocg->add_field(ocg, 0, "PARAM_ID", i_t);
		ocg->add_field(ocg, 0, "PARAM", r_t);

		/* Output model parameters */
		for (j = 0; j < 4; j++)
			ocg->add_set(ocg, 0, j, ed.gam[j]);

		for (j = 0; j < 3; j++) {
			for (i = 0; i < 8; i++)
				ocg->add_set(ocg, 0, 10 * (j + 1) + i, 100.0 * ed.k[j][i]);
		}

		if (verb) {
			double aver = 0.0;
			double maxer = 0.0;
			for (i = 0; i < ed.npat; i++) {
				double err = sqrt(ed.cols[i].err);
				if (err > maxer)
					maxer = err;
				aver += err;
			}
			aver = aver/((double)i);
			printf("Average fit error = %f, maximum = %f\n",aver,maxer);
		}
	} else if (strcmp(icg->t[0].kdata[ti],"RGB") == 0) {
		error ("We can't handle RGB !");
	} else if (strcmp(icg->t[0].kdata[ti],"W") == 0) {
		error ("We can't handle Grey !");
	} else
		error ("Input file keyword COLOR_REPS has unknown value");

	if (ocg->write_name(ocg, outname))
		error("Write error : %s",ocg->err);

	free(ed.cols);
	ocg->del(ocg);		/* Clean up */
	icg->del(icg);		/* Clean up */

	return 0;
}
Beispiel #21
0
int
main(int argc, char * argv[])
{
	if(argc!=2)
	{
		printf("usage: localtime HH:MM:SS\n");
        printf("will add enough to current time to make it that time\n");
        printf("will assume the start is just before DST, Oct 27 2002 1:30am,");
        printf(" at 2 am it's fall back so it'll be 1 hr back 1 2am\n");
        exit(0);
	}
    unsigned int hour = 0;
    unsigned int minutes = 0;
    unsigned int seconds = 0;

    if (sscanf(argv[1], "%u:%u:%u", &hour, &minutes, &seconds) != 3)
    {
        printf("time %s is not correct format, should be HH:MM:SS\n",
                argv[1]);
        exit(0);
    }
    printf("Want to add: hour(%u), minutes(%u), seconds(%u)\n",
            hour, minutes, seconds);

    time_t currTime = 0;
    time_t gcTime = 0;

    struct tm timeStruct;
    struct tm gcStruct;

/*
    // error setup of time before jan 1 1970 dec 31 1969
    timeStruct.tm_sec = 0;
    timeStruct.tm_min = 1;
    timeStruct.tm_hour = 2;
    timeStruct.tm_mday = 31;
    timeStruct.tm_mon = 11;
    timeStruct.tm_year = 69;
    timeStruct.tm_wday = 0;
    timeStruct.tm_yday = 365;
    timeStruct.tm_isdst = 0; // not dst
*/

    // setup the current time as oct 24 2:01am
    //
/*
    timeStruct.tm_sec = 0;
    timeStruct.tm_min = 1;
    timeStruct.tm_hour = 2;
    timeStruct.tm_mday = 24;
    timeStruct.tm_mon = 9;
    timeStruct.tm_year = 102;
    timeStruct.tm_wday = 0;
    timeStruct.tm_yday = 296;
    timeStruct.tm_isdst = 1; // currently dst
*/

    // Set time to Apr 4th 2:30am not DST, apr 7th 2002 at 2am is dst
    //
    timeStruct.tm_sec = 0;
    timeStruct.tm_min = 30;
    timeStruct.tm_hour = 2;
    timeStruct.tm_mday = 4;
    timeStruct.tm_mon = 3;
    timeStruct.tm_year = 102;
    timeStruct.tm_wday = 0;
    timeStruct.tm_yday = 93;
    timeStruct.tm_isdst = 0; // currently not dst

    printf("current time: %s\n", asctime(&timeStruct));
    currTime = mktime(&timeStruct);

    localtime_r(&currTime, &gcStruct);
    printf("current time after mktime and localtime: %s\n", asctime(&gcStruct));

    // need to adjust current time so gc time is 
    // properly setup
    //
    // figure out the # hrs and minutes the gc 
    // time is less by.
    //
    int diffHr = timeStruct.tm_hour - hour; 
    int diffMin = timeStruct.tm_min - minutes;
    int diffSec = timeStruct.tm_sec - seconds; 

    int dayAdded = 0;
    // Now lets create the gc time for next 24 hr
    //
    gcTime = currTime;

    if ((diffHr > 0) || ((diffHr == 0) && (diffMin > 0)) ||
        ((diffHr == 0) && (diffMin == 0) && (diffSec > 0)) )
    {
        // add day
        //
        timeStruct.tm_mday++; 
        dayAdded = 1;
    }

    // day added not true that means GC time is this day in future just set
    // the time and use mktime to normalize it
    //
    timeStruct.tm_hour = hour;
    timeStruct.tm_min = minutes;
    timeStruct.tm_sec = seconds;

    gcTime = mktime(&timeStruct);

    if (dayAdded)
    {
        // hour added check if the currTime is within 1 hr past the gc time if
        // the 1 day wasn't added
        //
        time_t dayOldGc = gcTime - (24 * 60 * 60);
        if ( ((currTime - dayOldGc) > 0) &&
             ((currTime - dayOldGc) <= (60 * 60)) )
        {
            // curr time is w/n 1 hr of day old gc time
            //
            printf("currTime is within 1hr past gc time\n");
        }
    }

    localtime_r(&gcTime, &gcStruct);

    printf("old time: %s\n", asctime(&timeStruct));
    printf("gc time: %s\n", asctime(&gcStruct));
    for (int i=1; i < 30; i++)
    {
        gcStruct.tm_hour = hour;
        gcStruct.tm_min = minutes;
        gcStruct.tm_sec = seconds;
        int isDstBefore = gcStruct.tm_isdst;
        gcStruct.tm_mday++; 
        gcTime = mktime(&gcStruct);
        if (isDstBefore != gcStruct.tm_isdst)
        {
            printf("DST change resting to make sure we can handle the time\n");
            // looks like dst changed.  Reset the time and normalize it.  
            // This will ensure that we can represent the time in the new zone.
            // 
            gcStruct.tm_hour = hour;
            gcStruct.tm_min = minutes;
            gcStruct.tm_sec = seconds;
            gcTime = mktime(&gcStruct);
        }
        printf("day:%d gc time: %s\n", i + 1, asctime(&gcStruct));
    }
	
	return 0;
}
Beispiel #22
0
bool ARCStringTracker::DumpTracker(std::ostream& os)
{
	bool bNoError = true;

	os.setf(std::ios::hex);

	os << "Dumping ARCStringTracker tracker..." << std::endl;

	//------------------------------------------------------------
	// 
	try
	{
		os << "\t" << "The tracker is (" << convHex((unsigned long)&m_whoami) << " -> " << convHex((unsigned long)m_whoami) << ")\"" << readStringCarefully(m_whoami) << "\"." << std::endl;
	}
	catch (std::string& e)
	{
		os << std::endl << "Dumping failed(" << e << ")." << std::endl;
		bNoError = false;
	}
	//------------------------------------------------------------


	//------------------------------------------------------------
	// 
	try
	{
		os << "\t" << "The last track string is (" << convHex((unsigned long)m_lastStringTrackerName) << ")\"" << readStringCarefully(m_lastStringTrackerName) << "\"." << std::endl;
	}
	catch (std::string& e)
	{
		os << std::endl << "Dumping failed(" << e << ")." << std::endl;
		bNoError = false;
	}
	//------------------------------------------------------------


	//------------------------------------------------------------
	// 
#	ifdef _USE_CLASS_METHOD_TRACK_INCLUDE_STACK_
	os << "Dumping stack tracker..." << std::endl;
	try
	{
		ARCStringTracker* pTracker = m_lastStringTracker;
		while (pTracker)
		{
			if (checkReadable(pTracker, sizeof(ARCStringTracker)))
				throw std::string("ARCStringTracker corrupted");

			os << "\t(" << convHex((unsigned long)pTracker) << " -> " << convHex((unsigned long)pTracker->m_pTrackString) << ")" << readStringCarefully(pTracker->m_pTrackString) << std::endl;
			pTracker = pTracker->m_preStringTracker;
		}
	}
	catch (std::string& e)
	{
		os << std::endl << "Dumping failed(" << e << ")." << std::endl;
		bNoError = false;
	}
	os << "Dumping stack tracker finished." << std::endl;

	os << "Dumping stack tracker stored image..." << std::endl;
	std::vector<TrackRecord>::iterator ite = m_recs.begin();
	std::vector<TrackRecord>::iterator iteEn = m_recs.end();
	for (;ite!=iteEn;ite++)
	{
		const TrackRecord& rec = *ite;
		os << "\t(" << convHex((unsigned long)rec.pTracker) << " -> " << convHex((unsigned long)rec.pString) << ")" << readStringCarefully(rec.pString) << std::endl;
	}
	os << "Dumping stack tracker stored image finished." << std::endl;

#	endif // _USE_CLASS_METHOD_TRACK_INCLUDE_STACK_
	//------------------------------------------------------------

	os << std::endl << "All dumps finished." << std::endl << std::endl;

	__time64_t now;
	_time64( &now );
	os << "UTC time:   " << asctime( _gmtime64( &now ) )    << std::endl;
	os << "Local time: " << asctime( _localtime64( &now ) ) << std::endl;
	return bNoError;
}
Beispiel #23
0
void StatDumper::DumpStats()
{
	if( Filename[0] == NULL )
		return;
	FILE* f = fopen( Filename, "w" );
	if( !f )
		return;

	Log.Debug( "StatDumper", "Writing %s", Filename );

	// Dump Header
	fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
	fprintf(f, "<?xml-stylesheet type=\"text/xsl\" href=\"server_stats.xsl\"?>\n");
	fprintf(f, "<serverpage>\n");
	fprintf(f, "	<status>\n");

	uint32 races[RACE_DRAENEI+1];
	uint32 classes[DRUID+1];
	memset(&races[0], 0, sizeof(uint32)*(RACE_DRAENEI+1));
	memset(&classes[0], 0, sizeof(uint32)*(RACE_DRAENEI+1));
	std::deque<Player*> gms;
	{
		// Dump server information.
#ifndef WIN32
		fprintf(f, "	<platform>Ascent %s r%u/%s-%s (www.ascentemu.com)</platform>\n", BUILD_TAG, BUILD_REVISION, PLATFORM_TEXT, ARCH);	
#else
		fprintf(f, "	<platform>Ascent %s r%u/%s-Win-%s (www.ascentemu.com)</platform>\n", BUILD_TAG, BUILD_REVISION, CONFIG, ARCH);		
#endif
		fprintf(f, "	<updateinfo>Built at %s on %s by %[email protected]%s</updateinfo>\n", BUILD_TIME, BUILD_DATE, BUILD_USER, BUILD_WORKSTATION);
		char uptime[80];
		GenerateUptimeString(uptime);
		float AvgLat;
		uint32 GMCount;
		int gm = 0;
		int count = 0;
		int avg = 0;
		// lock players reader
		objmgr._playerslock.AcquireReadLock();

		HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;
		for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
		{
			if( itr->second->GetSession() && itr->second->IsInWorld() && itr->second->m_isGmInvisible < 2 )
			{
				count++;
				avg += itr->second->GetSession()->GetLatency();
				if( itr->second->RS_getAccess() >= RS_PROBEGM && itr->second->bGMTagOn )
				{
					gm++;
					gms.push_back(itr->second);
				}
				classes[itr->second->getClass()]++;
				races[itr->second->getRace()]++;
			}
		}
		objmgr._playerslock.ReleaseReadLock();

		AvgLat = count ? (float)((float)avg / (float)count) : 0;
		GMCount = gm;

		fprintf(f, "	<uptime>%s</uptime>\n", uptime);
		fprintf(f, "	<oplayers>%u</oplayers>\n", (unsigned int)(sWorld.AlliancePlayers + sWorld.HordePlayers));
		fprintf(f, "	<cpu>%2.2f</cpu>\n", GetCPUUsage());
		fprintf(f, "	<qplayers>%u</qplayers>\n", (unsigned int)sWorld.GetQueueCount());
		fprintf(f, "	<ram>%.3f</ram>\n", GetRAMUsage());
		fprintf(f, "	<avglat>%.3f</avglat>\n", AvgLat);
		fprintf(f, "	<threads>%u</threads>\n", (unsigned int)ThreadPool.GetActiveThreadCount());
		fprintf(f, "	<fthreads>%u</fthreads>\n", (unsigned int)ThreadPool.GetFreeThreadCount());
		time_t t = (time_t)UNIXTIME;
		fprintf(f, "	<gmcount>%u</gmcount>\n", (unsigned int)GMCount);
		fprintf(f, "	<lastupdate>%s</lastupdate>\n", asctime(localtime(&t)));
		fprintf(f, "	<alliance>%u</alliance>\n", (unsigned int)sWorld.AlliancePlayers);
		fprintf(f, "	<horde>%u</horde>\n", (unsigned int)sWorld.HordePlayers);
		fprintf(f, "	<acceptedconns>%u</acceptedconns>\n", (unsigned int)sWorld.mAcceptedConnections);
		fprintf(f, "	<peakcount>%u</peakcount>\n", (unsigned int)sWorld.PeakSessionCount);
		fprintf(f, "	<wdbquerysize>%u</wdbquerysize>\n", WorldDatabase.GetQueueSize());
		fprintf(f, "	<cdbquerysize>%u</cdbquerysize>\n", CharacterDatabase.GetQueueSize());
	}
	fprintf(f, "	</status>\n");
	static const char * race_names[RACE_DRAENEI+1] = {
		NULL,
		"human",
		"orc",
		"dwarf",
		"nightelf",
		"undead",
		"tauren",
		"gnome",
		"troll",
		NULL,
		"bloodelf",
		"draenei",
	};

	static const char * class_names[DRUID+1] = {
		NULL,
		"warrior",
		"paladin",
		"hunter",
		"rogue",
		"priest",
		NULL,
		"shaman",
		"mage",
		"warlock",
		NULL,
		"druid",
	};
	
	fprintf(f, "	<statsummary>\n");
	uint32 i;
	for(i = 0; i <= RACE_DRAENEI; ++i)
	{
		if( race_names[i] != NULL )
			fprintf(f, "	<%s>%u</%s>\n", race_names[i], races[i], race_names[i]);
	}

	for(i = 0; i <= DRUID; ++i)
	{
		if( class_names[i] != NULL )
			fprintf(f, "	<%s>%u</%s>\n", class_names[i], classes[i], class_names[i]);
	}
	fprintf(f, "	</statsummary>\n");

	Player * plr;
	uint32 t = (uint32)time(NULL);
	char otime[100];
	{
		fprintf(f, "	<instances>\n");
		
		// need a big buffer..
		static char buf[500000];
		memset(buf, 0, 500000);

		// Dump Instance Information
		//sWorldCreator.BuildXMLStats(buf);
		sInstanceMgr.BuildXMLStats(buf);
		fprintf(f, buf);
		fprintf(f, "	</instances>\n");
	}
	{
		// GM Information
		fprintf(f, "	<gms>\n");
		while(!gms.empty())
		{
			plr = gms.front();
			gms.pop_front();

			FillOnlineTime(t - plr->OnlineTime, otime);
			fprintf(f, "	<gmplr>\n");
			fprintf(f, "		<name>%s</name>\n", plr->GetName());
			fprintf(f, "		<race>%u</race>\n", plr->getRace());
			fprintf(f, "		<class>%u</class>\n", (unsigned int)plr->getClass());
			fprintf(f, "		<gender>%u</gender>\n", (unsigned int)plr->getGender());
			fprintf(f, "		<pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
			fprintf(f, "		<level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
			fprintf(f, "		<map>%u</map>\n", (unsigned int)plr->GetMapId());
			fprintf(f, "		<areaid>%u</areaid>\n", (unsigned int)plr->GetAreaID());
			fprintf(f, "		<ontime>%s</ontime>\n", otime);
			fprintf(f, "		<latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
			fprintf(f, "		<permissions>%s</permissions>\n", plr->GetSession()->GetPermissions());
			fprintf(f, "	</gmplr>\n");
		}

		fprintf(f, "  </gms>\n");
	}

	{
	fprintf(f, "  <sessions>\n");
		// Dump Player Information
		objmgr._playerslock.AcquireReadLock();
		HM_NAMESPACE::hash_map<uint32, Player*>::const_iterator itr;

		for (itr = objmgr._players.begin(); itr != objmgr._players.end(); itr++)
		{
			plr = itr->second;
			if( itr->second->GetSession() && itr->second->IsInWorld() && itr->second->m_isGmInvisible == INVIS_NONE )
			{
				FillOnlineTime(t - plr->OnlineTime, otime);

				fprintf(f, "	<plr>\n");
				fprintf(f, "		<name>%s</name>\n", plr->GetName());
				fprintf(f, "		<race>%u</race>\n", (unsigned int)plr->getRace());
				fprintf(f, "		<class>%u</class>\n", (unsigned int)plr->getClass());
				fprintf(f, "		<gender>%u</gender>\n", (unsigned int)plr->getGender());
				fprintf(f, "		<pvprank>%u</pvprank>\n", (unsigned int)plr->GetPVPRank());
				fprintf(f, "		<level>%u</level>\n", (unsigned int)plr->GetUInt32Value(UNIT_FIELD_LEVEL));
				fprintf(f, "		<map>%u</map>\n", (unsigned int)plr->GetMapId());
				fprintf(f, "		<areaid>%u</areaid>\n", (unsigned int)plr->GetAreaID());
				//requested by Zdarkside for he's online map. I hope it does not scre up any parser. If so, then make a better one :P
				fprintf(f, "		<xpos>%f</xpos>\n", plr->GetPositionX ());
				fprintf(f, "		<ypos>%f</ypos>\n", plr->GetPositionY());
				fprintf(f, "		<ontime>%s</ontime>\n", otime);
				fprintf(f, "		<latency>%u</latency>\n", (unsigned int)plr->GetSession()->GetLatency());
				fprintf(f, "	</plr>\n");
				if(plr->RS_getAccess() >= RS_PROBEGM && plr->bGMTagOn)
					gms.push_back(plr);
			}
		}
		objmgr._playerslock.ReleaseReadLock();
		fprintf(f, "	</sessions>\n");

		
	}

	fprintf(f, "</serverpage>\n");
	fclose(f);
}
Beispiel #24
0
int Recab::execute(int argc, char *argv[])
{
    bool verboseFlag = false;

    String inFile,outFile,logFile;

    bool noeof = false;
    bool params = false;

    SamFile samIn,samOut;

    ParameterList inputParameters;

    LongParamContainer parameters;

    parameters.addGroup("Required Generic Parameters");
    parameters.addString("in", &inFile);
    parameters.addString("out", &outFile);
    parameters.addGroup("Optional Generic Parameters");
    parameters.addString("log", &logFile);
    parameters.addBool("verbose", &verboseFlag);
    parameters.addBool("noeof", &noeof);
    parameters.addBool("params", &params);
    parameters.addPhoneHome(VERSION);
    addRecabSpecificParameters(parameters);
    inputParameters.Add(new LongParameters ("Input Parameters", 
                                            parameters.getLongParameterList()));
    
    // parameters start at index 2 rather than 1.
    inputParameters.Read(argc, argv, 2);
    
    // If no eof block is required for a bgzf file, set the bgzf file type to 
    // not look for it.
    if(noeof)
    {
        // Set that the eof block is not required.
        BgzfFileType::setRequireEofBlock(false);
    }

    if(inFile.IsEmpty())
    {
        usage();
        inputParameters.Status();
        std::cerr << "Missing required --in parameter" << std::endl;
        return EXIT_FAILURE;
    }

    if(outFile.IsEmpty())
    {
        usage();
        inputParameters.Status();
        std::cerr << "Missing required --out parameter" << std::endl;
        return EXIT_FAILURE;
    }

    int status = processRecabParam();
    if(status != 0)
    {
        inputParameters.Status();
        return(status);
    }

    if ( logFile.IsEmpty() )
    {
        logFile = outFile + ".log";
    }
  
    if(params)
    {
        inputParameters.Status();
    }
    
    Logger::gLogger = new Logger(logFile.c_str(), verboseFlag);

    ////////////////
    //////  Errormodel
    Logger::gLogger->writeLog("Initialize errormodel structure...");

    ////////////////////////////////////////
    // SAM/BAM file open
    ////////////////////////////////////////
    ////////////////////////////////////////

    // Iterate SAM records
    if(!samIn.OpenForRead(inFile.c_str()))
    {
        Logger::gLogger->error("Failed to open SAM/BAM file %s",inFile.c_str() );
        return EXIT_FAILURE;
    }

    Logger::gLogger->writeLog("Start iterating SAM/BAM file %s",inFile.c_str());

    time_t now = time(0);
    tm* localtm = localtime(&now);

    Logger::gLogger->writeLog("Start: %s", asctime(localtm));
    SamRecord samRecord;
    SamFileHeader samHeader;
    samIn.ReadHeader(samHeader);

    srand (time(NULL));

    int numRecs = 0;
    while(samIn.ReadRecord(samHeader, samRecord) == true)
    {
        processReadBuildTable(samRecord);

        //Status info
        numRecs++;
        if(verboseFlag)
        {
            if(numRecs%10000000==0)
                Logger::gLogger->writeLog("%ld records processed", numRecs);
        }
    }

    now = time(0);
    localtm = localtime(&now);
    Logger::gLogger->writeLog("End: %s", asctime(localtm));

    modelFitPrediction(outFile);

    Logger::gLogger->writeLog("Writing recalibrated file %s",outFile.c_str());

    ////////////////////////
    ////////////////////////
    //// Write file
    samIn.OpenForRead(inFile.c_str());
    samOut.OpenForWrite(outFile.c_str());
    samIn.ReadHeader(samHeader);
    samOut.WriteHeader(samHeader);
    
    while(samIn.ReadRecord(samHeader, samRecord) == true)
    {
        // Recalibrate.
        processReadApplyTable(samRecord);
        samOut.WriteRecord(samHeader, samRecord);
    }

    Logger::gLogger->writeLog("Total # Reads recab table not applied to: %ld", myNumApplySkipped);
    Logger::gLogger->writeLog("Total # Reads recab table applied to: %ld", myNumApplyReads);
    Logger::gLogger->writeLog("Recalibration successfully finished");
    return EXIT_SUCCESS;
}
Beispiel #25
0
/**
 * @brief Print a formatted message to the console.
 * @details If the logging level is ERROR, this function will throw a
 *          runtime exception
 * @param level the logging level for this message
 * @param format variable list of C++ formatted arguments
 */
void log_printf(logLevel level, const char* format, ...) {

  char message[1024];
  std::string msg_string;
  if (level >= log_level) {
    va_list args;

    va_start(args, format);
    vsprintf(message, format, args);
    va_end(args);

    /* Append the log level to the message */
    switch (level) {
    case (DEBUG):
      {
        std::string msg = std::string(message);
        std::string level_prefix = "[  DEBUG  ]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";

        break;
      }
    case (INFO):
      {
        std::string msg = std::string(message);
        std::string level_prefix = "[  INFO   ]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";

        break;
      }
    case (NORMAL):
      {
        std::string msg = std::string(message);
        std::string level_prefix = "[  NORMAL ]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";

        break;
      }
    case (SEPARATOR):
      {
        std::string pad = std::string(line_length, separator_char);
        std::string prefix = std::string("[SEPARATOR]  ");
        std::stringstream ss;
        ss << prefix << pad << "\n";
        msg_string = ss.str();
        break;
      }
    case (HEADER):
      {
        int size = strlen(message);
        int halfpad = (line_length - 4 - size) / 2;
        std::string pad1 = std::string(halfpad, header_char);
        std::string pad2 = std::string(halfpad +
                           (line_length - 4 - size) % 2, header_char);
        std::string prefix = std::string("[  HEADER ]  ");
        std::stringstream ss;
        ss << prefix << pad1 << "  " << message << "  " << pad2 << "\n";
        msg_string = ss.str();
        break;
      }
    case (TITLE):
      {
        int size = strlen(message);
        int halfpad = (line_length - size) / 2;
        std::string pad = std::string(halfpad, ' ');
        std::string prefix = std::string("[  TITLE  ]  ");
        std::stringstream ss;
        ss << prefix << std::string(line_length, title_char) << "\n";
        ss << prefix << pad << message << pad << "\n";
        ss << prefix << std::string(line_length, title_char) << "\n";
        msg_string = ss.str();
        break;
      }
    case (WARNING):
      {
        std::string msg = std::string(message);
        std::string level_prefix = "[ WARNING ]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";

        break;
      }
    case (CRITICAL):
      {
        std::string msg = std::string(message);
        std::string level_prefix = "[ CRITICAL]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";

        break;
      }
    case (RESULT):
      msg_string = std::string("[  RESULT ]  ") + message + "\n";
      break;
    case (UNITTEST):
      {
        std::string msg = std::string(message);
        std::string level_prefix = "[   TEST  ]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";

        break;
      }
    case (ERROR):
      {
        /* Create message based on runtime error stack */
        va_start(args, format);
        vsprintf(message, format, args);
        va_end(args);
        std::string msg = std::string(message);
        std::string level_prefix = "[  ERROR  ]  ";

        /* If message is too long for a line, split into many lines */
        if (int(msg.length()) > line_length)
          msg_string = create_multiline_msg(level_prefix, msg);

        /* Puts message on single line */
        else
          msg_string = level_prefix + msg + "\n";
      }
    }

    /* If this is our first time logging, add a header with date, time */
    if (!logging) {

      /* If output directory was not defined by user, then log file is
       * written to a "log" subdirectory. Create it if it doesn't exist */
      if (output_directory.compare(".") == 0) {
        struct stat st;
        if (!stat("log", &st) == 0)
          mkdir("log", S_IRWXU);
      }

      /* Write the message to the output file */
      std::ofstream log_file;
      log_file.open((output_directory + "/" + log_filename).c_str(),
                   std::ios::app);

      /* Append date, time to the top of log output file */
      time_t rawtime;
      struct tm * timeinfo;
      time (&rawtime);
      timeinfo = localtime (&rawtime);
      log_file << "Current local time and date: " << asctime(timeinfo);
      logging = true;

      log_file.close();
    }

    /* Write the log message to the log_file */
    std::ofstream log_file;
    log_file.open((output_directory + "/" + log_filename).c_str(),
                  std::ios::app);
    log_file << msg_string;
    log_file.close();

    /* Write the log message to the shell */
    printf(msg_string.c_str());
  }


  /* If the message was a runtime error, exit the program */
  if (level == ERROR)
    exit(1);
}
Beispiel #26
0
int main(int argc, char **argv) {
	struct opts Options;
	int i;
	time_t CurrentTime;
	clock_t TotalClock = clock();
	
	/* Apply Mondriaan options. */
	SetDefaultOptions(&Options);
	
	if (!SetOptionsFromFile(&Options, "Mondriaan.defaults")) {
		fprintf(stderr, "main(): warning, cannot set options from 'Mondriaan.defaults', using default options!\n");
	}
	
	if (!ParseCommandLineOptions(&Options, argc, argv)) {
		fprintf(stderr, "main(): invalid command line parameters!\n");
		exit(EXIT_FAILURE);
	}
	
	if (!ApplyOptions(&Options)) {
		fprintf(stderr, "main(): could not apply given options!\n");
		exit(EXIT_FAILURE);
	}
	
	if (NumMatrices <= 0 || Matrices == NULL) {
		fprintf(stderr, "main(): Invalid number of supplied matrices or samples!\n");
		exit(EXIT_FAILURE);
	}
	
	/* Start profiling ... */
	fprintf(stderr, "Profiling Mondriaan for %d matrices, %d samples, %s processors, and %f imbalance.\n", NumMatrices, NumSamples, argv[1], Options.eps);
	
	for (i = 0; i < NumMatrices*NumNumProcs; ++i) {
		int j;
		
		fprintf(stderr, "[% 4d/%d] (% 4ld) %s ", i + 1, NumMatrices*NumNumProcs, Matrices[i].P, Matrices[i].File);
		fflush(stderr);
		
		if (!SetupAttributes(&Matrices[i])) {
			fprintf(stderr, "main(): Cannot setup attributes!\n");
			exit(EXIT_FAILURE);
		}
		
		Options.P = Matrices[i].P;
		
		/* Take the requested number of samples. */
		for (j = 0; j < NumSamples; ++j) {
			struct sparsematrix A;
			long int *UAssign, *VAssign, Symmetric;
			FILE *File;
			long l;
			int k;
			clock_t Clock;
			
			double Duration;
			long MaxNz, MinNz;
			long MaxComU, MaxComV, ComVolU, ComVolV;
			
			fprintf(stderr, ".");
			fflush(stderr);
			
			/* Read matrix from disk. */
			File = fopen(Matrices[i].File, "r");
			
			if (!File) {
				fprintf(stderr, "main(): Could not open '%s' for reading!\n", Matrices[i].File);
				exit(EXIT_FAILURE);
			}
				
			if (!MMReadSparseMatrix(File, &A)) {
				fprintf(stderr, "main(): Could not read matrix!\n");
				exit(EXIT_FAILURE);
			}
			
			fclose(File);
			
			/* Remove double zeroes. */
			if (!SparseMatrixRemoveDuplicates(&A)) exit(EXIT_FAILURE);
			
			/* Check symmetry. */
			if (A.m == A.n && (A.MMTypeCode[3] == 'S' || A.MMTypeCode[3] == 'K' || A.MMTypeCode[3] == 'H')) Symmetric = TRUE;
			else Symmetric = FALSE;
			
			if (Symmetric)
			{
				if (Options.SymmetricMatrix_UseSingleEntry == SingleEntNo) SparseMatrixSymmetric2Full(&A);
				else if (Options.SymmetricMatrix_SingleEntryType == ETypeRandom) SparseMatrixSymmetricLower2Random(&A);
			}
			
			/* Add dummies if requested. */
			if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes && Options.SquareMatrix_DistributeVectorsEqual_AddDummies == DumYes) AddDummiesToSparseMatrix(&A);
			
			/* Initialise processor array. */
			A.NrProcs = Options.P;
			A.Pstart = (long *)malloc((A.NrProcs + 1)*sizeof(long));
			
			if (A.Pstart == NULL) {
				fprintf(stderr, "main(): Cannot allocate processor array!\n");
				exit(EXIT_FAILURE);
			}
			
			A.Pstart[0] = 0;
			
			for (k = 1; k <= A.NrProcs; ++k) {
				A.Pstart[k] = A.NrNzElts;
			}
		
			/* Distribute the processors among the matrix entries. */
			SetRandomSeed(Options.Seed = 137*j + 12345);
			
			/* ==== Start Mondriaan */
			Clock = clock();
			
			if (!DistributeMatrixMondriaan(&A, Options.P, Options.eps, &Options, NULL)) {
				fprintf(stderr, "main(): Unable to distribute matrix!\n");
				exit(EXIT_FAILURE);
			}
			
			/* Remove dummies. */
			if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes && Options.SquareMatrix_DistributeVectorsEqual_AddDummies == DumYes) RemoveDummiesFromSparseMatrix(&A);
			
			/* Convert randomly represented matrix to lower triangular form. */
			if (Symmetric && Options.SymmetricMatrix_UseSingleEntry == SingleEntYes && Options.SymmetricMatrix_SingleEntryType == ETypeRandom) SparseMatrixSymmetricRandom2Lower(&A);
			
			/* Distribute vectors. */
			UAssign = (long int *)malloc(A.m*sizeof(long int));
			VAssign = (long int *)malloc(A.n*sizeof(long int));
			
			if (UAssign == NULL || VAssign == NULL) {
				fprintf(stderr, "main(): Cannot allocate vertex assign arrays!\n");
				exit(EXIT_FAILURE);
			}
			
			/* Convert symmetrically partitioned matrix to full form. */
			if (Symmetric && Options.SymmetricMatrix_UseSingleEntry == SingleEntYes) SparseMatrixSymmetric2Full(&A);
			
			if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes) {
				if (Symmetric && Options.SymmetricMatrix_UseSingleEntry == SingleEntYes) {
					MaxComV = DistributeVec(&A, VAssign, ROW, &Options);
					
					if (MaxComV < 0) {
						fprintf(stderr, "main(): Unable to distribute vector!\n");
						exit(EXIT_FAILURE);
					}
					
					for (k = 0; k < A.m; k++) {
						UAssign[k] = VAssign[k];
					}
						
					MaxComU = MaxComV;
				}
				else {
					MaxComU = DistributeVecOrigEq(&A, UAssign, VAssign, &Options);
					
					if (MaxComU < 0) {
						fprintf(stderr, "main(): Unable to distribute vector!\n");
						exit(EXIT_FAILURE);
					}
					
					MaxComV = 0;
				}
			}
			else {
				MaxComV = DistributeVec(&A, VAssign, ROW, &Options);
				MaxComU = DistributeVec(&A, UAssign, COL, &Options);
				
				if (MaxComV < 0 || MaxComU < 0) {
					fprintf(stderr, "main(): Unable to distribute vector!\n");
					exit(EXIT_FAILURE);
				}
			}
			
			/* ==== Stop Mondriaan */
			/* Calculate duration. */
			Duration = (double)(clock() - Clock)/(double)CLOCKS_PER_SEC;
			
			/* Determine minimum and maximum number of assigned nonzeroes. */
			MaxNz = MinNz = A.Pstart[1] - A.Pstart[0];
			
			for (k = 1; k < A.NrProcs; ++k) {
				l = A.Pstart[k + 1] - A.Pstart[k];
				
				if (l > MaxNz) MaxNz = l;
				if (l < MinNz) MinNz = l;
			}
			
			/* Calculate communication volume. */
			if (!CalcCom(&A, VAssign, ROW, &ComVolV, &l, &l, &l, &l) ||
			    !CalcCom(&A, UAssign, COL, &ComVolU, &l, &l, &l, &l)) {
				fprintf(stderr, "main(): Unable to calculate communication volume!\n");
				exit(EXIT_FAILURE);
			}
			
			/* Store attributes. */
			Matrices[i].NumNz = A.NrNzElts;
			Matrices[i].Rows = A.m;
			Matrices[i].Cols = A.n;
			
			Matrices[i].Attributes[0].Data[j] = Duration;
			Matrices[i].Attributes[1].Data[j] = (double)(Options.P*MaxNz - A.NrNzElts)/(double)A.NrNzElts;
			Matrices[i].Attributes[2].Data[j] = (double)(MaxComV + MaxComU);
			Matrices[i].Attributes[3].Data[j] = (double)(ComVolV + ComVolU);
			
			/* Free memory. */
			MMDeleteSparseMatrix(&A);
			free(UAssign);
			free(VAssign);
		}
		
		/* Average attributes. */
		if (!AverageAndFreeAttributes(&Matrices[i])) {
			fprintf(stderr, "main(): Cannot setup attributes!\n");
			exit(EXIT_FAILURE);
		}
		
		fprintf(stderr, "\n");
	}
	
	/* Write accumulated data to stdout. */
	fprintf(stderr, "Finished profiling, writing data ...\n");
	
	printf("%% Profiled Mondriaan for %d matrices, %d samples, and %f imbalance.\n", NumMatrices, NumSamples, Options.eps);
	printf("\\documentclass[a4paper, 10pt]{article}\n\n");
	printf("\\usepackage{lscape}\n");
	printf("\\usepackage{longtable}\n\n");
	printf("\\author{\\texttt{Profile.c}}\n");
	CurrentTime = time(NULL);
	printf("\\date{%s}\n", asctime(localtime(&CurrentTime)));
	printf("\\title{Profiling Mondriaan %s with %d %s}\n\n", MONDRIAANVERSION, NumMatrices, NumMatrices > 1 ? "matrices" : "matrix");
	printf("\\begin{document}\n\n");
	
	printf("\\maketitle\n\n");
	
	printf("\\section{Results}\n\n");
	printf("Used Mondriaan version %s to distribute %d matrices (listed in table \\ref{MondriaanMatrices}) over %d processors with maximum imbalance %f, taking the average of %d samples. The used options can be found in table \\ref{MondriaanSettings} en the numerical results in table \\ref{MondriaanResults}.\n", MONDRIAANVERSION, NumMatrices, Options.P, Options.eps, NumSamples);
	printf("This took %.1f minutes in total.\n\n", (double)(clock() - TotalClock)/(60.0*(double)CLOCKS_PER_SEC));
	
	/* Export options. */
	printf("\\begin{table}\n");
	printf("\\caption{Mondriaan configuration.}\n");
	printf("\\label{MondriaanSettings}\n");
	printf("\\begin{center}\n");
	
	if (!ExportOptionsToLaTeX(stdout, &Options)) {
		fprintf(stderr, "main(): Unable to create option table!\n");
		exit(EXIT_FAILURE);
	}
	
	printf("\\end{center}\n");
	printf("\\end{table}\n\n");
	
	/* Export list of test matrices. */
	printf("\\begin{table}\n");
	printf("\\caption{%d tested matrices.}\n", NumMatrices);
	printf("\\label{MondriaanMatrices}\n");
	printf("\\begin{center}\n");
	printf("\\begin{tabular}{l|lll}\nFile & $\\mathit{nz}$ & $m$ & $n$ \\\\\n\\hline\n");
	
	for (i = 0; i < NumMatrices*NumNumProcs; i += NumNumProcs) {
		printf("\\verb|%s| & %ld & %ld & %ld \\\\\n", Matrices[i].File, Matrices[i].NumNz, Matrices[i].Rows, Matrices[i].Cols);
	}
	
	printf("\\hline\n");
	
	printf("\\end{tabular}\n");
	printf("\\end{center}\n");
	printf("\\end{table}\n\n");
	
	/* Export test data. */
	printf("\\begin{landscape}\n");
	printf("\\begin{longtable}{lrrrrr}");
	printf("\\caption[Profile results]{Profile results for %d matrices.}\n", NumMatrices);
	printf("\\label{MondriaanResults} \\\\\n\n");
	
	printf("\\multicolumn{1}{c}{File} & \\multicolumn{1}{c}{$p$} & \\multicolumn{1}{c}{Time (s)} & \\multicolumn{1}{c}{$\\varepsilon$} & \\multicolumn{1}{c}{Max. com.} & \\multicolumn{1}{c}{Com. vol.} \\\\ \\hline\n");
	printf("\\endfirsthead\n\n");
	
	printf("\\multicolumn{6}{c}{\\tablename\\ \\thetable{} -- continued from previous page.} \\\\\n");
	printf("\\multicolumn{1}{c}{File} & \\multicolumn{1}{c}{$p$} & \\multicolumn{1}{c}{Time (s)} & \\multicolumn{1}{c}{$\\varepsilon$} & \\multicolumn{1}{c}{Max. com.} & \\multicolumn{1}{c}{Com. vol.} \\\\ \\hline\n");
	printf("\\endhead\n\n");
	
	printf("\\multicolumn{6}{c}{Continued on next page.} \\\\\n");
	printf("\\endfoot\n\n");
	
	printf("\\hline\n\\endlastfoot\n\n");
	
	for (i = 0; i < NumMatrices*NumNumProcs; i += NumNumProcs) {
		int j;
		
		for (j = 0; j < NumNumProcs; ++j) {
			char Tmp[256];
			const struct sMatrixData *Mat = &Matrices[i + j];
			
			if (j == 0) printf("\\verb|%s| & %ld", Mat->File, Mat->P);
			else printf(" & %ld", Mat->P);
			
			/*
			int k;
			for (k = 0; k < NUM_ATTRIBUTES; ++k) {
				char Tmp[256];
				
				DoubleToLaTeX(Tmp, Mat->Attributes[k].Average, 3);
				printf(" & $%s \\pm ", Tmp);
				DoubleToLaTeX(Tmp, sqrt(Mat->Attributes[k].Variance), 1);
				printf("%s$", Tmp);
			}
			*/
			
			DoubleToLaTeX(Tmp, Mat->Attributes[0].Average, 3);
			printf(" & $%s \\pm ", Tmp);
			DoubleToLaTeX(Tmp, sqrt(Mat->Attributes[0].Variance), 1);
			printf("%s$", Tmp);
			
			DoubleToLaTeX(Tmp, Mat->Attributes[1].Average, 3);
			printf(" & $%s$", Tmp);
			
			printf(" & $%ld \\pm %ld$", (long)Mat->Attributes[2].Average, (long)sqrt(Mat->Attributes[2].Variance));
			printf(" & $%ld \\pm %ld$", (long)Mat->Attributes[3].Average, (long)sqrt(Mat->Attributes[3].Variance));
			
			printf(" \\\\\n");
		}
		printf("\\hline\n");
	}
	
	printf("\n\\end{longtable}\n");
	printf("\\end{landscape}\n\n");
	
	printf("\\end{document}\n\n");
	
	/* Append raw data. */
	printf("Raw data:\n");
	
	for (i = 0; i < NumMatrices*NumNumProcs; ++i) {
		int j;
		
		printf("%s\t%ld\t%ld\t%ld\t%ld\t", Matrices[i].File, Matrices[i].NumNz, Matrices[i].Rows, Matrices[i].Cols, Matrices[i].P);
		
		for (j = 0; j < NUM_ATTRIBUTES - 1; ++j) printf("%e\t%e\t", Matrices[i].Attributes[j].Average, sqrt(Matrices[i].Attributes[j].Variance));
		printf("%e\t%e\n", Matrices[i].Attributes[j].Average, sqrt(Matrices[i].Attributes[j].Variance));
	}
	printf("\n");
	
	free(Matrices);

	fprintf(stderr, "Done!\n");
	
	exit(EXIT_SUCCESS);
}
Beispiel #27
0
/// @brief Atomistic output function
///
/// @details Outputs formatted data snapshot for visualisation
///
///   //------------------------------------------------------
///   // Atomistic coordinate configuration file for vampire
///   //------------------------------------------------------
///   // Date: xx/xx/xxxx xx.xx.xx
///   //------------------------------------------------------
///   Number of atoms: $n_spins
///   //------------------------------------------------------
///   Number of atom files: $n_files
///   atoms-coords-00CPU0.cfg
///   atoms-coords-00CPU1.cfg
///   atoms-coords-00CPU2.cfg
///   //------------------------------------------------------
///   Number of local atoms: $n_loc_atoms
///   $material $category $x $y $z $species
///   $material $category $x $y $z $species
///   $material $category $x ...
///
/// @section License
/// Use of this code, either in source or compiled form, is subject to license from the authors.
/// Copyright \htmlonly &copy \endhtmlonly Richard Evans, 2009-2011. All Rights Reserved.
///
/// @section Information
/// @author  Richard Evans, [email protected]
/// @version 1.0
/// @date    31/05/2011
///
/// @internal
///   Created: 31/05/2011
///   Revision:   ---
///=====================================================================================
///
double legacy_atoms_coords()
{

   // instantiate timer
   vutil::vtimer_t timer;

   // check calling of routine if error checking is activated
   if (err::check == true)
   {
      std::cout << "config::atoms_coords has been called" << std::endl;
   }

   // Set local output filename
   std::stringstream file_sstr;
   file_sstr << "atoms-coords";
   // Set CPUID on non-root process
   if (vmpi::my_rank != 0)
   {
      file_sstr << "-" << std::setfill('0') << std::setw(5) << vmpi::my_rank;
   }
   file_sstr << ".cfg";
   std::string cfg_file = file_sstr.str();
   const char *cfg_filec = cfg_file.c_str();

   // Declare and open output file
   std::ofstream cfg_file_ofstr;
   cfg_file_ofstr.open(cfg_filec);

   // start timer
   timer.start();

   // Output masterfile header on root process
   if (vmpi::my_rank == 0)
   {
      // Get system date
      time_t rawtime = time(NULL);
      struct tm *timeinfo = localtime(&rawtime);

      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Atomistic coordinates configuration file for vampire" << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Date: " << asctime(timeinfo);
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "Number of atoms: " << config::internal::total_output_atoms << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "Number of spin files: " << vmpi::num_processors - 1 << std::endl;
      for (int p = 1; p < vmpi::num_processors; p++)
      {
         std::stringstream cfg_sstr;
         cfg_sstr << "atoms-coords-" << std::setfill('0') << std::setw(5) << p << ".cfg";
         cfg_file_ofstr << cfg_sstr.str() << std::endl;
      }
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
   }

   // Everyone now outputs their atom list
   cfg_file_ofstr << local_output_atom_list.size() << std::endl;
   for (int i = 0; i < local_output_atom_list.size(); i++)
   {
      const int atom = local_output_atom_list[i];
      cfg_file_ofstr << atoms::type_array[atom] << "\t" << atoms::category_array[atom] << "\t" << atoms::x_coord_array[atom] << "\t" << atoms::y_coord_array[atom] << "\t" << atoms::z_coord_array[atom] << "\t";
      if (config::internal::identify_surface_atoms == true && atoms::surface_array[atom] == true)
         cfg_file_ofstr << "O " << std::endl;
      else
         cfg_file_ofstr << mp::material[atoms::type_array[atom]].element << std::endl;
   }

   // stop the timer
   timer.stop();

   cfg_file_ofstr.close();

   double io_time = timer.elapsed_time(); // seconds

   #ifdef MPICF
      // find maximum time for i/o
      double max_io_time = 0.0;
      // calculate actual bandwidth on root process
      MPI_Reduce(&io_time, &max_io_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
      io_time = max_io_time;
   #endif

   return io_time;

}
Beispiel #28
0
int
main (int argc, char **argv)
{
  logical labels_saved, printing, header, first, last_was_blank_line;
  time_t ltoday;
  struct tm *tm;
  char *labels, *p, *today;
  struct linebuffer data;

#ifdef MSDOS
  _fmode = O_BINARY;		/* all of files are treated as binary files */
#if __DJGPP__ > 1
  if (!isatty (fileno (stdout)))
    setmode (fileno (stdout), O_BINARY);
  if (!isatty (fileno (stdin)))
    setmode (fileno (stdin), O_BINARY);
#else /* not __DJGPP__ > 1 */
  (stdout)->_flag &= ~_IOTEXT;
  (stdin)->_flag &= ~_IOTEXT;
#endif /* not __DJGPP__ > 1 */
#endif
  progname = argv[0];

  while (1)
    {
      int opt = getopt_long (argc, argv, "hV", longopts, 0);
      if (opt == EOF)
	break;

      switch (opt)
	{
	case 'V':
	  printf ("%s (GNU Emacs %s)\n", "b2m", VERSION);
	  puts ("b2m is in the public domain.");
	  exit (EXIT_SUCCESS);

	case 'h':
	  fprintf (stderr, "Usage: %s <babylmailbox >unixmailbox\n", progname);
	  exit (EXIT_SUCCESS);
	}
    }

  if (optind != argc)
    {
      fprintf (stderr, "Usage: %s <babylmailbox >unixmailbox\n", progname);
      exit (EXIT_SUCCESS);
    }

  labels_saved = printing = header = last_was_blank_line = FALSE;
  first = TRUE;
  ltoday = time (0);
  /* Convert to a string, checking for out-of-range time stamps.
     Don't use 'ctime', as that might dump core if the hardware clock
     is set to a bizarre value.  */
  tm = localtime (&ltoday);
  if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year)
	 && (today = asctime (tm))))
    fatal ("current time is out of range");
  data.size = 200;
  data.buffer = xnew (200, char);

  if (readline (&data, stdin) == 0
      || !strneq (data.buffer, "BABYL OPTIONS:", 14))
    fatal ("standard input is not a Babyl mailfile.");

  while (readline (&data, stdin) > 0)
    {
      if (streq (data.buffer, "*** EOOH ***") && !printing)
	{
	  printing = header = TRUE;
	  printf ("From \"Babyl to mail by %s\" %s", progname, today);
	  continue;
	}

      if (data.buffer[0] == '\037')
	{
	  if (data.buffer[1] == '\0')
	    continue;
	  else if (data.buffer[1] == '\f')
	    {
	      if (first)
		first = FALSE;
	      else if (! last_was_blank_line)
		puts("");
	      /* Save labels. */
	      readline (&data, stdin);
	      p = strtok (data.buffer, " ,\r\n\t");
	      labels = "X-Babyl-Labels: ";

	      while ((p = strtok (NULL, " ,\r\n\t")))
		labels = concat (labels, p, ", ");

	      p = &labels[strlen (labels) - 2];
	      if (*p == ',')
		*p = '\0';
	      printing = header = FALSE;
	      labels_saved = TRUE;
	      continue;
	    }
	}

      if ((data.buffer[0] == '\0') && header)
	{
	  header = FALSE;
	  if (labels_saved)
	    puts (labels);
	}

      if (printing)
	{
	  puts (data.buffer);
	  if (data.buffer[0] == '\0')
	    last_was_blank_line = TRUE;
	  else
	    last_was_blank_line = FALSE;
	}
    }

  return EXIT_SUCCESS;
}
Beispiel #29
0
/// @brief Cells output function
///
/// @details Outputs formatted data snapshot for visualisation
///
///   //------------------------------------------------------
///   // Atomistic coordinate configuration file for vampire
///   //------------------------------------------------------
///   // Date: xx/xx/xxxx xx.xx.xx
///   //------------------------------------------------------
///   Number of cells: $n_cells
///   //------------------------------------------------------
///   Number of atom files: $n_files
///   atoms-coords-00CPU0.cfg
///   atoms-coords-00CPU1.cfg
///   atoms-coords-00CPU2.cfg
///   //------------------------------------------------------
///   Number of local cells: $n_loc_cells
///   $material $category $x $y $z $species
///   $material $category $x $y $z $species
///   $material $category $x ...
///
/// @section License
/// Use of this code, either in source or compiled form, is subject to license from the authors.
/// Copyright \htmlonly &copy \endhtmlonly Richard Evans, 2009-2011. All Rights Reserved.
///
/// @section Information
/// @author  Richard Evans, [email protected]
/// @version 1.0
/// @date    31/05/2011
///
/// @internal
///   Created:    31/05/2011
///   Revision:     ---
///=====================================================================================
///
void legacy_cells_coords()
{

   // wait for all processes
   vmpi::barrier();

   // instantiate timer
   vutil::vtimer_t timer;

   // Set local output filename
   std::stringstream file_sstr;
   file_sstr << "cells-coords";
   file_sstr << ".cfg";
   std::string cfg_file = file_sstr.str();
   const char *cfg_filec = cfg_file.c_str();

   // start timer
   timer.start();

   // Output masterfile header on root process
   if (vmpi::my_rank == 0)
   {

      zlog << zTs() << "Outputting cell coordinates to disk" << std::flush;

      // Declare and open output file
      std::ofstream cfg_file_ofstr;
      cfg_file_ofstr.open(cfg_filec);

      // Get system date
      time_t rawtime = time(NULL);
      struct tm *timeinfo = localtime(&rawtime);

      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Cell coordinates configuration file for vampire" << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Date: " << asctime(timeinfo);
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "# Number of cells: " << cells::num_cells << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;
      cfg_file_ofstr << "#" << std::endl;
      cfg_file_ofstr << "#" << std::endl;
      cfg_file_ofstr << "#" << std::endl;
      cfg_file_ofstr << "#" << std::endl;
      cfg_file_ofstr << "#" << std::endl;
      cfg_file_ofstr << "#------------------------------------------------------" << std::endl;

      config::internal::total_output_cells = 0;

      for (int cell = 0; cell < cells::num_cells; cell++){
         if (cells::num_atoms_in_cell_global[cell] > 0){
            cfg_file_ofstr << cell << "\t" << cells::num_atoms_in_cell_global[cell] << "\t" << cells::pos_and_mom_array[4 * cell + 0] << "\t" << cells::pos_and_mom_array[4 * cell + 1] << "\t" << cells::pos_and_mom_array[4 * cell + 2] << std::endl;
            config::internal::total_output_cells++;
         }
      }
      cfg_file_ofstr.close();
   }

   // stop the timer
   timer.stop();

   const double data_size = double(config::internal::total_output_cells) * 2.0 * sizeof(int) * 3.0 * sizeof(double);
   const double io_time = timer.elapsed_time();

   zlog << " of size " << data_size*1.0e-6 << " MB [ " << data_size*1.0e-9/timer.elapsed_time() << " GB/s in " << io_time << " s ]" << std::endl;

   // wait for all processes
   vmpi::barrier();

   return;
}
Beispiel #30
0
int main(int argc, char *argv[]){
  
  long int arg1;         /*arg1 is used for the ticks*/ 
  char * endptr;         /*errorchecking*/
  struct timeval tv;     /*holds the value of current time*/
  struct tm time;        /*struct that holds the time*/
  struct tm *timePtr;    /*utilized to get the current time*/
  int errorChecking=0;   /*determines if there is an error*/
  int parseReturn;       /*what parsing returns*/
  int numOfTicks=0;      /*num of ticks specified*/
  int counter=0;         /*counter for ticks*/
  unsigned char clock[CLOCKSIZE];     /*size of the clock*/
  
  /*error check for when there is too many args*/
  if(argc > MAX_ARGS){
    usage(argv[0]);
    exit(EXIT_FAILURE);
  }
  
  /*error check for when the argument is more than or equal to two*/
  if(argc>=2){
    /*if the user inputs --help pring the usage info*/
    if(strcmp(argv[1],STR_HELP)==0){
      usage(argv[0]);
      exit(EXIT_SUCCESS);
    }
    else{
      /*get the number of ticks from argv[1] and set it to numofTicks*/
      arg1 = strtol(argv[1],&endptr,BASE);
      numOfTicks=arg1;
      /*if tick cannot be converted*/
      if(errno!=0){
        (void)fprintf(stderr,STR_ERR_TICK_VALUE);
        errorChecking=1;
      
      }
      /*if tick is not an integer*/
      else if(*endptr!=NULL){
        (void)fprintf(stderr,STR_ERR_TICK_VALUE);
        errorChecking=1;
       
      }
      /*if it is not within the specified range*/
      if(checkRange(arg1,MIN_TICKS,MAX_TICKS)==0){
        (void)fprintf(stderr,STR_ERR_TICK_RANGE,MIN_TICKS,MAX_TICKS);
        errorChecking=1;
      }
    }
  }

  /*if there is the right amount of arguments*/
  if(argc == 3){
    /*parses the argument*/
    parseReturn = parseStartTime(&time,argv[2]);
    /*makes sure the time format is right*/
    if(parseReturn & ERR_TIME_FORMAT){
      (void)fprintf(stderr,STR_ERR_TIME_FORMAT);
      errorChecking=1;
    }
    /*makes sure the hr value valid*/
    if(parseReturn & ERR_HR_VALUE){
      (void)fprintf(stderr,STR_ERR_HR_VALUE);
      errorChecking=1;
    }
    /*makes sure the hr value is in the valid range*/
    if(parseReturn & ERR_HR_RANGE){
      (void)fprintf(stderr,STR_ERR_HR_RANGE,MIN_HR,MAX_HR);
      errorChecking=1;
    }
    /*makes sure the min is valid*/
    if(parseReturn & ERR_MIN_VALUE){
      (void)fprintf(stderr,STR_ERR_MIN_VALUE);
      errorChecking=1;
    }
    /*makes sure the min value is valid*/
    if(parseReturn & ERR_MIN_RANGE){
      (void)fprintf(stderr,STR_ERR_MIN_RANGE,MIN_MIN,MAX_MIN);
      errorChecking=1;
    }
    /*makes sure the sec value is valid*/
    if(parseReturn & ERR_SEC_VALUE){
      (void)fprintf(stderr,STR_ERR_SEC_VALUE);
      errorChecking=1;
    }
    /*makes sure the second range value is valid*/
    if(parseReturn & ERR_SEC_RANGE){
      (void)fprintf(stderr,STR_ERR_SEC_RANGE,MIN_SEC,MAX_SEC);
      errorChecking=1;
    }
  }
  
  /*if errors along the way print a usage message*/
  if(errorChecking){
    usage(argv[0]);
    exit(EXIT_FAILURE);
  }

  /*if there is only one argument get the current time and print it*/
  if(argc == 1){
    (void)pa2gettimeofday(&tv,NULL);
    timePtr=localtime(&tv.tv_sec);
    (void)printf(asctime(timePtr));
    (void)printf("\n");
    numOfTicks=DEF_TICKS;
  }
  
  /*if only the tick get that time of day and print it*/
  if(argc == 2){
    (void)pa2gettimeofday(&tv,NULL);
    timePtr=localtime(&tv.tv_sec);
    (void)printf(asctime(timePtr));
    (void)printf("\n");

  }
  
  /*increment the number of ticks*/
  numOfTicks++;
  /*if less than two arguments it is current time*/
  if(argc <= 2){
    setBCDClock(timePtr,clock);
  }
  /*user inputted time*/
  else{
    setBCDClock(&time,clock);
  }
  
  /*display the clock and update it given the number of ticks*/
  for(counter=0;counter<numOfTicks;counter++){
    displayBCDClock(clock);
    (void)printf("\n");
    updateBCDClock(clock);
  }
  return 0;
}