<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "basecheckoutwizard.h"
#include "checkoutwizarddialog.h"

#include <coreplugin/featureprovider.h>

#include <projectexplorer/projectexplorer.h>

#include <QCoreApplication>
#include <QDir>
#include <QMessageBox>

/*!
    \class VcsBase::BaseCheckoutWizard

    \brief The BaseCheckoutWizard class implements a wizard for initially
    checking out a project using a version control system.

   Implements all of Core::IWizard with the exception of
   name()/description() and icon().

   Pops up a QWizard consisting of a Parameter Page which is created
   by a virtual factory function and a progress
   page containing a log text. The factory function createJob()
   creates a job with the output connected to the log window,
   returning the path to the checkout.

   On success, the wizard tries to locate a project file
   and open it.

   \sa VcsBase::BaseCheckoutWizardPage
*/

namespace VcsBase {
namespace Internal {

class BaseCheckoutWizardPrivate
{
public:
    BaseCheckoutWizardPrivate() : dialog(0) {}
    void clear();

    Internal::CheckoutWizardDialog *dialog;
    QList<QWizardPage *> parameterPages;
    QString checkoutPath;
    QString progressTitle;
    QString startedStatus;
};

void BaseCheckoutWizardPrivate::clear()
{
    parameterPages.clear();
    dialog = 0;
    checkoutPath.clear();
}

} // namespace Internal

BaseCheckoutWizard::BaseCheckoutWizard(QObject *parent) :
    Core::IWizard(parent),
    d(new Internal::BaseCheckoutWizardPrivate)
{
    setWizardKind(IWizard::ProjectWizard);
    setCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY));
    setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
        ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY_DISPLAY));
    setFlags(Core::IWizard::PlatformIndependent);
}

BaseCheckoutWizard::~BaseCheckoutWizard()
{
    delete d;
}

void BaseCheckoutWizard::runWizard(const QString &path, QWidget *parent, const QString & /*platform*/, const QVariantMap &extraValues)
{
    Q_UNUSED(extraValues)
    // Create dialog and launch
    d->parameterPages = createParameterPages(path);
    Internal::CheckoutWizardDialog dialog(d->parameterPages, parent);
    if (!d->progressTitle.isEmpty())
        dialog.setTitle(d->progressTitle);
    if (!d->startedStatus.isEmpty())
        dialog.setStartedStatus(d->startedStatus);
    d->dialog = &dialog;
    connect(&dialog, SIGNAL(progressPageShown()), this, SLOT(slotProgressPageShown()));
    dialog.setWindowTitle(displayName());
    if (dialog.exec() != QDialog::Accepted)
        return;
    // Now try to find the project file and open
    const QString checkoutPath = d->checkoutPath;
    d->clear();
    QString errorMessage;
    const QString projectFile = openProject(checkoutPath, &errorMessage);
    if (projectFile.isEmpty()) {
        QMessageBox msgBox(QMessageBox::Warning, tr("Cannot Open Project"),
                           tr("Failed to open project in '%1'.").arg(QDir::toNativeSeparators(checkoutPath)));
        msgBox.setDetailedText(errorMessage);
        msgBox.exec();
    }
}

static inline QString msgNoProjectFiles(const QDir &dir, const QStringList &patterns)
{
    return BaseCheckoutWizard::tr("Could not find any project files matching (%1) in the directory '%2'.").arg(patterns.join(QLatin1String(", ")), QDir::toNativeSeparators(dir.absolutePath()));
}

// Try to find the project files in a project directory with some smartness
static QFileInfoList findProjectFiles(const QDir &projectDir, QString *errorMessage)
{
    const QStringList projectFilePatterns = ProjectExplorer::ProjectExplorerPlugin::projectFilePatterns();
    // Project directory
    QFileInfoList projectFiles = projectDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
    if (!projectFiles.empty())
        return projectFiles;
    // Try a 'src' directory
    QFileInfoList srcDirs = projectDir.entryInfoList(QStringList(QLatin1String("src")), QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable);
    if (srcDirs.empty()) {
        *errorMessage = msgNoProjectFiles(projectDir, projectFilePatterns);
        return QFileInfoList();
    }
    const QDir srcDir = QDir(srcDirs.front().absoluteFilePath());
    projectFiles = srcDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
    if (projectFiles.empty()) {
        *errorMessage = msgNoProjectFiles(srcDir, projectFilePatterns);
        return QFileInfoList();
    }
    return projectFiles;
}

QString BaseCheckoutWizard::openProject(const QString &path, QString *errorMessage)
{
    ProjectExplorer::ProjectExplorerPlugin *pe  = ProjectExplorer::ProjectExplorerPlugin::instance();
    if (!pe) {
        *errorMessage = tr("The Project Explorer is not available.");
        return QString();
    }

    // Search the directory for project files
    const QDir dir(path);
    if (!dir.exists()) {
        *errorMessage = tr("'%1' does not exist.").
                        arg(QDir::toNativeSeparators(path)); // Should not happen
        return QString();
    }
    QFileInfoList projectFiles = findProjectFiles(dir, errorMessage);
    if (projectFiles.empty())
        return QString();
    // Open. Do not use a busy cursor here as additional wizards might pop up
    const QString projectFile = projectFiles.front().absoluteFilePath();
    if (!pe->openProject(projectFile, errorMessage))
        return QString();

    return projectFile;
}

void BaseCheckoutWizard::setCustomLabels(const QString &progressTitle, const QString &startedStatus)
{
    d->progressTitle = progressTitle;
    d->startedStatus = startedStatus;
}

void BaseCheckoutWizard::slotProgressPageShown()
{
    Command *command = createCommand(d->parameterPages, &(d->checkoutPath));
    d->dialog->start(command);
}

} // namespace VcsBase
<commit_msg>BaseCheckoutWizard: Add button to message box informing about failure<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "basecheckoutwizard.h"
#include "checkoutwizarddialog.h"

#include <coreplugin/featureprovider.h>

#include <projectexplorer/projectexplorer.h>

#include <QCoreApplication>
#include <QDir>
#include <QMessageBox>

/*!
    \class VcsBase::BaseCheckoutWizard

    \brief The BaseCheckoutWizard class implements a wizard for initially
    checking out a project using a version control system.

   Implements all of Core::IWizard with the exception of
   name()/description() and icon().

   Pops up a QWizard consisting of a Parameter Page which is created
   by a virtual factory function and a progress
   page containing a log text. The factory function createJob()
   creates a job with the output connected to the log window,
   returning the path to the checkout.

   On success, the wizard tries to locate a project file
   and open it.

   \sa VcsBase::BaseCheckoutWizardPage
*/

namespace VcsBase {
namespace Internal {

class BaseCheckoutWizardPrivate
{
public:
    BaseCheckoutWizardPrivate() : dialog(0) {}
    void clear();

    Internal::CheckoutWizardDialog *dialog;
    QList<QWizardPage *> parameterPages;
    QString checkoutPath;
    QString progressTitle;
    QString startedStatus;
};

void BaseCheckoutWizardPrivate::clear()
{
    parameterPages.clear();
    dialog = 0;
    checkoutPath.clear();
}

} // namespace Internal

BaseCheckoutWizard::BaseCheckoutWizard(QObject *parent) :
    Core::IWizard(parent),
    d(new Internal::BaseCheckoutWizardPrivate)
{
    setWizardKind(IWizard::ProjectWizard);
    setCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY));
    setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
        ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY_DISPLAY));
    setFlags(Core::IWizard::PlatformIndependent);
}

BaseCheckoutWizard::~BaseCheckoutWizard()
{
    delete d;
}

void BaseCheckoutWizard::runWizard(const QString &path, QWidget *parent, const QString & /*platform*/, const QVariantMap &extraValues)
{
    Q_UNUSED(extraValues)
    // Create dialog and launch
    d->parameterPages = createParameterPages(path);
    Internal::CheckoutWizardDialog dialog(d->parameterPages, parent);
    if (!d->progressTitle.isEmpty())
        dialog.setTitle(d->progressTitle);
    if (!d->startedStatus.isEmpty())
        dialog.setStartedStatus(d->startedStatus);
    d->dialog = &dialog;
    connect(&dialog, SIGNAL(progressPageShown()), this, SLOT(slotProgressPageShown()));
    dialog.setWindowTitle(displayName());
    if (dialog.exec() != QDialog::Accepted)
        return;
    // Now try to find the project file and open
    const QString checkoutPath = d->checkoutPath;
    d->clear();
    QString errorMessage;
    const QString projectFile = openProject(checkoutPath, &errorMessage);
    if (projectFile.isEmpty()) {
        QMessageBox msgBox(QMessageBox::Warning, tr("Cannot Open Project"),
                           tr("Failed to open project in '%1'.").arg(QDir::toNativeSeparators(checkoutPath)));
        msgBox.setDetailedText(errorMessage);
        msgBox.addButton(QMessageBox::Ok);
        msgBox.exec();
    }
}

static inline QString msgNoProjectFiles(const QDir &dir, const QStringList &patterns)
{
    return BaseCheckoutWizard::tr("Could not find any project files matching (%1) in the directory '%2'.").arg(patterns.join(QLatin1String(", ")), QDir::toNativeSeparators(dir.absolutePath()));
}

// Try to find the project files in a project directory with some smartness
static QFileInfoList findProjectFiles(const QDir &projectDir, QString *errorMessage)
{
    const QStringList projectFilePatterns = ProjectExplorer::ProjectExplorerPlugin::projectFilePatterns();
    // Project directory
    QFileInfoList projectFiles = projectDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
    if (!projectFiles.empty())
        return projectFiles;
    // Try a 'src' directory
    QFileInfoList srcDirs = projectDir.entryInfoList(QStringList(QLatin1String("src")), QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable);
    if (srcDirs.empty()) {
        *errorMessage = msgNoProjectFiles(projectDir, projectFilePatterns);
        return QFileInfoList();
    }
    const QDir srcDir = QDir(srcDirs.front().absoluteFilePath());
    projectFiles = srcDir.entryInfoList(projectFilePatterns, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable);
    if (projectFiles.empty()) {
        *errorMessage = msgNoProjectFiles(srcDir, projectFilePatterns);
        return QFileInfoList();
    }
    return projectFiles;
}

QString BaseCheckoutWizard::openProject(const QString &path, QString *errorMessage)
{
    ProjectExplorer::ProjectExplorerPlugin *pe  = ProjectExplorer::ProjectExplorerPlugin::instance();
    if (!pe) {
        *errorMessage = tr("The Project Explorer is not available.");
        return QString();
    }

    // Search the directory for project files
    const QDir dir(path);
    if (!dir.exists()) {
        *errorMessage = tr("'%1' does not exist.").
                        arg(QDir::toNativeSeparators(path)); // Should not happen
        return QString();
    }
    QFileInfoList projectFiles = findProjectFiles(dir, errorMessage);
    if (projectFiles.empty())
        return QString();
    // Open. Do not use a busy cursor here as additional wizards might pop up
    const QString projectFile = projectFiles.front().absoluteFilePath();
    if (!pe->openProject(projectFile, errorMessage))
        return QString();

    return projectFile;
}

