<commit_before>#include "Sandbox.h"

#include "TestObject.h"
#include "Entity.h"

#include <spdlog/spdlog.h>
#include <stdexcept>
#include <memory>
#include <imgui.h>
#include "imgui_impl_opengl3.h"
#include "imgui_impl_glfw.h"

int main(int argc, char* argv[])
{
    auto console = spdlog::stdout_color_mt("console");
    spdlog::set_level(spdlog::level::info);

    try
    {
        auto box = std::make_shared<Moonshine::Sandbox>();
        auto entity = std::make_shared<Moonshine::TestObject>();

        while (true)
        {
            if (box->isStopping())
            {
                break;
            }

            box->poolEvents();

            // Start the Dear ImGui frame
            ImGui_ImplOpenGL3_NewFrame();
            ImGui_ImplGlfw_NewFrame();
            ImGui::NewFrame();

            entity->render();

            ImGui::Render();
            ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

            box->swapBuffers();
        }
    }
    catch (std::exception& e)
    {
        console->critical(u8"(┛◉Д◉)┛彡┻━┻: {0}\n", e.what());

        return 1;
    }

    return 0;
}
<commit_msg>Using fmt instead of spdlog for logging exception.<commit_after>#include "Sandbox.h"

#include "TestObject.h"
#include "Entity.h"

#include <spdlog/spdlog.h>
#include <stdexcept>
#include <memory>
#include <fmt/format.h>
#include <imgui.h>
#include "imgui_impl_opengl3.h"
#include "imgui_impl_glfw.h"

