<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "buildconfiguration.h"

#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>

#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenu>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

///
/// BuildSettingsPanelFactory
///

bool BuildSettingsPanelFactory::supports(Project *project)
{
    return project->hasBuildSettings();
}

PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
    return new BuildSettingsPanel(project);
}

///
/// BuildSettingsPanel
///

BuildSettingsPanel::BuildSettingsPanel(Project *project)
        : PropertiesPanel(),
          m_widget(new BuildSettingsWidget(project))
{
}

BuildSettingsPanel::~BuildSettingsPanel()
{
    delete m_widget;
}

QString BuildSettingsPanel::name() const
{
    return tr("Build Settings");
}

QWidget *BuildSettingsPanel::widget()
{
    return m_widget;
}

///
// BuildSettingsSubWidgets
///

BuildSettingsSubWidgets::~BuildSettingsSubWidgets()
{
    clear();
}

void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget)
{
    QSpacerItem *item = new QSpacerItem(1, 10, QSizePolicy::Fixed, QSizePolicy::Fixed);

    QLabel *label = new QLabel(this);
    label->setText(name);
    QFont f = label->font();
    f.setBold(true);
    f.setPointSizeF(f.pointSizeF() *1.2);
    label->setFont(f);

    layout()->addItem(item);
    layout()->addWidget(label);
    layout()->addWidget(widget);

    m_labels.append(label);
    m_widgets.append(widget);
}

void BuildSettingsSubWidgets::clear()
{
    foreach(QSpacerItem *item, m_spacerItems)
        layout()->removeItem(item);
    qDeleteAll(m_spacerItems);
    qDeleteAll(m_widgets);
    qDeleteAll(m_labels);
    m_widgets.clear();
    m_labels.clear();
}

QList<QWidget *> BuildSettingsSubWidgets::widgets() const
{
    return m_widgets;
}

BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent)
    : QWidget(parent)
{
    new QVBoxLayout(this);
    layout()->setMargin(0);
}

///
/// BuildSettingsWidget
///

BuildSettingsWidget::~BuildSettingsWidget()
{
}

BuildSettingsWidget::BuildSettingsWidget(Project *project)
    : m_project(project)
{
    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setContentsMargins(0, -1, 0, -1);
    QHBoxLayout *hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
    m_buildConfigurationComboBox = new QComboBox(this);
    m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    hbox->addWidget(m_buildConfigurationComboBox);

    m_addButton = new QPushButton(this);
    m_addButton->setText(tr("Add"));
    m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_addButton);

    m_removeButton = new QPushButton(this);
    m_removeButton->setText(tr("Remove"));
    m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_removeButton);
    hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
    vbox->addLayout(hbox);

    m_subWidgets = new BuildSettingsSubWidgets(this);
    vbox->addWidget(m_subWidgets);

    m_addButtonMenu = new QMenu(this);
    m_addButton->setMenu(m_addButtonMenu);
    updateAddButtonMenu();

    m_buildConfiguration = m_project->activeBuildConfiguration()->name();

    connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentIndexChanged(int)));

    connect(m_removeButton, SIGNAL(clicked()),
            this, SLOT(deleteConfiguration()));

    connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
            this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));
    if (m_project->buildConfigurationFactory())
        connect(m_project->buildConfigurationFactory(), SIGNAL(availableCreationTypesChanged()), SLOT(updateAddButtonMenu()));

    updateBuildSettings();
}

void BuildSettingsWidget::updateAddButtonMenu()
{
    m_addButtonMenu->clear();
    m_addButtonMenu->addAction(tr("&Clone Selected"),
                             this, SLOT(cloneConfiguration()));
    IBuildConfigurationFactory *factory = m_project->buildConfigurationFactory();
    if (factory) {
        foreach (const QString &type, factory->availableCreationTypes()) {
            QAction *action = m_addButtonMenu->addAction(factory->displayNameForType(type), this, SLOT(createConfiguration()));
            action->setData(type);
        }
    }
}

void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration)
{
    for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) {
            m_buildConfigurationComboBox->setItemText(i, m_project->buildConfiguration(buildConfiguration)->displayName());
            break;
        }
    }
}

void BuildSettingsWidget::updateBuildSettings()
{
    // TODO save position, entry from combbox

    // Delete old tree items
    bool blocked = m_buildConfigurationComboBox->blockSignals(true);
    m_buildConfigurationComboBox->clear();
    m_subWidgets->clear();

    // update buttons
    m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);

    // Add pages
    BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget();
    m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget);

    m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project));
    m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));

    QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
    foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
        m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget);

    // Add tree items
    foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
        m_buildConfigurationComboBox->addItem(bc->displayName(), bc->name());
        if (bc->name() == m_buildConfiguration)
            m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
    }

    m_buildConfigurationComboBox->blockSignals(blocked);

    // TODO Restore position, entry from combbox
    // TODO? select entry from combobox ?
    activeBuildConfigurationChanged();
}

void BuildSettingsWidget::currentIndexChanged(int index)
{
    m_buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString();
    activeBuildConfigurationChanged();
}

void BuildSettingsWidget::activeBuildConfigurationChanged()
{
    for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == m_buildConfiguration) {
            m_buildConfigurationComboBox->setCurrentIndex(i);
            break;
        }
    }
    foreach (QWidget *widget, m_subWidgets->widgets()) {
        if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
            buildStepWidget->init(m_buildConfiguration);
        }
    }
}

void BuildSettingsWidget::createConfiguration()
{
    QAction *action = qobject_cast<QAction *>(sender());
    const QString &type = action->data().toString();
    if (m_project->buildConfigurationFactory()->create(type)) {
        // TODO switching to last buildconfiguration in list might not be what we want
        m_buildConfiguration = m_project->buildConfigurations().last()->name();
        updateBuildSettings();
    }
}

void BuildSettingsWidget::cloneConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    cloneConfiguration(configuration);
}

void BuildSettingsWidget::deleteConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    deleteConfiguration(configuration);
}

void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration)
{
    if (sourceConfiguration.isEmpty())
        return;

    QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:"));
    if (newBuildConfiguration.isEmpty())
        return;

    QString newDisplayName = newBuildConfiguration;
    QStringList buildConfigurationDisplayNames;
    foreach(BuildConfiguration *bc, m_project->buildConfigurations())
        buildConfigurationDisplayNames << bc->displayName();
    newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);

    QStringList buildConfigurationNames;
    foreach(BuildConfiguration *bc, m_project->buildConfigurations())
        buildConfigurationNames << bc->name();

    newBuildConfiguration = Project::makeUnique(newBuildConfiguration, buildConfigurationNames);

    m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration);
    m_project->setDisplayNameFor(m_project->buildConfiguration(newBuildConfiguration), newDisplayName);

    m_buildConfiguration = newBuildConfiguration;
    updateBuildSettings();
}

void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration)
{
    if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1)
        return;

    if (m_project->activeBuildConfiguration()->name() == deleteConfiguration) {
        foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
            if (bc->name() != deleteConfiguration) {
                m_project->setActiveBuildConfiguration(bc);
                break;
            }
        }
    }

    if (m_buildConfiguration == deleteConfiguration) {
        foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
            if (bc->name() != deleteConfiguration) {
                m_buildConfiguration = bc->name();
                break;
            }
        }
    }

    m_project->removeBuildConfiguration(m_project->buildConfiguration(deleteConfiguration));

    updateBuildSettings();
}
<commit_msg>Fix handling of spacers on Projects pane<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "buildconfiguration.h"

#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>

#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenu>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

///
/// BuildSettingsPanelFactory
///

bool BuildSettingsPanelFactory::supports(Project *project)
{
    return project->hasBuildSettings();
}

PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
    return new BuildSettingsPanel(project);
}

///
/// BuildSettingsPanel
///

BuildSettingsPanel::BuildSettingsPanel(Project *project)
        : PropertiesPanel(),
          m_widget(new BuildSettingsWidget(project))
{
}

BuildSettingsPanel::~BuildSettingsPanel()
{
    delete m_widget;
}

QString BuildSettingsPanel::name() const
{
    return tr("Build Settings");
}

QWidget *BuildSettingsPanel::widget()
{
    return m_widget;
}

///
// BuildSettingsSubWidgets
///

BuildSettingsSubWidgets::~BuildSettingsSubWidgets()
{
    clear();
}

void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget)
{
    QSpacerItem *item = new QSpacerItem(1, 10, QSizePolicy::Fixed, QSizePolicy::Fixed);

    QLabel *label = new QLabel(this);
    label->setText(name);
    QFont f = label->font();
    f.setBold(true);
    f.setPointSizeF(f.pointSizeF() *1.2);
    label->setFont(f);

    layout()->addItem(item);
    layout()->addWidget(label);
    layout()->addWidget(widget);

    m_spacerItems.append(item);
    m_labels.append(label);
    m_widgets.append(widget);
}

void BuildSettingsSubWidgets::clear()
{
    foreach(QSpacerItem *item, m_spacerItems)
        layout()->removeItem(item);
    qDeleteAll(m_spacerItems);
    qDeleteAll(m_widgets);
    qDeleteAll(m_labels);
    m_widgets.clear();
    m_labels.clear();
    m_spacerItems.clear();
}

QList<QWidget *> BuildSettingsSubWidgets::widgets() const
{
    return m_widgets;
}

BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent)
    : QWidget(parent)
{
    new QVBoxLayout(this);
    layout()->setMargin(0);
}

