Пример #1
0
/*!
    \internal

    Generates a unique file path and returns a native handle to the open file.
    \a path is used as a template when generating unique paths, \a pos
    identifies the position of the first character that will be replaced in the
    template and \a length the number of characters that may be substituted.

    Returns an open handle to the newly created file if successful, an invalid
    handle otherwise. In both cases, the string in \a path will be changed and
    contain the generated path name.
*/
static bool createFileFromTemplate(NativeFileHandle &file,
                                   QFileSystemEntry::NativePath &path, size_t pos, size_t length,
                                   QSystemError &error)
{
    Q_ASSERT(length != 0);
    Q_ASSERT(pos < size_t(path.length()));
    Q_ASSERT(length <= size_t(path.length()) - pos);

    Char *const placeholderStart = (Char *)path.data() + pos;
    Char *const placeholderEnd = placeholderStart + length;

    // Initialize placeholder with random chars + PID.
    {
        Char *rIter = placeholderEnd;

#if defined(QT_BUILD_CORE_LIB)
        quint64 pid = quint64(QCoreApplication::applicationPid());
        do {
            *--rIter = Latin1Char((pid % 10) + '0');
            pid /= 10;
        } while (rIter != placeholderStart && pid != 0);
#endif

        while (rIter != placeholderStart) {
            char ch = char((qrand() & 0xffff) % (26 + 26));
            if (ch < 26)
                *--rIter = Latin1Char(ch + 'A');
            else
                *--rIter = Latin1Char(ch - 26 + 'a');
        }
    }

    for (;;) {
        // Atomically create file and obtain handle
#if defined(Q_OS_WIN)
        file = CreateFile((const wchar_t *)path.constData(),
                          GENERIC_READ | GENERIC_WRITE,
                          FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW,
                          FILE_ATTRIBUTE_NORMAL, NULL);

        if (file != INVALID_HANDLE_VALUE)
            return true;

        DWORD err = GetLastError();
        if (err == ERROR_ACCESS_DENIED) {
            DWORD attributes = GetFileAttributes((const wchar_t *)path.constData());
            if (attributes == INVALID_FILE_ATTRIBUTES) {
                // Potential write error (read-only parent directory, etc.).
                error = QSystemError(err, QSystemError::NativeError);
                return false;
            } // else file already exists as a directory.
        } else if (err != ERROR_FILE_EXISTS) {
            error = QSystemError(err, QSystemError::NativeError);
            return false;
        }
#else // POSIX
        file = QT_OPEN(path.constData(),
                       QT_OPEN_CREAT | O_EXCL | QT_OPEN_RDWR | QT_OPEN_LARGEFILE,
                       0600);

        if (file != -1)
            return true;

        int err = errno;
        if (err != EEXIST) {
            error = QSystemError(err, QSystemError::NativeError);
            return false;
        }
#endif

        /* tricky little algorwwithm for backward compatibility */
        for (Char *iter = placeholderStart;;) {
            // Character progression: [0-9] => 'a' ... 'z' => 'A' .. 'Z'
            // String progression: "ZZaiC" => "aabiC"
            switch (char(*iter)) {
            case 'Z':
                // Rollover, advance next character
                *iter = Latin1Char('a');
                if (++iter == placeholderEnd) {
                    // Out of alternatives. Return file exists error, previously set.
                    error = QSystemError(err, QSystemError::NativeError);
                    return false;
                }

                continue;

            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                *iter = Latin1Char('a');
                break;

            case 'z':
                // increment 'z' to 'A'
                *iter = Latin1Char('A');
                break;

            default:
                ++*iter;
                break;
            }
            break;
        }
    }

    Q_ASSERT(false);
}
Пример #2
0
void Fixup<Bios>(Bios& p)
{
	p.size = size_t(p.encodedSize+1) * 64*KiB;
}
Пример #3
0
/** Adds an asynchronous request to the event log. */
void asynclog_delete(proxy_t* proxy,
                     const AccessPoint& ap,
                     folly::StringPiece key,
                     folly::StringPiece poolName) {
  dynamic json = {};
  const auto& host = ap.getHost();
  const auto& port = proxy->router().opts().asynclog_port_override == 0
    ? ap.getPort()
    : proxy->router().opts().asynclog_port_override;

  if (proxy->router().opts().use_asynclog_version2) {
    json = dynamic::object;
    json["f"] = proxy->router().opts().flavor_name;
    json["h"] = folly::sformat("[{}]:{}", host, port);
    json["p"] = poolName.str();
    json["k"] = key.str();
  } else {
    /* ["host", port, escaped_command] */
    json.push_back(host);
    json.push_back(port);
    json.push_back(folly::sformat("delete {}\r\n", key));
  }

  auto fd = asynclog_open(proxy);
  if (!fd) {
    MC_LOG_FAILURE(proxy->router().opts(),
                   memcache::failure::Category::kSystemError,
                   "asynclog_open() failed (key {}, pool {})",
                   key, poolName);
    return;
  }

  // ["AS1.0", 1289416829.836, "C", ["10.0.0.1", 11302, "delete foo\r\n"]]
  // OR ["AS2.0", 1289416829.836, "C", {"f":"flavor","h":"[10.0.0.1]:11302",
  //                                    "p":"pool_name","k":"foo\r\n"}]
  dynamic jsonOut = {};
  if (proxy->router().opts().use_asynclog_version2) {
    jsonOut.push_back(ASYNCLOG_MAGIC2);
  } else {
    jsonOut.push_back(ASYNCLOG_MAGIC);
  }

  struct timeval timestamp;
  CHECK(gettimeofday(&timestamp, nullptr) == 0);

  auto timestamp_ms =
    facebook::memcache::to<std::chrono::milliseconds>(timestamp).count();

  jsonOut.push_back(1e-3 * timestamp_ms);
  jsonOut.push_back(std::string("C"));

  jsonOut.push_back(json);

  auto jstr = folly::toJson(jsonOut) + "\n";

  ssize_t size = folly::writeFull(fd->fd(), jstr.data(), jstr.size());
  if (size == -1 || size_t(size) < jstr.size()) {
    MC_LOG_FAILURE(proxy->router().opts(),
                   memcache::failure::Category::kSystemError,
                   "Error fully writing asynclog request (key {}, pool {})",
                   key, poolName);
  }
}
Пример #4
0
ndsize_t BaseTagHDF5::featureCount() const {
    boost::optional<H5Group> g = feature_group(false);
    return g ? g->objectCount() : size_t(0);
}
Пример #5
0
 bool very_busy() const { return jobs_in_queue() > size_t(4 * m_size); }