int main(int argc, char* argv[])
{
    spdlog::set_level(spdlog::level::info);

    try
    {
        auto box = std::make_shared<Moonshine::Sandbox>();
        auto entity = std::make_shared<Moonshine::TestObject>();

        while (true)
        {
            if (box->isStopping())
            {
                break;
            }

            box->poolEvents();

            // Start the Dear ImGui frame
            ImGui_ImplOpenGL3_NewFrame();
            ImGui_ImplGlfw_NewFrame();
            ImGui::NewFrame();

            entity->render();

            ImGui::Render();
            ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

            box->swapBuffers();
        }
    }
    catch (std::exception& e)
    {
        fmt::format(u8"(┛◉Д◉)┛彡┻━┻: {0}\n", e.what());

        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Zubax, zubax.com
 * Distributed under the MIT License, available in the file LICENSE.
 * Author: Pavel Kirienko <pavel.kirienko@zubax.com>
 */

#pragma once

#include <zubax_chibios/os.hpp>
#include <zubax_chibios/util/helpers.hpp>
#include <cstdint>
#include <utility>
#include <array>
#include <cassert>
#include "util.hpp"

namespace os
{
namespace bootloader
{
/**
 * Bootloader states. Some of the states are designed as commands to the outer logic, e.g. @ref ReadyToBoot
 * means that the application should be started.
 */
enum class State
{
    NoAppToBoot,
    BootDelay,
    BootCancelled,
    AppUpgradeInProgress,
    ReadyToBoot,
};

static inline const char* stateToString(State state)
{
    switch (state)
    {
    case State::NoAppToBoot:            return "NoAppToBoot";
    case State::BootDelay:              return "BootDelay";
    case State::BootCancelled:          return "BootCancelled";
    case State::AppUpgradeInProgress:   return "AppUpgradeInProgress";
    case State::ReadyToBoot:            return "ReadyToBoot";
    default: return "INVALID_STATE";
    }
}

/**
 * These fields are defined by the Brickproof Bootloader specification.
 */
struct __attribute__((packed)) AppInfo
{
    std::uint64_t image_crc = 0;
    std::uint32_t image_size = 0;
    std::uint32_t vcs_commit = 0;
    std::uint8_t major_version = 0;
    std::uint8_t minor_version = 0;
};

/**
 * This interface abstracts the target-specific ROM routines.
 * Upgrade scenario:
 *  1. beginUpgrade()
 *  2. write() repeated until finished.
 *  3. endUpgrade(success or not)
 *
 * Please note that the performance of the ROM reading routine is critical.
 * Slow access may lead to watchdog timeouts (assuming that the watchdog is used),
 * disruption of communications, and premature expiration of the boot timeout.
 */
class IAppStorageBackend
{
public:
    virtual ~IAppStorageBackend() { }

    /**
     * @return 0 on success, negative on error
     */
    virtual int beginUpgrade() = 0;

    /**
     * @return number of bytes written; negative on error
     */
    virtual int write(std::size_t offset, const void* data, std::size_t size) = 0;

    /**
     * @return 0 on success, negative on error
     */
    virtual int endUpgrade(bool success) = 0;

    /**
     * @return number of bytes read; negative on error
     */
    virtual int read(std::size_t offset, void* data, std::size_t size) = 0;
};

/**
 * This interface proxies data received by the downloader into the bootloader.
 */
class IDownloadStreamSink
{
public:
    virtual ~IDownloadStreamSink() { }

    /**
     * @return Negative on error, non-negative on success.
     */
    virtual int handleNextDataChunk(const void* data, std::size_t size) = 0;
};

/**
 * Inherit this class to implement firmware loading protocol, from remote to the local storage.
 */
class IDownloader
{
public:
    virtual ~IDownloader() { }

    /**
     * Performs the download operation synchronously.
     * Every received data chunk is fed into the sink using the corresponding method (refer to the interface
     * definition). If the sink returns error, downloading will be aborted.
     * @return Negative on error, 0 on success.
     */
    virtual int download(IDownloadStreamSink& sink) = 0;
};

/**
 * Main bootloader controller.
 */
class Bootloader
{
    static constexpr unsigned DefaultBootDelayMSec = 5000;

    State state_;
    IAppStorageBackend& backend_;

    const std::uint32_t max_application_image_size_;
    const unsigned boot_delay_msec_;
    ::systime_t boot_delay_started_at_st_;

    chibios_rt::Mutex mutex_;

    /// Caching is needed because app check can sometimes take a very long time (several seconds)
    os::helpers::LazyConstructor<AppInfo> cached_app_info_;

    /**
     * Refer to the Brickproof Bootloader specs.
     * Note that the structure must be aligned at 8 bytes boundary, and the image must be padded to 8 bytes!
     */
    struct __attribute__((packed)) AppDescriptor
    {
        static constexpr unsigned ImagePaddingBytes = 8;

        std::array<std::uint8_t, 8> signature;
        AppInfo app_info;
        std::array<std::uint8_t, 6> reserved;

        static constexpr std::array<std::uint8_t, 8> getSignatureValue()
        {
            return {'A','P','D','e','s','c','0','0'};
        }

        bool isValid(const std::uint32_t max_application_image_size) const
        {
            const auto sgn = getSignatureValue();
            return std::equal(std::begin(signature), std::end(signature), std::begin(sgn)) &&
                   (app_info.image_size > 0) &&
                   (app_info.image_size <= max_application_image_size) &&
                   ((app_info.image_size % ImagePaddingBytes) == 0);
        }
    };
    static_assert(sizeof(AppDescriptor) == 32, "Invalid packing");

    std::pair<AppDescriptor, bool> locateAppDescriptor();

    void verifyAppAndUpdateState(const State state_on_success);

public:
    /**
     * Time since boot will be measured starting from the moment when the object was constructed.
     *
     * The max application image size parameter is very important for performance reasons;
     * without it, the bootloader may encounter an unrelated data structure in the ROM that looks like a
     * valid app descriptor (by virtue of having the same signature, which is only 64 bit long),
     * and it may spend a considerable amount of time trying to check the CRC that is certainly invalid.
     * Having an upper size limit for the application image allows the bootloader to weed out too large
     * values early, greatly improving robustness.
     */
    Bootloader(IAppStorageBackend& backend,
               std::uint32_t max_application_image_size = 0xFFFFFFFFU,
               unsigned boot_delay_msec = DefaultBootDelayMSec);

    /**
     * @ref State.
     */
    State getState();

    /**
     * Returns info about the application, if any.
     * @return First component is the application, second component is the status:
     *         true means that the info is valid, false means that there is no application to work with.
     */
    std::pair<AppInfo, bool> getAppInfo();

    /**
     * Switches the state to @ref BootCancelled, if allowed.
     */
    void cancelBoot();

    /**
     * Switches the state to @ref ReadyToBoot, if allowed.
     */
    void requestBoot();

    /**
     * Template method that implements all of the high-level steps of the application update procedure.
     */
    int upgradeApp(IDownloader& downloader);
};

}
}
<commit_msg>IAppStorageBackend made const<commit_after>/*
 * Copyright (c) 2016 Zubax, zubax.com
 * Distributed under the MIT License, available in the file LICENSE.
 * Author: Pavel Kirienko <pavel.kirienko@zubax.com>
 */

#pragma once

#include <zubax_chibios/os.hpp>
#include <zubax_chibios/util/helpers.hpp>
#include <cstdint>
#include <utility>
#include <array>
#include <cassert>
#include "util.hpp"

namespace os
{
namespace bootloader
{
/**
 * Bootloader states. Some of the states are designed as commands to the outer logic, e.g. @ref ReadyToBoot
 * means that the application should be started.
 */
enum class State
{
    NoAppToBoot,
    BootDelay,
    BootCancelled,
    AppUpgradeInProgress,
    ReadyToBoot,
};

static inline const char* stateToString(State state)
{
    switch (state)
    {
    case State::NoAppToBoot:            return "NoAppToBoot";
    case State::BootDelay:              return "BootDelay";
    case State::BootCancelled:          return "BootCancelled";
    case State::AppUpgradeInProgress:   return "AppUpgradeInProgress";
    case State::ReadyToBoot:            return "ReadyToBoot";
    default: return "INVALID_STATE";
    }
}

/**
 * These fields are defined by the Brickproof Bootloader specification.
 */
struct __attribute__((packed)) AppInfo
{
    std::uint64_t image_crc = 0;
    std::uint32_t image_size = 0;
    std::uint32_t vcs_commit = 0;
    std::uint8_t major_version = 0;
    std::uint8_t minor_version = 0;
};

/**
 * This interface abstracts the target-specific ROM routines.
 * Upgrade scenario:
 *  1. beginUpgrade()
 *  2. write() repeated until finished.
 *  3. endUpgrade(success or not)
 *
 * Please note that the performance of the ROM reading routine is critical.
 * Slow access may lead to watchdog timeouts (assuming that the watchdog is used),
 * disruption of communications, and premature expiration of the boot timeout.
 */
class IAppStorageBackend
{
public:
    virtual ~IAppStorageBackend() { }

    /**
     * @return 0 on success, negative on error
     */
    virtual int beginUpgrade() = 0;

    /**
     * @return number of bytes written; negative on error
     */
    virtual int write(std::size_t offset, const void* data, std::size_t size) = 0;

    /**
     * @return 0 on success, negative on error
     */
    virtual int endUpgrade(bool success) = 0;

    /**
     * @return number of bytes read; negative on error
     */
    virtual int read(std::size_t offset, void* data, std::size_t size) const = 0;
};

/**
 * This interface proxies data received by the downloader into the bootloader.
 */
class IDownloadStreamSink
{
public:
    virtual ~IDownloadStreamSink() { }

    /**
     * @return Negative on error, non-negative on success.
     */
    virtual int handleNextDataChunk(const void* data, std::size_t size) = 0;
};

/**
 * Inherit this class to implement firmware loading protocol, from remote to the local storage.
 */
class IDownloader
{
public:
    virtual ~IDownloader() { }

    /**
     * Performs the download operation synchronously.
     * Every received data chunk is fed into the sink using the corresponding method (refer to the interface
     * definition). If the sink returns error, downloading will be aborted.
     * @return Negative on error, 0 on success.
     */
    virtual int download(IDownloadStreamSink& sink) = 0;
};

/**
 * Main bootloader controller.
 */
class Bootloader
{
    static constexpr unsigned DefaultBootDelayMSec = 5000;

    State state_;
    IAppStorageBackend& backend_;

    const std::uint32_t max_application_image_size_;
    const unsigned boot_delay_msec_;
    ::systime_t boot_delay_started_at_st_;

    chibios_rt::Mutex mutex_;

    /// Caching is needed because app check can sometimes take a very long time (several seconds)
    os::helpers::LazyConstructor<AppInfo> cached_app_info_;

    /**
     * Refer to the Brickproof Bootloader specs.
     * Note that the structure must be aligned at 8 bytes boundary, and the image must be padded to 8 bytes!
     */
    struct __attribute__((packed)) AppDescriptor
    {
        static constexpr unsigned ImagePaddingBytes = 8;

        std::array<std::uint8_t, 8> signature;
        AppInfo app_info;
        std::array<std::uint8_t, 6> reserved;

        static constexpr std::array<std::uint8_t, 8> getSignatureValue()
        {
            return {'A','P','D','e','s','c','0','0'};
        }

        bool isValid(const std::uint32_t max_application_image_size) const
        {
            const auto sgn = getSignatureValue();
            return std::equal(std::begin(signature), std::end(signature), std::begin(sgn)) &&
                   (app_info.image_size > 0) &&
                   (app_info.image_size <= max_application_image_size) &&
                   ((app_info.image_size % ImagePaddingBytes) == 0);
        }
    };
    static_assert(sizeof(AppDescriptor) == 32, "Invalid packing");

    std::pair<AppDescriptor, bool> locateAppDescriptor();

    void verifyAppAndUpdateState(const State state_on_success);

public:
    /**
     * Time since boot will be measured starting from the moment when the object was constructed.
     *
     * The max application image size parameter is very important for performance reasons;
     * without it, the bootloader may encounter an unrelated data structure in the ROM that looks like a
     * valid app descriptor (by virtue of having the same signature, which is only 64 bit long),
     * and it may spend a considerable amount of time trying to check the CRC that is certainly invalid.
     * Having an upper size limit for the application image allows the bootloader to weed out too large
     * values early, greatly improving robustness.
     */
    Bootloader(IAppStorageBackend& backend,
               std::uint32_t max_application_image_size = 0xFFFFFFFFU,
               unsigned boot_delay_msec = DefaultBootDelayMSec);

    /**
     * @ref State.
     */
    State getState();

    /**
     * Returns info about the application, if any.
     * @return First component is the application, second component is the status:
     *         true means that the info is valid, false means that there is no application to work with.
     */
    std::pair<AppInfo, bool> getAppInfo();

    /**
     * Switches the state to @ref BootCancelled, if allowed.
     */
    void cancelBoot();

    /**
     * Switches the state to @ref ReadyToBoot, if allowed.
     */
    void requestBoot();

    /**
     * Template method that implements all of the high-level steps of the application update procedure.
     */
    int upgradeApp(IDownloader& downloader);
};

}
}
<|endoftext|>


<commit_before>/* Copyright (C) 2018, Project Pluto.  See LICENSE.

   This program will generate simulated geocentric observations
for a given object from a TLE.  In theory,  one can then fit these
pseudo-observations to a higher-quality physical model to get a
considerably more accurate ephemeris for the object.  */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "norad.h"
#include "observe.h"

#define PI 3.1415926535897932384626433832795028841971693993751058209749445923

int main( const int argc, const char **argv)
{
   FILE *ifile = fopen( argv[1], "rb");
   char line1[100], line2[100];
   const char *intl_id = NULL;
   double step_size = .1;
   int i, n_steps = 100;
   bool show_vectors = false;

   if( !ifile)
      {
      printf( "Couldn't open input file\n");
      exit( -1);
      }
   for( i = 1; i < argc; i++)
      if( argv[i][0] == '-')
         switch( argv[i][1])
            {
            case 'i':
               intl_id = argv[i] + 2;
               break;
            case 'n':
               n_steps = atoi( argv[i] + 2);
               break;
            case 's':
               step_size = atof( argv[i] + 2);
               break;
            case 'v':
               show_vectors = true;
               break;
            default:
               printf( "Unrecognized option '%s'\n", argv[i]);
               break;
            }
   *line1 = '\0';
   sxpx_set_implementation_param( SXPX_DUNDEE_COMPLIANCE, 1);
   while( fgets( line2, sizeof( line2), ifile))
      {
      tle_t tle; /* Pointer to two-line elements set for satellite */
      int err_val;

      if( (!intl_id || !memcmp( intl_id, line1 + 9, 6))
                && (err_val = parse_elements( line1, line2, &tle)) >= 0)
         {                  /* hey! we got a TLE! */
         int is_deep = select_ephemeris( &tle);
         double sat_params[N_SAT_PARAMS], observer_loc[3];
         double prev_pos[3];

         if( err_val)
            printf( "WARNING: TLE parsing error %d\n", err_val);
         for( i = 0; i < 3; i++)
            observer_loc[i] = '\0';
         if( is_deep)
            SDP4_init( sat_params, &tle);
         else
            SGP4_init( sat_params, &tle);
         for( i = 0; i < n_steps; i++)
            {
            double pos[3]; /* Satellite position vector */
            double t_since = (double)( i - n_steps / 2) * step_size;
            double jd = tle.epoch + t_since;

            t_since *= 1440.;
            if( is_deep)
               err_val = SDP4( t_since, &tle, sat_params, pos, NULL);
            else
               err_val = SGP4( t_since, &tle, sat_params, pos, NULL);
            if( err_val)
               printf( "Ephemeris error %d\n", err_val);
            if( show_vectors)
               {
               if( i)
                  printf( "%14.6f %14.6f %14.6f - ", pos[0] - prev_pos[0],
                                                 pos[1] - prev_pos[1],
                                                 pos[2] - prev_pos[2]);
               printf( "%14.6f %14.6f %14.6f\n", pos[0], pos[1], pos[2]);
               memcpy( prev_pos, pos, 3 * sizeof( double));
               }
            else
               {
               double ra, dec, dist_to_satellite;

               get_satellite_ra_dec_delta( observer_loc, pos,
                                 &ra, &dec, &dist_to_satellite);
               epoch_of_date_to_j2000( jd, &ra, &dec);
               printf( "%-14sC%13.5f    %08.4f    %+08.4f",
                     intl_id, jd, ra * 180. / PI, dec * 180. / PI);
               printf( "                    TLEs 500\n");
               }
            }
         }
      strcpy( line1, line2);
      }
   fclose( ifile);
   return( 0);
} /* End of main() */

<commit_msg>Why did I set a double-precision floating-point value to '\0' instead of to '0.'?  And how does this not get a warning message from gcc?<commit_after>/* Copyright (C) 2018, Project Pluto.  See LICENSE.

   This program will generate simulated geocentric observations
for a given object from a TLE.  In theory,  one can then fit these
pseudo-observations to a higher-quality physical model to get a
considerably more accurate ephemeris for the object.  */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "norad.h"
#include "observe.h"

#define PI 3.1415926535897932384626433832795028841971693993751058209749445923

int main( const int argc, const char **argv)
{
   FILE *ifile = fopen( argv[1], "rb");
   char line1[100], line2[100];
   const char *intl_id = NULL;
   double step_size = .1;
   int i, n_steps = 100;
   bool show_vectors = false;

   if( !ifile)
      {
      printf( "Couldn't open input file\n");
      exit( -1);
      }
   for( i = 1; i < argc; i++)
      if( argv[i][0] == '-')
         switch( argv[i][1])
            {
            case 'i':
               intl_id = argv[i] + 2;
               break;
            case 'n':
               n_steps = atoi( argv[i] + 2);
               break;
            case 's':
               step_size = atof( argv[i] + 2);
               break;
            case 'v':
               show_vectors = true;
               break;
            default:
               printf( "Unrecognized option '%s'\n", argv[i]);
               break;
            }
   *line1 = '\0';
   sxpx_set_implementation_param( SXPX_DUNDEE_COMPLIANCE, 1);
   while( fgets( line2, sizeof( line2), ifile))
      {
      tle_t tle; /* Pointer to two-line elements set for satellite */
      int err_val;

      if( (!intl_id || !memcmp( intl_id, line1 + 9, 6))
                && (err_val = parse_elements( line1, line2, &tle)) >= 0)
         {                  /* hey! we got a TLE! */
         int is_deep = select_ephemeris( &tle);
         double sat_params[N_SAT_PARAMS], observer_loc[3];
         double prev_pos[3];

         if( err_val)
            printf( "WARNING: TLE parsing error %d\n", err_val);
         for( i = 0; i < 3; i++)
            observer_loc[i] = 0.;
         if( is_deep)
            SDP4_init( sat_params, &tle);
         else
            SGP4_init( sat_params, &tle);
         for( i = 0; i < n_steps; i++)
            {
            double pos[3]; /* Satellite position vector */
            double t_since = (double)( i - n_steps / 2) * step_size;
            double jd = tle.epoch + t_since;

            t_since *= 1440.;
            if( is_deep)
               err_val = SDP4( t_since, &tle, sat_params, pos, NULL);
            else
               err_val = SGP4( t_since, &tle, sat_params, pos, NULL);
            if( err_val)
               printf( "Ephemeris error %d\n", err_val);
            if( show_vectors)
               {
               if( i)
                  printf( "%14.6f %14.6f %14.6f - ", pos[0] - prev_pos[0],
                                                 pos[1] - prev_pos[1],
                                                 pos[2] - prev_pos[2]);
               printf( "%14.6f %14.6f %14.6f\n", pos[0], pos[1], pos[2]);
               memcpy( prev_pos, pos, 3 * sizeof( double));
               }
            else
               {
               double ra, dec, dist_to_satellite;

               get_satellite_ra_dec_delta( observer_loc, pos,
                                 &ra, &dec, &dist_to_satellite);
               epoch_of_date_to_j2000( jd, &ra, &dec);
               printf( "%-14sC%13.5f    %08.4f    %+08.4f",
                     intl_id, jd, ra * 180. / PI, dec * 180. / PI);
               printf( "                    TLEs 500\n");
               }
            }
         }
      strcpy( line1, line2);
      }
   fclose( ifile);
   return( 0);
} /* End of main() */

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsgsimpletexturenode.h"

QT_BEGIN_NAMESPACE

static void qsgsimpletexturenode_update(QSGGeometry *g,
                                        QSGTexture *texture,
                                        const QRectF &rect)
{
    if (!texture)
        return;

    QSize ts = texture->textureSize();
    QRectF sourceRect(0, ts.height(), ts.width(), -ts.height());
    QSGGeometry::updateTexturedRectGeometry(g, rect, texture->convertToNormalizedSourceRect(sourceRect));
}

/*!
  \class QSGSimpleTextureNode
  \brief The QSGSimpleTextureNode provided for convenience to easily draw
  textured content using the QML scene graph.

  \warning The simple texture node class must have texture before being
  added to the scene graph to be rendered.
*/

/*!
    Constructs a new simple texture node
 */
QSGSimpleTextureNode::QSGSimpleTextureNode()
    : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
    setGeometry(&m_geometry);
    setMaterial(&m_material);
    setOpaqueMaterial(&m_opaque_material);
}

/*!
    Sets the filtering to be used for this texture node to \a filtering.

    For smooth scaling, use QSGTexture::Linear; for normal scaling, use
    QSGTexture::Nearest.
 */
void QSGSimpleTextureNode::setFiltering(QSGTexture::Filtering filtering)
{
    if (m_material.filtering() == filtering)
        return;

    m_material.setFiltering(filtering);
    m_opaque_material.setFiltering(filtering);
    markDirty(DirtyMaterial);
}

/*!
    Returns the filtering currently set on this texture node
 */
QSGTexture::Filtering QSGSimpleTextureNode::filtering() const
{
    return m_material.filtering();
}

/*!
    Sets the target rect of this texture node to \a r
 */
void QSGSimpleTextureNode::setRect(const QRectF &r)
{
    if (m_rect == r)
        return;
    m_rect = r;
    qsgsimpletexturenode_update(&m_geometry, texture(), m_rect);
    markDirty(DirtyGeometry);
}

/*!
    Returns the target rect of this texture node.
 */
QRectF QSGSimpleTextureNode::rect() const
{
    return m_rect;
}

/*!
    Sets the texture of this texture node to \a texture.

    \warning A texture node must have a texture before being added
    to the scenegraph to be rendered.
 */
void QSGSimpleTextureNode::setTexture(QSGTexture *texture)
{
    if (m_material.texture() == texture)
        return;
    m_material.setTexture(texture);
    m_opaque_material.setTexture(texture);
    qsgsimpletexturenode_update(&m_geometry, texture, m_rect);
    markDirty(DirtyMaterial);
}

/*!
    Returns the texture for this texture node
 */
QSGTexture *QSGSimpleTextureNode::texture() const
{
    return m_material.texture();
}

QT_END_NAMESPACE
<commit_msg>Fixes wrong flipping of textures.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsgsimpletexturenode.h"

QT_BEGIN_NAMESPACE

static void qsgsimpletexturenode_update(QSGGeometry *g,
                                        QSGTexture *texture,
                                        const QRectF &rect)
{
    if (!texture)
        return;

    QSize ts = texture->textureSize();
    QRectF sourceRect(0, 0, ts.width(), ts.height());
    QSGGeometry::updateTexturedRectGeometry(g, rect, texture->convertToNormalizedSourceRect(sourceRect));
}

/*!
  \class QSGSimpleTextureNode
  \brief The QSGSimpleTextureNode provided for convenience to easily draw
  textured content using the QML scene graph.

  \warning The simple texture node class must have texture before being
  added to the scene graph to be rendered.
*/

/*!
    Constructs a new simple texture node
 */
QSGSimpleTextureNode::QSGSimpleTextureNode()
    : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
    setGeometry(&m_geometry);
    setMaterial(&m_material);
    setOpaqueMaterial(&m_opaque_material);
}