void BaseCheckoutWizard::setCustomLabels(const QString &progressTitle, const QString &startedStatus)
{
    d->progressTitle = progressTitle;
    d->startedStatus = startedStatus;
}

void BaseCheckoutWizard::slotProgressPageShown()
{
    Command *command = createCommand(d->parameterPages, &(d->checkoutPath));
    d->dialog->start(command);
}

} // namespace VcsBase
<|endoftext|>


<commit_before>#ifndef TAMER_XBASE_HH
#define TAMER_XBASE_HH 1
/* Copyright (c) 2007-2012, Eddie Kohler
 * Copyright (c) 2007, Regents of the University of California
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, subject to the conditions
 * listed in the Tamer LICENSE file. These conditions include: you must
 * preserve this copyright notice, and you cannot mention the copyright
 * holders in advertising related to the Software without their permission.
 * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
 * notice is a summary of the Tamer LICENSE file; the license in that file is
 * legally binding.
 */
#include <stdexcept>
#include <stdint.h>
namespace tamer {

#if __GNUC__
#define TAMER_CLOSUREVARATTR __attribute__((unused))
#define TAMER_DEPRECATEDATTR __attribute__((deprecated))
#else
#define TAMER_CLOSUREVARATTR
#define TAMER_DEPRECATEDATTR
#endif

template <typename I0=void, typename I1=void> class rendezvous;
template <typename T0=void, typename T1=void, typename T2=void, typename T3=void> class event;
inline event<> distribute(const event<> &, const event<> &);
inline event<> distribute(const event<> &, const event<> &, const event<> &);
template <typename T0> event<T0> unbind(const event<> &);
class driver;
class gather_rendezvous;

class tamer_error : public std::runtime_error { public:
    explicit tamer_error(const std::string &arg)
	: runtime_error(arg) {
    }
};

struct no_slot {
};

enum rendezvous_flags {
    rnormal,
    rvolatile
};

namespace tamerpriv {

class simple_event;
class abstract_rendezvous;
class tamer_closure;
class distribute_rendezvous;
event<> hard_distribute(const event<> &e1, const event<> &e2);

class simple_event { public:

    // DO NOT derive from this class!

    inline simple_event()
	: _refcount(1), _r(0), _rid(0), _r_next(0), _r_pprev(0),
	  _at_trigger(0) {
    }

    template <typename R, typename I0, typename I1>
    inline simple_event(R &r, const I0 &i0, const I1 &i1);

    template <typename R, typename I0>
    inline simple_event(R &r, const I0 &i0);

    template <typename R>
    inline simple_event(R &r);

    static inline void use(simple_event *e) {
	if (e)
	    ++e->_refcount;
    }

    static inline void unuse(simple_event *e) {
	if (e && --e->_refcount == 0) {
	    if (e->_r)
		e->trigger(false);
	    delete e;
	}
    }

    unsigned refcount() const {
	return _refcount;
    }

    typedef unsigned (simple_event::*unspecified_bool_type)() const;

    operator unspecified_bool_type() const {
	return _r ? &simple_event::refcount : 0;
    }

    bool empty() const {
	return _r == 0;
    }

    abstract_rendezvous *rendezvous() const {
	return _r;
    }

    inline void initialize(abstract_rendezvous *r, uintptr_t rid);

    uintptr_t rid() const {
	return _rid;
    }

    inline bool trigger(bool values);

    static inline void at_trigger(simple_event *x, const event<> &e);

    inline bool has_at_trigger() const {
	return _at_trigger && *_at_trigger;
    }

  protected:

    unsigned _refcount;
    abstract_rendezvous *_r;
    uintptr_t _rid;
    simple_event *_r_next;
    simple_event **_r_pprev;
    simple_event *_at_trigger;

    simple_event(const simple_event &);
    simple_event &operator=(const simple_event &);

    inline ~simple_event() {
	assert(!_r && !_r_pprev);
    }

    friend class abstract_rendezvous;
    friend class event<void, void, void, void>;

};

class abstract_rendezvous { public:

    abstract_rendezvous(rendezvous_flags flags = rnormal)
	: _events(0), _unblocked_next(0), _unblocked_prev(0),
	  _blocked_closure(0), _flags(flags) {
    }

    virtual inline ~abstract_rendezvous();

    virtual void complete(uintptr_t rid, bool values) = 0;

    virtual inline void clear();

    virtual bool is_distribute() const {
	return false;
    }

    bool is_volatile() const {
	return _flags == rvolatile;
    }

    void set_volatile(bool v) {
	_flags = (v ? rvolatile : rnormal);
    }

    virtual tamer_closure *linked_closure() const {
	return _blocked_closure;
    }

    tamer_closure *blocked_closure() const {
	return _blocked_closure;
    }

    inline void block(tamer_closure &c, unsigned where);
    inline void unblock();
    inline void run();
    inline void remove_all();

    class clearer { public:
	clearer(abstract_rendezvous &r)
	    : _r(&r) {
	}
	~clearer() {
	    if (_r)
		_r->clear();
	}
	void kill() {
	    _r = 0;
	}
      private:
	abstract_rendezvous *_r;
    };

    static abstract_rendezvous *unblocked;
    static abstract_rendezvous *unblocked_tail;

  private:

    simple_event *_events;
    abstract_rendezvous *_unblocked_next;
    abstract_rendezvous *_unblocked_prev;
    tamer_closure *_blocked_closure;
    unsigned _blocked_closure_blockid;
    rendezvous_flags _flags;

    abstract_rendezvous(const abstract_rendezvous &);
    abstract_rendezvous &operator=(const abstract_rendezvous &);

    friend class simple_event;
    friend class driver;

};

struct tamer_closure {

    tamer_closure()
	: _refcount(1) {
    }

    virtual ~tamer_closure() {
    }

    void use() {
	_refcount++;
    }

    void unuse() {
	if (--_refcount == 0)
	    delete this;
    }

    virtual void tamer_closure_activate(unsigned) = 0;

    virtual bool block_landmark(const char *&file, unsigned &line);

  protected:

    unsigned _refcount;

};

struct tamer_debug_closure : public tamer_closure {

    tamer_debug_closure()
	: _block_file(0), _block_line(0) {
    }

    bool block_landmark(const char *&file, unsigned &line);

    void set_block_landmark(const char *file, unsigned line) {
	_block_file = file;
	_block_line = line;
    }

  protected:

    const char *_block_file;
    unsigned _block_line;

};

namespace message {
void event_prematurely_dereferenced(simple_event *e, abstract_rendezvous *r);
}

inline void abstract_rendezvous::remove_all() {
    for (simple_event *e = _events; e; e = e->_r_next)
	e->_r = 0;
    while (_events)
	_events->trigger(false);
}

inline void abstract_rendezvous::clear() {
    remove_all();
}

inline abstract_rendezvous::~abstract_rendezvous() {
    // take all events off this rendezvous and call their triggerers
    remove_all();

    if (_unblocked_prev)
	_unblocked_prev->_unblocked_next = _unblocked_next;
    else if (unblocked == this)
	unblocked = _unblocked_next;
    if (_unblocked_next)
	_unblocked_next->_unblocked_prev = _unblocked_prev;
    else if (unblocked_tail == this)
	unblocked_tail = _unblocked_prev;
    if (_blocked_closure)
	_blocked_closure->unuse();
}

inline void simple_event::initialize(abstract_rendezvous *r, uintptr_t rid)
{
    // NB this can be called before e has been fully initialized.
    _r = r;
    _rid = rid;
    _r_pprev = &r->_events;
    if (r->_events)
	r->_events->_r_pprev = &_r_next;
    _r_next = r->_events;
    r->_events = this;
}

inline bool simple_event::trigger(bool values) {
    abstract_rendezvous *r = _r;
    simple_event *at_trigger = _at_trigger;

    if (_r_pprev)
	*_r_pprev = _r_next;
    if (_r_next)
	_r_next->_r_pprev = _r_pprev;

    _r = 0;
    _at_trigger = 0;
    _r_pprev = 0;
    _r_next = 0;

    if (r && _refcount == 0)
	message::event_prematurely_dereferenced(this, r);
    if (r)
	r->complete(_rid, values);
    if (at_trigger) {
	at_trigger->trigger(false);
	unuse(at_trigger);
    }

    return r != 0;
}

inline void abstract_rendezvous::block(tamer_closure &c, unsigned where) {
    assert(!_blocked_closure && &c);
    c.use();
    _blocked_closure = &c;
    _blocked_closure_blockid = where;
}

inline void abstract_rendezvous::unblock() {
    if (_blocked_closure && !_unblocked_prev && unblocked != this) {
	_unblocked_next = 0;
	_unblocked_prev = unblocked_tail;
	if (unblocked_tail)
	    unblocked_tail->_unblocked_next = this;
	else
	    unblocked = this;
	unblocked_tail = this;
    }
}

inline void abstract_rendezvous::run() {
    tamer_closure *c = _blocked_closure;
    _blocked_closure = 0;
    if (_unblocked_prev)
	_unblocked_prev->_unblocked_next = _unblocked_next;
    else if (unblocked == this)
	unblocked = _unblocked_next;
    if (_unblocked_next)
	_unblocked_next->_unblocked_prev = _unblocked_prev;
    else if (unblocked_tail == this)
	unblocked_tail = _unblocked_next;
    _unblocked_next = _unblocked_prev = 0;
    c->tamer_closure_activate(_blocked_closure_blockid);
    c->unuse();
}

}}
#endif /* TAMER_BASE_HH */
<commit_msg>Internal: Clean up some unused code.<commit_after>#ifndef TAMER_XBASE_HH
#define TAMER_XBASE_HH 1
/* Copyright (c) 2007-2012, Eddie Kohler
 * Copyright (c) 2007, Regents of the University of California
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, subject to the conditions
 * listed in the Tamer LICENSE file. These conditions include: you must
 * preserve this copyright notice, and you cannot mention the copyright
 * holders in advertising related to the Software without their permission.
 * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
 * notice is a summary of the Tamer LICENSE file; the license in that file is
 * legally binding.
 */
#include <stdexcept>
#include <stdint.h>
namespace tamer {

#if __GNUC__
#define TAMER_CLOSUREVARATTR __attribute__((unused))
#define TAMER_DEPRECATEDATTR __attribute__((deprecated))
#else
#define TAMER_CLOSUREVARATTR
#define TAMER_DEPRECATEDATTR
#endif

template <typename I0=void, typename I1=void> class rendezvous;
template <typename T0=void, typename T1=void, typename T2=void, typename T3=void> class event;
inline event<> distribute(const event<> &, const event<> &);
inline event<> distribute(const event<> &, const event<> &, const event<> &);
template <typename T0> event<T0> unbind(const event<> &);
class driver;
class gather_rendezvous;

class tamer_error : public std::runtime_error { public:
    explicit tamer_error(const std::string &arg)
	: runtime_error(arg) {
    }
};

struct no_slot {
};

enum rendezvous_flags {
    rnormal,
    rvolatile
};

namespace tamerpriv {

class simple_event;
class abstract_rendezvous;
class tamer_closure;
class distribute_rendezvous;
event<> hard_distribute(const event<> &e1, const event<> &e2);

class simple_event { public:

    // DO NOT derive from this class!

    inline simple_event()
	: _refcount(1), _r(0), _rid(0), _r_next(0), _r_pprev(0),
	  _at_trigger(0) {
    }

