<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee Modules --- Error Page
 *
 * The Error Page module allows the user to select a custom error page.
 *
 * @author Sam Baskinger <sbaskinger@qualys.com>
 */

#include "ironbee_config_auto.h"

#include <ironbeepp/configuration_directives.hpp>
#include <ironbeepp/configuration_parser.hpp>
#include <ironbeepp/c_trampoline.hpp>
#include <ironbeepp/module.hpp>
#include <ironbeepp/module_bootstrap.hpp>
#include <ironbeepp/module_delegate.hpp>
#include <ironbeepp/transaction.hpp>

#include <ironbee/rule_engine.h>
#include <ironbee/string.h>

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/iostreams/device/mapped_file.hpp>

/* Enable PRId64 printf. */
extern "C" {
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
}

/**
 * Error Page Module implementation.
 */
class ErrorPageModule : public IronBee::ModuleDelegate
{
public:
    typedef ib_status_t(error_page_fn_t)(
        ib_tx_t        *tx,
        const uint8_t **page,
        size_t         *page_sz);
    /**
     * Constructor.
     * @param[in] module The IronBee++ module.
     */
    explicit ErrorPageModule(IronBee::Module module);

    ~ErrorPageModule();

private:

    /**
     * Member to store the C trampoline information.
     *
     * Note that m_trampoline_pair.second must be destroyed.
     */
    std::pair<ib_rule_error_page_fn_t, void*> m_trampoline_pair;

    /**
     * Produce an error page for the given transaction.
     *
     * @param[in] tx The transaction.
     * @param[out] page The page data is placed here.
     * @param[out] page_sz The page size is placed here.
     *
     * @returns
     * - IB_OK On success.
     * - IB_DECLINED If the error page is not available but not because
     *               of an error.
     * - Other on error.
     */
    ib_status_t error_page_fn(
        ib_tx_t        *tx,
        const uint8_t **page,
        size_t         *page_sz);

    void directive(
        IronBee::ConfigurationParser  cp,
        const char                   *name,
        const char                   *param1,
        const char                   *param2);
};

IBPP_BOOTSTRAP_MODULE_DELEGATE("ErrorPageModule", ErrorPageModule);

/**
 * Context configuration value for the ErrorPageModule.
 */
struct ErrorPageCtxConfig {
    /**
     * The mapping from an HTTP status code to the file to return.
     */
    std::map<ib_num_t, std::string> status_to_file;

    /**
     * The mapping from an HTTP status code to the memory mapped file.
     */
    std::map<ib_num_t, boost::iostreams::mapped_file_source>
        status_to_mapped_file_source;
};

/* Implementation */

ErrorPageModule::ErrorPageModule(IronBee::Module module):
    /* Initialize the parent. */
    IronBee::ModuleDelegate(module),

    /* Build the C callback for ib_rule_set_error_page_fn(). */
    m_trampoline_pair(
        IronBee::make_c_trampoline<error_page_fn_t>(
            boost::bind(&ErrorPageModule::error_page_fn, this, _1, _2, _3)))
{
    /* Register the callback with the IronBee engine. */
    ib_rule_set_error_page_fn(
        module.engine().ib(),
        m_trampoline_pair.first,
        m_trampoline_pair.second);

    /* Setup the directive callbacks. */
    module.engine().register_configuration_directives().
        param2(
            "HttpStatusCodeContents",
            boost::bind(
                &ErrorPageModule::directive, this, _1, _2, _3, _4));

    module.set_configuration_data<ErrorPageCtxConfig>();
}

ErrorPageModule::~ErrorPageModule() {
    IronBee::delete_c_trampoline(m_trampoline_pair.second);
}

void ErrorPageModule::directive(
        IronBee::ConfigurationParser  cp,
        const char                   *name,
        const char                   *param1,
        const char                   *param2)
{
    ib_num_t num;

    ErrorPageCtxConfig &cfg =
        module().configuration_data<ErrorPageCtxConfig>(cp.current_context());

    /* Convert the incoming parameter. */
    IronBee::throw_if_error(ib_string_to_num(param1, 10, &num));

    /* Set the mapping in the context configuration. */
    cfg.status_to_file[num] = std::string(param2);

    try {
        cfg.status_to_mapped_file_source[num] =
            boost::iostreams::mapped_file_source(param2);
    }
    catch (const std::exception& e) {
        BOOST_THROW_EXCEPTION(
            IronBee::enoent()
                << IronBee::errinfo_what(e.what()));
    }
}

ib_status_t ErrorPageModule::error_page_fn(
    ib_tx_t *tx,
    const uint8_t **page,
    size_t *len)
{
    assert(tx->block_method == IB_BLOCK_METHOD_STATUS);

    IronBee::Transaction txpp(tx);

    ErrorPageCtxConfig &cfg =
        module().configuration_data<ErrorPageCtxConfig>(
            txpp.context());

    ib_log_debug_tx(
        tx,
        "Returning custom error page with status %" PRId64 " for context %s.",
        tx->block_status,
        txpp.context().name());

    std::map<ib_num_t, std::string>::iterator itr =
        cfg.status_to_file.find(tx->block_status);

    /* If we can't find a mapping, decline. The default will take over. */
    if (itr == cfg.status_to_file.end()) {
        ib_log_debug_tx(
            tx,
            "No custom page mapped for status %" PRId64 " and context %s. "
            "Declining.",
            tx->block_status,
            txpp.context().name());
        return IB_DECLINED;
    }

    const std::string& file = itr->second;
    const boost::iostreams::mapped_file_source &source =
        cfg.status_to_mapped_file_source[tx->block_status];

    ib_log_debug_tx(
        tx,
        "Using custom error page file %.*s.",
        static_cast<int>(file.length()),
        file.data());

    *page = reinterpret_cast<const uint8_t*>(source.data());
    *len = source.size();

    /* Until we write this, decline the action. */
    return IB_OK;
}
<commit_msg>error_page: Removing assert.<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee Modules --- Error Page
 *
 * The Error Page module allows the user to select a custom error page.
 *
 * @author Sam Baskinger <sbaskinger@qualys.com>
 */

#include "ironbee_config_auto.h"

#include <ironbeepp/configuration_directives.hpp>
#include <ironbeepp/configuration_parser.hpp>
#include <ironbeepp/c_trampoline.hpp>
#include <ironbeepp/module.hpp>
#include <ironbeepp/module_bootstrap.hpp>
#include <ironbeepp/module_delegate.hpp>
#include <ironbeepp/transaction.hpp>

#include <ironbee/rule_engine.h>
#include <ironbee/string.h>

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/iostreams/device/mapped_file.hpp>

/* Enable PRId64 printf. */
extern "C" {
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
}

/**
 * Error Page Module implementation.
 */
class ErrorPageModule : public IronBee::ModuleDelegate
{
public:
    typedef ib_status_t(error_page_fn_t)(
        ib_tx_t        *tx,
        const uint8_t **page,
        size_t         *page_sz);
    /**
     * Constructor.
     * @param[in] module The IronBee++ module.
     */
    explicit ErrorPageModule(IronBee::Module module);

    ~ErrorPageModule();

private:

    /**
     * Member to store the C trampoline information.
     *
     * Note that m_trampoline_pair.second must be destroyed.
     */
    std::pair<ib_rule_error_page_fn_t, void*> m_trampoline_pair;

    /**
     * Produce an error page for the given transaction.
     *
     * @param[in] tx The transaction.
     * @param[out] page The page data is placed here.
     * @param[out] page_sz The page size is placed here.
     *
     * @returns
     * - IB_OK On success.
     * - IB_DECLINED If the error page is not available but not because
     *               of an error.
     * - Other on error.
     */
    ib_status_t error_page_fn(
        ib_tx_t        *tx,
        const uint8_t **page,
        size_t         *page_sz);

    void directive(
        IronBee::ConfigurationParser  cp,
        const char                   *name,
        const char                   *param1,
        const char                   *param2);
};

IBPP_BOOTSTRAP_MODULE_DELEGATE("ErrorPageModule", ErrorPageModule);

/**
 * Context configuration value for the ErrorPageModule.
 */
struct ErrorPageCtxConfig {
    /**
     * The mapping from an HTTP status code to the file to return.
     */
    std::map<ib_num_t, std::string> status_to_file;

    /**
     * The mapping from an HTTP status code to the memory mapped file.
     */
    std::map<ib_num_t, boost::iostreams::mapped_file_source>
        status_to_mapped_file_source;
};

/* Implementation */

ErrorPageModule::ErrorPageModule(IronBee::Module module):
    /* Initialize the parent. */
    IronBee::ModuleDelegate(module),

    /* Build the C callback for ib_rule_set_error_page_fn(). */
    m_trampoline_pair(
        IronBee::make_c_trampoline<error_page_fn_t>(
            boost::bind(&ErrorPageModule::error_page_fn, this, _1, _2, _3)))
{
    /* Register the callback with the IronBee engine. */
    ib_rule_set_error_page_fn(
        module.engine().ib(),
        m_trampoline_pair.first,
        m_trampoline_pair.second);

    /* Setup the directive callbacks. */
    module.engine().register_configuration_directives().
        param2(
            "HttpStatusCodeContents",
            boost::bind(
                &ErrorPageModule::directive, this, _1, _2, _3, _4));

    module.set_configuration_data<ErrorPageCtxConfig>();
}