/*!
    Sets the filtering to be used for this texture node to \a filtering.

    For smooth scaling, use QSGTexture::Linear; for normal scaling, use
    QSGTexture::Nearest.
 */
void QSGSimpleTextureNode::setFiltering(QSGTexture::Filtering filtering)
{
    if (m_material.filtering() == filtering)
        return;

    m_material.setFiltering(filtering);
    m_opaque_material.setFiltering(filtering);
    markDirty(DirtyMaterial);
}

/*!
    Returns the filtering currently set on this texture node
 */
QSGTexture::Filtering QSGSimpleTextureNode::filtering() const
{
    return m_material.filtering();
}

/*!
    Sets the target rect of this texture node to \a r
 */
void QSGSimpleTextureNode::setRect(const QRectF &r)
{
    if (m_rect == r)
        return;
    m_rect = r;
    qsgsimpletexturenode_update(&m_geometry, texture(), m_rect);
    markDirty(DirtyGeometry);
}

/*!
    Returns the target rect of this texture node.
 */
QRectF QSGSimpleTextureNode::rect() const
{
    return m_rect;
}

/*!
    Sets the texture of this texture node to \a texture.

    \warning A texture node must have a texture before being added
    to the scenegraph to be rendered.
 */
void QSGSimpleTextureNode::setTexture(QSGTexture *texture)
{
    if (m_material.texture() == texture)
        return;
    m_material.setTexture(texture);
    m_opaque_material.setTexture(texture);
    qsgsimpletexturenode_update(&m_geometry, texture, m_rect);
    markDirty(DirtyMaterial);
}

/*!
    Returns the texture for this texture node
 */
QSGTexture *QSGSimpleTextureNode::texture() const
{
    return m_material.texture();
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "AutoTypeExpression.h"

#include "../../declarations/VariableDeclaration.h"
#include "../../types/ErrorType.h"

#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(OOModel::AutoTypeExpression)

namespace OOModel {

COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression)

Type* AutoTypeExpression::type()
{
	auto t = dynamic_cast<OOModel::VariableDeclaration*>(parent());
	Q_ASSERT(t);
	if(t->initialValue()) return t->initialValue()->type();
	return new ErrorType("No initial value in auto type");
}

}
<commit_msg>Fix AutoTypeExpression type() resolution Add support for auto& and auto*<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "AutoTypeExpression.h"

#include "../../declarations/VariableDeclaration.h"
#include "../../types/ErrorType.h"

#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(OOModel::AutoTypeExpression)

namespace OOModel {

COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression)

Type* AutoTypeExpression::type()
{
	auto p = parent();
	VariableDeclaration* varDecl = nullptr;
	if(!(varDecl = dynamic_cast<VariableDeclaration*>(p)))
		varDecl = dynamic_cast<VariableDeclaration*>(p->parent());
	Q_ASSERT(varDecl);
	if(!varDecl->initialValue())
		return new ErrorType("No initial value in auto type");
	auto initType = varDecl->initialValue()->type();
	if(varDecl == p)
		return initType;
	if(dynamic_cast<ReferenceTypeExpression*>(p))
		return new ReferenceType(initType, initType->isValueType());
	if(dynamic_cast<PointerTypeExpression*>(p))
		return new PointerType(initType, initType->isValueType());
	// this can/should not happen
	Q_ASSERT(0);
	return nullptr;
}

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include "src/args/args.h"
#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/system/terminal.h"
#include "src/ext/x64asm/include/x64asm.h"

using namespace cpputil;
using namespace std;
using namespace x64asm;

auto& h1 = Heading::create("I/O options:");

auto& binary = ValueArg<string>::create("object")
	.usage("<path/to/bin>")
	.description("Object file to scrape code from")
	.default_val("./a.out");

auto& out_dir = ValueArg<string>::create("out")
  .alternate("o")
	.usage("<path/to/dir>")
  .description("Directory to write results to")
  .default_val("bins");

bool exists(const string& file) {
	ifstream temp(file);
	return temp.is_open();
}

bool symdump(const string& file) {
	Terminal term1;
	term1 << "nm -a " << file
		<< " | grep \" [WTti] \" | sed \"s/.* [WTti] //\" > /tmp/stoke.$USER.symdump" << endl;

	Terminal term2;
	term2 << "nm -D " << file
		<< " | grep \" [WTti] \" | sed \"s/.* [WTti] //\" >> /tmp/stoke.$USER.symdump" << endl;

  return term1.result() == 0 || term2.result() == 0;
}