Пример #6
0
int WorldSocket::handle_input_missing_data(void)
{
    char buf [4096];

    ACE_Data_Block db(sizeof(buf),
                      ACE_Message_Block::MB_DATA,
                      buf,
                      0,
                      0,
                      ACE_Message_Block::DONT_DELETE,
                      0);

    ACE_Message_Block message_block(&db,
                                    ACE_Message_Block::DONT_DELETE,
                                    0);

    const size_t recv_size = message_block.space();

    const ssize_t n = peer().recv(message_block.wr_ptr(),
                                  recv_size);

    if (n <= 0)
        return (int)n;

    message_block.wr_ptr(n);

    while (message_block.length() > 0)
    {
        if (m_Header.space() > 0)
        {
            // need to receive the header
            const size_t to_header = (message_block.length() > m_Header.space() ? m_Header.space() : message_block.length());
            m_Header.copy(message_block.rd_ptr(), to_header);
            message_block.rd_ptr(to_header);

            if (m_Header.space() > 0)
            {
                // Couldn't receive the whole header this time.
                MANGOS_ASSERT(message_block.length() == 0);
                errno = EWOULDBLOCK;
                return -1;
            }

            // We just received nice new header
            if (handle_input_header() == -1)
            {
                MANGOS_ASSERT((errno != EWOULDBLOCK) && (errno != EAGAIN));
                return -1;
            }
        }

        // Its possible on some error situations that this happens
        // for example on closing when epoll receives more chunked data and stuff
        // hope this is not hack ,as proper m_RecvWPct is asserted around
        if (!m_RecvWPct)
        {
            sLog.outError("Forcing close on input m_RecvWPct = NULL");
            errno = EINVAL;
            return -1;
        }

        // We have full read header, now check the data payload
        if (m_RecvPct.space() > 0)
        {
            // need more data in the payload
            const size_t to_data = (message_block.length() > m_RecvPct.space() ? m_RecvPct.space() : message_block.length());
            m_RecvPct.copy(message_block.rd_ptr(), to_data);
            message_block.rd_ptr(to_data);

            if (m_RecvPct.space() > 0)
            {
                // Couldn't receive the whole data this time.
                MANGOS_ASSERT(message_block.length() == 0);
                errno = EWOULDBLOCK;
                return -1;
            }
        }

        // just received fresh new payload
        if (handle_input_payload() == -1)
        {
            MANGOS_ASSERT((errno != EWOULDBLOCK) && (errno != EAGAIN));
            return -1;
        }
    }

    return size_t(n) == recv_size ? 1 : 2;
}
Пример #7
0
template<typename samp_type> void recv_to_file(
    uhd::usrp::multi_usrp::sptr usrp,
    const std::string &cpu_format,
    const std::string &wire_format,
    const std::string &channel,
    const std::string &file,
    size_t samps_per_buff,
    unsigned long long num_requested_samples,
    double time_requested = 0.0,
    bool bw_summary = false,
    bool stats = false,
    bool null = false,
    bool enable_size_map = false,
    bool continue_on_bad_packet = false
){
    unsigned long long num_total_samps = 0;
    //create a receive streamer
    uhd::stream_args_t stream_args(cpu_format,wire_format);
    std::vector<size_t> channel_nums;
    channel_nums.push_back(boost::lexical_cast<size_t>(channel));
    stream_args.channels = channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile;
    if (not null)
        outfile.open(file.c_str(), std::ofstream::binary);
    bool overflow_message = true;

    //setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)?
        uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
        uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
    );
    stream_cmd.num_samps = size_t(num_requested_samples);
    stream_cmd.stream_now = true;
    stream_cmd.time_spec = uhd::time_spec_t();
    rx_stream->issue_stream_cmd(stream_cmd);

    boost::system_time start = boost::get_system_time();
    unsigned long long ticks_requested = (long)(time_requested * (double)boost::posix_time::time_duration::ticks_per_second());
    boost::posix_time::time_duration ticks_diff;
    boost::system_time last_update = start;
    unsigned long long last_update_samps = 0;

    typedef std::map<size_t,size_t> SizeMap;
    SizeMap mapSizes;

    while(not stop_signal_called and (num_requested_samples != num_total_samps or num_requested_samples == 0)) {
        boost::system_time now = boost::get_system_time();

        size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, 3.0, enable_size_map);

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW){
            if (overflow_message) {
                overflow_message = false;
                std::cerr << boost::format(
                    "Got an overflow indication. Please consider the following:\n"
                    "  Your write medium must sustain a rate of %fMB/s.\n"
                    "  Dropped samples will not be written to the file.\n"
                    "  Please modify this example for your purposes.\n"
                    "  This message will not appear again.\n"
                ) % (usrp->get_rx_rate()*sizeof(samp_type)/1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
            std::string error = str(boost::format("Receiver error: %s") % md.strerror());
            if (continue_on_bad_packet){
                std::cerr << error << std::endl;
                continue;
            }
            else
                throw std::runtime_error(error);
        }

        if (enable_size_map) {
            SizeMap::iterator it = mapSizes.find(num_rx_samps);
            if (it == mapSizes.end())
                mapSizes[num_rx_samps] = 0;
            mapSizes[num_rx_samps] += 1;
        }

        num_total_samps += num_rx_samps;

        if (outfile.is_open())
            outfile.write((const char*)&buff.front(), num_rx_samps*sizeof(samp_type));

        if (bw_summary) {
            last_update_samps += num_rx_samps;
            boost::posix_time::time_duration update_diff = now - last_update;
            if (update_diff.ticks() > boost::posix_time::time_duration::ticks_per_second()) {
                double t = (double)update_diff.ticks() / (double)boost::posix_time::time_duration::ticks_per_second();
                double r = (double)last_update_samps / t;
                std::cout << boost::format("\t%f Msps") % (r/1e6) << std::endl;
                last_update_samps = 0;
                last_update = now;
            }
        }

        ticks_diff = now - start;
        if (ticks_requested > 0){
            if ((unsigned long long)ticks_diff.ticks() > ticks_requested)
                break;
        }
    }

    stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
    rx_stream->issue_stream_cmd(stream_cmd);

    if (outfile.is_open())
        outfile.close();

    if (stats) {
        std::cout << std::endl;

        double t = (double)ticks_diff.ticks() / (double)boost::posix_time::time_duration::ticks_per_second();
        std::cout << boost::format("Received %d samples in %f seconds") % num_total_samps % t << std::endl;
        double r = (double)num_total_samps / t;
        std::cout << boost::format("%f Msps") % (r/1e6) << std::endl;

        if (enable_size_map) {
            std::cout << std::endl;
            std::cout << "Packet size map (bytes: count)" << std::endl;
            for (SizeMap::iterator it = mapSizes.begin(); it != mapSizes.end(); it++)
                std::cout << it->first << ":\t" << it->second << std::endl;
        }
    }
}
Пример #8
0
/// Only _static_ data send in this packet !!!
void WorldSession::HandleCreatureQueryOpcode( WorldPacket & recv_data )
{
    uint32 entry;
    recv_data >> entry;
    uint64 guid;
    recv_data >> guid;

    CreatureInfo const *ci = ObjectMgr::GetCreatureTemplate(entry);
    if (ci)
    {
        std::string Name, SubName;
        Name = ci->Name;
        SubName = ci->SubName;

        int loc_idx = GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
        {
            CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(entry);
            if (cl)
            {
                if (cl->Name.size() > size_t(loc_idx) && !cl->Name[loc_idx].empty())
                    Name = cl->Name[loc_idx];
                if (cl->SubName.size() > size_t(loc_idx) && !cl->SubName[loc_idx].empty())
                    SubName = cl->SubName[loc_idx];
            }
        }
        DETAIL_LOG("WORLD: CMSG_CREATURE_QUERY '%s' - Entry: %u.", ci->Name, entry);
                                                            // guess size
        WorldPacket data( SMSG_CREATURE_QUERY_RESPONSE, 100 );
        data << uint32(entry);                              // creature entry
        data << Name;
        data << uint8(0) << uint8(0) << uint8(0);           // name2, name3, name4, always empty
        data << SubName;
        data << ci->IconName;                               // "Directions" for guard, string for Icons 2.3.0
        data << uint32(ci->type_flags);                     // flags
        data << uint32(ci->type);                           // CreatureType.dbc
        data << uint32(ci->family);                         // CreatureFamily.dbc
        data << uint32(ci->rank);                           // Creature Rank (elite, boss, etc)
        data << uint32(ci->KillCredit[0]);                  // new in 3.1, kill credit
        data << uint32(ci->KillCredit[1]);                  // new in 3.1, kill credit

        for(int i = 0; i < MAX_CREATURE_MODEL; ++i)
            data << uint32(ci->ModelId[i]);

        data << float(ci->unk16);                           // health modifier
        data << float(ci->unk17);                           // power modifier
        data << uint8(ci->RacialLeader);
        for(uint32 i = 0; i < 6; ++i)
            data << uint32(ci->questItems[i]);              // itemId[6], quest drop
        data << uint32(ci->movementId);                     // CreatureMovementInfo.dbc
        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent SMSG_CREATURE_QUERY_RESPONSE" );
    }
    else
    {
        DEBUG_LOG("WORLD: CMSG_CREATURE_QUERY - NO CREATURE INFO! (GUID: %u, ENTRY: %u)",
            GUID_LOPART(guid), entry);
        WorldPacket data( SMSG_CREATURE_QUERY_RESPONSE, 4 );
        data << uint32(entry | 0x80000000);
        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent SMSG_CREATURE_QUERY_RESPONSE" );
    }
}
Пример #9
0
void WorldSession::HandleNpcTextQueryOpcode( WorldPacket & recv_data )
{
    uint32 textID;
    uint64 guid;

    recv_data >> textID;
    DETAIL_LOG("WORLD: CMSG_NPC_TEXT_QUERY ID '%u'", textID);

    recv_data >> guid;
    _player->SetTargetGUID(guid);

    GossipText const* pGossip = sObjectMgr.GetGossipText(textID);

    WorldPacket data( SMSG_NPC_TEXT_UPDATE, 100 );          // guess size
    data << textID;

    if (!pGossip)
    {
        for(uint32 i = 0; i < 8; ++i)
        {
            data << float(0);
            data << "Greetings $N";
            data << "Greetings $N";
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
        }
    }
    else
    {
        std::string Text_0[8], Text_1[8];
        for (int i = 0; i < 8; ++i)
        {
            Text_0[i]=pGossip->Options[i].Text_0;
            Text_1[i]=pGossip->Options[i].Text_1;
        }

        int loc_idx = GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
        {
            NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textID);
            if (nl)
            {
                for (int i = 0; i < 8; ++i)
                {
                    if (nl->Text_0[i].size() > size_t(loc_idx) && !nl->Text_0[i][loc_idx].empty())
                        Text_0[i]=nl->Text_0[i][loc_idx];
                    if (nl->Text_1[i].size() > size_t(loc_idx) && !nl->Text_1[i][loc_idx].empty())
                        Text_1[i]=nl->Text_1[i][loc_idx];
                }
            }
        }

        for (int i = 0; i < 8; ++i)
        {
            data << pGossip->Options[i].Probability;

            if ( Text_0[i].empty() )
                data << Text_1[i];
            else
                data << Text_0[i];

            if ( Text_1[i].empty() )
                data << Text_0[i];
            else
                data << Text_1[i];

            data << pGossip->Options[i].Language;

            for(int j = 0; j < 3; ++j)
            {
                data << pGossip->Options[i].Emotes[j]._Delay;
                data << pGossip->Options[i].Emotes[j]._Emote;
            }
        }
    }

    SendPacket( &data );

    DEBUG_LOG( "WORLD: Sent SMSG_NPC_TEXT_UPDATE" );
}
Пример #10
0
BEGIN_NCBI_SCOPE