///
/// BuildSettingsWidget
///

BuildSettingsWidget::~BuildSettingsWidget()
{
}

BuildSettingsWidget::BuildSettingsWidget(Project *project)
    : m_project(project)
{
    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setContentsMargins(0, -1, 0, -1);
    QHBoxLayout *hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
    m_buildConfigurationComboBox = new QComboBox(this);
    m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    hbox->addWidget(m_buildConfigurationComboBox);

    m_addButton = new QPushButton(this);
    m_addButton->setText(tr("Add"));
    m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_addButton);

    m_removeButton = new QPushButton(this);
    m_removeButton->setText(tr("Remove"));
    m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_removeButton);
    hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
    vbox->addLayout(hbox);

    m_subWidgets = new BuildSettingsSubWidgets(this);
    vbox->addWidget(m_subWidgets);

    m_addButtonMenu = new QMenu(this);
    m_addButton->setMenu(m_addButtonMenu);
    updateAddButtonMenu();

    m_buildConfiguration = m_project->activeBuildConfiguration()->name();

    connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentIndexChanged(int)));

    connect(m_removeButton, SIGNAL(clicked()),
            this, SLOT(deleteConfiguration()));

    connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
            this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));
    if (m_project->buildConfigurationFactory())
        connect(m_project->buildConfigurationFactory(), SIGNAL(availableCreationTypesChanged()), SLOT(updateAddButtonMenu()));

    updateBuildSettings();
}

void BuildSettingsWidget::updateAddButtonMenu()
{
    m_addButtonMenu->clear();
    m_addButtonMenu->addAction(tr("&Clone Selected"),
                             this, SLOT(cloneConfiguration()));
    IBuildConfigurationFactory *factory = m_project->buildConfigurationFactory();
    if (factory) {
        foreach (const QString &type, factory->availableCreationTypes()) {
            QAction *action = m_addButtonMenu->addAction(factory->displayNameForType(type), this, SLOT(createConfiguration()));
            action->setData(type);
        }
    }
}

void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration)
{
    for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) {
            m_buildConfigurationComboBox->setItemText(i, m_project->buildConfiguration(buildConfiguration)->displayName());
            break;
        }
    }
}

void BuildSettingsWidget::updateBuildSettings()
{
    // TODO save position, entry from combbox

    // Delete old tree items
    bool blocked = m_buildConfigurationComboBox->blockSignals(true);
    m_buildConfigurationComboBox->clear();
    m_subWidgets->clear();

    // update buttons
    m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);

    // Add pages
    BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget();
    m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget);

    m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project));
    m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));

    QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
    foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
        m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget);

    // Add tree items
    foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
        m_buildConfigurationComboBox->addItem(bc->displayName(), bc->name());
        if (bc->name() == m_buildConfiguration)
            m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
    }

    m_buildConfigurationComboBox->blockSignals(blocked);

    // TODO Restore position, entry from combbox
    // TODO? select entry from combobox ?
    activeBuildConfigurationChanged();
}

void BuildSettingsWidget::currentIndexChanged(int index)
{
    m_buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString();
    activeBuildConfigurationChanged();
}

void BuildSettingsWidget::activeBuildConfigurationChanged()
{
    for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == m_buildConfiguration) {
            m_buildConfigurationComboBox->setCurrentIndex(i);
            break;
        }
    }
    foreach (QWidget *widget, m_subWidgets->widgets()) {
        if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
            buildStepWidget->init(m_buildConfiguration);
        }
    }
}

void BuildSettingsWidget::createConfiguration()
{
    QAction *action = qobject_cast<QAction *>(sender());
    const QString &type = action->data().toString();
    if (m_project->buildConfigurationFactory()->create(type)) {
        // TODO switching to last buildconfiguration in list might not be what we want
        m_buildConfiguration = m_project->buildConfigurations().last()->name();
        updateBuildSettings();
    }
}

void BuildSettingsWidget::cloneConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    cloneConfiguration(configuration);
}

void BuildSettingsWidget::deleteConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    deleteConfiguration(configuration);
}

void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration)
{
    if (sourceConfiguration.isEmpty())
        return;

    QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:"));
    if (newBuildConfiguration.isEmpty())
        return;

    QString newDisplayName = newBuildConfiguration;
    QStringList buildConfigurationDisplayNames;
    foreach(BuildConfiguration *bc, m_project->buildConfigurations())
        buildConfigurationDisplayNames << bc->displayName();
    newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);

    QStringList buildConfigurationNames;
    foreach(BuildConfiguration *bc, m_project->buildConfigurations())
        buildConfigurationNames << bc->name();

    newBuildConfiguration = Project::makeUnique(newBuildConfiguration, buildConfigurationNames);

    m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration);
    m_project->setDisplayNameFor(m_project->buildConfiguration(newBuildConfiguration), newDisplayName);

    m_buildConfiguration = newBuildConfiguration;
    updateBuildSettings();
}

void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration)
{
    if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1)
        return;

    if (m_project->activeBuildConfiguration()->name() == deleteConfiguration) {
        foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
            if (bc->name() != deleteConfiguration) {
                m_project->setActiveBuildConfiguration(bc);
                break;
            }
        }
    }

    if (m_buildConfiguration == deleteConfiguration) {
        foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
            if (bc->name() != deleteConfiguration) {
                m_buildConfiguration = bc->name();
                break;
            }
        }
    }

    m_project->removeBuildConfiguration(m_project->buildConfiguration(deleteConfiguration));

    updateBuildSettings();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: openflag.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:52:34 $
 *
 *  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 _SFX_OPENFLAG_HXX
#define _SFX_OPENFLAG_HXX

// Datei zum Bearbeiten "offnen, anschliessend funktioniert nur noch
// die dritte Variante (Lesen einer Kopie)
#define SFX_STREAM_READWRITE  (STREAM_READWRITE |  STREAM_SHARE_DENYWRITE)
// Ich arbeite roh auf dem Original, keine Kopie
// -> Datei kann anschliessend nicht zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY   (STREAM_READ | STREAM_SHARE_DENYWRITE) // + !bDirect
// Jemand anders bearbeitet das File, es wird eine Kopie erstellt
// -> Datei kann anschliessend zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY_MAKECOPY   (STREAM_READ | STREAM_SHARE_DENYNONE)

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1086); FILE MERGED 2005/09/06 13:05:35 rt 1.1.1.1.1086.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: openflag.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:08:20 $
 *
 *  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 _SFX_OPENFLAG_HXX
#define _SFX_OPENFLAG_HXX

// Datei zum Bearbeiten "offnen, anschliessend funktioniert nur noch
// die dritte Variante (Lesen einer Kopie)
#define SFX_STREAM_READWRITE  (STREAM_READWRITE |  STREAM_SHARE_DENYWRITE)
// Ich arbeite roh auf dem Original, keine Kopie
// -> Datei kann anschliessend nicht zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY   (STREAM_READ | STREAM_SHARE_DENYWRITE) // + !bDirect
// Jemand anders bearbeitet das File, es wird eine Kopie erstellt
// -> Datei kann anschliessend zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY_MAKECOPY   (STREAM_READ | STREAM_SHARE_DENYNONE)

#endif
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "ThreadProfiler.h"

#include "Logger.h"
#include "Exception.h"
#include "ProfilingZone.h"
#include "ScopeTimer.h"

#include <sstream>
#include <iomanip>
#include <iostream>

using namespace std;
using namespace boost;

namespace avg {

thread_specific_ptr<ThreadProfiler*> ThreadProfiler::s_pInstance;

ThreadProfiler* ThreadProfiler::get()
{
    if (s_pInstance.get() == 0) {
        s_pInstance.reset(new (ThreadProfiler*));
        *s_pInstance = new ThreadProfiler();
    }
    return *s_pInstance;
}

void ThreadProfiler::kill()
{
    s_pInstance.reset();
}

ThreadProfiler::ThreadProfiler()
    : m_sName(""),
      m_LogCategory(Logger::PROFILE)
{
    m_bRunning = false;
    ScopeTimer::enableTimers(Logger::get()->isFlagSet(Logger::PROFILE));
}

ThreadProfiler::~ThreadProfiler()
{
}

void ThreadProfiler::setLogCategory(long category)
{
    AVG_ASSERT(!m_bRunning);
    m_LogCategory = category;
}

void ThreadProfiler::start()
{
    m_bRunning = true;
}

void ThreadProfiler::restart()
{
    ZoneVector::iterator it;
    for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
        (*it)->restart();
    }
}

void ThreadProfiler::startZone(const ProfilingZoneID& zoneID)
{
    ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
    // Duplicated code to avoid instantiating a new smart pointer when it's not
    // necessary.
    if (it == m_ZoneMap.end()) {
        ProfilingZonePtr pZone = addZone(zoneID);
        pZone->start();
        m_ActiveZones.push_back(pZone);
    } else {
        ProfilingZonePtr& pZone = it->second;
        pZone->start();
        m_ActiveZones.push_back(pZone);
    }
}

void ThreadProfiler::stopZone(const ProfilingZoneID& zoneID)
{
    ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
    ProfilingZonePtr& pZone = it->second;
    pZone->stop();
    m_ActiveZones.pop_back();
}