bool objdump(const string& file) {
	Terminal term;
	term << "objdump -d -Msuffix " << file << " > /tmp/stoke.$USER.objdump" << endl;
	return term.result() == 0;
}

bool mkdir() {
	Terminal term;
  term << "mkdir -p " << out_dir.value() << endl;
  return term.result() == 0;
}

int main(int argc, char** argv) {
	CommandLineConfig::strict_with_convenience(argc, argv);

	if ( !exists(binary) ) {
		cout << "Unable to read binary file " << binary.value() << "!" << endl;
		return 1;
	} else if ( !symdump(binary) ) {
		cout << "Unable to extract symbols from binary file " << binary.value() << "!" << endl;
		return 1;
	} else if ( !objdump(binary) ) {
		cout << "Unable to extract object code from binary file " << binary.value() << "!" << endl;
    return 1;
	} else if ( !mkdir() ) {
    cout << "Unable to create output directory " << out_dir.value() << "!" << endl;
    return 1;
  }

	return 0;
}

<commit_msg>Using term instead of fstream for checking file.<commit_after>#include <iostream>
#include <string>

#include "src/args/args.h"
#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/system/terminal.h"
#include "src/ext/x64asm/include/x64asm.h"

using namespace cpputil;
using namespace std;
using namespace x64asm;

auto& h1 = Heading::create("I/O options:");

auto& binary = ValueArg<string>::create("object")
	.usage("<path/to/bin>")
	.description("Object file to scrape code from")
	.default_val("./a.out");

auto& out_dir = ValueArg<string>::create("out")
  .alternate("o")
	.usage("<path/to/dir>")
  .description("Directory to write results to")
  .default_val("bins");

bool exists(const string& file) {
	Terminal term;
	term << "ls " << file << endl;
	return term.result() == 0;
}

bool symdump(const string& file) {
	Terminal term1;
	term1 << "nm -a " << file
		<< " | grep \" [WTti] \" | sed \"s/.* [WTti] //\" > /tmp/stoke.$USER.symdump" << endl;

	Terminal term2;
	term2 << "nm -D " << file
		<< " | grep \" [WTti] \" | sed \"s/.* [WTti] //\" >> /tmp/stoke.$USER.symdump" << endl;

  return term1.result() == 0 || term2.result() == 0;
}

bool objdump(const string& file) {
	Terminal term;
	term << "objdump -d -Msuffix " << file << " > /tmp/stoke.$USER.objdump" << endl;
	return term.result() == 0;
}

bool mkdir() {
	Terminal term;
  term << "mkdir -p " << out_dir.value() << endl;
  return term.result() == 0;
}

int main(int argc, char** argv) {
	CommandLineConfig::strict_with_convenience(argc, argv);

	if ( !exists(binary) ) {
		cout << "Unable to read binary file " << binary.value() << "!" << endl;
		return 1;
	} else if ( !symdump(binary) ) {
		cout << "Unable to extract symbols from binary file " << binary.value() << "!" << endl;
		return 1;
	} else if ( !objdump(binary) ) {
		cout << "Unable to extract object code from binary file " << binary.value() << "!" << endl;
    return 1;
	} else if ( !mkdir() ) {
    cout << "Unable to create output directory " << out_dir.value() << "!" << endl;
    return 1;
  }

	return 0;
}

<|endoftext|>


<commit_before>#include "amd64.h"
#include "distribution.hh"
#include "spinbarrier.hh"
#include "libutil.h"

#include <fcntl.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>

#include <string>
#include <thread>

using std::string;

enum { warmup_secs = 1 };
enum { duration = 5 };

const char *message =
  "Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\n"
  "        by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\n"
  "        Tue, 19 Mar 2013 22:45:50 -0400\n"
  "X-Sieve: CMU Sieve 2.2\n"
  "Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\n"
  "        by incoming.csail.mit.edu with esmtps\n"
  "        (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\n"
  "        (Exim 4.72)\n"
  "        (envelope-from <xxxxxxxx@MIT.EDU>)\n"
  "        id 1UI92E-0007D2-7N\n"
  "        for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\n"
  "Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\n"
  "        by mailhub-auth-3.mit.edu (8.13.8/8.9.2) with ESMTP id r2K2jnO5025684\n"
  "        for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n"
  "Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\n"
  "        (authenticated bits=0)\n"
  "        (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\n"
  "        by outgoing.mit.edu (8.13.8/8.12.4) with ESMTP id r2K2jmc7032022\n"
  "        (version=TLSv1/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\n"
  "        for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n"
  "Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\n"
  "        (envelope-from <xxxxxxxx@mit.edu>)\n"
  "        id 1UI92C-0000il-4L\n"
  "        for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\n"
  "From: Austin Clements <xxxxxxxx@MIT.EDU>\n"
  "To: xxxxxxxx@mit.edu\n"
  "Subject: Test message\n"
  "User-Agent: Notmuch/0.15+6~g7d4cb73 (http://notmuchmail.org) Emacs/23.4.1\n"
  "        (i486-pc-linux-gnu)\n"
  "Date: Tue, 19 Mar 2013 22:45:48 -0400\n"
  "Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\n"
  "MIME-Version: 1.0\n"
  "Content-Type: text/plain; charset=us-ascii\n"
  "\n"
  "Hello.\n";

extern char **environ;

static spin_barrier bar;

static concurrent_distribution<uint64_t> start_tsc, stop_tsc;
static concurrent_distribution<uint64_t> start_usec, stop_usec;
static concurrent_distribution<uint64_t> count;

static volatile bool stop __mpalign__;
static volatile bool warmup;
static __padout__ __attribute__((unused));

static void
timer_thread(void)
{
  warmup = true;
  bar.join();
  bar.join();
  sleep(warmup_secs);
  warmup = false;
  sleep(duration);
  stop = true;
}

static void
do_mua(int cpu, string spooldir, string msgpath)
{
  const char *argv[] = {"./mail-enqueue", spooldir.c_str(), "user", nullptr};
#if defined(XV6_USER)
  int errno;
#endif
  setaffinity(cpu);

  // Open message file (alternatively, we could use an open spawn
  // action)
  int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC);
  if (msgfd < 0)
    edie("open %s failed", msgpath.c_str());

  bool mywarmup = true;
  uint64_t mycount = 0;
  while (!stop) {
    if (__builtin_expect(warmup != mywarmup, 0)) {
      mywarmup = warmup;
      mycount = 0;
      start_usec.add(now_usec());
      start_tsc.add(rdtsc());
    }

    pid_t pid;
    posix_spawn_file_actions_t actions;
    if ((errno = posix_spawn_file_actions_init(&actions)))
      edie("posix_spawn_file_actions_init failed");
    if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))
      edie("posix_spawn_file_actions_adddup2 failed");
    if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,
                             const_cast<char *const*>(argv), environ)))
      edie("posix_spawn failed");
    if ((errno = posix_spawn_file_actions_destroy(&actions)))
      edie("posix_spawn_file_actions_destroy failed");

    int status;
    if (waitpid(pid, &status, 0) < 0)
      edie("waitpid failed");
    if (!WIFEXITED(status) || WEXITSTATUS(status))
      die("deliver failed: status %d", status);

    ++mycount;
  }

  stop_usec.add(now_usec());
  stop_tsc.add(rdtsc());
  count.add(mycount);
}

static void
xmkdir(const string &d)
{
  if (mkdir(d.c_str(), 0777) < 0)
    edie("failed to mkdir %s", d.c_str());
}

static void
create_spool(const string &base)
{
  xmkdir(base);
  xmkdir(base + "/pid");
  xmkdir(base + "/todo");
  xmkdir(base + "/mess");
}

static void
create_maildir(const string &base)
{
  xmkdir(base);
  xmkdir(base + "/tmp");
  xmkdir(base + "/new");
  xmkdir(base + "/cur");
}

void
usage(const char *argv0)
{
  fprintf(stderr, "Usage: %s basedir nthreads\n", argv0);
  exit(2);
}

int
main(int argc, char **argv)
{
  if (argc != 3)
    usage(argv[0]);

  string basedir(argv[1]);
  const char *nthreads_str = argv[2];
  int nthreads = atoi(nthreads_str);
  if (nthreads <= 0)
    usage(argv[0]);

  // Create spool and inboxes
  // XXX This terminology is wrong.  The spool is where mail
  // ultimately gets delivered to.
  string spooldir = basedir + "/spool";
  create_spool(spooldir);
  string mailroot = basedir + "/mail";
  xmkdir(mailroot);
  create_maildir(mailroot + "/user");

  // Start queue manager
  const char *qman[] = {"./mail-qman", spooldir.c_str(), mailroot.c_str(),
                        nthreads_str, nullptr};
  pid_t qman_pid;
  if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr,
                  const_cast<char *const*>(qman), environ) != 0)
    die("posix_spawn %s failed", qman[0]);
  sleep(1);

  // Write message to a file
  int fd = open((basedir + "/msg").c_str(), O_CREAT|O_WRONLY, 0666);
  if (fd < 0)
    edie("open");
  xwrite(fd, message, strlen(message));
  close(fd);

  printf("# --cores=%d --duration=%ds\n", nthreads, duration);

  // Run benchmark
  bar.init(nthreads + 1);

  std::thread timer(timer_thread);

  std::thread *threads = new std::thread[nthreads];
  for (int i = 0; i < nthreads; ++i)
    threads[i] = std::thread(do_mua, i, basedir + "/spool", basedir + "/msg");

  // Wait
  timer.join();
  for (int i = 0; i < nthreads; ++i)
    threads[i].join();

  // XXX Kill qman and wait for it to exit

  // Summarize
  printf("%lu start usec skew\n", start_usec.span());
  printf("%lu stop usec skew\n", stop_usec.span());
  uint64_t usec = stop_usec.mean() - start_usec.mean();
  printf("%f secs\n", (double)usec / 1e6);
  printf("%lu cycles\n", stop_tsc.mean() - start_tsc.mean());

  uint64_t iters = count.sum();
  printf("%lu iters\n", iters);
  if (iters) {
    printf("%lu cycles/iter\n", (stop_tsc.sum() - start_tsc.sum()) / iters);
    printf("%lu iters/sec\n", iters * 1000000 / usec);
  }
}
<commit_msg>mailbench: Exit the queue manager<commit_after>#include "amd64.h"
#include "distribution.hh"
#include "spinbarrier.hh"
#include "libutil.h"