///////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(Test_Procedure)
{
    try {
        // Test a regular IStatement with "exec"
        // Parameters are not allowed with this construction.
        {
            unique_ptr<IStatement> auto_stmt( GetConnection().GetStatement() );

            // Execute it first time ...
            auto_stmt->SendSql( "exec sp_databases" );
            while( auto_stmt->HasMoreResults() ) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch ( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_ParamResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_StatusResult:
                        while( rs->Next() ) {
                            _TRACE("status: " << rs->GetVariant(1).GetInt4());
                        }
                        break;
                    case eDB_ComputeResult:
                    case eDB_CursorResult:
                        break;
                    }
                }
            }

            // Execute it second time ...
            auto_stmt->SendSql( "exec sp_databases" );
            while( auto_stmt->HasMoreResults() ) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch ( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_ParamResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_StatusResult:
                        while( rs->Next() ) {
                            _TRACE("status: " << rs->GetVariant(1).GetInt4());
                        }
                        break;
                    case eDB_ComputeResult:
                    case eDB_CursorResult:
                        break;
                    }
                }
            }

            // Same as before but do not retrieve data ...
            auto_stmt->SendSql( "exec sp_databases" );
            auto_stmt->SendSql( "exec sp_databases" );
        }

        // Test ICallableStatement
        // No parameters at this time.
        {
            // Execute it first time ...
            unique_ptr<ICallableStatement> auto_stmt(
                GetConnection().GetCallableStatement("sp_databases")
                );
            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            auto_stmt->GetReturnStatus();


            // Execute it second time ...
            auto_stmt.reset( GetConnection().GetCallableStatement("sp_databases") );
            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            auto_stmt->GetReturnStatus();


            // Same as before but do not retrieve data ...
            auto_stmt.reset( GetConnection().GetCallableStatement("sp_databases") );
            auto_stmt->Execute();
            auto_stmt.reset( GetConnection().GetCallableStatement("sp_databases") );
            auto_stmt->Execute();
        }

        // Temporary test ...
        // !!! This is a bug ...
        if (false) {
            unique_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "anyone",
                "allowed",
                "PUBSEQ_OS_LXA",
                ""
                );

            unique_ptr<ICallableStatement> auto_stmt(
                conn->GetCallableStatement("id_seqid4gi")
                );
            auto_stmt->SetParam( CVariant(1), "@gi" );
            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            _TRACE("status: " << auto_stmt->GetReturnStatus());
        }

        if (false) {
            const string query("[db_alias] is not null");

            unique_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "*****",
                "******",
                "MSSQL31",
                "AlignDb_Info"
                );

            unique_ptr<ICallableStatement> auto_stmt(
                conn->PrepareCall("[dbo].[FindAttributesEx]")
                );
            auto_stmt->SetParam( CVariant(1), "@userid" );
            auto_stmt->SetParam( CVariant("ALIGNDB"), "@application" );
            auto_stmt->SetParam( CVariant("AlignDbMasterInfo"), "@classname" );
            // LongChar doesn't work.
            // auto_stmt->SetParam( CVariant(new CDB_LongChar(query.length(), query)), "@query" );
            // auto_stmt->SetParam( CVariant::LongChar(query.data(), query.length()), "@query" );
            auto_stmt->SetParam( CVariant(query), "@query" );
            auto_stmt->SetParam( CVariant(1), "@max_results" );

            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            _TRACE("status: " << auto_stmt->GetReturnStatus());
        }


        // Test returned recordset ...
        {
            // In case of MS SQL 2005 sp_databases returns empty result set.
            // It is not a bug. It is a difference in setiings for MS SQL
            // 2005.
            if (GetArgs().GetServerType() != CDBConnParams::eMSSqlServer) {
                int num = 0;
                // Execute it first time ...
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_databases")
                    );

                auto_stmt->Execute();

                BOOST_CHECK(auto_stmt->HasMoreResults());
                BOOST_CHECK(auto_stmt->HasRows());
                unique_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                BOOST_CHECK(rs.get() != NULL);

                while (rs->Next()) {
                    BOOST_CHECK(rs->GetVariant(1).GetString().size() > 0);
                    BOOST_CHECK(rs->GetVariant(2).GetInt8() > 0);
                    BOOST_CHECK_EQUAL(rs->GetVariant(3).IsNull(), true);
                    ++num;
                }

                BOOST_CHECK(num > 0);

                DumpResults(auto_stmt.get());
            }

            {
                int num = 0;
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_server_info")
                    );

                auto_stmt->Execute();

                BOOST_CHECK(auto_stmt->HasMoreResults());
                BOOST_CHECK(auto_stmt->HasRows());
                unique_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                BOOST_CHECK(rs.get() != NULL);

                while (rs->Next()) {
                    BOOST_CHECK(rs->GetVariant(1).GetInt4() > 0);
                    BOOST_CHECK(rs->GetVariant(2).GetString().size() > 0);
                    BOOST_CHECK(rs->GetVariant(3).GetString().size() > 0);
                    ++num;
                }

                BOOST_CHECK(num > 0);

                DumpResults(auto_stmt.get());
            }
        }

        // Test ICallableStatement
        // With parameters.
        {
            {
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_server_info")
                    );

                // Set parameter to NULL ...
                auto_stmt->SetParam( CVariant(eDB_Int), "@attribute_id" );
                auto_stmt->Execute();

                if (GetArgs().GetServerType() == CDBConnParams::eSybaseSQLServer) {
                    BOOST_CHECK_EQUAL( size_t(30), GetNumOfRecords(auto_stmt) );
                } else {
                    BOOST_CHECK_EQUAL( size_t(29), GetNumOfRecords(auto_stmt) );
                }

                // Set parameter to 1 ...
                auto_stmt->SetParam( CVariant( Int4(1) ), "@attribute_id" );
                auto_stmt->Execute();

                BOOST_CHECK_EQUAL( size_t(1), GetNumOfRecords(auto_stmt) );
            }

            // NULL value with CVariant ...
            {
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_statistics")
                    );

                auto_stmt->SetParam(CVariant((const char*) NULL), "@table_name");
                auto_stmt->Execute();
                DumpResults(auto_stmt.get());
            }

            // Doesn't work for some reason ...
            if (false) {
                // Execute it first time ...
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_statistics")
                    );

                auto_stmt->SetParam(CVariant(GetTableName()), "@table_name");
                auto_stmt->Execute();

                {
                    BOOST_CHECK(auto_stmt->HasMoreResults());
                    BOOST_CHECK(auto_stmt->HasRows());
                    unique_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                    BOOST_CHECK(rs.get() != NULL);

                    BOOST_CHECK(rs->Next());
                    DumpResults(auto_stmt.get());
                }

                // Execute it second time ...
                auto_stmt->SetParam(CVariant("#bulk_insert_table"), "@table_name");
                auto_stmt->Execute();

                {
                    BOOST_CHECK(auto_stmt->HasMoreResults());
                    BOOST_CHECK(auto_stmt->HasRows());
                    unique_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                    BOOST_CHECK(rs.get() != NULL);

                    BOOST_CHECK(rs->Next());
                    DumpResults(auto_stmt.get());
                }
            }

            if (false) {
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("DBAPI_Sample..TestBigIntProc")
                    );

                auto_stmt->SetParam(CVariant(Int8(1234567890)), "@num");
                auto_stmt->ExecuteUpdate();
            }
        }

        // Test output parameters ...
        if (false) {
            CRef<CDB_UserHandler_Diag> handler(new  CDB_UserHandler_Diag());
            I_DriverContext* drv_context = GetDS().GetDriverContext();

            drv_context->PushDefConnMsgHandler(handler);

            unique_ptr<ICallableStatement> auto_stmt(
                GetConnection().GetCallableStatement("DBAPI_Sample..SampleProc3")
                );
            auto_stmt->SetParam(CVariant(1), "@id");
            auto_stmt->SetParam(CVariant(2.0), "@f");
            auto_stmt->SetOutputParam(CVariant(eDB_Int), "@o");

            auto_stmt->Execute();
    //         auto_stmt->SendSql( "exec DBAPI_Sample..TestProc4 @test_out output" );

             while(auto_stmt->HasMoreResults()) {
                 if( auto_stmt->HasRows() ) {
                     unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                     switch( rs->GetResultType() ) {
                     case eDB_RowResult:
                         while(rs->Next()) {
                             // retrieve row results
                         }
                         break;
                     case eDB_ParamResult:
                         BOOST_CHECK(rs->Next());
                         NcbiCout << "Output param: "
                                  << rs->GetVariant(1).GetInt4()
                                  << endl;
                         break;
                     case eDB_ComputeResult:
                         break;
                     case eDB_StatusResult:
                         break;
                     case eDB_CursorResult:
                         break;
                     default:
                         break;
                     }
                 }
             }

    //         BOOST_CHECK(auto_stmt->HasMoreResults());
    //         BOOST_CHECK(auto_stmt->HasRows());
    //         unique_ptr<IResultSet> rs(auto_stmt->GetResultSet());
    //         BOOST_CHECK(rs.get() != NULL);
    //
    //         while (rs->Next()) {
    //             BOOST_CHECK(rs->GetVariant(1).GetString().size() > 0);
    //             BOOST_CHECK(rs->GetVariant(2).GetInt4() > 0);
    //             BOOST_CHECK_EQUAL(rs->GetVariant(3).IsNull(), true);
    //             ++num;
    //         }
    //
    //         BOOST_CHECK(num > 0);

            DumpResults(auto_stmt.get());

            drv_context->PopDefConnMsgHandler(handler);
        }

        // Temporary test ...
        if (false) {
            unique_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "anyone",
                "allowed",
                "",
                "GenomeHits"
                );

            unique_ptr<ICallableStatement> auto_stmt(
                conn->GetCallableStatement("NewSub")
                );
            auto_stmt->SetParam(CVariant("tsub2"), "@name");
            auto_stmt->SetParam(CVariant("tst"), "@center");
            auto_stmt->SetParam(CVariant("9606"), "@taxid");
            auto_stmt->SetParam(CVariant("H**o sapiens"), "@organism");
            auto_stmt->SetParam(CVariant(""), "@notes");
            auto_stmt->Execute();

            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }

            // Get status
            _TRACE("status: " << auto_stmt->GetReturnStatus());
        }

        // Temporary test ...
        if (false && GetArgs().GetServerType() != CDBConnParams::eSybaseSQLServer) {
            unique_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "pmcupdate",
                "*******",
                "PMC3QA",
                "PMC3QA"
                );

            unique_ptr<ICallableStatement> auto_stmt(
                conn->PrepareCall("id_new_id")
                );
            auto_stmt->SetParam(CVariant("tsub2"), "@IdName");

            auto_stmt->Execute();

            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    unique_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }

            // Get status
            _TRACE("status: " << auto_stmt->GetReturnStatus());
        }
    }
    catch(const CException& ex) {
        DBAPI_BOOST_FAIL(ex);
    }
}
Пример #11
0
 std::size_t operator()(const cast_key_t& k) const
 {
     return (size_t(k.first) << 32) | size_t(k.second);
 }