void ThreadProfiler::dumpStatistics()
{
    if (!m_Zones.empty()) {
        AVG_TRACE(m_LogCategory, "Thread " << m_sName);
        AVG_TRACE(m_LogCategory, "Zone name                          Avg. time");
        AVG_TRACE(m_LogCategory, "---------                          ---------");

        ZoneVector::iterator it;
        for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
            AVG_TRACE(m_LogCategory,
                    std::setw(35) << std::left
                    << ((*it)->getIndentString()+(*it)->getName())
                    << std::setw(9) << std::right << (*it)->getAvgUSecs());
        }
        AVG_TRACE(m_LogCategory, "");
    }
}

void ThreadProfiler::reset()
{
    ZoneVector::iterator it;
    for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
        (*it)->reset();
    }
}

int ThreadProfiler::getNumZones()
{
    return m_Zones.size();
}

const std::string& ThreadProfiler::getName() const
{
    return m_sName;
}

void ThreadProfiler::setName(const std::string& sName)
{
    m_sName = sName;
}

ProfilingZonePtr ThreadProfiler::addZone(const ProfilingZoneID& zoneID)
{
    ProfilingZonePtr pZone(new ProfilingZone(zoneID));
    m_ZoneMap[&zoneID] = pZone;
    ZoneVector::iterator it;
    int parentIndent = -2;
    if (m_ActiveZones.empty()) {
        it = m_Zones.end();
    } else {
        ProfilingZonePtr pActiveZone = m_ActiveZones.back();
        bool bParentFound = false;
        for (it = m_Zones.begin(); it != m_Zones.end(); ++it)
        {
            if (pActiveZone == *it) {
                bParentFound = true;
                break;
            }
        }
        AVG_ASSERT(bParentFound);
        parentIndent = pActiveZone->getIndentLevel();
        ++it;
        for (; it != m_Zones.end() && (*it)->getIndentLevel() > parentIndent; ++it) {};
    }
    m_Zones.insert(it, pZone);
    pZone->setIndentLevel(parentIndent+2);
    return pZone;
}

}

<commit_msg>video branch: Merge from trunk.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "ThreadProfiler.h"

#include "Logger.h"
#include "Exception.h"
#include "ProfilingZone.h"
#include "ScopeTimer.h"

#include <sstream>
#include <iomanip>
#include <iostream>

using namespace std;
using namespace boost;

namespace avg {

thread_specific_ptr<ThreadProfiler*> ThreadProfiler::s_pInstance;

ThreadProfiler* ThreadProfiler::get()
{
    if (s_pInstance.get() == 0) {
        s_pInstance.reset(new (ThreadProfiler*));
        *s_pInstance = new ThreadProfiler();
    }
    return *s_pInstance;
}

void ThreadProfiler::kill()
{
    delete *s_pInstance;
    s_pInstance.reset();
}

ThreadProfiler::ThreadProfiler()
    : m_sName(""),
      m_LogCategory(Logger::PROFILE)
{
    m_bRunning = false;
    ScopeTimer::enableTimers(Logger::get()->isFlagSet(Logger::PROFILE));
}

ThreadProfiler::~ThreadProfiler()
{
}

void ThreadProfiler::setLogCategory(long category)
{
    AVG_ASSERT(!m_bRunning);
    m_LogCategory = category;
}

void ThreadProfiler::start()
{
    m_bRunning = true;
}

void ThreadProfiler::restart()
{
    ZoneVector::iterator it;
    for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
        (*it)->restart();
    }
}

void ThreadProfiler::startZone(const ProfilingZoneID& zoneID)
{
    ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
    // Duplicated code to avoid instantiating a new smart pointer when it's not
    // necessary.
    if (it == m_ZoneMap.end()) {
        ProfilingZonePtr pZone = addZone(zoneID);
        pZone->start();
        m_ActiveZones.push_back(pZone);
    } else {
        ProfilingZonePtr& pZone = it->second;
        pZone->start();
        m_ActiveZones.push_back(pZone);
    }
}

void ThreadProfiler::stopZone(const ProfilingZoneID& zoneID)
{
    ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
    ProfilingZonePtr& pZone = it->second;
    pZone->stop();
    m_ActiveZones.pop_back();
}

void ThreadProfiler::dumpStatistics()
{
    if (!m_Zones.empty()) {
        AVG_TRACE(m_LogCategory, "Thread " << m_sName);
        AVG_TRACE(m_LogCategory, "Zone name                          Avg. time");
        AVG_TRACE(m_LogCategory, "---------                          ---------");

        ZoneVector::iterator it;
        for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
            AVG_TRACE(m_LogCategory,
                    std::setw(35) << std::left
                    << ((*it)->getIndentString()+(*it)->getName())
                    << std::setw(9) << std::right << (*it)->getAvgUSecs());
        }
        AVG_TRACE(m_LogCategory, "");
    }
}

void ThreadProfiler::reset()
{
    ZoneVector::iterator it;
    for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
        (*it)->reset();
    }
}

int ThreadProfiler::getNumZones()
{
    return m_Zones.size();
}

const std::string& ThreadProfiler::getName() const
{
    return m_sName;
}

void ThreadProfiler::setName(const std::string& sName)
{
    m_sName = sName;
}

ProfilingZonePtr ThreadProfiler::addZone(const ProfilingZoneID& zoneID)
{
    ProfilingZonePtr pZone(new ProfilingZone(zoneID));
    m_ZoneMap[&zoneID] = pZone;
    ZoneVector::iterator it;
    int parentIndent = -2;
    if (m_ActiveZones.empty()) {
        it = m_Zones.end();
    } else {
        ProfilingZonePtr pActiveZone = m_ActiveZones.back();
        bool bParentFound = false;
        for (it = m_Zones.begin(); it != m_Zones.end(); ++it)
        {
            if (pActiveZone == *it) {
                bParentFound = true;
                break;
            }
        }
        AVG_ASSERT(bParentFound);
        parentIndent = pActiveZone->getIndentLevel();
        ++it;
        for (; it != m_Zones.end() && (*it)->getIndentLevel() > parentIndent; ++it) {};
    }
    m_Zones.insert(it, pZone);
    pZone->setIndentLevel(parentIndent+2);
    return pZone;
}

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: impldde.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-22 10:55:09 $
 *
 *  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 _IMPLDDE_HXX
#define _IMPLDDE_HXX

#include <linksrc.hxx>
#include <tools/string.hxx>

class DdeConnection;
class DdeData;
class DdeLink;
class DdeRequest;
class DdeTransaction;

namespace sfx2
{

class SvDDEObject : public SvLinkSource
{
    String sItem;

    DdeConnection* pConnection;
    DdeLink* pLink;
    DdeRequest* pRequest;
    ::com::sun::star::uno::Any * pGetData;

    BYTE bWaitForData : 1;                  // wird auf Daten gewartet?
    BYTE nError     : 7;                    // Error Code fuer den Dialog

    BOOL ImplHasOtherFormat( DdeTransaction& );
    DECL_LINK( ImplGetDDEData, DdeData* );
    DECL_LINK( ImplDoneDDEData, void* );

protected:
    virtual ~SvDDEObject();

public:
    SvDDEObject();

    virtual BOOL    GetData( ::com::sun::star::uno::Any & rData /*out param*/,
                                const String & aMimeType,
                                BOOL bSynchron = FALSE );

    virtual BOOL    Connect( SvBaseLink * );
    virtual void    Edit( Window* pParent, sfx2::SvBaseLink* pBaseLink, const Link& rEndEditHdl );

    virtual BOOL    IsPending() const;
    virtual BOOL    IsDataComplete() const;
};

}

#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.154); FILE MERGED 2007/06/04 13:34:39 vg 1.4.154.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: impldde.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 22:59:10 $
 *
 *  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 _IMPLDDE_HXX
#define _IMPLDDE_HXX

#include <sfx2/linksrc.hxx>
#include <tools/string.hxx>

class DdeConnection;
class DdeData;
class DdeLink;
class DdeRequest;
class DdeTransaction;

namespace sfx2
{

class SvDDEObject : public SvLinkSource
{
    String sItem;

    DdeConnection* pConnection;
    DdeLink* pLink;
    DdeRequest* pRequest;
    ::com::sun::star::uno::Any * pGetData;

    BYTE bWaitForData : 1;                  // wird auf Daten gewartet?
    BYTE nError     : 7;                    // Error Code fuer den Dialog

    BOOL ImplHasOtherFormat( DdeTransaction& );
    DECL_LINK( ImplGetDDEData, DdeData* );
    DECL_LINK( ImplDoneDDEData, void* );

protected:
    virtual ~SvDDEObject();

public:
    SvDDEObject();

    virtual BOOL    GetData( ::com::sun::star::uno::Any & rData /*out param*/,
                                const String & aMimeType,
                                BOOL bSynchron = FALSE );

    virtual BOOL    Connect( SvBaseLink * );
    virtual void    Edit( Window* pParent, sfx2::SvBaseLink* pBaseLink, const Link& rEndEditHdl );

    virtual BOOL    IsPending() const;
    virtual BOOL    IsDataComplete() const;
};

}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: viewfac.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-21 13:21:31 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
// INCLUDE ---------------------------------------------------------------

#ifndef GCC
#pragma hdrstop
#endif

#include "app.hxx"
#include "viewfac.hxx"

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxViewFactory);

SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh )
{
    DBG_CHKTHIS(SfxViewFactory, 0);
    return (*fnCreate)(pFrame, pOldSh);
}

void SfxViewFactory::InitFactory()
{
    DBG_CHKTHIS(SfxViewFactory, 0);
    (*fnInit)();
}

// CTOR / DTOR -----------------------------------------------------------

SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI,
                                USHORT nOrdinal, const ResId& aDescrResId ):
    fnCreate(fnC),
    fnInit(fnI),
    nOrd(nOrdinal),
    aDescription(aDescrResId.GetId(), aDescrResId.GetResMgr())
{
    aDescription.SetRT(aDescrResId.GetRT());
    DBG_CTOR(SfxViewFactory, 0);
//  SFX_APP()->RegisterViewFactory_Impl(*this);
}

SfxViewFactory::~SfxViewFactory()
{
    DBG_DTOR(SfxViewFactory, 0);
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.566); FILE MERGED 2005/09/06 13:06:16 rt 1.2.566.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: viewfac.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:32:01 $
 *
 *  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
 *
 ************************************************************************/
// INCLUDE ---------------------------------------------------------------

#ifndef GCC
#pragma hdrstop
#endif

#include "app.hxx"
#include "viewfac.hxx"

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxViewFactory);

SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh )
{
    DBG_CHKTHIS(SfxViewFactory, 0);
    return (*fnCreate)(pFrame, pOldSh);
}

void SfxViewFactory::InitFactory()
{
    DBG_CHKTHIS(SfxViewFactory, 0);
    (*fnInit)();
}

// CTOR / DTOR -----------------------------------------------------------

SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI,
                                USHORT nOrdinal, const ResId& aDescrResId ):
    fnCreate(fnC),
    fnInit(fnI),
    nOrd(nOrdinal),
    aDescription(aDescrResId.GetId(), aDescrResId.GetResMgr())
{
    aDescription.SetRT(aDescrResId.GetRT());
    DBG_CTOR(SfxViewFactory, 0);
//  SFX_APP()->RegisterViewFactory_Impl(*this);
}

SfxViewFactory::~SfxViewFactory()
{
    DBG_DTOR(SfxViewFactory, 0);
}

<|endoftext|>


<commit_before><commit_msg>fdo#83302 don't display read-only infobar for Base form in normal mode<commit_after><|endoftext|>


<commit_before>#include <iostream>

using namespace std;

// devuelve true si hay elementos iguales o si hay algún cero
bool verificarElementosArray(int numero, int siguiente, int array[9])
{
	if (numero > 7) return false;

	int i = siguiente;
	while (numero <= 7 && i <= 8)
	{
		if ( (array[numero] == 0 || array[i] == 0) || (array[numero] == array[i]) )
		{
			return true;
			break;
		}

		i++;
	}

	return verificarElementosArray(numero +1, siguiente +1, array[9]);
}

bool verificarColumnas(int tablero[9][9])
{
	int arr[9];

	for(int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			arr[j] = tablero[j][i];
		}

		return verificarElementosArray(0, 1, arr[9]);

	}
}

bool verificarCuadrantes (int tablero[3][3])
{
	int indice;
	int arrayMatriz[9];

	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			indice = matriz[i][j] -1;
			arrayMatriz[indice] = matriz[i][j];
		}
	}

	return verificarElementosArray(0, 1, arrayMatriz[9]);
}

void obtenerCuadrantes (tablero[9][9]) // esta función debe devolver una matriz de 3x3
{
	int  columna = 0;
	int limiteColumna = 3;
	int cambioLimitesColumna;

	int fila = 0;
	int limiteFila = 3;
	int cambioLimitesFila;

	int subMatriz[3][3];

	int i = 0
	while (i < 9)
	{
		for (fila; fila < limiteFila; fila++)
		{
			for (columna; columna < limiteColumna; columna++)
			{
				subMatriz[fila][columna] = tablero[fila][columna];
			}
		}

		verificarCuadrantes(subMatriz[3][3]);
	}

	cambioLimitesFila = limiteFila
	fila = cambioLimitesFila;
	limiteFila += 3;

	if (limiteFila > 9)
	{
		limiteFila = 3;
		fila = 0;

		cambioLimitesColumna = limiteColumna;
		columna = cambioLimitesColumna;
		limiteColumna += 3;
	}

	i++;

}

int main ()
{
	int matriz[9][9] = {
		{00, 01 ,02, 03, 04, 05, 06, 07,  8},
		{10, 11, 12, 13, 14, 15, 16, 17, 18},
		{20, 21, 22, 23, 24, 25, 26, 27, 28},
		{30, 31, 32, 33, 34, 35, 36, 37, 38},
		{40, 41, 42, 43, 44, 45, 46, 47, 48},
		{50, 51, 52, 53, 54, 55, 56, 57, 58},
		{60, 61, 62, 63, 64, 65, 66, 67, 68},
		{70, 71, 72, 73, 74, 75, 76, 77, 78},
		{80, 81, 82, 83, 84, 85, 86, 87, 88}
	};

	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			cout << matriz[i][j] << " ";
		}
		cout << endl;
	}

	cout << "\n\n";

	int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	if (verificarElementosArray(0, 1, arr[])) cout << "hay elementos repeditos\n";
	else cout << "no hay elementos repetidos\n";

	return 0;
}
<commit_msg>Se agrega debug para encontrar errores en el codigo<commit_after>#include <iostream>

using namespace std;

// devuelve true si hay elementos iguales o si hay algún cero
bool verificarElementosArray(int numero, int siguiente, int array[9])
{
	if (numero > 7) return false;

	int i = siguiente;
	cout <<"\n\t verificarElementosArray"<<endl;

	cout <<"numero: "<<numero<<endl;
	cout <<"siguiente: "<<siguiente<<endl;

	while (numero <= 7 && i <= 8)
	{
		cout <<"i: "<<i<<endl;
		cout <<"A[numero]: A["<<numero<<"]: "<<array[numero]<<endl;
		cout <<"A[i]: A["<<i<<"]: "<<array[i]<<endl;
		if ( /*(array[numero] == 0 || array[i] == 0) ||*/ (array[numero] == array[i]) )
		{
			return true;
		}
		i++;
	}

	return verificarElementosArray(numero +1, siguiente +1, array);
}

bool verificarColumnas(int tablero[9][9])
{
	int arr[9];

	for(int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			arr[j] = tablero[j][i];
		}

		return verificarElementosArray(0, 1, arr);

	}
}

bool verificarCuadrantes (int tablero[3][3])
{
	int indice;
	int arrayMatriz[9];

	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			indice = tablero[i][j] - 1;
			arrayMatriz[indice] = tablero[i][j];
		}
	}

	return verificarElementosArray(0, 1, arrayMatriz);
}

void obtenerCuadrantes (int tablero[9][9]) // esta función debe devolver una matriz de 3x3
{
	int  columna = 0;
	int limiteColumna = 3;
	int cambioLimitesColumna;

	int fila = 0;
	int limiteFila = 3;
	int cambioLimitesFila;

	int subMatriz[3][3];

	int i = 0;
	while (i < 9)
	{
		for (fila; fila < limiteFila; fila++)
		{
			for (columna; columna < limiteColumna; columna++)
			{
				subMatriz[fila][columna] = tablero[fila][columna];
			}
		}

		verificarCuadrantes(subMatriz);
	}

	cambioLimitesFila = limiteFila;
	fila = cambioLimitesFila;
	limiteFila += 3;

	if (limiteFila > 9)
	{
		limiteFila = 3;
		fila = 0;

		cambioLimitesColumna = limiteColumna;
		columna = cambioLimitesColumna;
		limiteColumna += 3;
	}

	i++;

}

void imprimirArray(int a[]){

		for (int j = 0; j < 9; j++)
		{
			cout << a[j] << " ";
		}
		cout <<endl;
}

int main ()
{
	int matriz[9][9] = {
		{00, 01 ,02, 03, 04, 05, 06, 07,  8},
		{10, 11, 12, 13, 14, 15, 16, 17, 18},
		{20, 21, 22, 23, 24, 25, 26, 27, 28},
		{30, 31, 32, 33, 34, 35, 36, 37, 38},
		{40, 41, 42, 43, 44, 45, 46, 47, 48},
		{50, 51, 52, 53, 54, 55, 56, 57, 58},
		{60, 61, 62, 63, 64, 65, 66, 67, 68},
		{70, 71, 72, 73, 74, 75, 76, 77, 78},
		{80, 81, 82, 83, 84, 85, 86, 87, 88}
	};

	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			cout << matriz[i][j] << " ";
		}
		cout << endl;
	}

	cout << "\n\n";

	int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	imprimirArray(arr);

	bool respuesta = verificarElementosArray(0, 1, arr);
	cout <<" -> "<<respuesta<<endl;

	if (respuesta) cout << " hay elementos repeditos\n";
	else cout << "no hay elementos repetidos\n";

	return 0;
}
<|endoftext|>