    template <typename R, typename I0, typename I1>
    inline simple_event(R &r, const I0 &i0, const I1 &i1);

    template <typename R, typename I0>
    inline simple_event(R &r, const I0 &i0);

    template <typename R>
    inline simple_event(R &r);

    static inline void use(simple_event *e) {
	if (e)
	    ++e->_refcount;
    }

    static inline void unuse(simple_event *e) {
	if (e && --e->_refcount == 0) {
	    if (e->_r)
		e->trigger(false);
	    delete e;
	}
    }

    unsigned refcount() const {
	return _refcount;
    }

    typedef unsigned (simple_event::*unspecified_bool_type)() const;

    operator unspecified_bool_type() const {
	return _r ? &simple_event::refcount : 0;
    }

    bool empty() const {
	return _r == 0;
    }

    abstract_rendezvous *rendezvous() const {
	return _r;
    }

    inline void initialize(abstract_rendezvous *r, uintptr_t rid);

    inline void trigger(bool values);

    static inline void at_trigger(simple_event *x, const event<> &e);

    inline bool has_at_trigger() const {
	return _at_trigger && *_at_trigger;
    }

  protected:

    unsigned _refcount;
    abstract_rendezvous *_r;
    uintptr_t _rid;
    simple_event *_r_next;
    simple_event **_r_pprev;
    simple_event *_at_trigger;

    simple_event(const simple_event &);
    simple_event &operator=(const simple_event &);

    inline ~simple_event() {
	assert(!_r && !_r_pprev);
    }

    friend class abstract_rendezvous;
    friend class event<void, void, void, void>;

};

class abstract_rendezvous { public:

    abstract_rendezvous(rendezvous_flags flags = rnormal)
	: _events(0), _unblocked_next(0), _unblocked_prev(0),
	  _blocked_closure(0), _flags(flags) {
    }

    virtual inline ~abstract_rendezvous();

    virtual void complete(uintptr_t rid, bool values) = 0;

    virtual inline void clear();

    virtual bool is_distribute() const {
	return false;
    }

    bool is_volatile() const {
	return _flags == rvolatile;
    }

    void set_volatile(bool v) {
	_flags = (v ? rvolatile : rnormal);
    }

    virtual tamer_closure *linked_closure() const {
	return _blocked_closure;
    }

    tamer_closure *blocked_closure() const {
	return _blocked_closure;
    }

    inline void block(tamer_closure &c, unsigned where);
    inline void unblock();
    inline void run();
    inline void remove_all();

    class clearer { public:
	clearer(abstract_rendezvous &r)
	    : _r(&r) {
	}
	~clearer() {
	    if (_r)
		_r->clear();
	}
	void kill() {
	    _r = 0;
	}
      private:
	abstract_rendezvous *_r;
    };

    static abstract_rendezvous *unblocked;
    static abstract_rendezvous *unblocked_tail;

  private:

    simple_event *_events;
    abstract_rendezvous *_unblocked_next;
    abstract_rendezvous *_unblocked_prev;
    tamer_closure *_blocked_closure;
    unsigned _blocked_closure_blockid;
    rendezvous_flags _flags;

    abstract_rendezvous(const abstract_rendezvous &);
    abstract_rendezvous &operator=(const abstract_rendezvous &);

    friend class simple_event;
    friend class driver;

};

struct tamer_closure {

    tamer_closure()
	: _refcount(1) {
    }

    virtual ~tamer_closure() {
    }

    void use() {
	_refcount++;
    }

    void unuse() {
	if (--_refcount == 0)
	    delete this;
    }

    virtual void tamer_closure_activate(unsigned) = 0;

    virtual bool block_landmark(const char *&file, unsigned &line);

  protected:

    unsigned _refcount;

};

struct tamer_debug_closure : public tamer_closure {

    tamer_debug_closure()
	: _block_file(0), _block_line(0) {
    }

    bool block_landmark(const char *&file, unsigned &line);

    void set_block_landmark(const char *file, unsigned line) {
	_block_file = file;
	_block_line = line;
    }

  protected:

    const char *_block_file;
    unsigned _block_line;

};

namespace message {
void event_prematurely_dereferenced(simple_event *e, abstract_rendezvous *r);
}

inline void abstract_rendezvous::remove_all() {
    for (simple_event *e = _events; e; e = e->_r_next)
	e->_r = 0;
    while (_events)
	_events->trigger(false);
}

inline void abstract_rendezvous::clear() {
    remove_all();
}

inline abstract_rendezvous::~abstract_rendezvous() {
    // take all events off this rendezvous and call their triggerers
    remove_all();

    if (_unblocked_prev)
	_unblocked_prev->_unblocked_next = _unblocked_next;
    else if (unblocked == this)
	unblocked = _unblocked_next;
    if (_unblocked_next)
	_unblocked_next->_unblocked_prev = _unblocked_prev;
    else if (unblocked_tail == this)
	unblocked_tail = _unblocked_prev;
    if (_blocked_closure)
	_blocked_closure->unuse();
}

inline void simple_event::initialize(abstract_rendezvous *r, uintptr_t rid)
{
    // NB this can be called before e has been fully initialized.
    _r = r;
    _rid = rid;
    _r_pprev = &r->_events;
    if (r->_events)
	r->_events->_r_pprev = &_r_next;
    _r_next = r->_events;
    r->_events = this;
}

inline void simple_event::trigger(bool values) {
    abstract_rendezvous *r = _r;
    simple_event *at_trigger = _at_trigger;

    if (_r_pprev)
	*_r_pprev = _r_next;
    if (_r_next)
	_r_next->_r_pprev = _r_pprev;

    _r = 0;
    _at_trigger = 0;
    _r_pprev = 0;
    _r_next = 0;

    if (r && _refcount == 0)
	message::event_prematurely_dereferenced(this, r);
    if (r)
	r->complete(_rid, values);
    if (at_trigger) {
	at_trigger->trigger(false);
	unuse(at_trigger);
    }
}

inline void abstract_rendezvous::block(tamer_closure &c, unsigned where) {
    assert(!_blocked_closure && &c);
    c.use();
    _blocked_closure = &c;
    _blocked_closure_blockid = where;
}

inline void abstract_rendezvous::unblock() {
    if (_blocked_closure && !_unblocked_prev && unblocked != this) {
	_unblocked_next = 0;
	_unblocked_prev = unblocked_tail;
	if (unblocked_tail)
	    unblocked_tail->_unblocked_next = this;
	else
	    unblocked = this;
	unblocked_tail = this;
    }
}

inline void abstract_rendezvous::run() {
    tamer_closure *c = _blocked_closure;
    _blocked_closure = 0;
    if (_unblocked_prev)
	_unblocked_prev->_unblocked_next = _unblocked_next;
    else if (unblocked == this)
	unblocked = _unblocked_next;
    if (_unblocked_next)
	_unblocked_next->_unblocked_prev = _unblocked_prev;
    else if (unblocked_tail == this)
	unblocked_tail = _unblocked_next;
    _unblocked_next = _unblocked_prev = 0;
    c->tamer_closure_activate(_blocked_closure_blockid);
    c->unuse();
}

}}
#endif /* TAMER_BASE_HH */
<|endoftext|>


<commit_before>#include <cxxtest/TestDrive.h>

#include <openma/io.h>

#include "trial/c3dhandlerTest_def.h"
#include "test_file_path.h"

CXXTEST_SUITE(IoTest)
{
  CXXTEST_TEST(readOne)
  {
    auto root = ma::io::read(OPENMA_TDD_PATH_IN("c3d/standard/sample01/Eb015pi.c3d"));
    c3dhandlertest_sample01("PI", "Eb015pi.c3d", root);
  };

  CXXTEST_TEST(readTwo)
  {
    ma::Node root("root");
    TS_ASSERT_EQUALS(ma::io::read(&root, OPENMA_TDD_PATH_IN("c3d/standard/sample01/Eb015pi.c3d")), true);
    c3dhandlertest_sample01("PI", "Eb015pi.c3d", &root);
  };
};

CXXTEST_SUITE_REGISTRATION(IoTest)
CXXTEST_TEST_REGISTRATION(IoTest, readOne)
CXXTEST_TEST_REGISTRATION(IoTest, readTwo)<commit_msg>The function c3dhandlertest_sample01 was also in the file ioTest.cpp.<commit_after>#include <cxxtest/TestDrive.h>

#include <openma/io.h>

#include "trial/c3dhandlerTest_def.h"
#include "test_file_path.h"

CXXTEST_SUITE(IoTest)
{
  CXXTEST_TEST(readOne)
  {
    auto root = ma::io::read(OPENMA_TDD_PATH_IN("c3d/standard/sample01/Eb015pi.c3d"));
    c3dhandlertest_read_sample01("PI", "Eb015pi.c3d", root);
  };

  CXXTEST_TEST(readTwo)
  {
    ma::Node root("root");
    TS_ASSERT_EQUALS(ma::io::read(&root, OPENMA_TDD_PATH_IN("c3d/standard/sample01/Eb015pi.c3d")), true);
    c3dhandlertest_read_sample01("PI", "Eb015pi.c3d", &root);
  };
};

CXXTEST_SUITE_REGISTRATION(IoTest)
CXXTEST_TEST_REGISTRATION(IoTest, readOne)
CXXTEST_TEST_REGISTRATION(IoTest, readTwo)<|endoftext|>


<commit_before>#include <bitset>
#include "streams.h"

namespace augs {
	void stream::read(char* data, size_t bytes) {
		memcpy(data, buf.data() + pos, bytes);
		pos += bytes;
	}

	bool stream::operator==(const stream& b) const {
		return std::equal(data(), data() + size(), b.data(), b.data() + size());
	}

	char* stream::data() {
		return buf.data();
	}

	const char* stream::data() const {
		return buf.data();
	}

	void stream::write(const char* data, size_t bytes) {
		memcpy(buf.data() + pos, data, bytes);
		pos += bytes;
	}

	void output_stream_reserver::write(const char*, size_t bytes) {
		pos += bytes;
	}

	stream output_stream_reserver::make_stream() {
		stream reserved;
		reserved.reserve(pos);
		return std::move(reserved);
	}

	void stream::reserve(size_t bytes) {
		reset_pos();
		buf.resize(bytes);
	};

	void stream::reserve(const output_stream_reserver& r) {
		reserve(r.size());
	};

	void bits_stream::read_variable_length_index(unsigned short& idx) {
		std::bitset<4> index_bitcount;
		read(index_bitcount);

		auto bit_count = index_bitcount.to_ulong();

		std::bitset<16> decoded_index;
		read(decoded_index, bit_count);

		idx = decoded_index.to_ulong();
	}

	void bits_stream::write_variable_length_index(unsigned short idx) {
		if (idx == 0) {
			write(std::bitset<4>());
			return;
		}

		unsigned long mask = idx;
		unsigned long index;

		bool non_zero = _BitScanReverse(&index, mask);

		if (non_zero) {
			const unsigned bits_needed = index + 1;

			write(std::bitset<4>(bits_needed));
			write(std::bitset<16>(idx), bits_needed);
		}
	}
}<commit_msg>unnecessary if<commit_after>#include <bitset>
#include "streams.h"