#include <fcntl.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>

#include <string>
#include <thread>

// Set to 1 to manage the queue manager's life time from this program.
// Set to 0 if the queue manager is started and stopped outside of
// mailbench.
#define START_QMAN 1

using std::string;

enum { warmup_secs = 1 };
enum { duration = 5 };

const char *message =
  "Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\n"
  "        by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\n"
  "        Tue, 19 Mar 2013 22:45:50 -0400\n"
  "X-Sieve: CMU Sieve 2.2\n"
  "Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\n"
  "        by incoming.csail.mit.edu with esmtps\n"
  "        (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\n"
  "        (Exim 4.72)\n"
  "        (envelope-from <xxxxxxxx@MIT.EDU>)\n"
  "        id 1UI92E-0007D2-7N\n"
  "        for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\n"
  "Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\n"
  "        by mailhub-auth-3.mit.edu (8.13.8/8.9.2) with ESMTP id r2K2jnO5025684\n"
  "        for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n"
  "Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\n"
  "        (authenticated bits=0)\n"
  "        (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\n"
  "        by outgoing.mit.edu (8.13.8/8.12.4) with ESMTP id r2K2jmc7032022\n"
  "        (version=TLSv1/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\n"
  "        for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\n"
  "Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\n"
  "        (envelope-from <xxxxxxxx@mit.edu>)\n"
  "        id 1UI92C-0000il-4L\n"
  "        for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\n"
  "From: Austin Clements <xxxxxxxx@MIT.EDU>\n"
  "To: xxxxxxxx@mit.edu\n"
  "Subject: Test message\n"
  "User-Agent: Notmuch/0.15+6~g7d4cb73 (http://notmuchmail.org) Emacs/23.4.1\n"
  "        (i486-pc-linux-gnu)\n"
  "Date: Tue, 19 Mar 2013 22:45:48 -0400\n"
  "Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\n"
  "MIME-Version: 1.0\n"
  "Content-Type: text/plain; charset=us-ascii\n"
  "\n"
  "Hello.\n";

extern char **environ;

static spin_barrier bar;

static concurrent_distribution<uint64_t> start_tsc, stop_tsc;
static concurrent_distribution<uint64_t> start_usec, stop_usec;
static concurrent_distribution<uint64_t> count;

static volatile bool stop __mpalign__;
static volatile bool warmup;
static __padout__ __attribute__((unused));

static void
timer_thread(void)
{
  warmup = true;
  bar.join();
  bar.join();
  sleep(warmup_secs);
  warmup = false;
  sleep(duration);
  stop = true;
}

static void
xwaitpid(int pid, const char *cmd)
{
  int status;
  if (waitpid(pid, &status, 0) < 0)
    edie("waitpid %s failed", cmd);
  if (!WIFEXITED(status) || WEXITSTATUS(status))
    die("status %d from %s", status, cmd);
}

static void
do_mua(int cpu, string spooldir, string msgpath)
{
  const char *argv[] = {"./mail-enqueue", spooldir.c_str(), "user", nullptr};
#if defined(XV6_USER)
  int errno;
#endif
  setaffinity(cpu);

  // Open message file (alternatively, we could use an open spawn
  // action)
  int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC);
  if (msgfd < 0)
    edie("open %s failed", msgpath.c_str());

  bool mywarmup = true;
  uint64_t mycount = 0;
  while (!stop) {
    if (__builtin_expect(warmup != mywarmup, 0)) {
      mywarmup = warmup;
      mycount = 0;
      start_usec.add(now_usec());
      start_tsc.add(rdtsc());
    }

    pid_t pid;
    posix_spawn_file_actions_t actions;
    if ((errno = posix_spawn_file_actions_init(&actions)))
      edie("posix_spawn_file_actions_init failed");
    if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))
      edie("posix_spawn_file_actions_adddup2 failed");
    if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,
                             const_cast<char *const*>(argv), environ)))
      edie("posix_spawn failed");
    if ((errno = posix_spawn_file_actions_destroy(&actions)))
      edie("posix_spawn_file_actions_destroy failed");
    xwaitpid(pid, argv[0]);

    ++mycount;
  }

  stop_usec.add(now_usec());
  stop_tsc.add(rdtsc());
  count.add(mycount);
}

static void
xmkdir(const string &d)
{
  if (mkdir(d.c_str(), 0777) < 0)
    edie("failed to mkdir %s", d.c_str());
}

static void
create_spool(const string &base)
{
  xmkdir(base);
  xmkdir(base + "/pid");
  xmkdir(base + "/todo");
  xmkdir(base + "/mess");
}

static void
create_maildir(const string &base)
{
  xmkdir(base);
  xmkdir(base + "/tmp");
  xmkdir(base + "/new");
  xmkdir(base + "/cur");
}

void
usage(const char *argv0)
{
  fprintf(stderr, "Usage: %s basedir nthreads\n", argv0);
  exit(2);
}

int
main(int argc, char **argv)
{
  if (argc != 3)
    usage(argv[0]);

  string basedir(argv[1]);
  const char *nthreads_str = argv[2];
  int nthreads = atoi(nthreads_str);
  if (nthreads <= 0)
    usage(argv[0]);

  // Create spool and inboxes
  // XXX This terminology is wrong.  The spool is where mail
  // ultimately gets delivered to.
  string spooldir = basedir + "/spool";
  if (START_QMAN)
    create_spool(spooldir);
  string mailroot = basedir + "/mail";
  xmkdir(mailroot);
  create_maildir(mailroot + "/user");

  pid_t qman_pid;
  if (START_QMAN) {
    // Start queue manager
    const char *qman[] = {"./mail-qman", spooldir.c_str(), mailroot.c_str(),
                          nthreads_str, nullptr};
    if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr,
                    const_cast<char *const*>(qman), environ) != 0)
      die("posix_spawn %s failed", qman[0]);
    sleep(1);
  }

  // Write message to a file
  int fd = open((basedir + "/msg").c_str(), O_CREAT|O_WRONLY, 0666);
  if (fd < 0)
    edie("open");
  xwrite(fd, message, strlen(message));
  close(fd);

  printf("# --cores=%d --duration=%ds\n", nthreads, duration);

  // Run benchmark
  bar.init(nthreads + 1);

  std::thread timer(timer_thread);

  std::thread *threads = new std::thread[nthreads];
  for (int i = 0; i < nthreads; ++i)
    threads[i] = std::thread(do_mua, i, basedir + "/spool", basedir + "/msg");

  // Wait
  timer.join();
  for (int i = 0; i < nthreads; ++i)
    threads[i].join();

  if (START_QMAN) {
    // Kill qman and wait for it to exit
    const char *enq[] = {"./mail-enqueue", "--exit", spooldir.c_str(), nullptr};
    pid_t enq_pid;
    if (posix_spawn(&enq_pid, enq[0], nullptr, nullptr,
                    const_cast<char *const*>(enq), environ) != 0)
      die("posix_spawn %s failed", enq[0]);
    xwaitpid(enq_pid, "mail-enqueue --exit");
    xwaitpid(qman_pid, "mail-qman");
  }

  // Summarize
  printf("%lu start usec skew\n", start_usec.span());
  printf("%lu stop usec skew\n", stop_usec.span());
  uint64_t usec = stop_usec.mean() - start_usec.mean();
  printf("%f secs\n", (double)usec / 1e6);
  printf("%lu cycles\n", stop_tsc.mean() - start_tsc.mean());

  uint64_t iters = count.sum();
  printf("%lu iters\n", iters);
  if (iters) {
    printf("%lu cycles/iter\n", (stop_tsc.sum() - start_tsc.sum()) / iters);
    printf("%lu iters/sec\n", iters * 1000000 / usec);
  }

  printf("\n");
}
<|endoftext|>


<commit_before>/**
 * Copyright 2007-2013 IMP Inventors. All rights reserved.
 */

#include <exception>
#include <iostream>
#include <sstream>
#include <string>

#include "RMF/FileConstHandle.h"
#include "RMF/ID.h"
#include "RMF/info.h"
#include "common.h"

namespace {
std::string description("Print out information about categories and keys.");

unsigned int frame = 0;
}

int main(int argc, char** argv) {
  try {
    options.add_options()("frame,f",
                          boost::program_options::value<unsigned int>(&frame),
                          "Frame to use");
    RMF_ADD_INPUT_FILE("rmf");
    process_options(argc, argv);

    RMF::FileConstHandle rh = RMF::open_rmf_file_read_only(input);
    if (!rh.get_description().empty()) {
      std::cout << "description: " << rh.get_description();
    }
    rh.set_current_frame(RMF::FrameID(frame));
    std::cout << "frames: " << rh.get_number_of_frames() << std::endl;
    RMF::show_info(rh, std::cout);
    return 0;
  }
  catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
}
<commit_msg>print producer when set<commit_after>/**
 * Copyright 2007-2013 IMP Inventors. All rights reserved.
 */

#include <exception>
#include <iostream>
#include <sstream>
#include <string>

#include "RMF/FileConstHandle.h"
#include "RMF/ID.h"
#include "RMF/info.h"
#include "common.h"

namespace {
std::string description("Print out information about categories and keys.");

unsigned int frame = 0;
}