ErrorPageModule::~ErrorPageModule() {
    IronBee::delete_c_trampoline(m_trampoline_pair.second);
}

void ErrorPageModule::directive(
        IronBee::ConfigurationParser  cp,
        const char                   *name,
        const char                   *param1,
        const char                   *param2)
{
    ib_num_t num;

    ErrorPageCtxConfig &cfg =
        module().configuration_data<ErrorPageCtxConfig>(cp.current_context());

    /* Convert the incoming parameter. */
    IronBee::throw_if_error(ib_string_to_num(param1, 10, &num));

    /* Set the mapping in the context configuration. */
    cfg.status_to_file[num] = std::string(param2);

    try {
        cfg.status_to_mapped_file_source[num] =
            boost::iostreams::mapped_file_source(param2);
    }
    catch (const std::exception& e) {
        BOOST_THROW_EXCEPTION(
            IronBee::enoent()
                << IronBee::errinfo_what(e.what()));
    }
}

ib_status_t ErrorPageModule::error_page_fn(
    ib_tx_t *tx,
    const uint8_t **page,
    size_t *len)
{
    IronBee::Transaction txpp(tx);

    ErrorPageCtxConfig &cfg =
        module().configuration_data<ErrorPageCtxConfig>(
            txpp.context());

    ib_log_debug_tx(
        tx,
        "Returning custom error page with status %" PRId64 " for context %s.",
        tx->block_status,
        txpp.context().name());

    std::map<ib_num_t, std::string>::iterator itr =
        cfg.status_to_file.find(tx->block_status);

    /* If we can't find a mapping, decline. The default will take over. */
    if (itr == cfg.status_to_file.end()) {
        ib_log_debug_tx(
            tx,
            "No custom page mapped for status %" PRId64 " and context %s. "
            "Declining.",
            tx->block_status,
            txpp.context().name());
        return IB_DECLINED;
    }

    const std::string& file = itr->second;
    const boost::iostreams::mapped_file_source &source =
        cfg.status_to_mapped_file_source[tx->block_status];

    ib_log_debug_tx(
        tx,
        "Using custom error page file %.*s.",
        static_cast<int>(file.length()),
        file.data());

    *page = reinterpret_cast<const uint8_t*>(source.data());
    *len = source.size();

    /* Until we write this, decline the action. */
    return IB_OK;
}
<|endoftext|>


<commit_before><?hh

include ('blackhole/blackhole.hh');

require_once ('vendor/facebook/xhp-lib/init.php');

require_once ('header.hh');
require_once ('forms.hh');
require_once ('footer.hh');

require_once ('aws.hh');

require_once ('config/aws_config.hh');
require_once ('config/jump_config.hh');
require_once ('config/key_config.hh');

require ('index.hh');
require ('go.hh');
require ('submit.hh');
require ('result.hh');
require ('error.hh');
require ('api.hh');

function main(): void {

  $matches = array();

  $uri = "";

  // trap bad bots or vuln scanning
  if (preg_match(
        "~^/+(cgi-bin|admin|wp-admin|blackhole)/~",
        $_SERVER['REQUEST_URI'],
      ) ===
      1) {
    include ('blackhole/index.hh');
  }

  if (!preg_match("~/([^/]*)(\?.*)?~", $_SERVER['REQUEST_URI'], $matches)) {
    i_main();
  } else {
    $uri = $matches[1];
  }

  $body = null;

  if ($uri === 'a') {
    apiHandler::handle();
  } else if ($uri === 's') {
    s_main($_POST['action']);
  } else if ($uri === 'r') {
    r_main();
  } else if ($uri === '404') {
    error_page(404, $uri);
  } else if ($uri !== "") {
    g_main($uri);
  } else if ($uri === "") {
    i_main();
  }
}

main();
<commit_msg>Correctly handle GET params -- ignored except by API<commit_after><?hh

include ('blackhole/blackhole.hh');

require_once ('vendor/facebook/xhp-lib/init.php');

require_once ('header.hh');
require_once ('forms.hh');
require_once ('footer.hh');

require_once ('aws.hh');

require_once ('config/aws_config.hh');
require_once ('config/jump_config.hh');
require_once ('config/key_config.hh');

require ('index.hh');
require ('go.hh');
require ('submit.hh');
require ('result.hh');
require ('error.hh');
require ('api.hh');

function main(): void {

  $matches = array();

  $uri = "";

  // trap bad bots or vuln scanning
  if (preg_match(
        "~^/+(cgi-bin|admin|wp-admin|blackhole)/~",
        $_SERVER['REQUEST_URI'],
      ) ===
      1) {
    include ('blackhole/index.hh');
  }

  if (!preg_match("~/([^/?]*)(\?.*)?~", $_SERVER['REQUEST_URI'], $matches)) {
    i_main();
  } else {
    $uri = $matches[1];
  }

  if ($uri === 'a') {
    apiHandler::handle();
  } else if ($uri === 's') {
    s_main($_POST['action']);
  } else if ($uri === 'r') {
    r_main();
  } else if ($uri === '404') {
    error_page(404, $uri);
  } else if ($uri !== '') {
    g_main($uri);
  } else /*if ($uri === "")*/ {
    i_main();
  }
}

main();
<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     pluginitem.cpp
 * @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>
 * @since    0.1.0
 * @date     August, 2013
 *
 * @section  LICENSE
 *
 * Copyright (C) 2013, Christoph Dinh. 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 MNE-CPP authors 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 OWNER 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.
 *
 *
 * @brief     PluginItem class implementation
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "pluginitem.h"
#include "arrow.h"

#include <QGraphicsScene>
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
#include <QPainter>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNESCAN;

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

PluginItem::PluginItem(SCSHAREDLIB::AbstractPlugin::SPtr pPlugin, QMenu *contextMenu, QGraphicsItem *parent)
: QGraphicsPolygonItem(parent)
, m_pPlugin(pPlugin)
, m_iWidth(60)
, m_iHeight(40)
, m_contextMenu(contextMenu)
{
    QPainterPath path;
    m_qLinearGradientFace = QLinearGradient(m_iWidth/2, -10, m_iWidth/2, m_iHeight);
    m_qLinearGradientFace.setColorAt(1, Qt::white);
    m_qPolygon << QPointF(-m_iWidth/2, -m_iHeight/2) << QPointF(m_iWidth/2, -m_iHeight/2)
               << QPointF(m_iWidth/2, m_iHeight/2) << QPointF(-m_iWidth/2, m_iHeight/2)
               << QPointF(-m_iWidth/2, -m_iHeight/2);
    switch (m_pPlugin->getType()) {
//        case StartEnd:
//            m_qColorContour = QColor(79, 136, 187);
//            m_qLinearGradientFace.setColorAt(0, QColor(234, 239, 247));
//            break;
        case SCSHAREDLIB::AbstractPlugin::_IAlgorithm:
            m_qColorContour = QColor(98, 152, 61);
            m_qLinearGradientFace.setColorAt(0, QColor(235, 241, 233));
            break;
        case SCSHAREDLIB::AbstractPlugin::_ISensor:
            m_qColorContour = QColor(79, 136, 187);
            m_qLinearGradientFace.setColorAt(0, QColor(234, 239, 247));
            break;
        default:
            m_qColorContour = QColor(125, 125, 125);
            m_qLinearGradientFace.setColorAt(0, QColor(125, 125, 125));
            break;
    }
    setBrush(m_qLinearGradientFace);
    setPen(QPen(m_qColorContour,1));
    setPolygon(m_qPolygon);
    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}

//=============================================================================================================

PluginItem::~PluginItem()
{
    m_pPlugin->unload();
}

//=============================================================================================================

void PluginItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    auto textSize = painter->fontMetrics().size(Qt::TextSingleLine, m_pPlugin->getName());
    int iHorizontalSpacing = 4;
    int iVerticalSpacing = 4;

    resizeAsRectangle(textSize.width() + 2 * iHorizontalSpacing,
                      textSize.height() + 2* iVerticalSpacing);

    QGraphicsPolygonItem::paint(painter, option, widget);

    painter->setPen(QPen(m_qColorContour, 1));

//    QString sKind("");
//    switch (m_diagramType) {
//        case StartEnd:
//            break;
//        case Algorithm:
//            sKind = QString("Tool");
//            break;
//        case Sensor:
//            sKind = QString("Sensor");
//            break;
//        default:
//            sKind = QString("IO");
//            break;
//    }

    painter->drawText(-m_iWidth/2+ iHorizontalSpacing, iVerticalSpacing,m_pPlugin->getName());
}

//=============================================================================================================

void PluginItem::removeArrow(Arrow *arrow)
{
    int index = arrows.indexOf(arrow);

    if (index != -1)
        arrows.removeAt(index);
}

//=============================================================================================================

void PluginItem::removeArrows()
{
    foreach (Arrow *arrow, arrows) {
        arrow->startItem()->removeArrow(arrow);
        arrow->endItem()->removeArrow(arrow);
        scene()->removeItem(arrow);
        delete arrow;
    }
}