namespace augs {
	void stream::read(char* data, size_t bytes) {
		memcpy(data, buf.data() + pos, bytes);
		pos += bytes;
	}

	bool stream::operator==(const stream& b) const {
		return std::equal(data(), data() + size(), b.data(), b.data() + size());
	}

	char* stream::data() {
		return buf.data();
	}

	const char* stream::data() const {
		return buf.data();
	}

	void stream::write(const char* data, size_t bytes) {
		memcpy(buf.data() + pos, data, bytes);
		pos += bytes;
	}

	void output_stream_reserver::write(const char*, size_t bytes) {
		pos += bytes;
	}

	stream output_stream_reserver::make_stream() {
		stream reserved;
		reserved.reserve(pos);
		return std::move(reserved);
	}

	void stream::reserve(size_t bytes) {
		reset_pos();
		buf.resize(bytes);
	};

	void stream::reserve(const output_stream_reserver& r) {
		reserve(r.size());
	};

	void bits_stream::read_variable_length_index(unsigned short& idx) {
		std::bitset<4> index_bitcount;
		read(index_bitcount);

		auto bit_count = index_bitcount.to_ulong();

		std::bitset<16> decoded_index;
		read(decoded_index, bit_count);

		idx = decoded_index.to_ulong();
	}

	void bits_stream::write_variable_length_index(unsigned short idx) {
		if (idx == 0) {
			write(std::bitset<4>());
			return;
		}

		unsigned long mask = idx;
		unsigned long index;

		bool non_zero = _BitScanReverse(&index, mask);

		const unsigned bits_needed = index + 1;

		write(std::bitset<4>(bits_needed));
		write(std::bitset<16>(idx), bits_needed);
	}
}<|endoftext|>


<commit_before>#include "generator/booking_dataset.hpp"
#include "generator/booking_scoring.hpp"
#include "generator/feature_builder.hpp"
#include "generator/osm_source.hpp"

#include "indexer/classificator_loader.hpp"

#include "geometry/distance_on_sphere.hpp"

#include "coding/file_name_utils.hpp"

#include "std/fstream.hpp"
#include "std/iostream.hpp"
#include "std/numeric.hpp"
#include "std/random.hpp"
#include "std/unique_ptr.hpp"

#include "3party/gflags/src/gflags/gflags.h"

DEFINE_string(osm_file_name, "", "Input .o5m file");
DEFINE_string(booking_data, "", "Path to booking data in .tsv format");
DEFINE_string(sample_data, "", "Sample output path");
DEFINE_uint64(selection_size, 1000, "Selection size");
DEFINE_uint64(seed, minstd_rand::default_seed, "Seed for random shuffle");

using namespace generator;

namespace
{
string PrintBuilder(FeatureBuilder1 const & fb)
{
  ostringstream s;

  s << "Name: " << fb.GetName(StringUtf8Multilang::kDefaultCode) << '\t';

  auto const params = fb.GetParams();
  auto const street = params.GetStreet();
  auto const house = params.house.Get();

  string address = street;
  if (!house.empty())
  {
    if (!street.empty())
      address += ", ";
    address += house;
  }

  if (!address.empty())
    s << "Address: " << address << '\t';

  auto const center = MercatorBounds::ToLatLon(fb.GetKeyPoint());
  s << "lat: " << center.lat << " lon: " << center.lon << '\t';

  if (fb.GetGeomType() == feature::GEOM_POINT)
    s << "GeomType: GEOM_POINT";
  else if (fb.GetGeomType() == feature::GEOM_AREA)
    s << "GeomType: GEOM_AREA";
  else
    CHECK(false, ());

  return s.str();
}

struct Emitter : public EmitterBase
{
  Emitter(feature::GenerateInfo const & info)
    : m_bookingDataset(info.m_bookingDatafileName)
  {
    LOG_SHORT(LINFO, (m_bookingDataset.Size(), "hotels are loaded from Booking."));
    LOG_SHORT(LINFO, ("OSM data:", FLAGS_osm_file_name));
  }

  void operator()(FeatureBuilder1 & fb) override
  {
    if (m_bookingDataset.CanBeBooking(fb))
      m_features.emplace_back(fb);
  }

  void GetNames(vector<string> & names) const override
  {
    names.clear();
  }

  bool Finish() override
  {
    LOG_SHORT(LINFO, ("Num of tourism elements:", m_features.size()));
    vector<size_t> elementIndexes(m_features.size());
    iota(elementIndexes.begin(), elementIndexes.end(), 0);

    shuffle(elementIndexes.begin(), elementIndexes.end(), minstd_rand(FLAGS_seed));
    if (FLAGS_selection_size < elementIndexes.size())
      elementIndexes.resize(FLAGS_selection_size);

    stringstream outStream;

    for (size_t i : elementIndexes)
    {
      auto const & fb = m_features[i];
      auto const bookingIndexes = m_bookingDataset.GetNearestHotels(
          MercatorBounds::ToLatLon(fb.GetKeyPoint()),
          BookingDataset::kMaxSelectedElements,
          BookingDataset::kDistanceLimitInMeters);

      for (size_t const j : bookingIndexes)
      {
        auto const & hotel = m_bookingDataset.GetHotel(j);
        auto const score = booking_scoring::Match(hotel, fb);

        double const distanceMeters = ms::DistanceOnEarth(center.lat, center.lon,
                                                          hotel.lat, hotel.lon);
        auto const matched = score.IsMatched();

        outStream << "# ------------------------------------------" << fixed << setprecision(6)
                  << endl;
        outStream << (matched ? 'y' : 'n') << " \t" << i << "\t " << j
                  << "\tdistance: " << distanceMeters
                  << "\tdistance score: " << score.m_linearNormDistanceScore
                  << "\tname score: " << score.m_nameSimilarityScore
                  << "\tresult score: " << score.GetMatchingScore()
                  << endl;
        outStream << "# " << PrintBuilder(fb) << endl;
        outStream << "# " << hotel << endl;
        outStream << "# URL: https://www.openstreetmap.org/?mlat=" << hotel.lat
                  << "&mlon=" << hotel.lon << "#map=18/" << hotel.lat << "/" << hotel.lon << endl;
      }
      if (!bookingIndexes.empty())
        outStream << endl << endl;
    }

    if (FLAGS_sample_data.empty())
    {
      cout << outStream.str();
    }
    else
    {
      ofstream file(FLAGS_sample_data);
      if (file.is_open())
      {
        file << outStream.str();
      }
      else
      {
        LOG(LERROR, ("Can't output into", FLAGS_sample_data));
        return false;
      }
    }

    return true;
  }

  BookingDataset m_bookingDataset;
  vector<FeatureBuilder1> m_features;
};

unique_ptr<Emitter> GetEmitter(feature::GenerateInfo const & info)
{
  LOG_SHORT(LINFO, ("Booking data:", FLAGS_booking_data));
  return make_unique<Emitter>(info);
}

feature::GenerateInfo GetGenerateInfo()
{
  feature::GenerateInfo info;
  info.m_bookingDatafileName = FLAGS_booking_data;
  info.m_osmFileName = FLAGS_osm_file_name;
  info.SetNodeStorageType("map");
  info.SetOsmFileType("o5m");

  info.m_intermediateDir =  my::GetDirectory(FLAGS_sample_data);

  // ...

  return info;
}
}  // namespace

int main(int argc, char * argv[])
{
  google::SetUsageMessage(
      "Takes OSM XML data from stdin and creates"
      " data and index files in several passes.");
  google::ParseCommandLineFlags(&argc, &argv, true);

  classificator::Load();

  auto info = GetGenerateInfo();
  GenerateIntermediateData(info);
  GenerateFeatures(info, GetEmitter);

  return 0;
}
<commit_msg>Fix gtool build.<commit_after>#include "generator/booking_dataset.hpp"
#include "generator/booking_scoring.hpp"
#include "generator/feature_builder.hpp"
#include "generator/osm_source.hpp"

#include "indexer/classificator_loader.hpp"

#include "geometry/distance_on_sphere.hpp"

#include "coding/file_name_utils.hpp"

#include "std/fstream.hpp"
#include "std/iostream.hpp"
#include "std/numeric.hpp"
#include "std/random.hpp"
#include "std/unique_ptr.hpp"

#include "3party/gflags/src/gflags/gflags.h"

DEFINE_string(osm_file_name, "", "Input .o5m file");
DEFINE_string(booking_data, "", "Path to booking data in .tsv format");
DEFINE_string(sample_data, "", "Sample output path");
DEFINE_uint64(selection_size, 1000, "Selection size");
DEFINE_uint64(seed, minstd_rand::default_seed, "Seed for random shuffle");

using namespace generator;

namespace
{
string PrintBuilder(FeatureBuilder1 const & fb)
{
  ostringstream s;

  s << "Name: " << fb.GetName(StringUtf8Multilang::kDefaultCode) << '\t';

  auto const params = fb.GetParams();
  auto const street = params.GetStreet();
  auto const house = params.house.Get();

  string address = street;
  if (!house.empty())
  {
    if (!street.empty())
      address += ", ";
    address += house;
  }

  if (!address.empty())
    s << "Address: " << address << '\t';

  auto const center = MercatorBounds::ToLatLon(fb.GetKeyPoint());
  s << "lat: " << center.lat << " lon: " << center.lon << '\t';

  if (fb.GetGeomType() == feature::GEOM_POINT)
    s << "GeomType: GEOM_POINT";
  else if (fb.GetGeomType() == feature::GEOM_AREA)
    s << "GeomType: GEOM_AREA";
  else
    CHECK(false, ());

  return s.str();
}

struct Emitter : public EmitterBase
{
  Emitter(feature::GenerateInfo const & info)
    : m_bookingDataset(info.m_bookingDatafileName)
  {
    LOG_SHORT(LINFO, (m_bookingDataset.Size(), "hotels are loaded from Booking."));
    LOG_SHORT(LINFO, ("OSM data:", FLAGS_osm_file_name));
  }

  void operator()(FeatureBuilder1 & fb) override
  {
    if (m_bookingDataset.CanBeBooking(fb))
      m_features.emplace_back(fb);
  }

  void GetNames(vector<string> & names) const override
  {
    names.clear();
  }