Пример #12
0
 void ResetAll() {
     assert(result_ != EOF);
     width_ = 0;
     prec_ = size_t(-1);
     flags_ = 0;
 }
Пример #13
0
 void FormatWithCurrentFlags(const LOKI_SAFEFORMAT_UNSIGNED_LONG i) {
     // look at the format character
     Char formatChar = *format_;
     bool isSigned = formatChar == _T('d') || formatChar == _T('i');
     if (formatChar == _T('p')) {
         formatChar = _T('x'); // pointers go to hex
         SetAlternateForm(); // printed with '0x' in front
         isSigned = true; // that's what gcc does
     }
     if (!JQ_STRCHR(_T("cdiuoxX"), formatChar)) {
         result_ = -1;
         return;
     }
     Char buf[
         sizeof(LOKI_SAFEFORMAT_UNSIGNED_LONG) * 3 // digits
         + 1 // sign or ' '
         + 2 // 0x or 0X
         + 1]; // terminating zero
     const Char *const bufEnd = buf + (sizeof(buf) / sizeof(Char));
     Char * bufLast = buf + (sizeof(buf) / sizeof(Char) - 1);
     Char signChar = 0;
     unsigned int base = 10;
     
     if (formatChar == _T('c')) {
         // Format only one character
         // The 'fill with zeros' flag is ignored
         ResetFillZeros();
         *bufLast = static_cast<char_type>(i);
     } else {
         // TODO: inefficient code, refactor
         const bool negative = isSigned && static_cast<LOKI_SAFEFORMAT_SIGNED_LONG>(i) < 0;
         if (formatChar == _T('o')) base = 8;
         else if (formatChar == _T('x') || formatChar == _T('X')) base = 16;
         bufLast = isSigned
             ? RenderWithoutSign(static_cast<LOKI_SAFEFORMAT_SIGNED_LONG>(i), bufLast, base,
                 formatChar == _T('X'))
             : RenderWithoutSign(i, bufLast, base, 
                 formatChar == _T('X'));
         // Add the sign
         if (isSigned) {
             negative ? signChar = _T('-')
             : ShowSignAlways() ? signChar = _T('+')
             : Blank() ? signChar = _T(' ')
             : 0;
         }
     }
     // precision 
     size_t 
         countDigits = bufEnd - bufLast,
         countZeros = prec_ != size_t(-1) && countDigits < prec_ && 
                 formatChar != _T('c')
             ? prec_ - countDigits 
             : 0,
         countBase = base != 10 && AlternateForm() && i != 0
             ? (base == 16 ? 2 : countZeros > 0 ? 0 : 1)
             : 0,
         countSign = (signChar != 0),
         totalPrintable = countDigits + countZeros + countBase + countSign;
     size_t countPadLeft = 0, countPadRight = 0;
     if (width_ > totalPrintable) {
         if (LeftJustify()) {
             countPadRight = width_ - totalPrintable;
             countPadLeft = 0;
         } else {
             countPadLeft = width_ - totalPrintable;
             countPadRight = 0;
         }
     }
     if (FillZeros() && prec_ == size_t(-1)) {
         // pad with zeros and no precision - transfer padding to precision
         countZeros = countPadLeft;
         countPadLeft = 0;
     }
     // ok, all computed, ready to print to device
     Fill(' ', countPadLeft);
     if (signChar != 0) Write(&signChar, &signChar + 1);
     if (countBase > 0) Fill(_T('0'), 1);
     if (countBase == 2) Fill(formatChar, 1);
     Fill(_T('0'), countZeros);
     Write(bufLast, bufEnd);
     Fill(_T(' '), countPadRight);
     // done, advance
     Next();
 }
void TestEmptyQueue() {
    const tbb::concurrent_queue<T> queue;
    ASSERT( queue.size()==0, NULL );
    ASSERT( queue.capacity()>0, NULL );
    ASSERT( size_t(queue.capacity())>=size_t(-1)/(sizeof(void*)+sizeof(T)), NULL );
}
Пример #15
0
		// return a copy of the 20 bytes representing the sha1-hash as a std::string.
		// It's still a binary string with 20 binary characters.
		std::string to_string() const
		{
			return std::string(reinterpret_cast<char const*>(&m_number[0])
				, size_t(size));
		}
Пример #16
0
	void push_best_triangle()
	{
		/*
		there may be no known best triangle
		this happens in two cases:
		(1) in the very first iteration
		(2) towards the end, where the remaining triangles are spread around and isolated

		this is considerably slower than using the LRU cache, but typically happens rarely
		*/
		if (!has_best_triangle)
		{
			numeric_type_t score = numeric_type_t(-1);
			for (typename std::vector < triangle_data > ::iterator tri_iter = tri_data.begin(); tri_iter != tri_data.end(); ++tri_iter)
			{
				if (tri_iter->disabled)
					continue;

				if (tri_iter->score >= score)
				{
					score = tri_iter->score;
					best_triangle = tri_iter - tri_data.begin();
					has_best_triangle = true;
				}
			}
		}


		// the push_best_triangle() function is never called if there are no triangles to begin with,
		// and if there are some, the code above should always return a best triangle
		assert(has_best_triangle);


		// get the best triangle
		triangle_data &best_tri = tri_data[best_triangle];

		// push the best triangle's vertices to the top of the LRU cache, potentially expanding
		// the cache by up to 3 vertices
		// the loop is reversed to preserver order of the vertices inside the LRU cache; that is, triangle vertex index #0 shall
		// be the first in the LRU cache, index #1 the second etc.
		// TODO: reverse/nonreverse return different optimization results; test if this has an impact in cache efficiency
		{
			for (int i = 2; i >= 0; --i)
			{
				vertex_index_t idx = best_tri.indices[i];
				typename lru_cache_t::iterator cache_iter = std::find(lru_cache.begin(), lru_cache.end(), idx);
				if (cache_iter != lru_cache.end())
				{
					lru_cache.push_front(idx);
					lru_cache.erase(cache_iter);
				}
				else
				{
					lru_cache.push_front(idx);
				}
			}
		}

		// push the best triangle into the optimized triangle list, and disable it, meaning
		// it will not be considered a candidate for best triangle anymore
		optimized_tris.push_back(best_tri);
		best_tri.disabled = true;

		// remove the best triangle from the tri_indices_using vectors of its vertices
		for (int i = 0; i < 3; ++i)
		{
			vertex_data &vtx = vtx_data[best_tri.indices[i]];
			typename tri_indices_using_t::iterator iter = vtx.tri_indices_using.find(best_triangle);
			if (iter != vtx.tri_indices_using.end())
				vtx.tri_indices_using.erase(iter);
		}

		// now find a new best triangle
		{
			std::set < triangle_index_t > triangles_in_cache;

			// fill the triangles_in_cache vector by visiting each vertex in the LRU cache,
			// retrieving the indices of the triangles using these vertices, and storing them
			// in triangles_in_cache
			// the result is a set of indices of those triangles which are referred to by LRU cache
			// vertices; only these triangles are candidates for the new best triangle
			int pos = 0;
			for (typename lru_cache_t::iterator cache_iter = lru_cache.begin(); cache_iter != lru_cache.end(); ++cache_iter, ++pos)
			{
				vertex_data &vtx = vtx_data[*cache_iter];
				vtx.position = (pos < int(max_cache_size)) ? pos : -1;
				vtx.score = find_vertex_score(vtx);
				triangles_in_cache.insert(vtx.tri_indices_using.begin(), vtx.tri_indices_using.end());
			}

			numeric_type_t highest_score = 0;
			has_best_triangle = false;

			// amongst the candidate triangles, find the one with the highest score - this one
			// will become the new best triangle
			for (typename std::set < triangle_index_t > ::iterator tri_iter = triangles_in_cache.begin(); tri_iter != triangles_in_cache.end(); ++tri_iter)
			{
				triangle_data &tri_in_cache = tri_data[*tri_iter];
				if (tri_in_cache.disabled)
					continue; // if this triangle was a best triangle before, skip it

				// update the triangle's score
				tri_in_cache.score =
					vtx_data[tri_in_cache.indices[0]].score +
					vtx_data[tri_in_cache.indices[1]].score +
					vtx_data[tri_in_cache.indices[2]].score;

				// is this triangle's score higher than the highest score seen so far?
				// if so, it becomes the new candidate for the best triangle
				if (tri_in_cache.score > highest_score)
				{
					highest_score = tri_in_cache.score;
					best_triangle = *tri_iter;
					has_best_triangle = true;
				}
			}
		}

		// finally, prune the LRU cache if necessary
		while (lru_cache.size() > size_t(max_cache_size))
		{
			lru_cache.pop_back();
		}
	}