<commit_before>/**
 * staticunittest.cpp
 *
 * Copyright (C)  2004  Brad Hards <bradh@frogmouth.net>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "staticunittest.h"
#include "qca.h"

StaticUnitTest::StaticUnitTest()
    : Tester()
{

}

void StaticUnitTest::allTests()
{
    QCA::Initializer init;

    QByteArray test(10);
    test.fill('a');

    CHECK( QCA::arrayToHex(test), QString("61616161616161616161") );

    test.fill('b');
    test[7] = 0x00;

    CHECK( test == QCA::hexToArray(QString("62626262626262006262")), true );

    QSecureArray testArray(10);
    //testArray.fill( 'a' );
    for (unsigned int i = 0; i < testArray.size(); i++) {
	testArray[ i ] = 0x61;
    }
    CHECK( QCA::arrayToHex( testArray ), QString( "61616161616161616161" ) );
    //testArray.fill( 'b' );
    for (unsigned int i = 0; i < testArray.size(); i++) {
	testArray[ i ] = 0x62;
    }
    testArray[6] = 0x00;
    CHECK( testArray == QCA::hexToArray(QString("62626262626200626262")), true );

    // capabilities are reported as a list - that is a problem for
    // doing a direct comparison, since they change
    // We try to work around that using contains()
    QStringList supportedCapabilities = QCA::supportedFeatures();
    CHECK( supportedCapabilities.contains("random"), (size_t)1 );
    CHECK( supportedCapabilities.contains("sha1"), (size_t)1 );
    CHECK( supportedCapabilities.contains("sha0"), (size_t)1 );
    CHECK( supportedCapabilities.contains("md2"), (size_t)1 );
    CHECK( supportedCapabilities.contains("md4"), (size_t)1 );
    CHECK( supportedCapabilities.contains("md5"), (size_t)1 );
    CHECK( supportedCapabilities.contains("ripemd160"), (size_t)1 );

    QStringList defaultCapabilities = QCA::defaultFeatures();
    CHECK( defaultCapabilities.contains("random"), (size_t)1 );

    CHECK( QCA::isSupported("random"), true );
    CHECK( QCA::isSupported("sha0"), true );
    CHECK( QCA::isSupported("sha0,sha1"), true );
    CHECK( QCA::isSupported("md2,md4,md5"), true );
    CHECK( QCA::isSupported("md5"), true );
    CHECK( QCA::isSupported("ripemd160"), true );
    CHECK( QCA::isSupported("nosuchfeature"), false );

    QString caps( "random,sha1,md5,ripemd160");
    QStringList capList;
    capList.split( caps, "," );
    CHECK( QCA::isSupported(capList), true );
    capList.append("noSuch");
    CHECK( QCA::isSupported(capList), false );

}

<commit_msg>One more test step, covering the "just one, doesn't exist" provider<commit_after>/**
 * staticunittest.cpp
 *
 * Copyright (C)  2004  Brad Hards <bradh@frogmouth.net>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "staticunittest.h"
#include "qca.h"

StaticUnitTest::StaticUnitTest()
    : Tester()
{

}

void StaticUnitTest::allTests()
{
    QCA::Initializer init;

    QByteArray test(10);
    test.fill('a');

    CHECK( QCA::arrayToHex(test), QString("61616161616161616161") );

    test.fill('b');
    test[7] = 0x00;

    CHECK( test == QCA::hexToArray(QString("62626262626262006262")), true );

    QSecureArray testArray(10);
    //testArray.fill( 'a' );
    for (unsigned int i = 0; i < testArray.size(); i++) {
	testArray[ i ] = 0x61;
    }
    CHECK( QCA::arrayToHex( testArray ), QString( "61616161616161616161" ) );
    //testArray.fill( 'b' );
    for (unsigned int i = 0; i < testArray.size(); i++) {
	testArray[ i ] = 0x62;
    }
    testArray[6] = 0x00;
    CHECK( testArray == QCA::hexToArray(QString("62626262626200626262")), true );

    // capabilities are reported as a list - that is a problem for
    // doing a direct comparison, since they change
    // We try to work around that using contains()
    QStringList supportedCapabilities = QCA::supportedFeatures();
    CHECK( supportedCapabilities.contains("random"), (size_t)1 );
    CHECK( supportedCapabilities.contains("sha1"), (size_t)1 );
    CHECK( supportedCapabilities.contains("sha0"), (size_t)1 );
    CHECK( supportedCapabilities.contains("md2"), (size_t)1 );
    CHECK( supportedCapabilities.contains("md4"), (size_t)1 );
    CHECK( supportedCapabilities.contains("md5"), (size_t)1 );
    CHECK( supportedCapabilities.contains("ripemd160"), (size_t)1 );

    QStringList defaultCapabilities = QCA::defaultFeatures();
    CHECK( defaultCapabilities.contains("random"), (size_t)1 );

    CHECK( QCA::isSupported("random"), true );
    CHECK( QCA::isSupported("sha0"), true );
    CHECK( QCA::isSupported("sha0,sha1"), true );
    CHECK( QCA::isSupported("md2,md4,md5"), true );
    CHECK( QCA::isSupported("md5"), true );
    CHECK( QCA::isSupported("ripemd160"), true );
    CHECK( QCA::isSupported("nosuchfeature"), false );

    QString caps( "random,sha1,md5,ripemd160");
    QStringList capList;
    capList.split( caps, "," );
    CHECK( QCA::isSupported(capList), true );
    capList.append("noSuch");
    CHECK( QCA::isSupported(capList), false );
    capList.clear();
    capList.append("noSuch");
    CHECK( QCA::isSupported(capList), false );
}

<|endoftext|>


<commit_before>// ==Montelight==
// Tegan Brennan, Stephen Merity, Taiyo Wilson
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#define EPSILON 0.1f

using namespace std;

struct Vector {
  double x, y, z;
  //
  Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {}
  Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {}
  inline Vector operator+(const Vector &o) const {
    return Vector(x + o.x, y + o.y, z + o.z);
  }
  inline Vector operator-(const Vector &o) const {
    return Vector(x - o.x, y - o.y, z - o.z);
  }
  inline Vector operator*(const Vector &o) const {
    return Vector(x * o.x, y * o.y, z * o.z);
  }
  inline Vector operator*(double o) const {
    return Vector(x * o, y * o, z * o);
  }
  inline double dot(const Vector &o) const {
    return x * o.x + y * o.y + z * o.z;
  }
  inline Vector &norm(){
    return *this = *this * (1 / sqrt(x * x + y * y + z * z));
  }
  inline Vector cross(Vector &o){
    return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x);
  }
  inline double max() {
    return fmax(x, fmax(y, z));
  }
};

struct Ray {
  Vector origin, direction;
  Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {}
};

struct Image {
  unsigned int width, height;
  Vector *pixels;
  //
  Image(unsigned int w, unsigned int h) : width(w), height(h) {
    pixels = new Vector[width * height];
  }
  void setPixel(unsigned int x, unsigned int y, const Vector &v) {
    pixels[(height - y) * width + x] = v;
  }
  void save(std::string filePrefix) {
    std::string filename = filePrefix + ".ppm";
    std::ofstream f;
    f.open(filename.c_str(), std::ofstream::out);
    // PPM header: P3 => RGB, width, height, and max RGB value
    f << "P3 " << width << " " << height << " " << 255 << std::endl;
    // For each pixel, write the space separated RGB values
    for (int i=0; i < width * height; i++) {
      unsigned int r = pixels[i].x * 255, g = pixels[i].y * 255, b = pixels[i].z * 255;
      f << r << " " << g << " " << b << std::endl;
    }
  }
  ~Image() {
    delete[] pixels;
  }
};

struct Shape {
  Vector color, emit;
  //
  Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {}
  virtual double intersects(const Ray &r) const { return 0; }
  virtual Vector randomPoint() const { return Vector(); }
};

struct Sphere : Shape {
  Vector center;
  double radius;
  //
  Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) :
    Shape(color_, emit_), center(center_), radius(radius_) {}
  double intersects(const Ray &r) const {
    // Find if, and at what distance, the ray intersects with this object
    // Equation follows from solving quadratic equation of (r - c) ^ 2
    // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
    Vector offset = r.origin - center;
    double a = r.direction.dot(r.direction);
    double b = 2 * offset.dot(r.direction);
    double c = offset.dot(offset) - radius * radius;
    // Find discriminant for use in quadratic equation (b^2 - 4ac)
    double disc = b * b - 4 * a * c;
    // If the discriminant is negative, there are no real roots
    // (ray misses sphere)
    if (disc < 0) {
      return 0;
    }
    // The smallest positive root is the closest intersection point
    disc = sqrt(disc);
    double t = - b - disc;
    if (t > EPSILON) {
      return t / 2;
    }
    t = - b + disc;
    if (t > EPSILON) {
      return t / 2;
    }
    return 0;
  }
  Vector randomPoint() const {
    return center;
  }
};

struct Tracer {
  std::vector<Shape *> scene;
  //
  Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {}
  std::pair<Shape *, double> getIntersection(const Ray &r) const {
    Shape *hitObj = NULL;
    double closest = 1e20f;
    for (Shape *obj : scene) {
      double distToHit = obj->intersects(r);
      if (distToHit > 0 && distToHit < closest) {
        hitObj = obj;
        closest = distToHit;
      }
    }
    return std::make_pair(hitObj, closest);
  }
  Vector getRadiance(const Ray &r, int depth) {
    // Work out what (if anything) was hit
    auto result = getIntersection(r);
    if (!result.first) {
      return Vector();
    }
    Vector hit = r.origin + r.direction * result.second;
    // Work out the color
    Vector color;
    for (Shape *light : scene) {
      // Skip any objects that don't emit light
      if (light->emit.max() == 0) {
        continue;
      }
      Vector lightDirection = (light->randomPoint() - hit).norm();
      Ray rayToLight = Ray(hit, lightDirection);
      auto lightHit = getIntersection(rayToLight);
      if (light == lightHit.first) {
        color = light->emit * result.first->color;
      }
    }
    return result.first->emit + color;
  }
};

int main(int argc, const char *argv[]) {
  // Initialize the image
  int w = 256, h = 256;
  Image img(w, h);
  // Set up the scene
  // Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html
  std::vector<Shape *> scene = {//Scene: radius, position, emission, color, material
    new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left
    new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght
    new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back
    new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt
    new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm
    new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top
    new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Mirr
    new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.9, Vector(0.4, 0.4, 0.4)),//Glas
    //new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1)) //Light
    new Sphere(Vector(50,65.1,81.6), 1.5, Vector(1,1,1), Vector(1,1,1)) //Light
  };
  Tracer tracer = Tracer(scene);
  // Set up the camera
  Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm());
  // Upright camera with field of view angle set by 0.5135
  Vector cx = Vector((w * 0.5135) / h, 0, 0);
  // Cross product gets the vector perpendicular to cx and the "gaze" direction
  Vector cy = (cx.cross(camera.direction)).norm() * 0.5135;
  // Take a set number of samples per pixel
  for (int samples = 0; samples < 1; ++samples) {
    // For each pixel, sample a ray in that direction
    for (int y = 0; y < h; ++y) {
      for (int x = 0; x < w; ++x) {
        // Calculate the direction of the camera ray
        Vector d = (cx * ((x / float(w)) - 0.5)) + (cy * ((y / float(h)) - 0.5)) + camera.direction;
        Ray ray = Ray(camera.origin + d * 140, d.norm());
        Vector color = tracer.getRadiance(ray, 0);
        // Add result of sample to image
        img.setPixel(x, y, color);
      }
    }
  }
  // Save the resulting raytraced image
  img.save("render");
  return 0;
}
<commit_msg>Montelight now does global illumination<commit_after>// ==Montelight==
// Tegan Brennan, Stephen Merity, Taiyo Wilson
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#define EPSILON 0.001f

using namespace std;

struct Vector {
  double x, y, z;
  //
  Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {}
  Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {}
  inline Vector operator+(const Vector &o) const {
    return Vector(x + o.x, y + o.y, z + o.z);
  }
  inline Vector operator-(const Vector &o) const {
    return Vector(x - o.x, y - o.y, z - o.z);
  }
  inline Vector operator*(const Vector &o) const {
    return Vector(x * o.x, y * o.y, z * o.z);
  }
  inline Vector operator/(double o) const {
    return Vector(x / o, y / o, z / o);
  }

  inline Vector operator*(double o) const {
    return Vector(x * o, y * o, z * o);
  }
  inline double dot(const Vector &o) const {
    return x * o.x + y * o.y + z * o.z;
  }
  inline Vector &norm(){
    return *this = *this * (1 / sqrt(x * x + y * y + z * z));
  }
  inline Vector cross(Vector &o){
    return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x);
  }
  inline double max() {
    return fmax(x, fmax(y, z));
  }
};

struct Ray {
  Vector origin, direction;
  Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {}
};

struct Image {
  unsigned int width, height;
  Vector *pixels;
  unsigned int *samples;
  //
  Image(unsigned int w, unsigned int h) : width(w), height(h) {
    pixels = new Vector[width * height];
    samples = new unsigned int[width * height];
  }
  void setPixel(unsigned int x, unsigned int y, const Vector &v) {
    unsigned int index = (height - y) * width + x;
    pixels[index] = pixels[index] + v;
    samples[index] += 1;
  }
  void save(std::string filePrefix) {
    std::string filename = filePrefix + ".ppm";
    std::ofstream f;
    f.open(filename.c_str(), std::ofstream::out);
    // PPM header: P3 => RGB, width, height, and max RGB value
    f << "P3 " << width << " " << height << " " << 255 << std::endl;
    // For each pixel, write the space separated RGB values
    for (int i=0; i < width * height; i++) {
      auto p = pixels[i] / samples[i];
      unsigned int r = fmin(255, p.x * 255), g = fmin(255, p.y * 255), b = fmin(255, p.z * 255);
      f << r << " " << g << " " << b << std::endl;
    }
  }
  ~Image() {
    delete[] pixels;
    delete[] samples;
  }
};

struct Shape {
  Vector color, emit;
  //
  Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {}
  virtual double intersects(const Ray &r) const { return 0; }
  virtual Vector randomPoint() const { return Vector(); }
  virtual Vector getNormal(const Vector &p) const { return Vector(); }
};

struct Sphere : Shape {
  Vector center;
  double radius;
  //
  Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) :
    Shape(color_, emit_), center(center_), radius(radius_) {}
  double intersects(const Ray &r) const {
    // Find if, and at what distance, the ray intersects with this object
    // Equation follows from solving quadratic equation of (r - c) ^ 2
    // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
    Vector offset = r.origin - center;
    double a = r.direction.dot(r.direction);
    double b = 2 * offset.dot(r.direction);
    double c = offset.dot(offset) - radius * radius;
    // Find discriminant for use in quadratic equation (b^2 - 4ac)
    double disc = b * b - 4 * a * c;
    // If the discriminant is negative, there are no real roots
    // (ray misses sphere)
    if (disc < 0) {
      return 0;
    }
    // The smallest positive root is the closest intersection point
    disc = sqrt(disc);
    double t = - b - disc;
    if (t > EPSILON) {
      return t / 2;
    }
    t = - b + disc;
    if (t > EPSILON) {
      return t / 2;
    }
    return 0;
  }
  Vector randomPoint() const {
    return center;
  }
  Vector getNormal(const Vector &p) const {
    // Normalize the normal by using radius instead of a sqrt call
    return (p - center) / radius;
  }
};

struct Tracer {
  std::vector<Shape *> scene;
  //
  Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {}
  std::pair<Shape *, double> getIntersection(const Ray &r) const {
    Shape *hitObj = NULL;
    double closest = 1e20f;
    for (Shape *obj : scene) {
      double distToHit = obj->intersects(r);
      if (distToHit > 0 && distToHit < closest) {
        hitObj = obj;
        closest = distToHit;
      }
    }
    return std::make_pair(hitObj, closest);
  }
  Vector getRadiance(const Ray &r, int depth) {
    // Work out what (if anything) was hit
    auto result = getIntersection(r);
    Shape *hitObj = result.first;
    if (!hitObj || depth > 4) {
      return Vector();
    }
    Vector hitPos = r.origin + r.direction * result.second;
    // Work out the contribution from directly sampling the emitters
    Vector lightSampling;
    /*
    for (Shape *light : scene) {
      // Skip any objects that don't emit light
      if (light->emit.max() == 0) {
        continue;
      }
      Vector lightDirection = (light->randomPoint() - hitPos).norm();
      Ray rayToLight = Ray(hitPos, lightDirection);
      auto lightHit = getIntersection(rayToLight);
      if (light == lightHit.first) {
        lightSampling = light->emit * hitObj->color;
      }
    }
    */
    // Work out contribution from reflected light
    Vector norm = hitObj->getNormal(hitPos);
    // Orient the normal according to how the ray struck the object
    if (norm.dot(r.direction) > 0) {
      norm = norm * -1;
    }
    // TODO: Clean up this section
    double r1 = 2 * M_PI * drand48();
    double r2 = drand48();
    double r2s = sqrt(r2);
    Vector u = (fabs(norm.x)>.1 ? Vector(0, 1) : Vector(1)).cross(norm).norm();
    Vector v = norm.cross(u);
    Vector d = (u * cos(r1) * r2s + v * sin(r1) * r2s + norm * sqrt(1-r2)).norm();
    Vector reflected = getRadiance(Ray(hitPos, d), depth + 1);
    //
    return hitObj->emit + lightSampling + hitObj->color * reflected;
  }
};