  bool Finish() override
  {
    LOG_SHORT(LINFO, ("Num of tourism elements:", m_features.size()));
    vector<size_t> elementIndexes(m_features.size());
    iota(elementIndexes.begin(), elementIndexes.end(), 0);

    shuffle(elementIndexes.begin(), elementIndexes.end(), minstd_rand(FLAGS_seed));
    if (FLAGS_selection_size < elementIndexes.size())
      elementIndexes.resize(FLAGS_selection_size);

    stringstream outStream;

    for (size_t i : elementIndexes)
    {
      auto const & fb = m_features[i];
      auto const bookingIndexes = m_bookingDataset.GetNearestHotels(
          MercatorBounds::ToLatLon(fb.GetKeyPoint()),
          BookingDataset::kMaxSelectedElements,
          BookingDataset::kDistanceLimitInMeters);

      for (size_t const j : bookingIndexes)
      {
        auto const & hotel = m_bookingDataset.GetHotel(j);
        auto const score = booking_scoring::Match(hotel, fb);

        auto const center = MercatorBounds::ToLatLon(fb.GetKeyPoint());
        double const distanceMeters = ms::DistanceOnEarth(center.lat, center.lon,
                                                          hotel.lat, hotel.lon);
        auto const matched = score.IsMatched();

        outStream << "# ------------------------------------------" << fixed << setprecision(6)
                  << endl;
        outStream << (matched ? 'y' : 'n') << " \t" << i << "\t " << j
                  << "\tdistance: " << distanceMeters
                  << "\tdistance score: " << score.m_linearNormDistanceScore
                  << "\tname score: " << score.m_nameSimilarityScore
                  << "\tresult score: " << score.GetMatchingScore()
                  << endl;
        outStream << "# " << PrintBuilder(fb) << endl;
        outStream << "# " << hotel << endl;
        outStream << "# URL: https://www.openstreetmap.org/?mlat=" << hotel.lat
                  << "&mlon=" << hotel.lon << "#map=18/" << hotel.lat << "/" << hotel.lon << endl;
      }
      if (!bookingIndexes.empty())
        outStream << endl << endl;
    }

    if (FLAGS_sample_data.empty())
    {
      cout << outStream.str();
    }
    else
    {
      ofstream file(FLAGS_sample_data);
      if (file.is_open())
      {
        file << outStream.str();
      }
      else
      {
        LOG(LERROR, ("Can't output into", FLAGS_sample_data));
        return false;
      }
    }

    return true;
  }

  BookingDataset m_bookingDataset;
  vector<FeatureBuilder1> m_features;
};

unique_ptr<Emitter> GetEmitter(feature::GenerateInfo const & info)
{
  LOG_SHORT(LINFO, ("Booking data:", FLAGS_booking_data));
  return make_unique<Emitter>(info);
}

feature::GenerateInfo GetGenerateInfo()
{
  feature::GenerateInfo info;
  info.m_bookingDatafileName = FLAGS_booking_data;
  info.m_osmFileName = FLAGS_osm_file_name;
  info.SetNodeStorageType("map");
  info.SetOsmFileType("o5m");

  info.m_intermediateDir =  my::GetDirectory(FLAGS_sample_data);

  // ...

  return info;
}
}  // namespace

int main(int argc, char * argv[])
{
  google::SetUsageMessage(
      "Takes OSM XML data from stdin and creates"
      " data and index files in several passes.");
  google::ParseCommandLineFlags(&argc, &argv, true);

  classificator::Load();

  auto info = GetGenerateInfo();
  GenerateIntermediateData(info);
  GenerateFeatures(info, GetEmitter);

  return 0;
}
<|endoftext|>


<commit_before>
/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/scenarios/side_pass/side_pass_scenario.h"

#include "cyber/common/log.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/time/time.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/obstacle_blocking_analyzer.h"
#include "modules/planning/scenarios/side_pass/stage_approach_obstacle.h"
#include "modules/planning/scenarios/side_pass/stage_backup.h"
#include "modules/planning/scenarios/side_pass/stage_detect_safety.h"
#include "modules/planning/scenarios/side_pass/stage_generate_path.h"
#include "modules/planning/scenarios/side_pass/stage_pass_obstacle.h"
#include "modules/planning/scenarios/side_pass/stage_stop_on_wait_point.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {

apollo::common::util::Factory<
    ScenarioConfig::StageType, Stage,
    Stage* (*)(const ScenarioConfig::StageConfig& stage_config)>
    SidePassScenario::s_stage_factory_;

// The clearance distance from intersection/destination.
// If ADC is too close, then do not enter SIDE_PASS.
constexpr double kClearDistance = 15.0;

void SidePassScenario::RegisterStages() {
  s_stage_factory_.Clear();
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageApproachObstacle(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_DETECT_SAFETY,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageDetectSafety(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_GENERATE_PATH,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageGeneratePath(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageStopOnWaitPoint(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_PASS_OBSTACLE,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StagePassObstacle(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_BACKUP,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageBackup(config);
      });
}

SidePassScenario::SidePassScenario(const ScenarioConfig& config,
                                   const ScenarioContext* scenario_context)
    : Scenario(config, scenario_context) {
  side_pass_context_.scenario_config_.CopyFrom(config.side_pass_config());
}

std::unique_ptr<Stage> SidePassScenario::CreateStage(
    const ScenarioConfig::StageConfig& stage_config) {
  if (s_stage_factory_.Empty()) {
    RegisterStages();
  }
  auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(),
                                                 stage_config);
  if (ptr == nullptr) {
    AERROR << "Failed to create stage for config: "
           << stage_config.DebugString();
    return nullptr;
  }
  ptr->SetContext(&side_pass_context_);
  return ptr;
}

bool SidePassScenario::IsTransferable(const Scenario& current_scenario,
                                      const common::TrajectoryPoint& ego_point,
                                      const Frame& frame) {
  // Sanity checks.
  if (frame.reference_line_info().size() > 1) {
    return false;
  }
  if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) {
    // Check if the blocking obstacle is still static.
    // If not, then switch to LANE_FOLLOW.
    const auto front_blocking_obstacle =
        const_cast<Frame&>(frame).Find(front_blocking_obstacle_id_);
    if (front_blocking_obstacle != nullptr &&
        !front_blocking_obstacle->IsStatic()) {
      AWARN << "Obstacle " << front_blocking_obstacle_id_
            << " starts to move. Change scenario from SIDE_PASS"
               " back to default scenario.";
      return false;
    }
    msg_ = "side pass obstacle: " + front_blocking_obstacle_id_;
    return (current_scenario.GetStatus() !=
            Scenario::ScenarioStatus::STATUS_DONE);
  } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) {
    // If in some other special scenario, then don't try to switch
    // to SIDE_PASS scenario.
    return false;
  } else {
    // If originally in LANE_FOLLOW, then decide whether we should
    // switch to SIDE_PASS scenario.
    bool is_side_pass = IsSidePassScenario(frame);
    if (is_side_pass) {
      msg_ = "side pass obstacle: " + front_blocking_obstacle_id_;
    }
    return is_side_pass;
  }
}

bool SidePassScenario::IsSidePassScenario(const Frame& frame) {
  return (IsFarFromDestination(frame) &&
          IsFarFromIntersection(frame) &&
          HasBlockingObstacle(frame));
}

bool SidePassScenario::IsFarFromDestination(const Frame& frame) {
  if (frame.reference_line_info().size() > 1) {
    return false;
  }
  const auto& reference_line_info = frame.reference_line_info().front();
  if (reference_line_info.SDistanceToDestination() < kClearDistance) {
    ADEBUG << "Too close to destination; don't SIDE_PASS";
    return false;
  }
  return true;
}

bool SidePassScenario::IsFarFromIntersection(const Frame& frame) {
  if (frame.reference_line_info().size() > 1) {
    return false;
  }
  const SLBoundary& adc_sl_boundary =
      frame.reference_line_info().front().AdcSlBoundary();
  const auto& first_encountered_overlaps =
      frame.reference_line_info().front().FirstEncounteredOverlaps();
  for (const auto& overlap : first_encountered_overlaps) {
    ADEBUG << "AdcSL: " << adc_sl_boundary.ShortDebugString();
    ADEBUG << overlap.first << ", " << overlap.second.DebugString();
    if (overlap.first != ReferenceLineInfo::CLEAR_AREA &&
        overlap.first != ReferenceLineInfo::CROSSWALK &&
        overlap.first != ReferenceLineInfo::PNC_JUNCTION &&
        overlap.first != ReferenceLineInfo::SIGNAL &&
        overlap.first != ReferenceLineInfo::STOP_SIGN) {
      continue;
    }

    auto distance = overlap.second.start_s - adc_sl_boundary.end_s();
    if (overlap.first == ReferenceLineInfo::SIGNAL) {
      if (distance < FLAGS_side_pass_min_signal_intersection_distance) {
        ADEBUG << "Too close to signal intersection ("
               << distance << "m); don't SIDE_PASS.";
        return false;
      }
    } else {
      if (distance < kClearDistance) {
        ADEBUG << "Too close to overlap_type[" << overlap.first
               << "] (" << distance << "m); don't SIDE_PASS";
        return false;
      }
    }
  }
  return true;
}

bool SidePassScenario::HasBlockingObstacle(const Frame& frame) {
  // Sanity checks.
  front_blocking_obstacle_id_ = "";
  if (frame.reference_line_info().size() > 1) {
    return false;
  }

  const auto& reference_line_info = frame.reference_line_info().front();
  const PathDecision& path_decision = reference_line_info.path_decision();
  double distance_to_closest_blocking_obstacle = -100.0;
  bool exists_a_blocking_obstacle = false;
  // A blocking obstacle is an obstacle blocks the road when it is not blocked
  // by other obstacles or traffic rules.
  // Loop through every obstacle to locate the closest blocking one, if there
  // exists such an obstacle.
  for (const auto* obstacle : path_decision.obstacles().Items()) {
    const auto& side_pass_config = side_pass_context_.scenario_config_;
    if (IsBlockingObstacleToSidePass(
            frame, obstacle,
            side_pass_config.block_obstacle_min_speed(),
            side_pass_config.min_front_obstacle_distance(),
            side_pass_config.enable_obstacle_blocked_check())) {
      exists_a_blocking_obstacle = true;
      double distance_between_adc_and_obstacle =
          GetDistanceBetweenADCAndObstacle(frame, obstacle);
      if (distance_to_closest_blocking_obstacle < 0.0 ||
          distance_between_adc_and_obstacle <
              distance_to_closest_blocking_obstacle) {
        // Only record the closest front blocking obstacle.
        distance_to_closest_blocking_obstacle =
            distance_between_adc_and_obstacle;
        front_blocking_obstacle_id_ = obstacle->Id() + "_0";
        side_pass_context_.front_blocking_obstacle_id_ = obstacle->Id();
      }
    }
  }
  if (exists_a_blocking_obstacle) {
    return true;
  } else {
    side_pass_context_.front_blocking_obstacle_id_ = "";
    return false;
  }
}

}  // namespace side_pass
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<commit_msg>planning: temporarily enable side pass at pnc junction w/o stop sign and traffic light<commit_after>
/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/scenarios/side_pass/side_pass_scenario.h"

#include "cyber/common/log.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/time/time.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/obstacle_blocking_analyzer.h"
#include "modules/planning/scenarios/side_pass/stage_approach_obstacle.h"
#include "modules/planning/scenarios/side_pass/stage_backup.h"
#include "modules/planning/scenarios/side_pass/stage_detect_safety.h"
#include "modules/planning/scenarios/side_pass/stage_generate_path.h"
#include "modules/planning/scenarios/side_pass/stage_pass_obstacle.h"
#include "modules/planning/scenarios/side_pass/stage_stop_on_wait_point.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {

apollo::common::util::Factory<
    ScenarioConfig::StageType, Stage,
    Stage* (*)(const ScenarioConfig::StageConfig& stage_config)>
    SidePassScenario::s_stage_factory_;

// The clearance distance from intersection/destination.
// If ADC is too close, then do not enter SIDE_PASS.
constexpr double kClearDistance = 15.0;