Пример #17
0
std::string word_wrap_text(const std::string& unwrapped_text, int font_size,
	int max_width, int max_height, int max_lines, bool partial_line)
{
	VALIDATE(max_width > 0, _("The maximum text width is less than 1."));

	utf8::iterator ch(unwrapped_text);
	std::string current_word;
	std::string current_line;
	size_t line_width = 0;
	size_t current_height = 0;
	bool line_break = false;
	bool first = true;
	bool start_of_line = true;
	std::string wrapped_text;
	std::string format_string;
	SDL_Color color;
	int font_sz = font_size;
	int style = TTF_STYLE_NORMAL;
	utf8::iterator end = utf8::iterator::end(unwrapped_text);

	while(1) {
		if(start_of_line) {
			line_width = 0;
			format_string.clear();
			while(ch != end && *ch < static_cast<ucs4::char_t>(0x100)
					&& is_format_char(*ch) && !ch.next_is_end()) {

				format_string.append(ch.substr().first, ch.substr().second);
				++ch;
			}
			// We need to parse the special format characters
			// to give the proper font_size and style to line_size()
			font_sz = font_size;
			style = TTF_STYLE_NORMAL;
			parse_markup(format_string.begin(),format_string.end(),&font_sz,&color,&style);
			current_line.clear();
			start_of_line = false;
		}

		// If there is no current word, get one
		if(current_word.empty() && ch == end) {
			break;
		} else if(current_word.empty()) {
			if(*ch == ' ' || *ch == '\n') {
				current_word = *ch;
				++ch;
			} else {
				ucs4::char_t previous = 0;
				for(;ch != utf8::iterator::end(unwrapped_text) &&
						*ch != ' ' && *ch != '\n'; ++ch) {

					if(!current_word.empty() &&
							break_before(*ch) &&
							!no_break_after(previous))
						break;

					if(!current_word.empty() &&
							break_after(previous) &&
							!no_break_before(*ch))
						break;

					current_word.append(ch.substr().first, ch.substr().second);

					previous = *ch;
				}
			}
		}

		if(current_word == "\n") {
			line_break = true;
			current_word.clear();
			start_of_line = true;
		} else {

			const size_t word_width = line_size(current_word, preferences::font_scaled(font_sz), style).w;

			line_width += word_width;

			if(static_cast<long>(line_width) > max_width) {
				if (!partial_line && static_cast<long>(word_width) > max_width) {
					cut_word(current_line,
						current_word, font_sz, style, max_width);
				}
				if(current_word == " ")
					current_word = "";
				line_break = true;
			} else {
				current_line += current_word;
				current_word = "";
			}
		}

		if(line_break || (current_word.empty() && ch == end)) {
			SDL_Rect size = line_size(current_line, preferences::font_scaled(font_sz), style);
			if(max_height > 0 && current_height + size.h >= size_t(max_height)) {
				return wrapped_text;
			}

			if(!first) {
				wrapped_text += '\n';
			}

			wrapped_text += format_string + current_line;
			current_line.clear();
			line_width = 0;
			current_height += size.h;
			line_break = false;
			first = false;

			if(--max_lines == 0) {
				return wrapped_text;
			}
		}
	}
	return wrapped_text;
}
Пример #18
0
void* smart_malloc(size_t nbytes) {
  auto& mm = MM();
  auto const size = mm.debugAddExtra(std::max(nbytes, size_t(1)));
  return mm.debugPostAllocate(mm.smartMalloc(size), 0, 0);
}
Пример #19
0
 size_t max_size() const {return size_t(~0) / sizeof(T);}
Пример #20
0
void wxMenu::GtkAppend(wxMenuItem* mitem, int pos)
{
    GtkWidget *menuItem;
    switch (mitem->GetKind())
    {
        case wxITEM_SEPARATOR:
            menuItem = gtk_separator_menu_item_new();
            break;
        case wxITEM_CHECK:
            menuItem = gtk_check_menu_item_new_with_label("");
            break;
        case wxITEM_RADIO:
            {
                // See if we need to create a new radio group for this item or
                // add it to an existing one.
                wxMenuItem* radioGroupItem = NULL;

                const size_t numItems = GetMenuItemCount();
                const size_t n = pos == -1 ? numItems - 1 : size_t(pos);

                if (n != 0)
                {
                    wxMenuItem* const itemPrev = FindItemByPosition(n - 1);
                    if ( itemPrev->GetKind() == wxITEM_RADIO )
                    {
                        // Appending an item after an existing radio item puts
                        // it into the same radio group.
                        radioGroupItem = itemPrev;
                    }
                }

                if (radioGroupItem == NULL && n != numItems - 1)
                {
                    wxMenuItem* const itemNext = FindItemByPosition(n + 1);
                    if ( itemNext->GetKind() == wxITEM_RADIO )
                    {
                        // Inserting an item before an existing radio item
                        // also puts it into the existing radio group.
                        radioGroupItem = itemNext;
                    }
                }

                GSList* group = NULL;
                if ( radioGroupItem )
                {
                    group = gtk_radio_menu_item_get_group(
                              GTK_RADIO_MENU_ITEM(radioGroupItem->GetMenuItem())
                            );
                }

                menuItem = gtk_radio_menu_item_new_with_label(group, "");
            }
            break;
        default:
            wxFAIL_MSG("unexpected menu item kind");
            // fall through
        case wxITEM_NORMAL:
            const wxBitmap& bitmap = mitem->GetBitmap();
            const char* stockid;
            if (bitmap.IsOk())
            {
                // always use pixbuf, because pixmap mask does not
                // work with disabled images in some themes
                GtkWidget* image = gtk_image_new_from_pixbuf(bitmap.GetPixbuf());
                menuItem = gtk_image_menu_item_new_with_label("");
                gtk_widget_show(image);
                gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menuItem), image);
            }
            else if ((stockid = wxGetStockGtkID(mitem->GetId())) != NULL)
                // use stock bitmap for this item if available on the assumption
                // that it never hurts to follow GTK+ conventions more closely
                menuItem = gtk_image_menu_item_new_from_stock(stockid, NULL);
            else
                menuItem = gtk_menu_item_new_with_label("");
            break;
    }
    mitem->SetMenuItem(menuItem);

    gtk_menu_shell_insert(GTK_MENU_SHELL(m_menu), menuItem, pos);

    gtk_widget_show( menuItem );

    if ( !mitem->IsSeparator() )
    {
        mitem->SetGtkLabel();
        g_signal_connect (menuItem, "select",
                          G_CALLBACK(menuitem_select), mitem);
        g_signal_connect (menuItem, "deselect",
                          G_CALLBACK(menuitem_deselect), mitem);

        if ( mitem->IsSubMenu() && mitem->GetKind() != wxITEM_RADIO && mitem->GetKind() != wxITEM_CHECK )
        {
            gtk_menu_item_set_submenu( GTK_MENU_ITEM(menuItem), mitem->GetSubMenu()->m_menu );

            gtk_widget_show( mitem->GetSubMenu()->m_menu );
        }
        else
        {
            g_signal_connect(menuItem, "can_activate_accel",
                G_CALLBACK(can_activate_accel), this);
            g_signal_connect (menuItem, "activate",
                              G_CALLBACK(menuitem_activate),
                              mitem);
        }
    }
}
Пример #21
0
//
// Created by spooky on 2016-07-20.
//

#include "gtest/gtest.h"
#include "../LIFO.h"
#include <unordered_set>
#include <future>
#include <Barrier.h>

class LIFOTest : public ::testing::TestWithParam<size_t> {

};

INSTANTIATE_TEST_CASE_P(Threads, LIFOTest, ::testing::Range(size_t(1), size_t(15)));