int main(int argc, const char *argv[]) {
  // Initialize the image
  int w = 256, h = 256;
  Image img(w, h);
  // Set up the scene
  // Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html
  std::vector<Shape *> scene = {//Scene: radius, position, emission, color, material
    new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left
    new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght
    new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back
    new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt
    new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm
    new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top
    new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Mirr
    new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Glas
    new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1) * 0.5, Vector(12,12,12)) //Light
    //new Sphere(Vector(50,65.1,81.6), 1.5, Vector(1,1,1), Vector(0.7,0.7,0.7)) //Light
  };
  Tracer tracer = Tracer(scene);
  // Set up the camera
  Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm());
  // Upright camera with field of view angle set by 0.5135
  Vector cx = Vector((w * 0.5135) / h, 0, 0);
  // Cross product gets the vector perpendicular to cx and the "gaze" direction
  Vector cy = (cx.cross(camera.direction)).norm() * 0.5135;
  // Take a set number of samples per pixel
  unsigned int SAMPLES = 1000;
  for (int sample = 0; sample < SAMPLES; ++sample) {
    std::cout << "Taking sample " << sample << "\r" << std::flush;
    // For each pixel, sample a ray in that direction
    #pragma omp parallel for schedule(dynamic, 1)
    for (int y = 0; y < h; ++y) {
      for (int x = 0; x < w; ++x) {
        // Calculate the direction of the camera ray
        Vector d = (cx * ((x / float(w)) - 0.5)) + (cy * ((y / float(h)) - 0.5)) + camera.direction;
        Ray ray = Ray(camera.origin + d * 140, d.norm());
        Vector color = tracer.getRadiance(ray, 0);
        // Add result of sample to image
        img.setPixel(x, y, color);
      }
    }
  }
  // Save the resulting raytraced image
  img.save("render");
  return 0;
}
<|endoftext|>


<commit_before>#include <mill/util/logger.hpp>
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include "mode_traj_convert.hpp"
#include <iostream>