void SidePassScenario::RegisterStages() {
  s_stage_factory_.Clear();
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageApproachObstacle(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_DETECT_SAFETY,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageDetectSafety(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_GENERATE_PATH,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageGeneratePath(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageStopOnWaitPoint(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_PASS_OBSTACLE,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StagePassObstacle(config);
      });
  s_stage_factory_.Register(
      ScenarioConfig::SIDE_PASS_BACKUP,
      [](const ScenarioConfig::StageConfig& config) -> Stage* {
        return new StageBackup(config);
      });
}

SidePassScenario::SidePassScenario(const ScenarioConfig& config,
                                   const ScenarioContext* scenario_context)
    : Scenario(config, scenario_context) {
  side_pass_context_.scenario_config_.CopyFrom(config.side_pass_config());
}

std::unique_ptr<Stage> SidePassScenario::CreateStage(
    const ScenarioConfig::StageConfig& stage_config) {
  if (s_stage_factory_.Empty()) {
    RegisterStages();
  }
  auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(),
                                                 stage_config);
  if (ptr == nullptr) {
    AERROR << "Failed to create stage for config: "
           << stage_config.DebugString();
    return nullptr;
  }
  ptr->SetContext(&side_pass_context_);
  return ptr;
}

bool SidePassScenario::IsTransferable(const Scenario& current_scenario,
                                      const common::TrajectoryPoint& ego_point,
                                      const Frame& frame) {
  // Sanity checks.
  if (frame.reference_line_info().size() > 1) {
    return false;
  }
  if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) {
    // Check if the blocking obstacle is still static.
    // If not, then switch to LANE_FOLLOW.
    const auto front_blocking_obstacle =
        const_cast<Frame&>(frame).Find(front_blocking_obstacle_id_);
    if (front_blocking_obstacle != nullptr &&
        !front_blocking_obstacle->IsStatic()) {
      AWARN << "Obstacle " << front_blocking_obstacle_id_
            << " starts to move. Change scenario from SIDE_PASS"
               " back to default scenario.";
      return false;
    }
    msg_ = "side pass obstacle: " + front_blocking_obstacle_id_;
    return (current_scenario.GetStatus() !=
            Scenario::ScenarioStatus::STATUS_DONE);
  } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) {
    // If in some other special scenario, then don't try to switch
    // to SIDE_PASS scenario.
    return false;
  } else {
    // If originally in LANE_FOLLOW, then decide whether we should
    // switch to SIDE_PASS scenario.
    bool is_side_pass = IsSidePassScenario(frame);
    if (is_side_pass) {
      msg_ = "side pass obstacle: " + front_blocking_obstacle_id_;
    }
    return is_side_pass;
  }
}

bool SidePassScenario::IsSidePassScenario(const Frame& frame) {
  return (IsFarFromDestination(frame) &&
          IsFarFromIntersection(frame) &&
          HasBlockingObstacle(frame));
}

bool SidePassScenario::IsFarFromDestination(const Frame& frame) {
  if (frame.reference_line_info().size() > 1) {
    return false;
  }
  const auto& reference_line_info = frame.reference_line_info().front();
  if (reference_line_info.SDistanceToDestination() < kClearDistance) {
    ADEBUG << "Too close to destination; don't SIDE_PASS";
    return false;
  }
  return true;
}

bool SidePassScenario::IsFarFromIntersection(const Frame& frame) {
  if (frame.reference_line_info().size() > 1) {
    return false;
  }
  const SLBoundary& adc_sl_boundary =
      frame.reference_line_info().front().AdcSlBoundary();
  const auto& first_encountered_overlaps =
      frame.reference_line_info().front().FirstEncounteredOverlaps();
  for (const auto& overlap : first_encountered_overlaps) {
    ADEBUG << "AdcSL: " << adc_sl_boundary.ShortDebugString();
    ADEBUG << overlap.first << ", " << overlap.second.DebugString();
    if (overlap.first != ReferenceLineInfo::CLEAR_AREA &&
        overlap.first != ReferenceLineInfo::CROSSWALK &&
        // TODO(yifei) temporarily enable side pass at pnc junction without
        // stop sign and traffic light.
        // overlap.first != ReferenceLineInfo::PNC_JUNCTION &&
        overlap.first != ReferenceLineInfo::SIGNAL &&
        overlap.first != ReferenceLineInfo::STOP_SIGN) {
      continue;
    }

    auto distance = overlap.second.start_s - adc_sl_boundary.end_s();
    if (overlap.first == ReferenceLineInfo::SIGNAL) {
      if (distance < FLAGS_side_pass_min_signal_intersection_distance) {
        ADEBUG << "Too close to signal intersection ("
               << distance << "m); don't SIDE_PASS.";
        return false;
      }
    } else {
      if (distance < kClearDistance) {
        ADEBUG << "Too close to overlap_type[" << overlap.first
               << "] (" << distance << "m); don't SIDE_PASS";
        return false;
      }
    }
  }
  return true;
}

bool SidePassScenario::HasBlockingObstacle(const Frame& frame) {
  // Sanity checks.
  front_blocking_obstacle_id_ = "";
  if (frame.reference_line_info().size() > 1) {
    return false;
  }

  const auto& reference_line_info = frame.reference_line_info().front();
  const PathDecision& path_decision = reference_line_info.path_decision();
  double distance_to_closest_blocking_obstacle = -100.0;
  bool exists_a_blocking_obstacle = false;
  // A blocking obstacle is an obstacle blocks the road when it is not blocked
  // by other obstacles or traffic rules.
  // Loop through every obstacle to locate the closest blocking one, if there
  // exists such an obstacle.
  for (const auto* obstacle : path_decision.obstacles().Items()) {
    const auto& side_pass_config = side_pass_context_.scenario_config_;
    if (IsBlockingObstacleToSidePass(
            frame, obstacle,
            side_pass_config.block_obstacle_min_speed(),
            side_pass_config.min_front_obstacle_distance(),
            side_pass_config.enable_obstacle_blocked_check())) {
      exists_a_blocking_obstacle = true;
      double distance_between_adc_and_obstacle =
          GetDistanceBetweenADCAndObstacle(frame, obstacle);
      if (distance_to_closest_blocking_obstacle < 0.0 ||
          distance_between_adc_and_obstacle <
              distance_to_closest_blocking_obstacle) {
        // Only record the closest front blocking obstacle.
        distance_to_closest_blocking_obstacle =
            distance_between_adc_and_obstacle;
        front_blocking_obstacle_id_ = obstacle->Id() + "_0";
        side_pass_context_.front_blocking_obstacle_id_ = obstacle->Id();
      }
    }
  }
  if (exists_a_blocking_obstacle) {
    return true;
  } else {
    side_pass_context_.front_blocking_obstacle_id_ = "";
    return false;
  }
}

}  // namespace side_pass
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>
#include "QtApp.hpp"
#include "QtMenu.hpp"
#include "PythonHelpers.h"
#include "PyThreading.hpp"
#include <QAction>

// Dummy vars for QApplication.
// Note that the App construction is late at init. The Python code
// has already parsed all args and warned about unknown ones, etc.
// If we want to allow some Qt args, we should add some Python arg
// like "--qtargs" and pass those here.
static int dummy_argc = 1;
static char* dummy_argv[] = {(char*)"musicplayer", NULL};

QtApp::QtApp() : QApplication(dummy_argc, dummy_argv) {
	{
		QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(boost::function<void(void)>)");
		int methodIndex = this->metaObject()->indexOfSlot(normalizedSignature);
		assert(methodIndex >= 0);
		genericExec_method = this->metaObject()->method(methodIndex);
	}

	this->setOrganizationName("Albert Zeyer");
	this->setApplicationName("MusicPlayer");

	connect(this, SIGNAL(aboutToQuit()), this, SLOT(handleApplicationQuit()));
}

void QtApp::handleApplicationQuit() {
	PyScopedGIL gil;

	printf("about to quit ...\n");

	PyObject* guiMod = getModule("gui"); // borrowed
	if(!guiMod) {
		printf("QtApp::handleApplicationQuit: gui module not found");
		return;
	}

	PyObject* ret = PyObject_CallMethod(guiMod, (char*)"handleApplicationQuit", NULL);
	if(!ret && PyErr_Occurred()) PyErr_Print();
	Py_XDECREF(ret);
}

void QtApp::openWindowViaMenu() {
	if(sender() == NULL) {
		printf("QtApp::openWindowViaMenu: no sender\n");
		return;
	}

	QAction* act = qobject_cast<QAction*>(sender());
	if(!act) {
		printf("QtApp::openWindowViaMenu: sender is not QAction\n");
		return;
	}
	if(act->objectName().isEmpty()) {
		printf("QtApp::openWindowViaMenu: sender name is empty\n");
		return;
	}

	openWindow(act->objectName().toStdString());
}

void QtApp::openMainWindow() {
	openWindow("Main");
}

void QtApp::openWindow(const std::string& name) {
	QWidget* win = new QWidget();
	win->setWindowTitle(QString::fromStdString(name));
	// ...

	win->show();
}

void QtApp::minimizeWindow() {
	QWidget* win = qApp->activeWindow();
	if(win) win->showMinimized();
}

void QtApp::closeWindow() {
	QWidget* win = qApp->activeWindow();
	if(win) win->close();
}

void QtApp::edit_cut() {
	QWidget* w = QApplication::focusWidget();
	//...
}

void QtApp::edit_copy() {

}

void QtApp::edit_paste() {

}

void QtApp::edit_selectAll() {

}

void QtApp::handlePlayerUpdate() {
	updateControlMenu();
}

void QtApp::playPause() {
	PyScopedGIL gil;
	PyObject* mod = getModule("State"); // borrowed
	if(!mod) return;

	PyObject* player = NULL;
	PyObject* playing = NULL;
	bool playingBool = false;

	player = attrChain(mod, "state.player");
	if(!player) goto final;

	playing = PyObject_GetAttrString(player, "playing");
	if(!playing) goto final;

	switch(PyObject_IsTrue(playing)) {
	case 1: playingBool = true; break;
	case 0: playingBool = false; break;
	default: goto final;
	}

	playingBool = !playingBool;
	PyObject_SetAttrString_retain(player, "playing", PyBool_FromLong(playingBool));

final:
	if(PyErr_Occurred()) PyErr_Print();
	Py_XDECREF(player);
	Py_XDECREF(playing);
}

void QtApp::nextSong() {
	PyScopedGIL gil;
	PyObject* mod = getModule("State"); // borrowed
	if(!mod) return;

	PyObject* player = NULL;
	PyObject* ret = NULL;

	player = attrChain(mod, "state.player");
	ret = PyObject_CallMethod(player, "nextSong", NULL);

final:
	if(PyErr_Occurred()) PyErr_Print();
	Py_XDECREF(player);
	Py_XDECREF(ret);
}

void QtApp::debug_resetPlayer() {

}
<commit_msg>qt no QuitOnLastWindowClosed<commit_after>
#include "QtApp.hpp"
#include "QtMenu.hpp"
#include "PythonHelpers.h"
#include "PyThreading.hpp"
#include <QAction>

// Dummy vars for QApplication.
// Note that the App construction is late at init. The Python code
// has already parsed all args and warned about unknown ones, etc.
// If we want to allow some Qt args, we should add some Python arg
// like "--qtargs" and pass those here.
static int dummy_argc = 1;
static char* dummy_argv[] = {(char*)"musicplayer", NULL};