TEST_F (LIFOTest, test) {

    LIFO<size_t> l;
    ASSERT_EQ(0ul, l.pop(0ul));

    l.push_front(1lu);
    ASSERT_EQ(1ul, l.pop(0ul));
    ASSERT_EQ(0ul, l.pop(0ul));

    l.push_front(20lu);
    ASSERT_EQ(20ul, l.pop(0ul));
    ASSERT_EQ(0ul, l.pop(0ul));

    l.push_front(1lu);
    l.push_front(20lu);
Пример #22
0
void
SoundDriver::initialiseAudioQueue(const std::vector<MappedEvent> &events)
{
    AudioPlayQueue *newQueue = new AudioPlayQueue();

    for (std::vector<MappedEvent>::const_iterator i = events.begin();
            i != events.end(); ++i) {

        // Check for existence of file - if the sequencer has died
        // and been restarted then we're not always loaded up with
        // the audio file references we should have.  In the future
        // we could make this just get the gui to reload our files
        // when (or before) this fails.
        //
        AudioFile *audioFile = getAudioFile(i->getAudioID());

        if (audioFile) {
            MappedAudioFader *fader =
                dynamic_cast<MappedAudioFader*>
                (getMappedStudio()->getAudioFader(i->getInstrument()));

            if (!fader) {
                RG_DEBUG << "WARNING: SoundDriver::initialiseAudioQueue: no fader for audio instrument " << i->getInstrument();
                continue;
            }

            int channels = fader->getPropertyList(
                                        MappedAudioFader::Channels)[0].toInt();

            //#define DEBUG_PLAYING_AUDIO
#ifdef DEBUG_PLAYING_AUDIO

            RG_DEBUG << "Creating playable audio file: id " << audioFile->getId() << ", event time " << i->getEventTime() << ", time now " << getSequencerTime() << ", start marker " << i->getAudioStartMarker() << ", duration " << i->getDuration() << ", instrument " << i->getInstrument() << " channels " << channels;
#endif

            RealTime bufferLength = getAudioReadBufferLength();
            size_t bufferFrames = (size_t)RealTime::realTime2Frame
                                  (bufferLength, getSampleRate());

            PlayableAudioFile *paf = 0;

            try {
                paf = new PlayableAudioFile(i->getInstrument(),
                                            audioFile,
                                            i->getEventTime(),
                                            i->getAudioStartMarker(),
                                            i->getDuration(),
                                            bufferFrames,
                                            size_t(getSmallFileSize()) * 1024,
                                            channels,
                                            int(getSampleRate()));
            } catch (...) {
                continue;
            }

            paf->setRuntimeSegmentId(i->getRuntimeSegmentId());

            if (i->isAutoFading()) {
                paf->setAutoFade(true);
                paf->setFadeInTime(i->getFadeInTime());
                paf->setFadeOutTime(i->getFadeInTime());

                //#define DEBUG_AUTOFADING
#ifdef DEBUG_AUTOFADING

                RG_DEBUG << "SoundDriver::initialiseAudioQueue - "
                << "PlayableAudioFile is AUTOFADING - "
                << "in = " << i->getFadeInTime()
                << ", out = " << i->getFadeOutTime();
#endif

            }
#ifdef DEBUG_AUTOFADING
            else {
                RG_DEBUG << "PlayableAudioFile has no AUTOFADE";
            }
#endif

            newQueue->addScheduled(paf);
        } else {
            RG_DEBUG << "SoundDriver::initialiseAudioQueue - "
            << "can't find audio file reference for id " << i->getAudioID();

            RG_DEBUG << "SoundDriver::initialiseAudioQueue - "
            << "try reloading the current Rosegarden file";
        }
    }

    RG_DEBUG << "SoundDriver::initialiseAudioQueue -- new queue has "
    << newQueue->size() << " files";

    if (newQueue->empty()) {
        if (m_audioQueue->empty()) {
            delete newQueue;
            return ;
        }
    }

    AudioPlayQueue *oldQueue = m_audioQueue;
    m_audioQueue = newQueue;
    if (oldQueue)
        m_audioQueueScavenger.claim(oldQueue);
}
Пример #23
0
ndsize_t BaseTagHDF5::referenceCount() const {
    boost::optional<H5Group> g = refs_group(false);
    return g ? g->objectCount() : size_t(0);
}
Пример #24
0
void Allocator::FreeAligned(void* p)
{
    size_t src = size_t(p) - *(((size_t*)p)-1);
    Free((void*)src);
}
int main() {
    {
        boost::shared_ptr<int[]> a1 = boost::make_shared<int[]>(3);
        int* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<int>::value == 0);
        BOOST_TEST(a1[0] == 0);
        BOOST_TEST(a1[1] == 0);
        BOOST_TEST(a1[2] == 0);
    }
    {
        boost::shared_ptr<const int[]> a1 = boost::make_shared<const int[]>(3);
        const int* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<int>::value == 0);
        BOOST_TEST(a1[0] == 0);
        BOOST_TEST(a1[1] == 0);
        BOOST_TEST(a1[2] == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<type[]> a1 = boost::make_shared<type[]>(3);
        type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);
        BOOST_TEST(type::instances == 3);
        boost::weak_ptr<type[]> w1 = a1;
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<const type[]> a1 = boost::make_shared<const type[]>(3);
        const type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);
        BOOST_TEST(type::instances == 3);
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<type[]> a1 = boost::make_shared<type[]>(3, 1, 5);
        type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);        
        BOOST_TEST(type::instances == 3);
        boost::weak_ptr<type[]> w1 = a1;
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<type[3]> a1 = boost::make_shared<type[3]>(1, 5);
        type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);        
        BOOST_TEST(type::instances == 3);
        boost::weak_ptr<type[3]> w1 = a1;
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<const type[]> a1 = boost::make_shared<const type[]>(3, 1, 5);
        const type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);        
        BOOST_TEST(type::instances == 3);
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<const type[3]> a1 = boost::make_shared<const type[3]>(1, 5);
        const type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);        
        BOOST_TEST(type::instances == 3);
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
#endif
    {
        boost::shared_ptr<int[]> a1 = boost::make_shared_noinit<int[]>(3);
        int* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<int>::value == 0);       
    }
    {
        boost::shared_ptr<int[3]> a1 = boost::make_shared_noinit<int[3]>();
        int* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<int>::value == 0);       
    }
    {
        boost::shared_ptr<const int[]> a1 = boost::make_shared_noinit<const int[]>(3);
        const int* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<int>::value == 0);
    }
    {
        boost::shared_ptr<const int[3]> a1 = boost::make_shared_noinit<const int[3]>();
        const int* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<int>::value == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<type[]> a1 = boost::make_shared_noinit<type[]>(3);
        type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);
        BOOST_TEST(type::instances == 3);
        boost::weak_ptr<type[]> w1 = a1;
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<type[3]> a1 = boost::make_shared_noinit<type[3]>();
        type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);
        BOOST_TEST(type::instances == 3);
        boost::weak_ptr<type[3]> w1 = a1;
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<const type[]> a1 = boost::make_shared_noinit<const type[]>(3);
        const type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);
        BOOST_TEST(type::instances == 3);
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    {
        boost::shared_ptr<const type[3]> a1 = boost::make_shared_noinit<const type[3]>();
        const type* a2 = a1.get();
        BOOST_TEST(a1.use_count() == 1);
        BOOST_TEST(a2 != 0);
        BOOST_TEST(size_t(a2) % boost::alignment_of<type>::value == 0);
        BOOST_TEST(type::instances == 3);
        a1.reset();
        BOOST_TEST(type::instances == 0);
    }
    return boost::report_errors();
}
Пример #26
0
		explicit sha1_hash(std::string const& s)
		{
			TORRENT_ASSERT(s.size() >= 20);
			size_t sl = s.size() < size_t(size) ? s.size() : size_t(size);
			std::memcpy(m_number, s.c_str(), sl);
		}
Пример #27
0
// to intialize the class
DynMat::DynMat(int narg, char **arg)
{
    attyp = NULL;
    memory = NULL;
    M_inv_sqrt = NULL;
    interpolate = NULL;
    DM_q = DM_all = NULL;
    binfile = funit = dmfile = NULL;

    flag_reset_gamma = flag_skip = 0;

    // analyze the command line options
    int iarg = 1;
    while (narg > iarg) {
        if (strcmp(arg[iarg], "-s") == 0) {
            flag_reset_gamma = flag_skip = 1;

        } else if (strcmp(arg[iarg], "-r") == 0) {
            flag_reset_gamma = 1;

        } else if (strcmp(arg[iarg], "-h") == 0) {
            help();

        } else {
            if (binfile) delete []binfile;
            int n = strlen(arg[iarg]) + 1;
            binfile = new char[n];
            strcpy(binfile, arg[iarg]);
        }

        iarg++;
    }

    ShowVersion();
    // get the binary file name from user input if not found in command line
    char str[MAXLINE];
    if (binfile == NULL) {
        char *ptr = NULL;
        printf("\n");
        do {
            printf("Please input the binary file name from fix_phonon: ");
            fgets(str,MAXLINE,stdin);
            ptr = strtok(str, " \n\t\r\f");
        } while (ptr == NULL);

        int n = strlen(ptr) + 1;
        binfile = new char[n];
        strcpy(binfile, ptr);
    }

    // open the binary file
    FILE *fp = fopen(binfile, "rb");
    if (fp == NULL) {
        printf("\nFile %s not found! Programe terminated.\n", binfile);
        help();
    }

    // read header info from the binary file
    if ( fread(&sysdim, sizeof(int),    1, fp) != 1) {
        printf("\nError while reading sysdim from file: %s\n", binfile);
        fclose(fp);
        exit(2);
    }
    if ( fread(&nx,     sizeof(int),    1, fp) != 1) {
        printf("\nError while reading nx from file: %s\n", binfile);
        fclose(fp);
        exit(2);
    }
    if ( fread(&ny,     sizeof(int),    1, fp) != 1) {
        printf("\nError while reading ny from file: %s\n", binfile);
        fclose(fp);
        exit(2);
    }
    if ( fread(&nz,     sizeof(int),    1, fp) != 1) {
        printf("\nError while reading nz from file: %s\n", binfile);
        fclose(fp);
        exit(2);
    }
    if ( fread(&nucell, sizeof(int),    1, fp) != 1) {
        printf("\nError while reading nucell from file: %s\n", binfile);
        fclose(fp);
        exit(2);
    }
    if ( fread(&boltz,  sizeof(double), 1, fp) != 1) {
        printf("\nError while reading boltz from file: %s\n", binfile);
        fclose(fp);
        exit(2);
    }

    fftdim = sysdim*nucell;
    fftdim2 = fftdim*fftdim;
    npt = nx*ny*nz;

    // display info related to the read file
    printf("\n");
    for (int i=0; i<80; i++) printf("=");
    printf("\n");
    printf("Dynamical matrix is read from file: %s\n", binfile);
    printf("The system size in three dimension: %d x %d x %d\n", nx, ny, nz);
    printf("Number of atoms per unit cell     : %d\n", nucell);
    printf("System dimension                  : %d\n", sysdim);
    printf("Boltzmann constant in used units  : %g\n", boltz);
    for (int i=0; i<80; i++) printf("=");
    printf("\n");
    if (sysdim<1||sysdim>3||nx<1||ny<1||nz<1||nucell<1) {
        printf("Wrong values read from header of file: %s, please check the binary file!\n", binfile);
        fclose(fp);
        exit(3);
    }

    funit = new char[4];
    strcpy(funit, "THz");
    if (boltz == 1.) {
        eml2f = 1.;
        delete funit;
        funit=new char[22];
        strcpy(funit,"sqrt(epsilon/(m.sigma^2))");
    }
    else if (boltz == 0.0019872067) eml2f = 3.256576161;
    else if (boltz == 8.617343e-5)  eml2f = 15.63312493;
    else if (boltz == 1.3806504e-23) eml2f = 1.;
    else if (boltz == 1.3806504e-16) eml2f = 1.591549431e-14;
    else {
        printf("WARNING: Because of float precision, I cannot get the factor to convert sqrt(E/ML^2)\n");
        printf("into THz, instead, I set it to be 1; you should check the unit used by LAMMPS.\n");
        eml2f = 1.;
    }

    // now to allocate memory for DM
    memory = new Memory;
    DM_all = memory->create(DM_all, npt, fftdim2, "DynMat:DM_all");
    DM_q   = memory->create(DM_q, fftdim,fftdim,"DynMat:DM_q");

    // read all dynamical matrix info into DM_all
    if ( fread(DM_all[0], sizeof(doublecomplex), npt*fftdim2, fp) != size_t(npt*fftdim2)) {
        printf("\nError while reading the DM from file: %s\n", binfile);
        fclose(fp);
        exit(1);
    }

    // now try to read unit cell info from the binary file
    flag_latinfo = 0;
    basis = memory->create(basis,nucell,sysdim,"DynMat:basis");
    attyp = memory->create(attyp,nucell, "DynMat:attyp");
    M_inv_sqrt = memory->create(M_inv_sqrt, nucell, "DynMat:M_inv_sqrt");
    int flag_mass_read = 0;

    if ( fread(&Tmeasure,   sizeof(double), 1, fp) == 1) flag_latinfo |= 1;
    if ( fread(&basevec[0], sizeof(double), 9, fp) == 9) flag_latinfo |= 2;
    if ( fread(basis[0],    sizeof(double), fftdim, fp) == fftdim) flag_latinfo |= 4;
    if ( fread(&attyp[0],   sizeof(int),    nucell, fp) == nucell) flag_latinfo |= 8;
    if ( fread(&M_inv_sqrt[0], sizeof(double), nucell, fp) == nucell) flag_mass_read = 1;
    fclose(fp);

    if ((flag_latinfo&15) == 15) {
        car2dir(flag_mass_read);
        real2rec();

        flag_latinfo = 1;
    } else {
        Tmeasure = 0.;
        flag_latinfo = 0;
    }

    // initialize interpolation
    interpolate = new Interpolate(nx,ny,nz,fftdim2,DM_all);
    if (flag_reset_gamma) interpolate->reset_gamma();

    if ( flag_mass_read ) { // M_inv_sqrt info read, the data stored are force constant matrix instead of dynamical matrix.

        EnforceASR();

        // get the dynamical matrix from force constant matrix: D = 1/M x Phi
        for (int idq=0; idq< npt; idq++) {
            int ndim =0;
            for (int idim=0; idim<fftdim; idim++) {
                for (int jdim=0; jdim<fftdim; jdim++) {
                    double inv_mass = M_inv_sqrt[idim/sysdim]*M_inv_sqrt[jdim/sysdim];
                    DM_all[idq][ndim].r *= inv_mass;
                    DM_all[idq][ndim].i *= inv_mass;
                    ndim++;
                }
            }
        }
    }

    // ask for the interpolation method
    interpolate->set_method();

    return;
}
Пример #28
0
		void assign(std::string const& s)
		{
			TORRENT_ASSERT(s.size() >= 20);
			size_t sl = s.size() < size_t(size) ? s.size() : size_t(size);
			std::memcpy(m_number, s.c_str(), sl);
		}