namespace mill
{

const char* mode_traj_convert_usage() noexcept
{
    return "usage: mill traj convert [trajfile] [format] <reference>_opt\n"
           "       convert format from [trajfile] to [format].\n"
           "       Only the first frame in a reference file is used to merge information.\n";
}

int mode_traj_convert(std::deque<std::string_view> args)
{
    if(args.empty())
    {
        log::error("mill traj convert: too few arguments");
        log::error(mode_traj_convert_usage());
        return 1;
    }

    const auto input = args.front();
    args.pop_front();

    if(input == "help")
    {
        log::info(mode_traj_convert_usage());
        return 0;
    }

    const auto format = args.front();
    args.pop_front();

    using attribute_container_type = Trajectory::attribute_container_type;
    std::optional<attribute_container_type> ref_header = std::nullopt;
    std::optional<Snapshot>                 ref_frame  = std::nullopt;
    if(!args.empty())
    {
        auto     r = reader(args.front());
        ref_header = r.read_header();
        ref_frame  = r.read_frame(); // read 1st frame
    }

    const std::string output = std::string(input) + "_converted." + std::string(format);
    auto w = writer(output);
    auto r = reader(input);

    auto header = r.read_header();
    if(ref_header)
    {
        header.merge(*ref_header);
    }
    w.write_header(header);

    for(auto frame : r)
    {
        if(ref_frame)
        {
            // copy reference info because std::map::merge moves out the values
            Snapshot ref(*ref_frame);

            frame.merge_attributes(ref);
        }
        w.write_frame(frame);
    }
    return 0;
}

} // mill
<commit_msg>:sparkles: force overwrite attribute while conversion<commit_after>#include <mill/util/logger.hpp>
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include "mode_traj_convert.hpp"
#include <iostream>

namespace mill
{

const char* mode_traj_convert_usage() noexcept
{
    return "usage: mill traj convert [trajfile] [format] <reference>_opt\n"
           "       convert format from [trajfile] to [format].\n"
           "       Only the first frame in a reference file is used to merge information.\n";
}

int mode_traj_convert(std::deque<std::string_view> args)
{
    if(args.empty())
    {
        log::error("mill traj convert: too few arguments");
        log::error(mode_traj_convert_usage());
        return 1;
    }

    const auto input = args.front();
    args.pop_front();

    if(input == "help")
    {
        log::info(mode_traj_convert_usage());
        return 0;
    }

    const auto format = args.front();
    args.pop_front();

    using attribute_container_type = Trajectory::attribute_container_type;
    std::optional<attribute_container_type> ref_header = std::nullopt;
    std::optional<Snapshot>                 ref_frame  = std::nullopt;
    if(!args.empty())
    {
        auto     r = reader(args.front());
        ref_header = r.read_header();
        ref_frame  = r.read_frame(); // read 1st frame
    }

    const std::string output = std::string(input) + "_converted." + std::string(format);
    auto w = writer(output);
    auto r = reader(input);

    auto header = r.read_header();
    if(ref_header)
    {
        header.merge(*ref_header);
    }
    w.write_header(header);

    for(auto frame : r)
    {
        if(ref_frame)
        {
            if(ref_frame->size() != frame.size())
            {
                log::warn("number of particles in the reference file \"",
                          args.front(), "\" (", ref_frame->size(),
                          ") differs from the original \"", input, "\" (",
                          frame.size(), "). Skipping.");
            }
            else
            {
                for(std::size_t i=0; i<frame.size(); ++i)
                {
                    frame.at(i).attributes() = ref_frame->at(i).attributes();
                }
            }
        }
        w.write_frame(frame);
    }
    return 0;
}

} // mill
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Aldebaran
 *
 * Licensed 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 "memory_list.hpp"

namespace alros {

namespace converter {

MemoryListConverter::MemoryListConverter(const std::vector<std::string>& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):
    BaseConverter(name, frequency, session),
    p_memory_(session->service("ALMemory")),
    _key_list(key_list)
{}

void MemoryListConverter::reset(){

}

void MemoryListConverter::callAll(const std::vector<message_actions::MessageAction> &actions){
  // Get inertial data
  AL::ALValue memData = p_memory_.call<AL::ALValue>("getListData", _key_list);
  for(int i=0; i<memData.getSize(); i++){
    if(memData[i].isFloat())
    {
      naoqi_msgs::MemoryPairFloat tmp_msg;
      tmp_msg.memoryKey = _key_list[i];
      tmp_msg.data = memData[i];
      _msg.floats.push_back(tmp_msg);
    }
    else if(memData[i].isString())
    {
      naoqi_msgs::MemoryPairString tmp_msg;
      tmp_msg.memoryKey = _key_list[i];
      tmp_msg.data = memData[i];
      _msg.strings.push_back(tmp_msg);
    }
    else if(memData[i].isInt())
    {
      naoqi_msgs::MemoryPairInt tmp_msg;
      tmp_msg.memoryKey = _key_list[i];
      tmp_msg.data = memData[i];
      _msg.ints.push_back(tmp_msg);
    }
  }

  for_each( message_actions::MessageAction action, actions )
  {
    callbacks_[action]( _msg);
  }
}

void MemoryListConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
  callbacks_[action] = cb;
}

}

}
<commit_msg>Fix string in message creation in converter<commit_after>/*
 * Copyright 2015 Aldebaran
 *
 * Licensed 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 "memory_list.hpp"

namespace alros {

namespace converter {

MemoryListConverter::MemoryListConverter(const std::vector<std::string>& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):
    BaseConverter(name, frequency, session),
    p_memory_(session->service("ALMemory")),
    _key_list(key_list)
{}

void MemoryListConverter::reset(){

}

void MemoryListConverter::callAll(const std::vector<message_actions::MessageAction> &actions){
  // Get inertial data
  AL::ALValue memData = p_memory_.call<AL::ALValue>("getListData", _key_list);
  for(int i=0; i<memData.getSize(); i++){
    if(memData[i].isFloat())
    {
      naoqi_msgs::MemoryPairFloat tmp_msg;
      tmp_msg.memoryKey = _key_list[i];
      tmp_msg.data = memData[i];
      _msg.floats.push_back(tmp_msg);
    }
    else if(memData[i].isString())
    {
      naoqi_msgs::MemoryPairString tmp_msg;
      tmp_msg.memoryKey = _key_list[i];
      tmp_msg.data = memData[i].toString();
      _msg.strings.push_back(tmp_msg);
    }
    else if(memData[i].isInt())
    {
      naoqi_msgs::MemoryPairInt tmp_msg;
      tmp_msg.memoryKey = _key_list[i];
      tmp_msg.data = memData[i];
      _msg.ints.push_back(tmp_msg);
    }
  }

  for_each( message_actions::MessageAction action, actions )
  {
    callbacks_[action]( _msg);
  }
}

void MemoryListConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
  callbacks_[action] = cb;
}

}

}
<|endoftext|>


<commit_before>#include <iostream>
#include "time.h"
#include <string>
#include <unistd.h>
#include "novoht.h"
#include <cstdlib>
#include <cstddef>
#include <sys/time.h>//
#include <sys/stat.h>
#define KEY_LEN 32
#define VAL_LEN 128
using namespace std;
struct timeval tp;
double diffclock(clock_t clock1, clock_t clock2){
   double clock_ts=clock1-clock2;
   double diffms=(clock_ts*1000)/CLOCKS_PER_SEC;
   return diffms;
}
double getTime_usec() {
   gettimeofday(&tp, NULL);
   return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);
}
string randomString(int len) {
   string s(len, ' ');
   srand(/*getpid()*/ clock() + getTime_usec());
   static const char alphanum[] = "0123456789"
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
       "abcdefghijklmnopqrstuvwxyz";
   for (int i = 0; i < len; ++i) {
      s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
   }
   return s;
}
double testInsert(NoVoHT &map, string keys[], string vals[], int l){
   int fails =0;
   cout << "0\% Complete\r";
   cout.flush();
   //clock_t a=clock();
   double a = getTime_usec();
   int t;
   for (t = 0; t<l; t++){
      fails -= map.put(keys[t], vals[t]);
      if ((t+1)%1000 == 0)
         cout << (long)t*100/l << "\% Complete\r";
   }
   double b = getTime_usec();
   //clock_t b=clock();
   cout << "100\% Complete with " << fails << " not inserted" << endl;
   //return diffclock(b,a);
   return (b-a);
   ;
}
double testGet(NoVoHT &map, string keys[], string vals[], int l){
   int fails = 0;
   cout << "0\% Complete\r";
   double a = getTime_usec();
   for (int t=0; t<l; t++){
      string* s = map.get(keys[t]);
      if (!s) fails++;
      else if (s->compare(vals[t]) != 0)fails++;
      if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
   }
   double b = getTime_usec();
   cout << "100\% Complete with " << fails << " not found" << endl;
   return b-a;
}
double testRemove(NoVoHT &map, string keys[], int l){
   int fails = 0;
   cout << "0\% Complete\r";
   double a = getTime_usec();
   for (int t=0; t<l; t++){
      fails -= map.remove(keys[t]);
      if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
   }
   double b = getTime_usec();
   cout << "100\% Complete with " << fails << " not found" << endl;
   return b-a;
}
int main(int argc, char *argv[]){
   cout << "\nInitializing key-value pairs for testing\n";
   cout << "0\%\r";
   int size = atoi(argv[1]);
   string* keys = new string[size];
   string* vals = new string[size];
   for (int t=0; t<size; t++){
      keys[t] = randomString(KEY_LEN);
      vals[t] = randomString(VAL_LEN);
      if(t%1000 == 0)cout << (long)t*100/size << "\%\r";
   }
   cout << "Done\n" << endl;

   //NoVoHT map ("fbench.data", 1000000000, 10000);
   char c[40];
   struct stat fstate;
   sprintf(c, "cat /proc/%d/status | grep VmPeak", (int)getpid());
   system(c);
   const char* fn = "";
   if(argc > 2) fn = argv[2];
   NoVoHT map (fn, size, 10000, .7);
   stat(fn, &fstate);
   cout << "Initial file size: " << fstate.st_size << endl << endl;

   //NoVoHT map ("", 10000000, -1);
   //NoVoHT map ("", 1000000, 10000, .7);
   //NoVoHT map ("", 1000000, -1);
   //NoVoHT map ("/dev/shm/fbench.data", 1000000, -1);

   double ins, ret, rem;
   cout << "Testing Insertion: Inserting " << size << " elements" << endl;
   ins = testInsert(map, keys,vals,size);
   stat(fn, &fstate);
   cout << "File size after insertion test: " << fstate.st_size << endl << endl;

   cout << "Testing Retrieval: Retrieving " << size << " elements" << endl;
   ret = testGet(map,keys,vals,size);
   cout << endl;

   cout << "Testing Removal: Removing " << size << " elements" << endl;
   rem = testRemove(map,keys,size);
   stat(fn, &fstate);
   cout << "File size after removal test: " << fstate.st_size << endl << endl;

   cout << "\nInsertion done in " << ins << " microseconds" << endl;
   cout << "Retrieval done in " << ret << " microseconds" << endl;
   cout << "Removal done in " << rem << " microseconds" << endl;
   system(c);
   delete [] keys;
   delete [] vals;
   return 0;
}