QtApp::QtApp() : QApplication(dummy_argc, dummy_argv) {
	{
		QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(boost::function<void(void)>)");
		int methodIndex = this->metaObject()->indexOfSlot(normalizedSignature);
		assert(methodIndex >= 0);
		genericExec_method = this->metaObject()->method(methodIndex);
	}

	this->setOrganizationName("Albert Zeyer");
	this->setApplicationName("MusicPlayer");
	this->setQuitOnLastWindowClosed(false);

	connect(this, SIGNAL(aboutToQuit()), this, SLOT(handleApplicationQuit()));
}

void QtApp::handleApplicationQuit() {
	PyScopedGIL gil;

	printf("about to quit ...\n");

	PyObject* guiMod = getModule("gui"); // borrowed
	if(!guiMod) {
		printf("QtApp::handleApplicationQuit: gui module not found");
		return;
	}

	PyObject* ret = PyObject_CallMethod(guiMod, (char*)"handleApplicationQuit", NULL);
	if(!ret && PyErr_Occurred()) PyErr_Print();
	Py_XDECREF(ret);
}

void QtApp::openWindowViaMenu() {
	if(sender() == NULL) {
		printf("QtApp::openWindowViaMenu: no sender\n");
		return;
	}

	QAction* act = qobject_cast<QAction*>(sender());
	if(!act) {
		printf("QtApp::openWindowViaMenu: sender is not QAction\n");
		return;
	}
	if(act->objectName().isEmpty()) {
		printf("QtApp::openWindowViaMenu: sender name is empty\n");
		return;
	}

	openWindow(act->objectName().toStdString());
}

void QtApp::openMainWindow() {
	openWindow("Main");
}

void QtApp::openWindow(const std::string& name) {
	QWidget* win = new QWidget();
	win->setWindowTitle(QString::fromStdString(name));
	// ...

	win->show();
}

void QtApp::minimizeWindow() {
	QWidget* win = qApp->activeWindow();
	if(win) win->showMinimized();
}

void QtApp::closeWindow() {
	QWidget* win = qApp->activeWindow();
	if(win) win->close();
}

void QtApp::edit_cut() {
	QWidget* w = QApplication::focusWidget();
	//...
}

void QtApp::edit_copy() {

}

void QtApp::edit_paste() {

}

void QtApp::edit_selectAll() {

}

void QtApp::handlePlayerUpdate() {
	updateControlMenu();
}

void QtApp::playPause() {
	PyScopedGIL gil;
	PyObject* mod = getModule("State"); // borrowed
	if(!mod) return;

	PyObject* player = NULL;
	PyObject* playing = NULL;
	bool playingBool = false;

	player = attrChain(mod, "state.player");
	if(!player) goto final;

	playing = PyObject_GetAttrString(player, "playing");
	if(!playing) goto final;

	switch(PyObject_IsTrue(playing)) {
	case 1: playingBool = true; break;
	case 0: playingBool = false; break;
	default: goto final;
	}

	playingBool = !playingBool;
	PyObject_SetAttrString_retain(player, "playing", PyBool_FromLong(playingBool));

final:
	if(PyErr_Occurred()) PyErr_Print();
	Py_XDECREF(player);
	Py_XDECREF(playing);
}

void QtApp::nextSong() {
	PyScopedGIL gil;
	PyObject* mod = getModule("State"); // borrowed
	if(!mod) return;

	PyObject* player = NULL;
	PyObject* ret = NULL;

	player = attrChain(mod, "state.player");
	ret = PyObject_CallMethod(player, "nextSong", NULL);

final:
	if(PyErr_Occurred()) PyErr_Print();
	Py_XDECREF(player);
	Py_XDECREF(ret);
}

void QtApp::debug_resetPlayer() {

}
<|endoftext|>


<commit_before>// Copyright 2020 The Google Research Authors.
//
// 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.h"

namespace automl_zero {

template<FeatureIndexT F>
void Memory<F>::Wipe() {
  for (Scalar& value : scalar_) {
    value = 0.0;
  }
  for (Vector<F>& value : vector_) {
    value.setZero();
  }
  for (Matrix<F>& value : matrix_) {
    value.setZero();
  }
}

// Define here all the class-instances of the template that will be compiled.
// Bigger than 32 leads to allocs too large for dense-storage in Eigen in stack.
template class Memory<2>;
template class Memory<4>;
template class Memory<8>;
template class Memory<16>;
template class Memory<32>;

}  // namespace automl_zero
<commit_msg>Clean up dependencies.<commit_after>// Copyright 2020 The Google Research Authors.
//
// 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.h"

namespace automl_zero {

// Define here all the class-instances of the template that will be compiled.
// Bigger than 32 leads to allocs too large for dense-storage in Eigen in stack.
template class Memory<2>;
template class Memory<4>;
template class Memory<8>;
template class Memory<16>;
template class Memory<32>;

}  // namespace automl_zero
<|endoftext|>


<commit_before>/*
 * server_init.c
 *
 *  Created on: May 2, 2017
 *      Author: Daniel
 *
 *  Various intialization functions used by the server.
 *  Moved here for readability.
 */
#include "server_init.hpp"