//=============================================================================================================

void PluginItem::addArrow(Arrow *arrow)
{
    arrows.append(arrow);
}

//=============================================================================================================

QPixmap PluginItem::image() const
{
    QPixmap pixmap(m_iWidth, m_iHeight);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setPen(QPen(m_qColorContour, 2));
    painter.translate(m_iWidth/2, m_iHeight/2);

    painter.drawPolyline(m_qPolygon);

    painter.drawText(-m_iWidth/2+4,-m_iHeight/2+14,m_pPlugin->getName().mid(0,10));

    return pixmap;
}

//=============================================================================================================

void PluginItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    scene()->clearSelection();
    setSelected(true);
    m_contextMenu->exec(event->screenPos());
}

//=============================================================================================================

QVariant PluginItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemPositionChange) {
        foreach (Arrow *arrow, arrows) {
            arrow->updatePosition();
        }
    }

    return value;

//    if (change == ItemPositionChange && scene()) {
//        // value is the new position.
//        QPointF newPos = value.toPointF();
//        QRectF rect = scene()->sceneRect();
//        if (!rect.contains(newPos)) {
//            // Keep the item inside the scene rect.
//            newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
//            newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
//            return newPos;
//        }
//    }

//    return QGraphicsItem::itemChange(change, value);
}

//=============================================================================================================

void PluginItem::resizeAsRectangle(int width, int height)
{
    if(m_iWidth == width && m_iHeight == height){
        return;
    }

    m_iWidth = width;
    m_iHeight = height;

    m_qPolygon = QPolygonF();
    m_qPolygon << QPointF(-m_iWidth/2, -m_iHeight/2) << QPointF(m_iWidth/2, -m_iHeight/2)
               << QPointF(m_iWidth/2, m_iHeight/2) << QPointF(-m_iWidth/2, m_iHeight/2)
               << QPointF(-m_iWidth/2, -m_iHeight/2);

    this->setPolygon(m_qPolygon);
}
<commit_msg>MAINT: replace redundant default construct with initializer list, fix code spacing<commit_after>//=============================================================================================================
/**
 * @file     pluginitem.cpp
 * @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>
 * @since    0.1.0
 * @date     August, 2013
 *
 * @section  LICENSE
 *
 * Copyright (C) 2013, Christoph Dinh. 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 MNE-CPP authors 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 OWNER 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.
 *
 *
 * @brief     PluginItem class implementation
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "pluginitem.h"
#include "arrow.h"

#include <QGraphicsScene>
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
#include <QPainter>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNESCAN;

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

PluginItem::PluginItem(SCSHAREDLIB::AbstractPlugin::SPtr pPlugin, QMenu *contextMenu, QGraphicsItem *parent)
: QGraphicsPolygonItem(parent)
, m_pPlugin(pPlugin)
, m_iWidth(60)
, m_iHeight(40)
, m_contextMenu(contextMenu)
{
    QPainterPath path;
    m_qLinearGradientFace = QLinearGradient(m_iWidth/2, -10, m_iWidth/2, m_iHeight);
    m_qLinearGradientFace.setColorAt(1, Qt::white);
    m_qPolygon << QPointF(-m_iWidth/2, -m_iHeight/2) << QPointF(m_iWidth/2, -m_iHeight/2)
               << QPointF(m_iWidth/2, m_iHeight/2) << QPointF(-m_iWidth/2, m_iHeight/2)
               << QPointF(-m_iWidth/2, -m_iHeight/2);
    switch (m_pPlugin->getType()) {
//        case StartEnd:
//            m_qColorContour = QColor(79, 136, 187);
//            m_qLinearGradientFace.setColorAt(0, QColor(234, 239, 247));
//            break;
        case SCSHAREDLIB::AbstractPlugin::_IAlgorithm:
            m_qColorContour = QColor(98, 152, 61);
            m_qLinearGradientFace.setColorAt(0, QColor(235, 241, 233));
            break;
        case SCSHAREDLIB::AbstractPlugin::_ISensor:
            m_qColorContour = QColor(79, 136, 187);
            m_qLinearGradientFace.setColorAt(0, QColor(234, 239, 247));
            break;
        default:
            m_qColorContour = QColor(125, 125, 125);
            m_qLinearGradientFace.setColorAt(0, QColor(125, 125, 125));
            break;
    }
    setBrush(m_qLinearGradientFace);
    setPen(QPen(m_qColorContour,1));
    setPolygon(m_qPolygon);
    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}

//=============================================================================================================

PluginItem::~PluginItem()
{
    m_pPlugin->unload();
}

//=============================================================================================================

void PluginItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    auto textSize = painter->fontMetrics().size(Qt::TextSingleLine, m_pPlugin->getName());
    int iHorizontalSpacing = 4;
    int iVerticalSpacing = 4;

    resizeAsRectangle(textSize.width() + 2 * iHorizontalSpacing,
                      textSize.height() + 2 * iVerticalSpacing);

    QGraphicsPolygonItem::paint(painter, option, widget);

    painter->setPen(QPen(m_qColorContour, 1));

//    QString sKind("");
//    switch (m_diagramType) {
//        case StartEnd:
//            break;
//        case Algorithm:
//            sKind = QString("Tool");
//            break;
//        case Sensor:
//            sKind = QString("Sensor");
//            break;
//        default:
//            sKind = QString("IO");
//            break;
//    }

    painter->drawText(-m_iWidth/2 + iHorizontalSpacing, iVerticalSpacing, m_pPlugin->getName());
}

//=============================================================================================================

void PluginItem::removeArrow(Arrow *arrow)
{
    int index = arrows.indexOf(arrow);

    if (index != -1)
        arrows.removeAt(index);
}

//=============================================================================================================

void PluginItem::removeArrows()
{
    foreach (Arrow *arrow, arrows) {
        arrow->startItem()->removeArrow(arrow);
        arrow->endItem()->removeArrow(arrow);
        scene()->removeItem(arrow);
        delete arrow;
    }
}

//=============================================================================================================

void PluginItem::addArrow(Arrow *arrow)
{
    arrows.append(arrow);
}

//=============================================================================================================

QPixmap PluginItem::image() const
{
    QPixmap pixmap(m_iWidth, m_iHeight);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setPen(QPen(m_qColorContour, 2));
    painter.translate(m_iWidth/2, m_iHeight/2);

    painter.drawPolyline(m_qPolygon);

    painter.drawText(-m_iWidth/2+4,-m_iHeight/2+14,m_pPlugin->getName().mid(0,10));

    return pixmap;
}

//=============================================================================================================

void PluginItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    scene()->clearSelection();
    setSelected(true);
    m_contextMenu->exec(event->screenPos());
}

//=============================================================================================================

QVariant PluginItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemPositionChange) {
        foreach (Arrow *arrow, arrows) {
            arrow->updatePosition();
        }
    }

    return value;

//    if (change == ItemPositionChange && scene()) {
//        // value is the new position.
//        QPointF newPos = value.toPointF();
//        QRectF rect = scene()->sceneRect();
//        if (!rect.contains(newPos)) {
//            // Keep the item inside the scene rect.
//            newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
//            newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
//            return newPos;
//        }
//    }

//    return QGraphicsItem::itemChange(change, value);
}

//=============================================================================================================

void PluginItem::resizeAsRectangle(int width, int height)
{
    if(m_iWidth == width && m_iHeight == height){
        return;
    }

    m_iWidth = width;
    m_iHeight = height;

    m_qPolygon = QPolygonF({QPointF(-m_iWidth/2, -m_iHeight/2),
                            QPointF(m_iWidth/2, -m_iHeight/2),
                            QPointF(m_iWidth/2, m_iHeight/2),
                            QPointF(-m_iWidth/2, m_iHeight/2),
                            QPointF(-m_iWidth/2, -m_iHeight/2)});

    this->setPolygon(m_qPolygon);
}
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include <ts/TestBox.h>
#include "P_Eventsystem.h"
#include "MIME.h"

REGRESSION_TEST(MIME)(RegressionTest *t, int /* atype ATS_UNUSED */, int *pstatus)
{
  TestBox box(t, pstatus);
  box = REGRESSION_TEST_PASSED;

  MIMEField *field;
  MIMEHdr hdr;
  hdr.create(NULL);

  hdr.field_create("Test1", 5);
  hdr.field_create("Test2", 5);
  hdr.field_create("Test3", 5);
  hdr.field_create("Test4", 5);
  field = hdr.field_create("Test5", 5);

  box.check(hdr.m_mime->m_first_fblock.contains(field), "The field block doesn't contain the field but it should");
  box.check(!hdr.m_mime->m_first_fblock.contains(field + (1L << 32)), "The field block contains the field but it shouldn't");

  int slot_num = mime_hdr_field_slotnum(hdr.m_mime, field);
  box.check(slot_num == 4, "Slot number is %d but should be 4", slot_num);

  slot_num = mime_hdr_field_slotnum(hdr.m_mime, field + (1L << 32));
  box.check(slot_num == -1, "Slot number is %d but should be -1", slot_num);

  hdr.destroy();
}