Пример #29
0
 utility::mini_vector<size_t, 1> size_of_components() const {
  return {size_t(size())};
 }
static int main_(int argc, char** argv)
{
    // 0 - nothing
    // 1 - ratios only, in the form of "t:v; t:v; ..."
    // 2 - ratios only, one-per-line
    // 3 - as is

    int verbosity;

    XTESTS_COMMANDLINE_PARSEVERBOSITY(argc, argv, &verbosity);

#ifndef NDEBUG
    unsigned ITERATIONS =   3;
    unsigned WARMUPS    =   1;
#else /* ? !NDEBUG */
    unsigned ITERATIONS =   100000;
    unsigned WARMUPS    =   2;
#endif /* !NDEBUG */
    size_t   length     =   0;

    platformstl::performance_counter                counter;
    platformstl::performance_counter::interval_type tm_Streams          =   1;
    platformstl::performance_counter::interval_type tm_IOStreams        =   1;
    platformstl::performance_counter::interval_type tm_CString_Format   =   1;
    platformstl::performance_counter::interval_type tm_Boost            =   1;
    platformstl::performance_counter::interval_type tm_Loki             =   1;
    platformstl::performance_counter::interval_type tm_FF_Format        =   1;
    platformstl::performance_counter::interval_type tm_FF_Write         =   1;
#ifdef FASTFORMAT_USE_WIDE_STRINGS
    std::wstring                                    arg0                =   L"abc";
    const wchar_t                                   arg1[]              =   L"def";
    stlsoft::simple_wstring                         arg2                =   L"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
    std::string                                     arg0                =   "abc";
    const char                                      arg1[]              =   "def";
    stlsoft::simple_string                          arg2                =   "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#endif /* FASTFORMAT_USE_WIDE_STRINGS */
    int                                             arg3                =   -10;

    STLSOFT_SUPPRESS_UNUSED(arg3);

    // Test Identifier

    std::string TestId = PANTHEIOS_FE_PROCESS_IDENTITY;

    // IOStreams

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
#ifdef FASTFORMAT_USE_WIDE_STRINGS
            std::wstringstream   ss;
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
            std::stringstream   ss;
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            ss << TX("The first param '") << arg0 << TX("', and the second '") << arg1 << TX("', and the first again '") << arg0 << TX("'. Then the third '") << arg2 << TX("'. Finally, the last '") << arg3 << TX("'");
#elif defined(PERF_TEST_USE_3_PARAMS)
            ss << TX("The first param '") << arg0 << TX("', and the second '") << arg1 << TX("', and the first again '") << arg0 << TX("'. Finally, the third '") << arg2 << TX("'");
#else /* ? PERF_TEST_USE_3_PARAMS */
            ss << TX("The first param '") << arg0 << TX("', and the second '") << arg1 << TX("', and the first again '") << arg0 << TX("'");
#endif /* !PERF_TEST_USE_3_PARAMS */

#ifdef FASTFORMAT_USE_WIDE_STRINGS
            std::wstring        s   =   ss.str();
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
            std::string         s   =   ss.str();
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.size()), s.c_str());
#endif

            length += s.size();
        }}
        counter.stop();

        tm_IOStreams = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "IOStreams:  %lu\t(%lu)\n", (unsigned long)tm_IOStreams, (unsigned long)length);
        }
    }}


#ifdef FASTFORMAT_PERFTEST_USE_BOOST
    // Boost.Format

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            std::string s = boost::str( boost::format("The first param '%1%', and the second '%2%', and the first again '%1%'. Then the third '%3%'. Finally, the last '%4%'") % arg0 % arg1 % arg2 % arg3);
#elif defined(PERF_TEST_USE_3_PARAMS)
            std::string s = boost::str( boost::format("The first param '%1%', and the second '%2%', and the first again '%1%'. Finally, the third '%3%'") % arg0 % arg1 % arg2);
#else /* ? PERF_TEST_USE_3_PARAMS */
            std::string s = boost::str( boost::format("The first param '%1%', and the second '%2%', and the first again '%1%'") % arg0 % arg1);
#endif /* !PERF_TEST_USE_3_PARAMS */

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.size()), s.c_str());
#endif

            length += s.size();
        }}
        counter.stop();

        tm_Boost = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "Boost.Format: %lu\t(%lu)\n", (unsigned long)tm_Boost, (unsigned long)length);
        }
    }}
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */


#ifdef FASTFORMAT_PERFTEST_USE_LOKI
    // Loki.SafeFormat

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            std::string s;

#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            Loki::SPrintf(s, "The first param '%s', and the second '%s', and the first again '%s'. Then the third '%s'. Finally, the last '%d'")(arg0)(arg1)(arg0)(arg2.c_str())(arg3);
#elif defined(PERF_TEST_USE_3_PARAMS)
            Loki::SPrintf(s, "The first param '%s', and the second '%s', and the first again '%s'. Finally, the third '%s'")(arg0)(arg1)(arg0)(arg2.c_str());
#else /* ? PERF_TEST_USE_3_PARAMS */
            Loki::SPrintf(s, "The first param '%s', and the second '%s', and the first again '%s'")(arg0)(arg1)(arg0);
#endif /* !PERF_TEST_USE_3_PARAMS */

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.size()), s.c_str());
#endif

            length += s.size();
        }}
        counter.stop();

        tm_Loki = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "Loki.SafeFormat: %lu\t(%lu)\n", (unsigned long)tm_Loki, (unsigned long)length);
        }
    }}
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */


#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
    // CString::Format()

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            CString s;

#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            s.Format(TX("The first param '%s', and the second '%s', and the first again '%s'. Then the third '%d'. Finally, the last '%s'")
                        ,   arg0.c_str(), arg1, arg0.c_str(), arg2.c_str(), arg3);
#elif defined(PERF_TEST_USE_3_PARAMS)
            s.Format(TX("The first param '%s', and the second '%s', and the first again '%s'. Finally, the third '%s'")
                        ,   arg0.c_str(), arg1, arg0.c_str(), arg2.c_str());
#else /* ? PERF_TEST_USE_3_PARAMS */
            s.Format(TX("The first param '%s', and the second '%s', and the first again '%s'")
                        ,   arg0.c_str(), arg1, arg0.c_str());
#endif /* !PERF_TEST_USE_3_PARAMS */

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.GetLength()), static_cast<char const*>(s));
#endif

            length += size_t(s.GetLength());
        }}
        counter.stop();

        tm_CString_Format = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "CString::Format(): %lu\t(%lu)\n", (unsigned long)tm_CString_Format, (unsigned long)length);
        }
    }}