int main(int argc, char** argv) {
  try {
    options.add_options()("frame,f",
                          boost::program_options::value<unsigned int>(&frame),
                          "Frame to use");
    RMF_ADD_INPUT_FILE("rmf");
    process_options(argc, argv);

    RMF::FileConstHandle rh = RMF::open_rmf_file_read_only(input);
    if (!rh.get_description().empty()) {
      std::cout << "description: " << rh.get_description() << std::endl;
    }
    if (!rh.get_producer().empty()) {
      std::cout << "producer: " << rh.get_producer() << std::endl;
    }
    rh.set_current_frame(RMF::FrameID(frame));
    std::cout << "frames: " << rh.get_number_of_frames() << std::endl;
    RMF::show_info(rh, std::cout);
    return 0;
  }
  catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
}
<|endoftext|>


<commit_before>// $Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.4 2000/10/17 17:22:12 anker Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

// insert includes here
#include <BALL/KERNEL/system.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/FORMAT/INIFile.h>
#include <BALL/MOLMEC/COMMON/radiusRuleProcessor.h>
#include <BALL/SOLVATION/pair6_12InteractionEnergyProcessor.h>

///////////////////////////

START_TEST(class_name, "$Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.4 2000/10/17 17:22:12 anker Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;
using namespace std;

///  insert tests for each member function here
///

// GROSSBAUSTELLE

Pair6_12InteractionEnergyProcessor* pointer;

CHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor())
	pointer = new Pair6_12InteractionEnergyProcessor;
	TEST_NOT_EQUAL(pointer, 0)
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::~Pair6_12InteractionEnergyProcessor())
	delete pointer;
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor(const Pair6_12InteractionEnergyProcessor& proc))
	Pair6_12InteractionEnergyProcessor proc1;
	Pair6_12InteractionEnergyProcessor proc2(proc1);
	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::clear())
	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::operator = (const Pair6_12InteractionEnergyProcessor& proc))
	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::finish())
	PRECISION(0.0001)
	System S;
	HINFile f("data/6_12-test.hin");
	f >> S;
	f.close();
	INIFile ini("data/6_12-test.rul");
	ini.read();
	RadiusRuleProcessor radius_rules;
	radius_rules.initialize(ini, "RadiusRules");
	S.apply(radius_rules);

	Pair6_12InteractionEnergyProcessor proc;
	proc.options.readOptionFile("data/6_12-test.options");

	S.apply(proc);
	double val = proc.getEnergy();
	TEST_REAL_EQUAL(val, -6.027207050)

	proc.options.setBool(Pair6_12InteractionEnergyProcessor::Option::USE_RDF,
			true);
	S.apply(proc);
	val = proc.getEnergy();
	TEST_REAL_EQUAL(val, -6.027207050)

	proc.options.set(Pair6_12InteractionEnergyProcessor::Option::RDF_FILENAME,
	"data/6_12-test.rdf.ini");
	S.apply(proc);
	val = proc.getEnergy();
	TEST_REAL_EQUAL(val, -6.027207050)
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::isValid())
	Pair6_12InteractionEnergyProcessor proc;
	TEST_EQUAL(proc.isValid(), false)

	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::operator == ())
  // BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: RDF call with proper filename<commit_after>// $Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.5 2000/11/14 19:13:06 anker Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

// insert includes here
#include <BALL/KERNEL/system.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/FORMAT/INIFile.h>
#include <BALL/MOLMEC/COMMON/radiusRuleProcessor.h>
#include <BALL/SOLVATION/pair6_12InteractionEnergyProcessor.h>

///////////////////////////

START_TEST(class_name, "$Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.5 2000/11/14 19:13:06 anker Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;
using namespace std;

///  insert tests for each member function here
///

// GROSSBAUSTELLE

Pair6_12InteractionEnergyProcessor* pointer;

CHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor())
	pointer = new Pair6_12InteractionEnergyProcessor;
	TEST_NOT_EQUAL(pointer, 0)
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::~Pair6_12InteractionEnergyProcessor())
	delete pointer;
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor(const Pair6_12InteractionEnergyProcessor& proc))
	Pair6_12InteractionEnergyProcessor proc1;
	Pair6_12InteractionEnergyProcessor proc2(proc1);
	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::clear())
	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::operator = (const Pair6_12InteractionEnergyProcessor& proc))
	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::finish())
	PRECISION(0.0001)
	System S;
	HINFile f("data/6_12-test.hin");
	f >> S;
	f.close();
	INIFile ini("data/6_12-test.rul");
	ini.read();
	RadiusRuleProcessor radius_rules;
	radius_rules.initialize(ini, "RadiusRules");
	S.apply(radius_rules);

	Pair6_12InteractionEnergyProcessor proc;
	proc.options.readOptionFile("data/6_12-test.options");

	S.apply(proc);
	double val = proc.getEnergy();
	TEST_REAL_EQUAL(val, -6.027207050)

	proc.options.set(Pair6_12InteractionEnergyProcessor::Option::RDF_FILENAME,
	"data/6_12-test.rdf-fake.ini");
	proc.options.setBool(Pair6_12InteractionEnergyProcessor::Option::USE_RDF,
			true);
	S.apply(proc);
	val = proc.getEnergy();
	TEST_REAL_EQUAL(val, -6.027207050)

	proc.options.set(Pair6_12InteractionEnergyProcessor::Option::RDF_FILENAME,
	"data/6_12-test.rdf.ini");
	S.apply(proc);
	val = proc.getEnergy();
	TEST_REAL_EQUAL(val, -6.027207050)

	// BAUSTELLE: USE_RDF=true geht trotz nicht gesetzten Dateinamens!!!
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::isValid())
	Pair6_12InteractionEnergyProcessor proc;
	TEST_EQUAL(proc.isValid(), false)

	// BAUSTELLE
RESULT

CHECK(Pair6_12InteractionEnergyProcessor::operator == ())
  // BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * BP3Zfp.tcc :
 *
 *  Created on: Jul 18, 2018
 *      Author: William F Godoy godoywf@ornl.gov
 */

#ifndef ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_
#define ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_

#include "BP3Zfp.h"

#include "adios2/helper/adiosFunctions.h"

namespace adios2
{
namespace format
{

template <class T>
void BP3Zfp::SetDataCommon(
    const core::Variable<T> &variable,
    const typename core::Variable<T>::Info &blockInfo,
    const typename core::Variable<T>::Operation &operation,
    BufferSTL &bufferSTL) const noexcept
{
    const core::Operator &op = *operation.Op;
    const Params &parameters = operation.Parameters;

    const size_t outputSize = op.Compress(
        blockInfo.Data, blockInfo.Count, variable.m_ElementSize,
        variable.m_Type, bufferSTL.m_Buffer.data() + bufferSTL.m_Position,
        parameters);

    // being naughty here
    Params &info = const_cast<Params &>(operation.Info);
    info["OutputSize"] = std::to_string(outputSize);

    bufferSTL.m_Position += outputSize;
    bufferSTL.m_AbsolutePosition += outputSize;
}

template <class T>
void BP3Zfp::SetMetadataCommon(
    const core::Variable<T> &variable,
    const typename core::Variable<T>::Info &blockInfo,
    const typename core::Variable<T>::Operation &operation,
    std::vector<char> &buffer) const noexcept
{
    const uint64_t inputSize =
        helper::GetTotalSize(blockInfo.Count) * sizeof(T);
    // being naughty here
    Params &info = const_cast<Params &>(operation.Info);
    info["InputSize"] = std::to_string(inputSize);

    const uint64_t outputSize = 0; // not known yet

    auto itMode = operation.Parameters.find("accuracy");
    int32_t mode = -1;

    if (itMode != operation.Parameters.end())
    {
        mode = static_cast<int32_t>(zfp_mode_accuracy);
    }
    else
    {
        itMode = operation.Parameters.find("precision");
        if (itMode != operation.Parameters.end())
        {
            mode = static_cast<int32_t>(zfp_mode_precision);
        }
        itMode = operation.Parameters.find("rate");
        if (itMode != operation.Parameters.end())
        {
            mode = static_cast<int32_t>(zfp_mode_rate);
        }
    }
    const std::string modeStr = itMode->second;

    // fixed size
    constexpr uint16_t metadataSize = 532;
    helper::InsertToBuffer(buffer, &metadataSize);
    helper::InsertToBuffer(buffer, &inputSize);
    // to be filled out after operation is applied on data
    info["OutputSizeMetadataPosition"] = std::to_string(buffer.size());
    helper::InsertToBuffer(buffer, &outputSize);
    helper::InsertToBuffer(buffer, &mode);

    const size_t fixedRecordsPosition = buffer.size();
    buffer.resize(fixedRecordsPosition + 512, '\0');
    size_t backPosition = fixedRecordsPosition;
    helper::CopyToBuffer(buffer, backPosition, modeStr.data(), modeStr.size());
    backPosition = fixedRecordsPosition + 256;
    helper::CopyToBuffer(buffer, backPosition, variable.m_Name.data(),
                         variable.m_Name.size());
}

template <class T>
void BP3Zfp::UpdateMetadataCommon(
    const core::Variable<T> &variable,
    const typename core::Variable<T>::Info &blockInfo,
    const typename core::Variable<T>::Operation &operation,
    std::vector<char> &buffer) const noexcept
{
    const uint64_t outputSize =
        static_cast<uint64_t>(std::stoll(operation.Info.at("OutputSize")));

    size_t backPosition = static_cast<size_t>(
        std::stoll(operation.Info.at("OutputSizeMetadataPosition")));

    helper::CopyToBuffer(buffer, backPosition, &outputSize);

    // being naughty here
    Params &info = const_cast<Params &>(operation.Info);
    info.erase("OutputSizeMetadataPosition");
}

} // end namespace format
} // end namespace adios2

#endif /* ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_H_ */
<commit_msg>Fixed crash when using ZFP compression under fixed-precision mode<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * BP3Zfp.tcc :
 *
 *  Created on: Jul 18, 2018
 *      Author: William F Godoy godoywf@ornl.gov
 */

#ifndef ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_
#define ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_

#include "BP3Zfp.h"

#include "adios2/helper/adiosFunctions.h"