<commit_msg>changed key value length<commit_after>#include <iostream>
#include "time.h"
#include <string>
#include <unistd.h>
#include "novoht.h"
#include <cstdlib>
#include <cstddef>
#include <sys/time.h>//
#include <sys/stat.h>
#define KEY_LEN 48
#define VAL_LEN 24
using namespace std;
struct timeval tp;
double diffclock(clock_t clock1, clock_t clock2){
   double clock_ts=clock1-clock2;
   double diffms=(clock_ts*1000)/CLOCKS_PER_SEC;
   return diffms;
}
double getTime_usec() {
   gettimeofday(&tp, NULL);
   return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);
}
string randomString(int len) {
   string s(len, ' ');
   srand(/*getpid()*/ clock() + getTime_usec());
   static const char alphanum[] = "0123456789"
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
       "abcdefghijklmnopqrstuvwxyz";
   for (int i = 0; i < len; ++i) {
      s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
   }
   return s;
}
double testInsert(NoVoHT &map, string keys[], string vals[], int l){
   int fails =0;
   cout << "0\% Complete\r";
   cout.flush();
   //clock_t a=clock();
   double a = getTime_usec();
   int t;
   for (t = 0; t<l; t++){
      fails -= map.put(keys[t], vals[t]);
      if ((t+1)%1000 == 0)
         cout << (long)t*100/l << "\% Complete\r";
   }
   double b = getTime_usec();
   //clock_t b=clock();
   cout << "100\% Complete with " << fails << " not inserted" << endl;
   //return diffclock(b,a);
   return (b-a);
   ;
}
double testGet(NoVoHT &map, string keys[], string vals[], int l){
   int fails = 0;
   cout << "0\% Complete\r";
   double a = getTime_usec();
   for (int t=0; t<l; t++){
      string* s = map.get(keys[t]);
      if (!s) fails++;
      else if (s->compare(vals[t]) != 0)fails++;
      if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
   }
   double b = getTime_usec();
   cout << "100\% Complete with " << fails << " not found" << endl;
   return b-a;
}
double testRemove(NoVoHT &map, string keys[], int l){
   int fails = 0;
   cout << "0\% Complete\r";
   double a = getTime_usec();
   for (int t=0; t<l; t++){
      fails -= map.remove(keys[t]);
      if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
   }
   double b = getTime_usec();
   cout << "100\% Complete with " << fails << " not found" << endl;
   return b-a;
}
int main(int argc, char *argv[]){
   cout << "\nInitializing key-value pairs for testing\n";
   cout << "0\%\r";
   int size = atoi(argv[1]);
   string* keys = new string[size];
   string* vals = new string[size];
   for (int t=0; t<size; t++){
      keys[t] = randomString(KEY_LEN);
      vals[t] = randomString(VAL_LEN);
      if(t%1000 == 0)cout << (long)t*100/size << "\%\r";
   }
   cout << "Done\n" << endl;

   //NoVoHT map ("fbench.data", 1000000000, 10000);
   char c[40];
   struct stat fstate;
   sprintf(c, "cat /proc/%d/status | grep VmPeak", (int)getpid());
   system(c);
   const char* fn = "";
   if(argc > 2) fn = argv[2];
   NoVoHT map (fn, size, 10000, .7);
   stat(fn, &fstate);
   cout << "Initial file size: " << fstate.st_size << endl << endl;

   //NoVoHT map ("", 10000000, -1);
   //NoVoHT map ("", 1000000, 10000, .7);
   //NoVoHT map ("", 1000000, -1);
   //NoVoHT map ("/dev/shm/fbench.data", 1000000, -1);

   double ins, ret, rem;
   cout << "Testing Insertion: Inserting " << size << " elements" << endl;
   ins = testInsert(map, keys,vals,size);
   stat(fn, &fstate);
   cout << "File size after insertion test: " << fstate.st_size << endl << endl;

   cout << "Testing Retrieval: Retrieving " << size << " elements" << endl;
   ret = testGet(map,keys,vals,size);
   cout << endl;

   cout << "Testing Removal: Removing " << size << " elements" << endl;
   rem = testRemove(map,keys,size);
   stat(fn, &fstate);
   cout << "File size after removal test: " << fstate.st_size << endl << endl;

   cout << "\nInsertion done in " << ins << " microseconds" << endl;
   cout << "Retrieval done in " << ret << " microseconds" << endl;
   cout << "Removal done in " << rem << " microseconds" << endl;
   system(c);
   delete [] keys;
   delete [] vals;
   return 0;
}

<|endoftext|>


<commit_before>//
//  CompositeTileImageContribution.hpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 4/26/14.
//
//

#ifndef __G3MiOSSDK__CompositeTileImageContribution__
#define __G3MiOSSDK__CompositeTileImageContribution__

#include "TileImageContribution.hpp"
#include <vector>

class CompositeTileImageContribution : public TileImageContribution {
public:

  class ChildContribution {
  public:
    const int                    _childIndex;
    const TileImageContribution* _contribution;

    ChildContribution(const int                    childIndex,
                      const TileImageContribution* contribution);

    ~ChildContribution();
  };

  static const TileImageContribution* create(const std::vector<const ChildContribution*>& contributions);

private:
#ifdef C_CODE
  const std::vector<const ChildContribution*> _contributions;
#endif
#ifdef JAVA_CODE
  private final java.util.ArrayList<ChildContribution> _contributions;
#endif

  CompositeTileImageContribution(const std::vector<const ChildContribution*>& contributions) :
  TileImageContribution(false, 1),
  _contributions(contributions)
  {
  }

public:
  ~CompositeTileImageContribution() {
    const int size = _contributions.size();
    for (int i = 0; i < size; i++) {
#ifdef C_CODE
      const ChildContribution* contribution = _contributions[i];
#endif
#ifdef JAVA_CODE
      final ChildContribution contribution = _contributions.get(i);
#endif
      delete contribution;
    }
  }

  const int size() const {
    return _contributions.size();
  }

  const ChildContribution* get(int index) const {
#ifdef C_CODE
    return _contributions[index];
#endif
#ifdef JAVA_CODE
    return _contributions.get(index);
#endif
  }

};

#endif
<commit_msg>Tile's image creation refactoring - NOT YET USABLE<commit_after>//
//  CompositeTileImageContribution.hpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 4/26/14.
//
//

#ifndef __G3MiOSSDK__CompositeTileImageContribution__
#define __G3MiOSSDK__CompositeTileImageContribution__

#include "TileImageContribution.hpp"
#include <vector>

class CompositeTileImageContribution : public TileImageContribution {
public:

  class ChildContribution {
  public:
    const int                    _childIndex;
    const TileImageContribution* _contribution;

    ChildContribution(const int                    childIndex,
                      const TileImageContribution* contribution);

    ~ChildContribution();
  };

  static const TileImageContribution* create(const std::vector<const ChildContribution*>& contributions);

private:
#ifdef C_CODE
  const std::vector<const ChildContribution*> _contributions;
#endif
#ifdef JAVA_CODE
  private final java.util.ArrayList<ChildContribution> _contributions;
#endif

  CompositeTileImageContribution(const std::vector<const ChildContribution*>& contributions) :
  TileImageContribution(false, 1),
  _contributions(contributions)
  {
  }

public:
  ~CompositeTileImageContribution() {
    const int size = _contributions.size();
    for (int i = 0; i < size; i++) {
#ifdef C_CODE
      const ChildContribution* contribution = _contributions[i];
      delete contribution;
#endif
#ifdef JAVA_CODE
      final ChildContribution contribution = _contributions.get(i);
      contribution.dispose();
#endif
    }
  }

  const int size() const {
    return _contributions.size();
  }

  const ChildContribution* get(int index) const {
#ifdef C_CODE
    return _contributions[index];
#endif
#ifdef JAVA_CODE
    return _contributions.get(index);
#endif
  }

};

#endif
<|endoftext|>