int
main(int argc, char *argv[])
{
  Thread *main_thread = new EThread;
  main_thread->set_specific();
  mime_init();

  RegressionTest::run();
  return RegressionTest::final_status == REGRESSION_TEST_PASSED ? 0 : 1;
}
<commit_msg>Build fix.<commit_after>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include <ts/TestBox.h>
#include "P_EventSystem.h"
#include "MIME.h"

REGRESSION_TEST(MIME)(RegressionTest *t, int /* atype ATS_UNUSED */, int *pstatus)
{
  TestBox box(t, pstatus);
  box = REGRESSION_TEST_PASSED;

  MIMEField *field;
  MIMEHdr hdr;
  hdr.create(NULL);

  hdr.field_create("Test1", 5);
  hdr.field_create("Test2", 5);
  hdr.field_create("Test3", 5);
  hdr.field_create("Test4", 5);
  field = hdr.field_create("Test5", 5);

  box.check(hdr.m_mime->m_first_fblock.contains(field), "The field block doesn't contain the field but it should");
  box.check(!hdr.m_mime->m_first_fblock.contains(field + (1L << 32)), "The field block contains the field but it shouldn't");

  int slot_num = mime_hdr_field_slotnum(hdr.m_mime, field);
  box.check(slot_num == 4, "Slot number is %d but should be 4", slot_num);

  slot_num = mime_hdr_field_slotnum(hdr.m_mime, field + (1L << 32));
  box.check(slot_num == -1, "Slot number is %d but should be -1", slot_num);

  hdr.destroy();
}

int
main(int argc, char *argv[])
{
  Thread *main_thread = new EThread();
  main_thread->set_specific();
  mime_init();

  RegressionTest::run();
  return RegressionTest::final_status == REGRESSION_TEST_PASSED ? 0 : 1;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cupsmgr.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-18 17:46:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PSPRINT_CUPSMGR_HXX_
#define _PSPRINT_CUPSMGR_HXX_

#include <psprint/printerinfomanager.hxx>
#include <osl/module.h>
#include <osl/thread.h>
#include <osl/mutex.hxx>

namespace psp
{

class CUPSWrapper;
class PPDParser;

struct FPtrHash
{
    size_t operator()(const FILE* pPtr) const
    { return (size_t)pPtr; }
};

class CUPSManager : public PrinterInfoManager
{
    CUPSWrapper*                                                m_pCUPSWrapper;
    std::hash_map< FILE*, rtl::OString, FPtrHash >              m_aSpoolFiles;
    int                                                         m_nDests;
    void*                                                       m_pDests;
    bool                                                        m_bNewDests;
    std::hash_map< rtl::OUString, int, rtl::OUStringHash >      m_aCUPSDestMap;

    std::hash_map< rtl::OUString, PPDContext, rtl::OUStringHash > m_aDefaultContexts;

    rtl::OString                                                m_aUser;
    // this is a security risk, but the CUPS API demands
    // to deliver a pointer to a static buffer containing
    // the password, so this cannot be helped
    rtl::OString                                                m_aPassword;

    osl::Mutex                                                  m_aCUPSMutex;
    oslThread                                                   m_aDestThread;

    CUPSManager( CUPSWrapper* );
    virtual ~CUPSManager();

    virtual void initialize();

    void getOptionsFromDocumentSetup( const JobData& rJob, int& rNumOptions, void** rOptions ) const;
    void runDests();
    static void runDestThread(void* pMgr);
public:

    static CUPSManager* tryLoadCUPS();

    const PPDParser* createCUPSParser( const rtl::OUString& rPrinter );
    // wraps cupsGetPPD, so unlink after use !

    const char* authenticateUser( const char* );

    virtual FILE* startSpool( const rtl::OUString& rPrinterName );
    virtual int endSpool( const rtl::OUString& rPrinterName, const rtl::OUString& rJobTitle, FILE* pFile, const JobData& rDocumentJobData );
    virtual void setupJobContextData( JobData& rData );

    // changes the info about a named printer
    virtual void changePrinterInfo( const ::rtl::OUString& rPrinter, const PrinterInfo& rNewInfo );

    // check if the printer configuration has changed
    virtual bool checkPrintersChanged();

    // members for administration (->padmin)
    // disable for CUPS
    virtual bool addPrinter( const rtl::OUString& rPrinterName, const ::rtl::OUString& rDriverName );
    virtual bool removePrinter( const rtl::OUString& rPrinterName, bool bCheckOnly = false );
    virtual bool writePrinterConfig();
    virtual bool setDefaultPrinter( const rtl::OUString& rPrinterName );

    virtual bool addOrRemovePossible() const;
};

} // namespace psp

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.32); FILE MERGED 2005/09/05 12:06:30 rt 1.6.32.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cupsmgr.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:33:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PSPRINT_CUPSMGR_HXX_
#define _PSPRINT_CUPSMGR_HXX_

#include <psprint/printerinfomanager.hxx>
#include <osl/module.h>
#include <osl/thread.h>
#include <osl/mutex.hxx>

namespace psp
{

class CUPSWrapper;
class PPDParser;

struct FPtrHash
{
    size_t operator()(const FILE* pPtr) const
    { return (size_t)pPtr; }
};

class CUPSManager : public PrinterInfoManager
{
    CUPSWrapper*                                                m_pCUPSWrapper;
    std::hash_map< FILE*, rtl::OString, FPtrHash >              m_aSpoolFiles;
    int                                                         m_nDests;
    void*                                                       m_pDests;
    bool                                                        m_bNewDests;
    std::hash_map< rtl::OUString, int, rtl::OUStringHash >      m_aCUPSDestMap;

    std::hash_map< rtl::OUString, PPDContext, rtl::OUStringHash > m_aDefaultContexts;

    rtl::OString                                                m_aUser;
    // this is a security risk, but the CUPS API demands
    // to deliver a pointer to a static buffer containing
    // the password, so this cannot be helped
    rtl::OString                                                m_aPassword;

    osl::Mutex                                                  m_aCUPSMutex;
    oslThread                                                   m_aDestThread;

    CUPSManager( CUPSWrapper* );
    virtual ~CUPSManager();

    virtual void initialize();

    void getOptionsFromDocumentSetup( const JobData& rJob, int& rNumOptions, void** rOptions ) const;
    void runDests();
    static void runDestThread(void* pMgr);
public:

    static CUPSManager* tryLoadCUPS();

    const PPDParser* createCUPSParser( const rtl::OUString& rPrinter );
    // wraps cupsGetPPD, so unlink after use !

    const char* authenticateUser( const char* );

    virtual FILE* startSpool( const rtl::OUString& rPrinterName );
    virtual int endSpool( const rtl::OUString& rPrinterName, const rtl::OUString& rJobTitle, FILE* pFile, const JobData& rDocumentJobData );
    virtual void setupJobContextData( JobData& rData );

    // changes the info about a named printer
    virtual void changePrinterInfo( const ::rtl::OUString& rPrinter, const PrinterInfo& rNewInfo );

    // check if the printer configuration has changed
    virtual bool checkPrintersChanged();

    // members for administration (->padmin)
    // disable for CUPS
    virtual bool addPrinter( const rtl::OUString& rPrinterName, const ::rtl::OUString& rDriverName );
    virtual bool removePrinter( const rtl::OUString& rPrinterName, bool bCheckOnly = false );
    virtual bool writePrinterConfig();
    virtual bool setDefaultPrinter( const rtl::OUString& rPrinterName );

    virtual bool addOrRemovePossible() const;
};

} // namespace psp

#endif
<|endoftext|>


<commit_before>#include "xchainer/python/array_index.h"

#include "xchainer/array_index.h"

#include "xchainer/python/slice.h"