namespace adios2
{
namespace format
{

template <class T>
void BP3Zfp::SetDataCommon(
    const core::Variable<T> &variable,
    const typename core::Variable<T>::Info &blockInfo,
    const typename core::Variable<T>::Operation &operation,
    BufferSTL &bufferSTL) const noexcept
{
    const core::Operator &op = *operation.Op;
    const Params &parameters = operation.Parameters;

    const size_t outputSize = op.Compress(
        blockInfo.Data, blockInfo.Count, variable.m_ElementSize,
        variable.m_Type, bufferSTL.m_Buffer.data() + bufferSTL.m_Position,
        parameters);

    // being naughty here
    Params &info = const_cast<Params &>(operation.Info);
    info["OutputSize"] = std::to_string(outputSize);

    bufferSTL.m_Position += outputSize;
    bufferSTL.m_AbsolutePosition += outputSize;
}

template <class T>
void BP3Zfp::SetMetadataCommon(
    const core::Variable<T> &variable,
    const typename core::Variable<T>::Info &blockInfo,
    const typename core::Variable<T>::Operation &operation,
    std::vector<char> &buffer) const noexcept
{
    const uint64_t inputSize =
        helper::GetTotalSize(blockInfo.Count) * sizeof(T);
    // being naughty here
    Params &info = const_cast<Params &>(operation.Info);
    info["InputSize"] = std::to_string(inputSize);

    const uint64_t outputSize = 0; // not known yet

    auto itMode = operation.Parameters.find("accuracy");
    int32_t mode = -1;

    if (itMode != operation.Parameters.end())
    {
        mode = static_cast<int32_t>(zfp_mode_accuracy);
    }
    else
    {
        itMode = operation.Parameters.find("precision");
        if (itMode != operation.Parameters.end())
        {
            mode = static_cast<int32_t>(zfp_mode_precision);
        }
        else
        {
            itMode = operation.Parameters.find("rate");
            if (itMode != operation.Parameters.end())
            {
                mode = static_cast<int32_t>(zfp_mode_rate);
            }
        }
    }
    const std::string modeStr = itMode->second;

    // fixed size
    constexpr uint16_t metadataSize = 532;
    helper::InsertToBuffer(buffer, &metadataSize);
    helper::InsertToBuffer(buffer, &inputSize);
    // to be filled out after operation is applied on data
    info["OutputSizeMetadataPosition"] = std::to_string(buffer.size());
    helper::InsertToBuffer(buffer, &outputSize);
    helper::InsertToBuffer(buffer, &mode);

    const size_t fixedRecordsPosition = buffer.size();
    buffer.resize(fixedRecordsPosition + 512, '\0');
    size_t backPosition = fixedRecordsPosition;
    helper::CopyToBuffer(buffer, backPosition, modeStr.data(), modeStr.size());
    backPosition = fixedRecordsPosition + 256;
    helper::CopyToBuffer(buffer, backPosition, variable.m_Name.data(),
                         variable.m_Name.size());
}

template <class T>
void BP3Zfp::UpdateMetadataCommon(
    const core::Variable<T> &variable,
    const typename core::Variable<T>::Info &blockInfo,
    const typename core::Variable<T>::Operation &operation,
    std::vector<char> &buffer) const noexcept
{
    const uint64_t outputSize =
        static_cast<uint64_t>(std::stoll(operation.Info.at("OutputSize")));

    size_t backPosition = static_cast<size_t>(
        std::stoll(operation.Info.at("OutputSizeMetadataPosition")));

    helper::CopyToBuffer(buffer, backPosition, &outputSize);

    // being naughty here
    Params &info = const_cast<Params &>(operation.Info);
    info.erase("OutputSizeMetadataPosition");
}

} // end namespace format
} // end namespace adios2

#endif /* ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_H_ */
<|endoftext|>


<commit_before>#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <unordered_map>
#include <queue>
#include <deque>
#include <random>
#include <boost/bind.hpp>
#include <boost/coroutine/all.hpp>
#include <boost/coroutine/coroutine.hpp>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include "truncater.hpp"

typedef std::vector<std::vector<point_type>> matrix_type;
struct evaluate_set_type
{
    matrix_type matrix;
    point_type position;//場所
    point_type content;
    int score;
    std::string direct;
};

// class definition {{{1
class truncater::impl : boost::noncopyable
{
public:
    typedef truncater::return_type return_type;

    impl() = default;
    virtual ~impl() = default;

    auto get() -> boost::optional<return_type>;
    void reset(question_data const& data);

private:
    void process(boost::coroutines::coroutine<return_type>::push_type& yield);
    void operator() (boost::coroutines::coroutine<return_type>::push_type& yield);

    boost::optional<question_data> data_;
    boost::coroutines::coroutine<return_type>::pull_type co_;

    void ymove();
    int form_evaluate(matrix_type const& mat);
    point_type get_start_point(matrix_type const& mat);
    int eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position);
    evaluate_set_type try_u(evaluate_set_type return_set);
    evaluate_set_type try_r(evaluate_set_type return_set);
    evaluate_set_type try_d(evaluate_set_type return_set);
    evaluate_set_type try_l(evaluate_set_type return_set);

    matrix_type matrix;
    answer_type answer;
    int width;
    int height;
    int selectable;
};

// interfaces for Boost.Coroutine {{{1
truncater::truncater()
    : pimpl_(new impl())
{
}

truncater::~truncater()
{
    delete pimpl_;
}

auto truncater::get() -> boost::optional<return_type>
{
    return pimpl_->get();
}

void truncater::reset(question_data const& data)
{
    pimpl_->reset(data);
}

auto truncater::impl::get() -> boost::optional<return_type>
{
    if(co_ && data_)
    {
        auto&& result = co_.get();
        co_();
        return result;
    }
    return boost::none;
}

void truncater::impl::reset(question_data const& data)
{
    data_ = data.clone();
    co_   = boost::coroutines::coroutine<return_type>::pull_type(
            boost::bind(&impl::process, this, _1)
            );
}

void truncater::impl::process(boost::coroutines::coroutine<return_type>::push_type& yield)
{
    // 訳ありで転送するだけの関数
    (*this)(yield);
}

// yoshikawa {{{1
int truncater::impl::form_evaluate(matrix_type const& mat)
{
    int s = 0;
    for (int i = 0; i < mat.size(); ++i)
    {
        for (int j = 0; j < mat.at(0).size(); ++j)
        {
            s += mat[i][j].manhattan_pow({ j, i });
        }
    }
    return s;
}

point_type truncater::impl::get_start_point(matrix_type const& mat)
{
    int max_val = 0;
    point_type max_point;//実態
    point_type position;

    for (int i = 0; i < mat.size(); ++i)
    {
        for (int j = 0; j < mat.at(0).size(); ++j)
        {
            int temp = mat[i][j].manhattan_pow({ j, i });
            if (temp > max_val)
            {
                max_val = temp;
                max_point = point_type{ j, i };
                position = point_type{ mat[i][j].x, mat[i][j].y };
            }
        }
    }
    return position;
}

int truncater::impl::eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position)
{
    int s = 0;
    point_type const& content_a = eval_set.matrix[eval_set.position.y][eval_set.position.x];
    //aの新しい場所からの距離
    s += content_a.manhattan_pow(new_position);
    //aの古い場所からの距離
    s -= content_a.manhattan_pow(eval_set.position);
    point_type const& content_b = eval_set.matrix[new_position.y][new_position.x];
    //bの新しい場所からの距離
    s += content_b.manhattan_pow(eval_set.position);
    //bの古い場所からの距離
    s -= content_b.manhattan_pow(new_position);

    //assert(s == -2 || s == 0 || s == 2);
    return s;
}

evaluate_set_type truncater::impl::try_u(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x, return_set.position.y - 1 };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "U";
    return_set.position = new_position;
    return std::move(return_set);
}

evaluate_set_type truncater::impl::try_r(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x + 1, return_set.position.y };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "R";
    return_set.position = new_position;
    return std::move(return_set);
}

evaluate_set_type truncater::impl::try_d(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x, return_set.position.y + 1 };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "D";
    return_set.position = new_position;
    return std::move(return_set);
}

evaluate_set_type truncater::impl::try_l(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x - 1, return_set.position.y };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "L";
    return_set.position = new_position;
    return std::move(return_set);
}