#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
    // sprintf()

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            char    sz[1001];
#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            int     cch =   ::sprintf(&sz[0], "The first param '%s', and the second '%s', and the first again '%s'. Then the third '%s'. Finally, the last '%d'"
                                    , stlsoft::c_str_ptr(arg0), arg1, stlsoft::c_str_ptr(arg0), stlsoft::c_str_ptr(arg2), arg3);
#elif defined(PERF_TEST_USE_3_PARAMS)
            int     cch =   ::sprintf(&sz[0], "The first param '%s', and the second '%s', and the first again '%s'. Finally, the third '%s'"
                                    , stlsoft::c_str_ptr(arg0), arg1, stlsoft::c_str_ptr(arg0), stlsoft::c_str_ptr(arg2));
#else /* ? PERF_TEST_USE_3_PARAMS */
            int     cch =   ::sprintf(&sz[0], "The first param '%s', and the second '%s', and the first again '%s'"
                                    , stlsoft::c_str_ptr(arg0), arg1, stlsoft::c_str_ptr(arg0));
#endif /* !PERF_TEST_USE_3_PARAMS */

            std::string s(sz, size_t(cch));

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.size()), s.c_str());
#endif

            length += s.size();
        }}
        counter.stop();

        tm_Streams = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "sprintf():  %lu\t(%lu)\n", (unsigned long)tm_Streams, (unsigned long)length);
        }
    }}


    // FastFormat.Format

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
#ifdef FASTFORMAT_USE_WIDE_STRINGS
            std::wstring    s;
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
            std::string     s;
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            fastformat::fmt(s, TX("The first param '{0}', and the second '{1}', and the first again '{0}'. Then the third '{2}'. Finally, the last '{3}'")
                        ,   arg0, arg1, arg2, arg3);
#elif defined(PERF_TEST_USE_3_PARAMS)
            fastformat::fmt(s, TX("The first param '{0}', and the second '{1}', and the first again '{0}'. Finally, the third '{2}'")
                        ,   arg0, arg1, arg2);
#else /* ? PERF_TEST_USE_3_PARAMS */
            fastformat::fmt(s, TX("The first param '{0}', and the second '{1}', and the first again '{0}'")
                        ,   arg0, arg1);
#endif /* !PERF_TEST_USE_3_PARAMS */

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.size()), s.c_str());
#endif

            length += s.size();
        }}
        counter.stop();

        tm_FF_Format = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "FastFormat.Format: %lu\t(%lu)\n", (unsigned long)tm_FF_Format, (unsigned long)length);
        }
    }}


    // FastFormat.Write

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
#ifdef FASTFORMAT_USE_WIDE_STRINGS
            std::wstring    s;
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
            std::string     s;
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

#if defined(PERF_TEST_USE_4_PARAMS_3_STR_1_INT)
            fastformat::write(s, TX("The first param '"), arg0, TX("', and the second '"), arg1, TX("', and the first again '"), arg0, TX("'. Then the third '"), arg2, TX("'. Finally, the last '"), arg3, TX("'"));
#elif defined(PERF_TEST_USE_3_PARAMS)
            fastformat::write(s, TX("The first param '"), arg0, TX("', and the second '"), arg1, TX("', and the first again '"), arg0, TX("'. Finally, the third '"), arg2, TX("'"));
#else /* ? PERF_TEST_USE_3_PARAMS */
            fastformat::write(s, TX("The first param '"), arg0, TX("', and the second '"), arg1, TX("', and the first again '"), arg0, TX("'"));
#endif /* !PERF_TEST_USE_3_PARAMS */

#ifdef SHOW_FIRST_RESULT
(0 == i) && fprintf(stderr, "%.*s\n", int(s.size()), s.c_str());
#endif

            length += s.size();
        }}
        counter.stop();

        tm_FF_Write = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "FastFormat.Write: %lu\t(%lu)\n", (unsigned long)tm_FF_Write, (unsigned long)length);
        }
    }}

    STLSOFT_SUPPRESS_UNUSED(length);

    std::string     fmt1;
    std::string     fmt2;

    fastformat::ignore_unreferenced_arguments_scope scoper;

    switch(verbosity)
    {
        case    0:
            // no output
            break;
        case    1:
            fmt1 = "";
            fmt1 += "S:FF.F:\t{0}";
            fmt1 += "\tIOS:FF.F:\t{1}";
            fmt1 += "\tFF.W:FF.F:\t{3}";
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            fmt1 += "\tB.F:FF.F:\t{4}";
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            fmt1 += "\tL.SF:FF.F:\t{5}";
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            fmt1 += "\tMFC.F:FF.F:\t{2}";
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
            fastformat::fmtln(  std::cout, fmt1
                            ,   double(tm_Streams) / double(tm_FF_Format)
                            ,   double(tm_IOStreams) / double(tm_FF_Format)
                            ,   double(tm_CString_Format) / double(tm_FF_Format)
                            ,   double(tm_FF_Write) / double(tm_FF_Format)
                            ,   double(tm_Boost) / double(tm_FF_Format)
                            ,   double(tm_Loki) / double(tm_FF_Format));
            fmt1 = "";
            fmt1 += "S:FF.W:\t{0}";
            fmt1 += "\tIOS:FF.W:\t{1}";
            fmt1 += "\tFF.F:FF.W:\t{2}";
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            fmt1 += "\tB.F:FF.W:\t{3}";
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            fmt1 += "\tL.SF:FF.W:\t{3}";
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            fmt1 += "\tMFC.F:FF.W:\t{4}";
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
            fastformat::fmtln(  std::cout, fmt1
                            ,   double(tm_Streams) / double(tm_FF_Write)
                            ,   double(tm_IOStreams) / double(tm_FF_Write)
                            ,   double(tm_CString_Format) / double(tm_FF_Write)
                            ,   double(tm_FF_Format) / double(tm_FF_Write)
                            ,   double(tm_Boost) / double(tm_FF_Write)
                            ,   double(tm_Loki) / double(tm_FF_Write));
            break;
        case    2:
            fastformat::fmtln(std::cout, "{0}\tFastFormat.Format\tFastFormat.Write", TestId);
            fastformat::fmtln(std::cout, "Streams\t{0}\t{1}", double(tm_Streams) / double(tm_FF_Format), double(tm_Streams) / double(tm_FF_Write));
            fastformat::fmtln(std::cout, "IOStreams\t{0}\t{1}", double(tm_IOStreams) / double(tm_FF_Format), double(tm_IOStreams) / double(tm_FF_Write));
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            fastformat::fmtln(std::cout, "CString::Format\t{0}\t{1}", double(tm_CString_Format) / double(tm_FF_Format), double(tm_CString_Format) / double(tm_FF_Write));
#else /* ? FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
            fastformat::writeln(std::cout, "");
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            fastformat::fmtln(std::cout, "Boost.Format\t{0}\t{1}", double(tm_Boost) / double(tm_FF_Format), double(tm_Boost) / double(tm_FF_Write));
#else /* ? FASTFORMAT_PERFTEST_USE_BOOST */
            fastformat::writeln(std::cout, "");
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            fastformat::fmtln(std::cout, "Loki.SafeFormat\t{0}\t{1}", double(tm_Loki) / double(tm_FF_Format), double(tm_Loki) / double(tm_FF_Write));
#else /* ? FASTFORMAT_PERFTEST_USE_LOKI */
            fastformat::writeln(std::cout, "");
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
            fastformat::fmtln(std::cout, "FastFormat.Format\t{0}\t{1}", "", double(tm_FF_Format) / double(tm_FF_Write));
            fastformat::fmtln(std::cout, "FastFormat.Write\t{0}\t{1}", double(tm_FF_Write) / double(tm_FF_Format), "");
            break;
        case    3:
            ::puts("");
            ::fprintf(stdout, "sprintf():FastFormat.Format:         \t%2.04g\n", double(tm_Streams) / double(tm_FF_Format));
            ::fprintf(stdout, "IOStreams:FastFormat.Format:         \t%2.04g\n", double(tm_IOStreams) / double(tm_FF_Format));
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            ::fprintf(stdout, "CString::Format():FastFormat.Format: \t%2.04g\n", double(tm_CString_Format) / double(tm_FF_Format));
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            ::fprintf(stdout, "Boost.Format:FastFormat.Format:      \t%2.04g\n", double(tm_Boost) / double(tm_FF_Format));
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            ::fprintf(stdout, "Loki.SafeFormat:FastFormat.Format:   \t%2.04g\n", double(tm_Loki) / double(tm_FF_Format));
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
            ::puts("");
            ::fprintf(stdout, "sprintf():FastFormat.Write:          \t%2.04g\n", double(tm_Streams) / double(tm_FF_Write));
            ::fprintf(stdout, "IOStreams:FastFormat.Write:          \t%2.04g\n", double(tm_IOStreams) / double(tm_FF_Write));
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            ::fprintf(stdout, "CString::Format():FastFormat.Write:  \t%2.04g\n", double(tm_CString_Format) / double(tm_FF_Write));
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            ::fprintf(stdout, "Boost.Format:FastFormat.Write:       \t%2.04g\n", double(tm_Boost) / double(tm_FF_Write));
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            ::fprintf(stdout, "Loki.SafeFormat:FastFormat.Write:    \t%2.04g\n", double(tm_Loki) / double(tm_FF_Write));
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
            ::fprintf(stdout, "\n");
            ::fprintf(stdout, "FastFormat.Format:FastFormat.Write:  \t%2.04g\n", double(tm_FF_Format) / double(tm_FF_Write));
            break;
    }

    return EXIT_SUCCESS;
}