namespace xchainer {
namespace python {

namespace py = pybind11;

namespace {

ArrayIndex MakeArrayIndex(py::handle handle) {
    PyObject* obj = handle.ptr();
    if (obj == Py_None) {
        return ArrayIndex(NewAxis{});
    }
    if (PYBIND11_LONG_CHECK(obj)) {
        return ArrayIndex(py::cast<int64_t>(handle));
    }
    if (PySlice_Check(obj)) {
        return ArrayIndex(internal::MakeSlice(py::cast<py::slice>(handle)));
    }
    throw py::index_error("only integers, slices (`:`), xchainer.newaxis (`None`) are valid indices");
}

std::vector<ArrayIndex> MakeArrayIndicesFromTuple(py::tuple tup) {
    std::vector<ArrayIndex> indicies;
    for (auto& handle : tup) {
        indicies.emplace_back(MakeArrayIndex(handle));
    }
    return indicies;
}

} // namespace

namespace internal {

std::vector<ArrayIndex> MakeArrayIndices(py::handle handle) {
    PyObject* obj = handle.ptr();
    if (PyTuple_Check(obj)) {
        return MakeArrayIndicesFromTuple(py::cast<py::tuple>(handle));
    }
    return {MakeArrayIndex(handle)};
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<commit_msg>clang-format<commit_after>#include "xchainer/python/array_index.h"

#include "xchainer/array_index.h"

#include "xchainer/python/slice.h"

namespace xchainer {
namespace python {

namespace py = pybind11;

namespace {

ArrayIndex MakeArrayIndex(py::handle handle) {
    PyObject* obj = handle.ptr();
    if (obj == Py_None) {
        return ArrayIndex(NewAxis{});
    }
    if (PYBIND11_LONG_CHECK(obj)) {
        return ArrayIndex(py::cast<int64_t>(handle));
    }
    if (PySlice_Check(obj)) {
        return ArrayIndex(internal::MakeSlice(py::cast<py::slice>(handle)));
    }
    throw py::index_error("only integers, slices (`:`), xchainer.newaxis (`None`) are valid indices");
}

std::vector<ArrayIndex> MakeArrayIndicesFromTuple(py::tuple tup) {
    std::vector<ArrayIndex> indicies;
    for (auto& handle : tup) {
        indicies.emplace_back(MakeArrayIndex(handle));
    }
    return indicies;
}

}  // namespace

namespace internal {

std::vector<ArrayIndex> MakeArrayIndices(py::handle handle) {
    PyObject* obj = handle.ptr();
    if (PyTuple_Check(obj)) {
        return MakeArrayIndicesFromTuple(py::cast<py::tuple>(handle));
    }
    return {MakeArrayIndex(handle)};
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int A;
string S;
vector<int> V;

int calc(string str) {
  assert(str.size() <= 7);
  int tmp = 1;
  int ans = 0;
  for (auto i = 0; i < (int)str.size(); ++i) {
    ans += tmp * (str[i] - 'a' + 1);
    tmp *= A;
  }
  //cerr << ans << endl;
  return ans;
}

string maximal(int h) {
  string ans = "";
  while (h > 0) {
    for (auto i = 26; i >= 1; --i) {
      if (h - i < 0) continue;
      if ((h - i) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        h = (h - i)/A;
        break;
      }
    }
    //cerr << ans << " " << h << endl;
  }
  return ans;
}

int main () {
  cin >> A >> S;
  if (S.size() <= 7) {
    cout << maximal(calc(S)) << endl;
    return 0;
  }
  string T = S.substr(0, S.size()-7);
  cerr << T << endl;
  string U = S.substr(S.size()-7, 7);
  cerr << U << endl;
  assert(S == T + U);
  string ans = 0;
  int kari = 0;
  for (auto x : T) {
    int now = x - 'a' + 1;
    now -= kari;
    for (auto i = 26; i >= 1; --i) {
      if ((i - now) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        kari = (i - now)/A;
        break;
      }
    }
  }
  ans += maximal(calc(U) + kari);
  cout << ans << endl;
}
<commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int A;
string S;
vector<int> V;

int calc(string str) {
  assert(str.size() <= 7);
  int tmp = 1;
  int ans = 0;
  for (auto i = 0; i < (int)str.size(); ++i) {
    ans += tmp * (str[i] - 'a' + 1);
    tmp *= A;
  }
  //cerr << ans << endl;
  return ans;
}

string maximal(int h) {
  string ans = "";
  while (h > 0) {
    for (auto i = 26; i >= 1; --i) {
      if (h - i < 0) continue;
      if ((h - i) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        h = (h - i)/A;
        break;
      }
    }
    //cerr << ans << " " << h << endl;
  }
  return ans;
}

int main () {
  cin >> A >> S;
  if (S.size() <= 7) {
    cout << maximal(calc(S)) << endl;
    return 0;
  }
  string T = S.substr(0, S.size()-7);
  string U = S.substr(S.size()-7, 7);
  assert(S == T + U);
  cerr << "OK" << endl;

  string ans = 0;
  int kari = 0;
  for (auto x : T) {
    int now = x - 'a' + 1;
    now -= kari;
    for (auto i = 26; i >= 1; --i) {
      if ((i - now) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        kari = (i - now)/A;
        break;
      }
    }
  }
  ans += maximal(calc(U) + kari);
  cout << ans << endl;
}
<|endoftext|>


<commit_before>#include <stingray/toolkit/toolkit.h>

#include <stdio.h>
#include <stdarg.h>

#if defined(__GNUC__) || defined(__clang__)
#	include <cxxabi.h>
#endif

#include <stingray/log/Logger.h>
#include <stingray/toolkit/Backtrace.h>
#include <stingray/toolkit/ScopeExit.h>
#include <stingray/toolkit/StringUtils.h>
#include <stingray/toolkit/array.h>
#include <stingray/toolkit/bind.h>

namespace stingray
{

	std::string ToolkitWhere::ToString() const
	{ return StringBuilder() % "function '" % _functionName % "' in file '" % _file % "' at line " % _line; }

	NullPtrType null;

	void _append_extended_diagnostics(string_ostream& result, const Detail::IToolkitException& tkit_ex)
	{
		std::string backtrace = tkit_ex.GetBacktrace();
		result << "\n  in function '" << tkit_ex.GetFunctionName() << "'" <<
			"\n  in file '" << tkit_ex.GetFilename() << "' at line " << ToString(tkit_ex.GetLine());

		if (!backtrace.empty())
			result << "\n" << backtrace;
	}

	void DebuggingHelper::BreakpointHere()
	{
	}

	void DebuggingHelper::TerminateWithMessage(const std::string& str) throw()
	{
		std::string backtrace = Backtrace().Get();
		Logger::Error() << "Terminate was requested: " << str << (backtrace.empty() ? "" : ("\nbacktrace: " + backtrace));
		std::terminate();
	}

#if !defined(__GNUC__) && !defined(__clang__)
	std::string Demangle(const std::string& s)
	{ return s; }
#else
	std::string Demangle(const std::string& s)
	{
		int status = 0;
		char * result = abi::__cxa_demangle(s.c_str(), 0, 0, &status);
		ScopeExitInvoker sei(bind(&free, result));
		return (status != 0) ? s : std::string(result);
	}
#endif

}

#ifdef _STLP_DEBUG_MESSAGE
	void __stl_debug_message(const char * format_str, ...)
	{
		va_list args;
		va_start(args, format_str);

		stingray::array<char, 4096> buffer;
		int count = vsnprintf(buffer.data(), buffer.size(), format_str, args);
		if (count > 0)
		{
			std::string str(buffer.data(), count);
			stingray::Logger::Error() << str << stingray::Backtrace().Get();
		}
		else
			stingray::Logger::Error() << "Can't form stlport error message!\n" << stingray::Backtrace().Get();
		va_end(args);
	}
#endif
<commit_msg>Changed ToolkitWhere::ToString<commit_after>#include <stingray/toolkit/toolkit.h>

#include <stdio.h>
#include <stdarg.h>

#if defined(__GNUC__) || defined(__clang__)
#	include <cxxabi.h>
#endif

#include <stingray/log/Logger.h>
#include <stingray/toolkit/Backtrace.h>
#include <stingray/toolkit/ScopeExit.h>
#include <stingray/toolkit/StringUtils.h>
#include <stingray/toolkit/array.h>
#include <stingray/toolkit/bind.h>

namespace stingray
{

	std::string ToolkitWhere::ToString() const
	{ return StringBuilder() % _functionName % " (" % _file % ":" % _line % ")"; }

	NullPtrType null;

	void _append_extended_diagnostics(string_ostream& result, const Detail::IToolkitException& tkit_ex)
	{
		std::string backtrace = tkit_ex.GetBacktrace();
		result << "\n  in function '" << tkit_ex.GetFunctionName() << "'" <<
			"\n  in file '" << tkit_ex.GetFilename() << "' at line " << ToString(tkit_ex.GetLine());

		if (!backtrace.empty())
			result << "\n" << backtrace;
	}

	void DebuggingHelper::BreakpointHere()
	{
	}

	void DebuggingHelper::TerminateWithMessage(const std::string& str) throw()
	{
		std::string backtrace = Backtrace().Get();
		Logger::Error() << "Terminate was requested: " << str << (backtrace.empty() ? "" : ("\nbacktrace: " + backtrace));
		std::terminate();
	}

#if !defined(__GNUC__) && !defined(__clang__)
	std::string Demangle(const std::string& s)
	{ return s; }
#else
	std::string Demangle(const std::string& s)
	{
		int status = 0;
		char * result = abi::__cxa_demangle(s.c_str(), 0, 0, &status);
		ScopeExitInvoker sei(bind(&free, result));
		return (status != 0) ? s : std::string(result);
	}
#endif

}

#ifdef _STLP_DEBUG_MESSAGE
	void __stl_debug_message(const char * format_str, ...)
	{
		va_list args;
		va_start(args, format_str);

		stingray::array<char, 4096> buffer;
		int count = vsnprintf(buffer.data(), buffer.size(), format_str, args);
		if (count > 0)
		{
			std::string str(buffer.data(), count);
			stingray::Logger::Error() << str << stingray::Backtrace().Get();
		}
		else
			stingray::Logger::Error() << "Can't form stlport error message!\n" << stingray::Backtrace().Get();
		va_end(args);
	}
#endif
<|endoftext|>


<commit_before>/*
** Copyright 2012 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it
** and/or modify it under the terms of the GNU Affero General Public
** License as published by the Free Software Foundation, either version
** 3 of the License, or (at your option) any later version.
**
** Centreon Clib is distributed in the hope that it will be
** useful, but WITHOUT ANY WARRANTY; without even the implied warranty
** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <assert.h>
#include <stdlib.h>
#include "com/centreon/concurrency/condvar_win32.hh"
#include "com/centreon/concurrency/mutex_win32.hh"
#include "com/centreon/exceptions/basic.hh"

using namespace com::centreon::concurrency;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
condvar::condvar() {
  InitializeConditionVariable(&_cond);
}

/**
 *  Destructor.
 */
condvar::~condvar() throw () {}

/**
 *  Wait on condition variable.
 *
 *  @param[in] mutx Associated mutex.
 */
void condvar::wait(mutex* mutx) {
  _wait(mutx, INFINITE);
  return ;
}

/**
 *  Overload of wait().
 *
 *  @param[in] mutx    Associated mutex.
 *  @param[in] timeout Maximum number of milliseconds to wait to be
 *                     waked by condition variable.
 */
bool condvar::wait(mutex* mutx, unsigned long timeout) {
  return (_wait(mutx, timeout));
}

/**
 *  Wake all threads waiting on condition variable.
 */
void condvar::wake_all() {
  WakeAllConditionVariable(&_cond);
  return ;
}

/**
 *  Wake at least one thread waiting on the condition variable.
 */
void condvar::wake_one() {
  WakeConditionVariable(&_cond);
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Copy constructor.
 *
 *  @param[in] cv Unused.
 */
condvar::condvar(condvar const& cv) {
  _internal_copy(cv);
}

/**
 *  Assignment operator.
 *
 *  @param[in] cv Unused.
 *
 *  @return This object.
 */
condvar& condvar::operator=(condvar const& cv) {
  _internal_copy(cv);
  return (*this);
}

/**
 *  Copy internal data members.
 *
 *  @param[in] cv Object to copy.
 */
void condvar::_internal_copy(condvar const& cv) {
  (void)cv;
  assert(!"condition variable is not copyable");
  abort();
  return ;
}

/**
 *  Wait on condition variable.
 *
 *  @param[in] mutx    Associated mutex.
 *  @param[in] timeout Maximum number of milliseconds to wait.
 *
 *  @return true if mutex was acquired.
 */
bool condvar::_wait(mutex* mutx, DWORD timeout) {
  if (!mutx)
    throw (basic_error() << "wait was called with null mutex");
  bool retval(static_cast<bool>(SleepConditionVariableCS(
                                  &_cond,
                                  &mutx->_csection,
                                  timeout));
  if (!retval) {
    DWORD errcode(GetLastError());
    if (errcode != WAIT_TIMEOUT)
      throw (basic_error() << "failed to wait on condition variable " \
               "(error " << errcode << ")");
  }
  return (retval);
}
<commit_msg>Fix a compilation error on Windows.<commit_after>/*
** Copyright 2012 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it
** and/or modify it under the terms of the GNU Affero General Public
** License as published by the Free Software Foundation, either version
** 3 of the License, or (at your option) any later version.
**
** Centreon Clib is distributed in the hope that it will be
** useful, but WITHOUT ANY WARRANTY; without even the implied warranty
** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <assert.h>
#include <stdlib.h>
#include "com/centreon/concurrency/condvar_win32.hh"
#include "com/centreon/concurrency/mutex_win32.hh"
#include "com/centreon/exceptions/basic.hh"

using namespace com::centreon::concurrency;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
condvar::condvar() {
  InitializeConditionVariable(&_cond);
}

/**
 *  Destructor.
 */
condvar::~condvar() throw () {}

/**
 *  Wait on condition variable.
 *
 *  @param[in] mutx Associated mutex.
 */
void condvar::wait(mutex* mutx) {
  _wait(mutx, INFINITE);
  return ;
}

/**
 *  Overload of wait().
 *
 *  @param[in] mutx    Associated mutex.
 *  @param[in] timeout Maximum number of milliseconds to wait to be
 *                     waked by condition variable.
 */
bool condvar::wait(mutex* mutx, unsigned long timeout) {
  return (_wait(mutx, timeout));
}

/**
 *  Wake all threads waiting on condition variable.
 */
void condvar::wake_all() {
  WakeAllConditionVariable(&_cond);
  return ;
}

/**
 *  Wake at least one thread waiting on the condition variable.
 */
void condvar::wake_one() {
  WakeConditionVariable(&_cond);
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Copy constructor.
 *
 *  @param[in] cv Unused.
 */
condvar::condvar(condvar const& cv) {
  _internal_copy(cv);
}

/**
 *  Assignment operator.
 *
 *  @param[in] cv Unused.
 *
 *  @return This object.
 */
condvar& condvar::operator=(condvar const& cv) {
  _internal_copy(cv);
  return (*this);
}

/**
 *  Copy internal data members.
 *
 *  @param[in] cv Object to copy.
 */
void condvar::_internal_copy(condvar const& cv) {
  (void)cv;
  assert(!"condition variable is not copyable");
  abort();
  return ;
}

/**
 *  Wait on condition variable.
 *
 *  @param[in] mutx    Associated mutex.
 *  @param[in] timeout Maximum number of milliseconds to wait.
 *
 *  @return true if mutex was acquired.
 */
bool condvar::_wait(mutex* mutx, DWORD timeout) {
  if (!mutx)
    throw (basic_error() << "wait was called with null mutex");
  bool retval(static_cast<bool>(SleepConditionVariableCS(
                                  &_cond,
                                  &mutx->_csection,
                                  timeout)));
  if (!retval) {
    DWORD errcode(GetLastError());
    if (errcode != WAIT_TIMEOUT)
      throw (basic_error() << "failed to wait on condition variable " \
               "(error " << errcode << ")");
  }
  return (retval);
}
<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Condor ClassAd library
 * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI, and Rajesh Raman.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 *********************************************************************/

#include "common.h"
#include "xmlLexer.h"

using namespace std;

BEGIN_NAMESPACE( classad )

// Note that these must be in the same order as the enum TagID
struct xml_tag_mapping tag_mappings[] =
{
	{"classads",        XMLLexer::tagID_ClassAds},
	{"c",               XMLLexer::tagID_ClassAd},
	{"a",               XMLLexer::tagID_Attribute},
	{"n",               XMLLexer::tagID_Number},
	{"s",               XMLLexer::tagID_String},
	{"b",               XMLLexer::tagID_Bool},
	{"un",              XMLLexer::tagID_Undefined},
	{"er",              XMLLexer::tagID_Error},
	{"t",               XMLLexer::tagID_Time},
	{"l",               XMLLexer::tagID_List},
	{"e",               XMLLexer::tagID_Expr},
	{"?xml",            XMLLexer::tagID_XML},
	{"?xml-stylesheet", XMLLexer::tagID_XMLStylesheet},
	{"DOCTYPE",         XMLLexer::tagID_Doctype}
};

struct entity
{
	char *name;
	char *replacement_text;
	int length;
};

#define NUMBER_OF_ENTITIES (sizeof(entities) / sizeof(struct entity))
struct entity entities[] =
{
	{"&",  "&",  5},
	{"<",   "<",  4},
	{">",   ">",  4},
	{""", "\"", 6},
	{"'", "'",  6}
};

XMLLexer::Token::
Token()
{
	return;
}

XMLLexer::Token::
~Token()
{
	return;
}

void XMLLexer::Token::
ClearToken(void)
{
	token_type = tokenType_Invalid;
	tag_type   = tagType_Invalid;
	tag_id     = tagID_NoTag;
	text       = "";
	attributes.clear();
	return;
}

void XMLLexer::Token::
DumpToken(void)
{
	if (token_type == tokenType_Tag) {
		printf("TAG: \"%s\", ", text.c_str());
		printf("  Type: ");
		switch (tag_type) {
		case tagType_Start:   printf("start, ");   break;
		case tagType_End:     printf("end, ");     break;
		case tagType_Empty:   printf("empty, ");   break;
		case tagType_Invalid: printf("invalid, "); break;
		default: break;
		}
		printf("  ID: ");
		switch (tag_id) {
		case tagID_ClassAds:  printf("classads\n"); break;
		case tagID_ClassAd:   printf("classad\n"); break;
		case tagID_Attribute: printf("attribute\n"); break;
		case tagID_Number:    printf("number\n"); break;
		case tagID_String:    printf("string\n"); break;
		case tagID_Bool:      printf("bool\n"); break;
		case tagID_Undefined: printf("undefined\n"); break;
		case tagID_Error:     printf("error\n"); break;
		case tagID_Time:      printf("time\n"); break;
		case tagID_List:      printf("list\n"); break;
		case tagID_Expr:      printf("expr\n"); break;
		case tagID_XML:       printf("?xml\n"); break;
		case tagID_XMLStylesheet: printf("?xmlStyleSheet\n"); break;
		case tagID_Doctype:   printf("DOCTYPE\n"); break;
		case tagID_NoTag:     printf("notag\n"); break;
		}
		XMLAttributesIterator  iter;

		for (iter = attributes.begin(); iter != attributes.end(); iter++) {
			printf("  Attribute: %s = \"%s\"\n",
				   iter->first.c_str(), iter->second.c_str());
		}
	} else if (token_type == tokenType_Text) {
		printf("TEXT: \"%s\"\n", text.c_str());
	} else {
		printf("Invalid token.\n");
	}
	return;
}

XMLLexer::
XMLLexer ()
{
	lexer_source = NULL;
	return;
}

XMLLexer::
~XMLLexer ()
{
	return;
}

void XMLLexer::
SetLexerSource(LexerSource *source)
{
	lexer_source = source;

	return;
}

bool XMLLexer::
ConsumeToken(Token *token)
{
	bool have_token;

	if (!token_is_valid) {
		have_token = PeekToken(token);
	} else {
		have_token = true;
		if (token != NULL) {
			*token = current_token;
		}
	}
	token_is_valid = false;

	return have_token;
}

bool XMLLexer::
PeekToken(Token *token)
{
	bool have_token;

	if (token_is_valid) {
		have_token = true;
	} else {
		have_token = GrabToken();
	}

	if (have_token) {
		if (token != NULL) {
			*token = current_token;
		}
		token_is_valid = true;
	}
	return have_token;
}

bool XMLLexer::
GrabToken(void)
{
	bool have_token;
	bool have_character;
	int  character;

	current_token.ClearToken();

	// Find first non-whitespace character, to decide if we
	// are getting a tag or some text. If we get text, we preserve
	// whitespace, because we keep whitespace in strings.
	have_character = false;
	while (!lexer_source->AtEnd()) {
		character = lexer_source->ReadCharacter();
		if (!isspace(character)) {
			have_character = true;
			break;
		}
	}

	if (have_character) {
		if (character == '<') {
			have_token = GrabTag();
		} else {
			lexer_source->UnreadCharacter();
			have_token = GrabText();
		}
	} else {
		have_token = false;
	}

	//current_token.DumpToken();

	return have_token;
}

bool XMLLexer::
GrabTag(void)
{
	bool    have_token;
	int     character;
	string  complete_tag; // the tag and its attributes

	current_token.token_type = tokenType_Tag;
	complete_tag = "";
	character = -1;

	// Skip whitespace
	while (!lexer_source->AtEnd()) {
		character = lexer_source->ReadCharacter();
		if (!isspace(character)) {
			complete_tag += character;
			break;
		}
	}

	// Read the rest of the tag, a character at a time
	while (!lexer_source->AtEnd()) {
		character = lexer_source->ReadCharacter();
		if (character != '>') {
			complete_tag += character;
		} else {
			break;
		}
	}

	if (character != '>') {
		// We have an unclosed tag. This will not do.
		have_token = false;
	} else {
		BreakdownTag(complete_tag.c_str());
		have_token = true;
	}
	return true;
}

void XMLLexer::
BreakdownTag(const char *complete_tag)
{
	int length, i;
	int start, count;

	length = strlen(complete_tag);

	// Skip whitespace
	for (i = 0; i < length && isspace(complete_tag[i]); i++) {
		;
	}

	// Is it a begin or end tag?
	if (complete_tag[i] == '/') {
		current_token.tag_type = tagType_End;
		i++;
	} else if (complete_tag[length-1] == '/') {
		current_token.tag_type = tagType_Empty;
		length--; // skip the / in the processing that follows.
	} else {
		current_token.tag_type = tagType_Start;
	}

	// Now pull out the tag name
	current_token.text = "";
	start = i;
	count = 0;
	while (i < length && i != '>' && !isspace(complete_tag[i])) {
		//current_token.text += complete_tag[i];
		i++;
		count++;
	}
	// With gcc-2.x's STL, this is faster than using a bunch of += statements.
	current_token.text.assign(complete_tag+start, count);

	// Figure out which tag it is
	current_token.tag_id = tagID_NoTag;
	for (unsigned int x = 0; x < NUMBER_OF_TAG_MAPPINGS; x++) {
		if (!strcmp(current_token.text.c_str(), tag_mappings[x].tag_name)) {
			current_token.tag_id = tag_mappings[x].id;
			break;
		}
	}

	// If we're not at the end, we probably have attributes, so let's
	// pull them out. (We might just have whitespace though.)
	while (i < length) {
		string name, value;

		name  = "";
		value = "";

		// Skip whitespace
		while (i < length && isspace(complete_tag[i])) {
			i++;
		}

		// Now take text up to a whitespace or equal sign. This is the name
		start = i;
		count = 0;
		while (i < length
			   && !isspace(complete_tag[i])
			   && complete_tag[i] != '=') {
			//name += complete_tag[i];
			i++;
			count++;
		}
		// With gcc-2.x's STL, this is faster than using a bunch of += statements.
		name.assign(complete_tag+start, count);

		// Now skip whitespace and equal signs
		// Note that this allows some technically illegal things
		// like " == = = =", but who really cares?
		while (i < length
			   && (isspace(complete_tag[i]) || complete_tag[i] == '=')) {
			i++;
		}

		// Now pick out the value
		while (i < length && !isspace(complete_tag[i])) {
			if (complete_tag[i] != '"') {
				value += complete_tag[i];
			}
			i++;
		}
		if (name.size() > 0 && value.size() > 0) {
			current_token.attributes[name] = value;
		}
	}
	return;
}

bool XMLLexer::
GrabText(void)
{
	bool have_token;
	bool have_nonspace;

	current_token.token_type = tokenType_Text;
	have_nonspace = false;
	current_token.text = "";

	while (!lexer_source->AtEnd()) {
		int character;

		character = lexer_source->ReadCharacter();
		if (character == '<') {
			lexer_source->UnreadCharacter();
			break;
		} else {
			if (character == '&') {

				have_nonspace = true;

				// Figure out if this is an entity. If it is, figure
				// out what character should actually be put into the text;
				// First, find the text of the entity: it's text up and including
				// a semicolon. But finding a space or another & will stop us.

				string entity_text;
				entity_text = character;
				while (!lexer_source->AtEnd()) {
					int ch = lexer_source->ReadCharacter();
					if (ch == ' ') {
						// drop the entire text, including the space into the token
						entity_text += ch;
						current_token.text += entity_text;
						break;
					} else if (ch == '&') {
						// drop the text before the & into the token.
						// put back the & to be found the next time around, so
						// we can look for another entity
						lexer_source->UnreadCharacter();
						current_token.text += entity_text;
						break;
					} else if (ch == ';') {
						// End of an entity, do the comparison
						entity_text += ch;
						bool replaced_entity = false;
						for (unsigned int i = 0; i < NUMBER_OF_ENTITIES; i++){
							if (!strcmp(entity_text.c_str(), entities[i].name)) {
								current_token.text += entities[i].replacement_text;
								replaced_entity = true;
								break;
							}
						}
						if (!replaced_entity) {
							current_token.text += entity_text;
						}
						break;
					} else {
						entity_text += ch;
					}
				}
			} else {
				current_token.text += character;
				if (!isspace(character)) {
					have_nonspace = true;
				}
			}
		}
	}

	if (!have_nonspace) {
		// We know that we're at the end of the buffer, because
		// otherwise GrabTag would have been called.
		have_token = false;
	} else {
		have_token = true;
	}
	return have_token;
}

END_NAMESPACE // classad
<commit_msg>Correctly parse escape entities of the form &#nnn; now.<commit_after>/*********************************************************************
 *
 * Condor ClassAd library
 * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI, and Rajesh Raman.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 *********************************************************************/

#include "common.h"
#include "xmlLexer.h"

using namespace std;

BEGIN_NAMESPACE( classad )

// Note that these must be in the same order as the enum TagID
struct xml_tag_mapping tag_mappings[] =
{
	{"classads",        XMLLexer::tagID_ClassAds},
	{"c",               XMLLexer::tagID_ClassAd},
	{"a",               XMLLexer::tagID_Attribute},
	{"n",               XMLLexer::tagID_Number},
	{"s",               XMLLexer::tagID_String},
	{"b",               XMLLexer::tagID_Bool},
	{"un",              XMLLexer::tagID_Undefined},
	{"er",              XMLLexer::tagID_Error},
	{"t",               XMLLexer::tagID_Time},
	{"l",               XMLLexer::tagID_List},
	{"e",               XMLLexer::tagID_Expr},
	{"?xml",            XMLLexer::tagID_XML},
	{"?xml-stylesheet", XMLLexer::tagID_XMLStylesheet},
	{"DOCTYPE",         XMLLexer::tagID_Doctype}
};

struct entity
{
	char *name;
	char *replacement_text;
	int length;
};

#define NUMBER_OF_ENTITIES (sizeof(entities) / sizeof(struct entity))
struct entity entities[] =
{
	{"&",  "&",  5},
	{"<",   "<",  4},
	{">",   ">",  4},
	{""", "\"", 6},
	{"'", "'",  6}
};

XMLLexer::Token::
Token()
{
	return;
}

XMLLexer::Token::
~Token()
{
	return;
}

void XMLLexer::Token::
ClearToken(void)
{
	token_type = tokenType_Invalid;
	tag_type   = tagType_Invalid;
	tag_id     = tagID_NoTag;
	text       = "";
	attributes.clear();
	return;
}

void XMLLexer::Token::
DumpToken(void)
{
	if (token_type == tokenType_Tag) {
		printf("TAG: \"%s\", ", text.c_str());
		printf("  Type: ");
		switch (tag_type) {
		case tagType_Start:   printf("start, ");   break;
		case tagType_End:     printf("end, ");     break;
		case tagType_Empty:   printf("empty, ");   break;
		case tagType_Invalid: printf("invalid, "); break;
		default: break;
		}
		printf("  ID: ");
		switch (tag_id) {
		case tagID_ClassAds:  printf("classads\n"); break;
		case tagID_ClassAd:   printf("classad\n"); break;
		case tagID_Attribute: printf("attribute\n"); break;
		case tagID_Number:    printf("number\n"); break;
		case tagID_String:    printf("string\n"); break;
		case tagID_Bool:      printf("bool\n"); break;
		case tagID_Undefined: printf("undefined\n"); break;
		case tagID_Error:     printf("error\n"); break;
		case tagID_Time:      printf("time\n"); break;
		case tagID_List:      printf("list\n"); break;
		case tagID_Expr:      printf("expr\n"); break;
		case tagID_XML:       printf("?xml\n"); break;
		case tagID_XMLStylesheet: printf("?xmlStyleSheet\n"); break;
		case tagID_Doctype:   printf("DOCTYPE\n"); break;
		case tagID_NoTag:     printf("notag\n"); break;
		}
		XMLAttributesIterator  iter;

		for (iter = attributes.begin(); iter != attributes.end(); iter++) {
			printf("  Attribute: %s = \"%s\"\n",
				   iter->first.c_str(), iter->second.c_str());
		}
	} else if (token_type == tokenType_Text) {
		printf("TEXT: \"%s\"\n", text.c_str());
	} else {
		printf("Invalid token.\n");
	}
	return;
}

XMLLexer::
XMLLexer ()
{
	lexer_source = NULL;
	return;
}

XMLLexer::
~XMLLexer ()
{
	return;
}

void XMLLexer::
SetLexerSource(LexerSource *source)
{
	lexer_source = source;

	return;
}

bool XMLLexer::
ConsumeToken(Token *token)
{
	bool have_token;

	if (!token_is_valid) {
		have_token = PeekToken(token);
	} else {
		have_token = true;
		if (token != NULL) {
			*token = current_token;
		}
	}
	token_is_valid = false;

	return have_token;
}

bool XMLLexer::
PeekToken(Token *token)
{
	bool have_token;

	if (token_is_valid) {
		have_token = true;
	} else {
		have_token = GrabToken();
	}

	if (have_token) {
		if (token != NULL) {
			*token = current_token;
		}
		token_is_valid = true;
	}
	return have_token;
}

bool XMLLexer::
GrabToken(void)
{
	bool have_token;
	bool have_character;
	int  character;

	current_token.ClearToken();

	// Find first non-whitespace character, to decide if we
	// are getting a tag or some text. If we get text, we preserve
	// whitespace, because we keep whitespace in strings.
	have_character = false;
	while (!lexer_source->AtEnd()) {
		character = lexer_source->ReadCharacter();
		if (!isspace(character)) {
			have_character = true;
			break;
		}
	}

	if (have_character) {
		if (character == '<') {
			have_token = GrabTag();
		} else {
			lexer_source->UnreadCharacter();
			have_token = GrabText();
		}
	} else {
		have_token = false;
	}

	//current_token.DumpToken();

	return have_token;
}

bool XMLLexer::
GrabTag(void)
{
	bool    have_token;
	int     character;
	string  complete_tag; // the tag and its attributes

	current_token.token_type = tokenType_Tag;
	complete_tag = "";
	character = -1;

	// Skip whitespace
	while (!lexer_source->AtEnd()) {
		character = lexer_source->ReadCharacter();
		if (!isspace(character)) {
			complete_tag += character;
			break;
		}
	}

	// Read the rest of the tag, a character at a time
	while (!lexer_source->AtEnd()) {
		character = lexer_source->ReadCharacter();
		if (character != '>') {
			complete_tag += character;
		} else {
			break;
		}
	}

	if (character != '>') {
		// We have an unclosed tag. This will not do.
		have_token = false;
	} else {
		BreakdownTag(complete_tag.c_str());
		have_token = true;
	}
	return true;
}

void XMLLexer::
BreakdownTag(const char *complete_tag)
{
	int length, i;
	int start, count;

	length = strlen(complete_tag);

	// Skip whitespace
	for (i = 0; i < length && isspace(complete_tag[i]); i++) {
		;
	}

	// Is it a begin or end tag?
	if (complete_tag[i] == '/') {
		current_token.tag_type = tagType_End;
		i++;
	} else if (complete_tag[length-1] == '/') {
		current_token.tag_type = tagType_Empty;
		length--; // skip the / in the processing that follows.
	} else {
		current_token.tag_type = tagType_Start;
	}

	// Now pull out the tag name
	current_token.text = "";
	start = i;
	count = 0;
	while (i < length && i != '>' && !isspace(complete_tag[i])) {
		//current_token.text += complete_tag[i];
		i++;
		count++;
	}
	// With gcc-2.x's STL, this is faster than using a bunch of += statements.
	current_token.text.assign(complete_tag+start, count);

	// Figure out which tag it is
	current_token.tag_id = tagID_NoTag;
	for (unsigned int x = 0; x < NUMBER_OF_TAG_MAPPINGS; x++) {
		if (!strcmp(current_token.text.c_str(), tag_mappings[x].tag_name)) {
			current_token.tag_id = tag_mappings[x].id;
			break;
		}
	}

	// If we're not at the end, we probably have attributes, so let's
	// pull them out. (We might just have whitespace though.)
	while (i < length) {
		string name, value;

		name  = "";
		value = "";

		// Skip whitespace
		while (i < length && isspace(complete_tag[i])) {
			i++;
		}

		// Now take text up to a whitespace or equal sign. This is the name
		start = i;
		count = 0;
		while (i < length
			   && !isspace(complete_tag[i])
			   && complete_tag[i] != '=') {
			//name += complete_tag[i];
			i++;
			count++;
		}
		// With gcc-2.x's STL, this is faster than using a bunch of += statements.
		name.assign(complete_tag+start, count);

		// Now skip whitespace and equal signs
		// Note that this allows some technically illegal things
		// like " == = = =", but who really cares?
		while (i < length
			   && (isspace(complete_tag[i]) || complete_tag[i] == '=')) {
			i++;
		}

		// Now pick out the value
		while (i < length && !isspace(complete_tag[i])) {
			if (complete_tag[i] != '"') {
				value += complete_tag[i];
			}
			i++;
		}
		if (name.size() > 0 && value.size() > 0) {
			current_token.attributes[name] = value;
		}
	}
	return;
}

bool XMLLexer::
GrabText(void)
{
	bool have_token;
	bool have_nonspace;

	current_token.token_type = tokenType_Text;
	have_nonspace = false;
	current_token.text = "";

	while (!lexer_source->AtEnd()) {
		int character;

		character = lexer_source->ReadCharacter();
		if (character == '<') {
			lexer_source->UnreadCharacter();
			break;
		} else {
			if (character == '&') {

				have_nonspace = true;

				// Figure out if this is an entity. If it is, figure
				// out what character should actually be put into the text;
				// First, find the text of the entity: it's text up and including
				// a semicolon. But finding a space or another & will stop us.

				string entity_text;
				entity_text = character;
				while (!lexer_source->AtEnd()) {
					int ch = lexer_source->ReadCharacter();
					if (ch == ' ') {
						// drop the entire text, including the space into the token
						entity_text += ch;
						current_token.text += entity_text;
						break;
					} else if (ch == '&') {
						// drop the text before the & into the token.
						// put back the & to be found the next time around, so
						// we can look for another entity
						lexer_source->UnreadCharacter();
						current_token.text += entity_text;
						break;
					} else if (ch == ';') {
						bool replaced_entity = false;
						if (entity_text[1] == '#') {
							// We have a numeric entity, like A for 'A'
							const char *number_string = entity_text.c_str();
							int number = atoi(number_string+2); // +2 to skip &#
							if (number <= 255) {
								current_token.text += number;
								printf("current_token = %s\n", current_token.text.c_str());
								replaced_entity = true;
							}
						} else {
							// Non-numeric entity, do a comparison
							entity_text += ch;
							for (unsigned int i = 0; i < NUMBER_OF_ENTITIES; i++){
								if (!strcmp(entity_text.c_str(), entities[i].name)) {
									current_token.text += entities[i].replacement_text;
									replaced_entity = true;
									break;
								}
							}
						}
						if (!replaced_entity) {
							current_token.text += entity_text;
						}
						break;
					} else {
						entity_text += ch;
					}
				}
			} else {
				current_token.text += character;
				if (!isspace(character)) {
					have_nonspace = true;
				}
			}
		}
	}

	if (!have_nonspace) {
		// We know that we're at the end of the buffer, because
		// otherwise GrabTag would have been called.
		have_token = false;
	} else {
		have_token = true;
	}
	return have_token;
}

END_NAMESPACE // classad
<|endoftext|>