void truncater::impl::ymove()
{
    std::cout << "ymove start" << std::endl;

    int const width = matrix.at(0).size();
    int const height = matrix.size();

    std::queue<evaluate_set_type> que;
    std::vector<evaluate_set_type> children;
    children.reserve(900);

    point_type const start_position = get_start_point(matrix);
    evaluate_set_type start = evaluate_set_type{ matrix, start_position, matrix[start_position.y][start_position.x], form_evaluate(start.matrix), " " };
    evaluate_set_type best = start;

    que.push(start);

    //std::cout << "select piece position = " << start.position << std::endl;
    //std::cout << "select piece content = " << start.content << std::endl;

    auto P = [](int e, int ne, double T) {
        if( ne < e ) {
            return 1.0;
        } else {
            return std::exp((e - ne)/T);
        }
    };
    double T = 1000.0;

    std::random_device sec_rng;
    std::mt19937 mt(sec_rng());
    std::uniform_real_distribution<double> prob_dist(0.0, 1.0);
    auto prob = [&]{return prob_dist(mt);};

    auto is_transition = [&](int s, int ns) {
        return prob() < P(s, ns, T);
    };

    while (que.size() > 0 && T > 1.0)
    {
        //std::cout << "T = " << T << ", score = " << best.score << " que size = " << que.size() << std::endl;
        while (que.size() > 0)
        {
            auto const node = que.front();
            que.pop();

            if (best.score > node.score) best = node;

            if (node.position.y != 0 && node.direct.back() != 'D')
            {
                auto child = try_u(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
            if (node.position.x != width - 1 && node.direct.back() != 'L')
            {
                auto child = try_r(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
            if (node.position.y != height - 1 && node.direct.back() != 'U')
            {
                auto child = try_d(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
            if (node.position.x != 0 && node.direct.back() != 'R')
            {
                auto child = try_l(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
        }

        std::sort(children.begin(), children.end(), [](evaluate_set_type a, evaluate_set_type b){return a.score < b.score; });

        for (int i = 0; i < children.size() && i < 100; ++i)
        {
            que.push(children.at(i));
        }

        children.clear();

        T *= 0.95;
    }

    matrix = best.matrix;
    answer.list.push_back({ start_position, best.direct.substr(1) });

    std::cout << "ymove done." << std::endl;
}

// operator() {{{1
void truncater::impl::operator() (boost::coroutines::coroutine<return_type>::push_type& yield)
{
    algorithm algo;
    matrix = data_->block;
    width = data_->size.first;
    height = data_->size.second;
    selectable = data_->selectable;

    if ((width > 3 || height > 3) && selectable >= 3) ymove();

    auto qdata = question_data(
        data_->problem_id,
        data_->player_id,
        data_->size,
        data_->selectable,
        data_->cost_change,
        data_->cost_change,
        std::move(matrix)
    );
    algo.reset(std::move(qdata));
    answer_type subsequent_answer = *algo.get();
    std::copy(subsequent_answer.list.begin(), subsequent_answer.list.end(), std::back_inserter(answer.list));
    yield(std::move(answer));
}
<commit_msg>Update truncater.cpp<commit_after>#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <unordered_map>
#include <queue>
#include <deque>
#include <random>
#include <boost/bind.hpp>
#include <boost/coroutine/all.hpp>
#include <boost/coroutine/coroutine.hpp>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include "truncater.hpp"

typedef std::vector<std::vector<point_type>> matrix_type;
struct evaluate_set_type
{
    matrix_type matrix;
    point_type position;//場所
    point_type content;
    int score;
    std::string direct;
};

// class definition {{{1
class truncater::impl : boost::noncopyable
{
public:
    typedef truncater::return_type return_type;

    impl() = default;
    virtual ~impl() = default;

    auto get() -> boost::optional<return_type>;
    void reset(question_data const& data);

private:
    void process(boost::coroutines::coroutine<return_type>::push_type& yield);
    void operator() (boost::coroutines::coroutine<return_type>::push_type& yield);

    boost::optional<question_data> data_;
    boost::coroutines::coroutine<return_type>::pull_type co_;

    void ymove();
    int form_evaluate(matrix_type const& mat);
    point_type get_start_point(matrix_type const& mat);
    int eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position);
    evaluate_set_type try_u(evaluate_set_type return_set);
    evaluate_set_type try_r(evaluate_set_type return_set);
    evaluate_set_type try_d(evaluate_set_type return_set);
    evaluate_set_type try_l(evaluate_set_type return_set);

    matrix_type matrix;
    answer_type answer;
    int width;
    int height;
    int selectable;
};

// interfaces for Boost.Coroutine {{{1
truncater::truncater()
    : pimpl_(new impl())
{
}

truncater::~truncater()
{
    delete pimpl_;
}

auto truncater::get() -> boost::optional<return_type>
{
    return pimpl_->get();
}

void truncater::reset(question_data const& data)
{
    pimpl_->reset(data);
}

auto truncater::impl::get() -> boost::optional<return_type>
{
    if(co_ && data_)
    {
        auto&& result = co_.get();
        co_();
        return result;
    }
    return boost::none;
}

void truncater::impl::reset(question_data const& data)
{
    data_ = data.clone();
    co_   = boost::coroutines::coroutine<return_type>::pull_type(
            boost::bind(&impl::process, this, _1)
            );
}

void truncater::impl::process(boost::coroutines::coroutine<return_type>::push_type& yield)
{
    // 訳ありで転送するだけの関数
    (*this)(yield);
}

// yoshikawa {{{1
int truncater::impl::form_evaluate(matrix_type const& mat)
{
    int s = 0;
    for (int i = 0; i < mat.size(); ++i)
    {
        for (int j = 0; j < mat.at(0).size(); ++j)
        {
            s += mat[i][j].manhattan_pow({ j, i });
        }
    }
    return s;
}

point_type truncater::impl::get_start_point(matrix_type const& mat)
{
    int max_val = 0;
    point_type max_point;//実態
    point_type position;

    for (int i = 0; i < mat.size(); ++i)
    {
        for (int j = 0; j < mat.at(0).size(); ++j)
        {
            int temp = mat[i][j].manhattan_pow({ j, i });
            if (temp > max_val)
            {
                max_val = temp;
                max_point = point_type{ j, i };
                position = point_type{ mat[i][j].x, mat[i][j].y };
            }
        }
    }
    return position;
}

int truncater::impl::eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position)
{
    int s = 0;
    point_type const& content_a = eval_set.matrix[eval_set.position.y][eval_set.position.x];
    //aの新しい場所からの距離
    s += content_a.manhattan_pow(new_position);
    //aの古い場所からの距離
    s -= content_a.manhattan_pow(eval_set.position);
    point_type const& content_b = eval_set.matrix[new_position.y][new_position.x];
    //bの新しい場所からの距離
    s += content_b.manhattan_pow(eval_set.position);
    //bの古い場所からの距離
    s -= content_b.manhattan_pow(new_position);

    //assert(s == -2 || s == 0 || s == 2);
    return s;
}

evaluate_set_type truncater::impl::try_u(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x, return_set.position.y - 1 };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "U";
    return_set.position = new_position;
    return std::move(return_set);
}

evaluate_set_type truncater::impl::try_r(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x + 1, return_set.position.y };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "R";
    return_set.position = new_position;
    return std::move(return_set);
}

evaluate_set_type truncater::impl::try_d(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x, return_set.position.y + 1 };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "D";
    return_set.position = new_position;
    return std::move(return_set);
}

evaluate_set_type truncater::impl::try_l(evaluate_set_type return_set)
{
    point_type const& new_position = { return_set.position.x - 1, return_set.position.y };
    return_set.score += eval_two_piece(return_set, new_position);
    std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);
    return_set.direct += "L";
    return_set.position = new_position;
    return std::move(return_set);
}

void truncater::impl::ymove()
{
    std::cout << "ymove start" << std::endl;

    int const width = matrix.at(0).size();
    int const height = matrix.size();

    std::queue<evaluate_set_type> que;
    std::vector<evaluate_set_type> children;
    children.reserve(900);

    point_type const start_position = get_start_point(matrix);
    evaluate_set_type start = evaluate_set_type{ matrix, start_position, matrix[start_position.y][start_position.x], form_evaluate(start.matrix), " " };
    evaluate_set_type best = start;

    que.push(start);

    //std::cout << "select piece position = " << start.position << std::endl;
    //std::cout << "select piece content = " << start.content << std::endl;

    auto P = [](int e, int ne, double T) {
        if( ne < e ) {
            return 1.0;
        } else {
            return std::exp((e - ne)/T);
        }
    };
    double T = 1000.0;

    std::random_device sec_rng;
    std::mt19937 mt(sec_rng());
    std::uniform_real_distribution<double> prob_dist(0.0, 1.0);
    auto prob = [&]{return prob_dist(mt);};

    auto is_transition = [&](int s, int ns) {
        return prob() < P(s, ns, T);
    };

    while (que.size() > 0 && T > 1.0)
    {
        //std::cout << "T = " << T << ", score = " << best.score << " que size = " << que.size() << std::endl;
        while (que.size() > 0)
        {
            auto const node = que.front();
            que.pop();

            if (best.score > node.score) best = node;

            if (node.position.y != 0 && node.direct.back() != 'D')
            {
                auto child = try_u(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
            if (node.position.x != width - 1 && node.direct.back() != 'L')
            {
                auto child = try_r(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
            if (node.position.y != height - 1 && node.direct.back() != 'U')
            {
                auto child = try_d(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
            if (node.position.x != 0 && node.direct.back() != 'R')
            {
                auto child = try_l(node);
                //if (child.score <= node.score)
                if (is_transition(node.score, child.score))
                {
                    children.push_back(std::move(child));
                }
            }
        }

        std::sort(children.begin(), children.end(), [](evaluate_set_type a, evaluate_set_type b){return a.score < b.score; });

        for (int i = 0; i < children.size() && i < 100; ++i)
        {
            que.push(children.at(i));
        }

        children.clear();

        T *= 0.95;
    }

    matrix = best.matrix;
    answer.list.push_back({ start_position, best.direct.substr(1) });

    std::cout << "ymove done." << std::endl;
}

// operator() {{{1
void truncater::impl::operator() (boost::coroutines::coroutine<return_type>::push_type& yield)
{
    algorithm algo;
    matrix = data_->block;
    width = data_->size.first;
    height = data_->size.second;
    selectable = data_->selectable;

    if ((width > 3 || height > 3) && selectable >= 3) ymove();

    auto qdata = question_data(
        data_->problem_id,
        data_->player_id,
        data_->size,
        data_->selectable,
        data_->cost_select,
        data_->cost_change,
        std::move(matrix)
    );
    algo.reset(std::move(qdata));
    answer_type subsequent_answer = *algo.get();
    std::copy(subsequent_answer.list.begin(), subsequent_answer.list.end(), std::back_inserter(answer.list));
    yield(std::move(answer));
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <memory>

#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
#include "test/test_main_lib.h"

int main(int argc, char* argv[]) {
  // Initialize the symbolizer to get a human-readable stack trace
  // TODO(crbug.com/1050976): Breaks iossim tests, re-enable when fixed.
  // absl::InitializeSymbolizer(argv[0]);

  // absl::FailureSignalHandlerOptions options;
  // absl::InstallFailureSignalHandler(options);

  std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create();
  int err_code = main->Init(&argc, argv);
  if (err_code != 0) {
    return err_code;
  }
  return main->Run(argc, argv);
}
<commit_msg>Re-enable absl FailureSignalHandler in tests.<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <memory>

#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
#include "test/test_main_lib.h"

int main(int argc, char* argv[]) {
  // Initialize the symbolizer to get a human-readable stack trace
  absl::InitializeSymbolizer(argv[0]);

  absl::FailureSignalHandlerOptions options;
  absl::InstallFailureSignalHandler(options);

  std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create();
  int err_code = main->Init(&argc, argv);
  if (err_code != 0) {
    return err_code;
  }
  return main->Run(argc, argv);
}
<|endoftext|>