void readServerConfig(int &cmdPort, int &mediaPort, std::string &publicKeyFile, std::string &privateKeyFile, std::string &ciphers, std::string &dhfile, Logger *logger)
{
	std::ifstream conffile(CONFFILE());
	std::string line;
	bool gotPublicKey = false, gotPrivateKey = false, gotCiphers = false, gotCmdPort = false, gotMediaPort = false, gotDhFile = false;

	while(getline(conffile, line))
	{
		//skip blank lines and comment lines
		if(line.length() == 0 || line.at(0) == '#')
		{
			continue;
		}

		//read the variable and its value
		std::string var, value;
		std::stringstream ss(line);
		std::getline(ss, var, '=');
		std::getline(ss, value, '=');

		//cleanup the surrounding whitespace and strip the end of line comment
		var = Utils::trim(var);
		value = Utils::trim(value);

		//if there is no value then go on to the next line
		if(value == "")
		{
			continue;
		}

		if(var == "command")
		{
			cmdPort = atoi(value.c_str());
			gotCmdPort = true;
			continue;
		}
		else if (var == "media")
		{
			mediaPort = atoi(value.c_str());
			gotMediaPort = true;
			continue;
		}
		else if (var == "public")
		{
			publicKeyFile = value;
			gotPublicKey = true;
			continue;
		}
		else if (var == "private")
		{
			privateKeyFile = value;
			gotPrivateKey = true;
			continue;
		}
		else if (var == "ciphers")
		{
			ciphers = value;
			gotCiphers = true;
			continue;
		}
		else if (var == "dhfile")
		{
			dhfile = value;
			gotDhFile = true;
			continue;
		}
		else
		{
			std::string unknown = "unknown variable parsed: " + line;
			logger->insertLog(Log(Log::TAG::STARTUP, unknown, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
		}
	}

	//at the minimum a public and private key must be specified. everything else has a default value
	if (!gotPublicKey || !gotPrivateKey || !gotDhFile)
	{
		if(!gotPublicKey)
		{
			std::string error = "Your did not specify a PUBLIC key pem in: " + CONFFILE() + "\n";
			std::cout << error << "\n";
		}
		if(!gotPublicKey)
		{
			std::string error = "Your did not specify a PRIVATE key pem in: " + CONFFILE() + "\n";
			std::cout << error << "\n";
		}
		if(!gotDhFile)
		{
			std::string error = "Your did not specify a DH file for DHE ciphers in: " + CONFFILE() + "\n";
			std::cout << error << "\n";
		}
		exit(1);
	}

	//warn of default values if they're being used
	if(!gotCmdPort)
	{
		std::string message =  "Using default command port of: " + std::to_string(cmdPort);
		logger->insertLog(Log(Log::TAG::STARTUP, message, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
	}
	if(!gotMediaPort)
	{
		std::string message= "Using default media port of: " + std::to_string(mediaPort);
		logger->insertLog(Log(Log::TAG::STARTUP, message, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
	}
	if(!gotCiphers)
	{
		std::string message = "Using default ciphers (no ECDHE): " + ciphers;
		logger->insertLog(Log(Log::TAG::STARTUP, message, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
	}

}

SSL_CTX* setupOpenSSL(std::string const &ciphers, std::string const &privateKeyFile, std::string const &publicKeyFile, std::string const &dhfile)
{
	//openssl setup
	SSL_load_error_strings();
	SSL_library_init();
	OpenSSL_add_all_algorithms();

#if OPENSSL_VERSION_NUMBER >= 0x10100000 //openssl 1.1 requires the "flexible" tls_method
	SSL_CTX *result = SSL_CTX_new(TLS_method());
	SSL_CTX_set_min_proto_version(result, TLS1_2_VERSION); //force the "flexible" method's hand for only 1.2
#else
	SSL_CTX *result = SSL_CTX_new(TLSv1_2_server_method());
#endif

	//set ssl properties
	if(result == NULL)
	{
		std::string error = "ssl initialization problem";
		std::cout << error << "\n";
		perror(error.c_str());
		exit(1);
	}

	//ciphers
	SSL_CTX_set_cipher_list(result, ciphers.c_str());

	//private key
	if(SSL_CTX_use_PrivateKey_file(result, privateKeyFile.c_str(), SSL_FILETYPE_PEM) <= 0)
	{
		std::string error = "problems with the private key " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cout << error << "\n";
		exit(1);
	}

	//public key
	if(SSL_CTX_use_certificate_file(result, publicKeyFile.c_str(), SSL_FILETYPE_PEM) <= 0)
	{
		std::string error = "problems with the public key" + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cout << error << "\n";
		exit(1);
	}

	//dh params to make dhe ciphers work
	//https://www.openssl.org/docs/man1.0.1/ssl/SSL_CTX_set_tmp_dh.html
	DH *dh = NULL;
	FILE *paramfile;
	paramfile = fopen(dhfile.c_str(), "r");
	if(!paramfile)
	{
		std::string error = "problems opening dh param file at: " +  dhfile + " (" + std::to_string(errno) + ") " + std::string(strerror(errno));
		std::cout << error << "\n";
		exit(1);
	}
	dh = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
	fclose(paramfile);
	if(dh == NULL)
	{
		std::string error = "dh param file opened but openssl could not use dh param file at: " + dhfile + "; " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cout << error << "\n";
		exit(1);
	}
	if(SSL_CTX_set_tmp_dh(result, dh) != 1)
	{
		std::string error = "dh param file opened and interpreted but reject by context: " + dhfile + "; " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cout << error << "\n";
		exit(1);
	}
	//for ecdhe see SSL_CTX_set_tmp_ecdh
	return result;
}

void setupListeningSocket(int type, struct timeval *timeout, int *fd, struct sockaddr_in *info, int port)
{
	//setup command port to accept new connections
	*fd = socket(AF_INET, type, 0); //tcp socket
	if(*fd < 0)
	{
		std::string error = "cannot establish socket (" + std::to_string(errno) + ") " + std::string(strerror(errno));
		std::cout << error << "\n";
		exit(1);
	}
	memset((char *) info, 0, sizeof(struct sockaddr_in));
	info->sin_family = AF_INET; //ipv4
	info->sin_addr.s_addr = INADDR_ANY; //listen on any nic
	info->sin_port = htons(port);
	if(bind(*fd, (struct sockaddr *)info, sizeof(struct sockaddr_in)) < 0)
	{
		std::string error = "cannot bind socket to a nic (" + std::to_string(errno) + ") " + std::string(strerror(errno));
		std::cout << error << "\n";
		exit(1);
	}

	if(type == SOCK_STREAM)
	{
		if(setsockopt(*fd, SOL_SOCKET, SO_RCVTIMEO, (char*)timeout, sizeof(struct timeval)) < 0)
		{
			std::string error="cannot set tcp socket options (" + std::to_string(errno) + ") " + std::string(strerror(errno));
			std::cout << error << "\n";
			exit(1);
		}
		listen(*fd, MAXLISTENWAIT);
	}
}
<commit_msg>Shop stopper errors should be... errors<commit_after>/*
 * server_init.c
 *
 *  Created on: May 2, 2017
 *      Author: Daniel
 *
 *  Various intialization functions used by the server.
 *  Moved here for readability.
 */
#include "server_init.hpp"

void readServerConfig(int &cmdPort, int &mediaPort, std::string &publicKeyFile, std::string &privateKeyFile, std::string &ciphers, std::string &dhfile, Logger *logger)
{
	std::ifstream conffile(CONFFILE());
	std::string line;
	bool gotPublicKey = false, gotPrivateKey = false, gotCiphers = false, gotCmdPort = false, gotMediaPort = false, gotDhFile = false;

	while(getline(conffile, line))
	{
		//skip blank lines and comment lines
		if(line.length() == 0 || line.at(0) == '#')
		{
			continue;
		}

		//read the variable and its value
		std::string var, value;
		std::stringstream ss(line);
		std::getline(ss, var, '=');
		std::getline(ss, value, '=');

		//cleanup the surrounding whitespace and strip the end of line comment
		var = Utils::trim(var);
		value = Utils::trim(value);

		//if there is no value then go on to the next line
		if(value == "")
		{
			continue;
		}

		if(var == "command")
		{
			cmdPort = atoi(value.c_str());
			gotCmdPort = true;
			continue;
		}
		else if (var == "media")
		{
			mediaPort = atoi(value.c_str());
			gotMediaPort = true;
			continue;
		}
		else if (var == "public")
		{
			publicKeyFile = value;
			gotPublicKey = true;
			continue;
		}
		else if (var == "private")
		{
			privateKeyFile = value;
			gotPrivateKey = true;
			continue;
		}
		else if (var == "ciphers")
		{
			ciphers = value;
			gotCiphers = true;
			continue;
		}
		else if (var == "dhfile")
		{
			dhfile = value;
			gotDhFile = true;
			continue;
		}
		else
		{
			std::string unknown = "unknown variable parsed: " + line;
			logger->insertLog(Log(Log::TAG::STARTUP, unknown, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
		}
	}

	//at the minimum a public and private key must be specified. everything else has a default value
	if (!gotPublicKey || !gotPrivateKey || !gotDhFile)
	{
		if(!gotPublicKey)
		{
			std::string error = "Your did not specify a PUBLIC key pem in: " + CONFFILE() + "\n";
			std::cerr << error << "\n";
		}
		if(!gotPublicKey)
		{
			std::string error = "Your did not specify a PRIVATE key pem in: " + CONFFILE() + "\n";
			std::cerr << error << "\n";
		}
		if(!gotDhFile)
		{
			std::string error = "Your did not specify a DH file for DHE ciphers in: " + CONFFILE() + "\n";
			std::cerr << error << "\n";
		}
		exit(1);
	}

	//warn of default values if they're being used
	if(!gotCmdPort)
	{
		std::string message =  "Using default command port of: " + std::to_string(cmdPort);
		logger->insertLog(Log(Log::TAG::STARTUP, message, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
	}
	if(!gotMediaPort)
	{
		std::string message= "Using default media port of: " + std::to_string(mediaPort);
		logger->insertLog(Log(Log::TAG::STARTUP, message, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
	}
	if(!gotCiphers)
	{
		std::string message = "Using default ciphers (no ECDHE): " + ciphers;
		logger->insertLog(Log(Log::TAG::STARTUP, message, Log::SELF(), Log::TYPE::SYSTEM, Log::SELFIP()));
	}

}

SSL_CTX* setupOpenSSL(std::string const &ciphers, std::string const &privateKeyFile, std::string const &publicKeyFile, std::string const &dhfile)
{
	//openssl setup
	SSL_load_error_strings();
	SSL_library_init();
	OpenSSL_add_all_algorithms();

#if OPENSSL_VERSION_NUMBER >= 0x10100000 //openssl 1.1 requires the "flexible" tls_method
	SSL_CTX *result = SSL_CTX_new(TLS_method());
	SSL_CTX_set_min_proto_version(result, TLS1_2_VERSION); //force the "flexible" method's hand for only 1.2
#else
	SSL_CTX *result = SSL_CTX_new(TLSv1_2_server_method());
#endif

	//set ssl properties
	if(result == NULL)
	{
		std::string error = "ssl initialization problem " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cerr << error << "\n";
		exit(1);
	}

	//ciphers
	SSL_CTX_set_cipher_list(result, ciphers.c_str());

	//private key
	if(SSL_CTX_use_PrivateKey_file(result, privateKeyFile.c_str(), SSL_FILETYPE_PEM) <= 0)
	{
		std::string error = "problems with the private key " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cerr << error << "\n";
		exit(1);
	}

	//public key
	if(SSL_CTX_use_certificate_file(result, publicKeyFile.c_str(), SSL_FILETYPE_PEM) <= 0)
	{
		std::string error = "problems with the public key" + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cerr << error << "\n";
		exit(1);
	}

	//dh params to make dhe ciphers work
	//https://www.openssl.org/docs/man1.0.1/ssl/SSL_CTX_set_tmp_dh.html
	DH *dh = NULL;
	FILE *paramfile;
	paramfile = fopen(dhfile.c_str(), "r");
	if(!paramfile)
	{
		std::string error = "problems opening dh param file at: " +  dhfile + " (" + std::to_string(errno) + ") " + std::string(strerror(errno));
		std::cerr << error << "\n";
		exit(1);
	}
	dh = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
	fclose(paramfile);
	if(dh == NULL)
	{
		std::string error = "dh param file opened but openssl could not use dh param file at: " + dhfile + "; " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cerr << error << "\n";
		exit(1);
	}
	if(SSL_CTX_set_tmp_dh(result, dh) != 1)
	{
		std::string error = "dh param file opened and interpreted but reject by context: " + dhfile + "; " + std::string(ERR_error_string(ERR_get_error(), NULL));
		std::cerr << error << "\n";
		exit(1);
	}
	//for ecdhe see SSL_CTX_set_tmp_ecdh
	return result;
}

void setupListeningSocket(int type, struct timeval *timeout, int *fd, struct sockaddr_in *info, int port)
{
	//setup command port to accept new connections
	*fd = socket(AF_INET, type, 0); //tcp socket
	if(*fd < 0)
	{
		std::string error = "cannot establish socket (" + std::to_string(errno) + ") " + std::string(strerror(errno));
		std::cerr << error << "\n";
		exit(1);
	}
	memset((char *) info, 0, sizeof(struct sockaddr_in));
	info->sin_family = AF_INET; //ipv4
	info->sin_addr.s_addr = INADDR_ANY; //listen on any nic
	info->sin_port = htons(port);
	if(bind(*fd, (struct sockaddr *)info, sizeof(struct sockaddr_in)) < 0)
	{
		std::string error = "cannot bind socket to a nic (" + std::to_string(errno) + ") " + std::string(strerror(errno));
		std::cerr << error << "\n";
		exit(1);
	}

	if(type == SOCK_STREAM)
	{
		if(setsockopt(*fd, SOL_SOCKET, SO_RCVTIMEO, (char*)timeout, sizeof(struct timeval)) < 0)
		{
			std::string error="cannot set tcp socket options (" + std::to_string(errno) + ") " + std::string(strerror(errno));
			std::cerr << error << "\n";
			exit(1);
		}
		listen(*fd, MAXLISTENWAIT);
	}
}
<|endoftext|>


<commit_before>#include <atomic>
#include <thread>
#include <cassert>
namespace example_01 {  // acquire-release and relaxed orederings

std::atomic<int> data[5];
std::atomic<bool> sync1{ false }, sync2{ false };

void thread_1() {
    data[0].store(42, std::memory_order_relaxed);
    data[1].store(97, std::memory_order_relaxed);
    data[2].store(17, std::memory_order_relaxed);
    data[3].store(-141, std::memory_order_relaxed);
    data[4].store(2003, std::memory_order_relaxed);
    sync1.store(true, std::memory_order_release);
}

void thread_2() {
    while (not sync1.load(std::memory_order_acquire));
    sync2.store(true, std::memory_order_release);
}

void thread_3() {
    while (not sync2.load(std::memory_order_acquire));
    assert(42 == data[0].load(std::memory_order_relaxed));
    assert(97 == data[1].load(std::memory_order_relaxed));
    assert(17 == data[2].load(std::memory_order_relaxed));
    assert(-141 == data[3].load(std::memory_order_relaxed));
    assert(2003 == data[4].load(std::memory_order_relaxed));
}

void run() {
    std::thread t1{ thread_1 }, t2{ thread_2 }, t3{ thread_3 };
    t1.join(); t2.join(); t3.join();
}

} // example_01

#include <iostream>
int main() {
    std::cout << "example_01 => [OK]"; example_01::run(); std::cout << std::endl << std::endl;

    return 0;
}
<commit_msg>[a_williams-cpp_concurrency_in_action-2_ed][5] change the 12-th example<commit_after>#include <atomic>
#include <thread>
#include <cassert>
namespace example_01 { // transitive sync with acquire-release ordering

std::atomic<int> data[5];
std::atomic<bool> sync1{ false }, sync2{ false };

void thread_1() {
    data[0].store(42, std::memory_order_relaxed);
    data[1].store(97, std::memory_order_relaxed);
    data[2].store(17, std::memory_order_relaxed);
    data[3].store(-141, std::memory_order_relaxed);
    data[4].store(2003, std::memory_order_relaxed);
    sync1.store(true, std::memory_order_release);
}

void thread_2() {
    while (not sync1.load(std::memory_order_acquire));
    sync2.store(true, std::memory_order_release);
}

void thread_3() {
    while (not sync2.load(std::memory_order_acquire));
    assert(42 == data[0].load(std::memory_order_relaxed));
    assert(97 == data[1].load(std::memory_order_relaxed));
    assert(17 == data[2].load(std::memory_order_relaxed));
    assert(-141 == data[3].load(std::memory_order_relaxed));
    assert(2003 == data[4].load(std::memory_order_relaxed));
}

void run() {
    std::thread t1{ thread_1 }, t2{ thread_2 }, t3{ thread_3 };
    t1.join(), t2.join(), t3.join();
}
} // example_01

#include <iostream>
int main() {
    std::cout << "[ok] - example_01" << std::endl; example_01::run(); std::cout << std::endl;

    return 0;
}
<|endoftext|>