<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "evr9videowindowcontrol.h"
#include <QtWidgets/qwidget.h>
#include <QtCore/qdebug.h>
#include <QtCore/qglobal.h>

Evr9VideoWindowControl::Evr9VideoWindowControl(QObject *parent)
    : QVideoWindowControl(parent)
    , m_windowId(0)
    , m_dirtyValues(0)
    , m_aspectRatioMode(Qt::KeepAspectRatio)
    , m_brightness(0)
    , m_contrast(0)
    , m_hue(0)
    , m_saturation(0)
    , m_fullScreen(false)
    , m_currentActivate(0)
    , m_evrSink(0)
    , m_displayControl(0)
{
    if (FAILED(MFCreateVideoRendererActivate(0, &m_currentActivate))) {
        qWarning() << "Failed to create evr video renderer activate!";
        return;
    }
    if (FAILED(m_currentActivate->ActivateObject(IID_IMFMediaSink, (LPVOID*)(&m_evrSink)))) {
        qWarning() << "Failed to activate evr media sink!";
        return;
    }
    if (FAILED(MFGetService(m_evrSink, MR_VIDEO_RENDER_SERVICE, IID_PPV_ARGS(&m_displayControl)))) {
        qWarning() << "Failed to get display control from evr media sink!";
        return;
    }
    if (FAILED(MFGetService(m_evrSink,  MR_VIDEO_MIXER_SERVICE, IID_PPV_ARGS(&m_processor)))) {
        qWarning() << "Failed to get video processor from evr media sink!";
        return;
    }
}

Evr9VideoWindowControl::~Evr9VideoWindowControl()
{
    if (m_processor)
        m_processor->Release();
    if (m_displayControl)
        m_displayControl->Release();
    if (m_evrSink)
        m_evrSink->Release();
    if (m_currentActivate) {
        m_currentActivate->ShutdownObject();
        m_currentActivate->Release();
    }
}

WId Evr9VideoWindowControl::winId() const
{
    return m_windowId;
}

void Evr9VideoWindowControl::setWinId(WId id)
{
    m_windowId = id;

    if (QWidget *widget = QWidget::find(m_windowId)) {
        const QColor color = widget->palette().color(QPalette::Window);

        m_windowColor = RGB(color.red(), color.green(), color.blue());
    }

    if (m_displayControl) {
        m_displayControl->SetVideoWindow(HWND(m_windowId));
    }
}

QRect Evr9VideoWindowControl::displayRect() const
{
    return m_displayRect;
}

void Evr9VideoWindowControl::setDisplayRect(const QRect &rect)
{
    m_displayRect = rect;

    if (m_displayControl) {
        RECT displayRect = { rect.left(), rect.top(), rect.right() + 1, rect.bottom() + 1 };
        QSize sourceSize = nativeSize();

        RECT sourceRect = { 0, 0, sourceSize.width(), sourceSize.height() };

        if (m_aspectRatioMode == Qt::KeepAspectRatioByExpanding) {
            QSize clippedSize = rect.size();
            clippedSize.scale(sourceRect.right, sourceRect.bottom, Qt::KeepAspectRatio);

            sourceRect.left = (sourceRect.right - clippedSize.width()) / 2;
            sourceRect.top = (sourceRect.bottom - clippedSize.height()) / 2;
            sourceRect.right = sourceRect.left + clippedSize.width();
            sourceRect.bottom = sourceRect.top + clippedSize.height();
        }

        if (sourceSize.width() > 0 && sourceSize.height() > 0) {
            MFVideoNormalizedRect sourceNormRect;
            sourceNormRect.left = float(sourceRect.left) / float(sourceRect.right);
            sourceNormRect.top = float(sourceRect.top) / float(sourceRect.bottom);
            sourceNormRect.right = float(sourceRect.right) / float(sourceRect.right);
            sourceNormRect.bottom = float(sourceRect.bottom) / float(sourceRect.bottom);
            m_displayControl->SetVideoPosition(&sourceNormRect, &displayRect);
        } else {
            m_displayControl->SetVideoPosition(NULL, &displayRect);
        }
    }
}

bool Evr9VideoWindowControl::isFullScreen() const
{
    return m_fullScreen;
}

void Evr9VideoWindowControl::setFullScreen(bool fullScreen)
{
    if (m_fullScreen == fullScreen)
        return;
    emit fullScreenChanged(m_fullScreen = fullScreen);
}

void Evr9VideoWindowControl::repaint()
{
    QSize size = nativeSize();
    if (size.width() > 0 && size.height() > 0
        && m_displayControl
        && SUCCEEDED(m_displayControl->RepaintVideo())) {
        return;
    }

    PAINTSTRUCT paint;
    if (HDC dc = ::BeginPaint(HWND(m_windowId), &paint)) {
        HPEN pen = ::CreatePen(PS_SOLID, 1, m_windowColor);
        HBRUSH brush = ::CreateSolidBrush(m_windowColor);
        ::SelectObject(dc, pen);
        ::SelectObject(dc, brush);

        ::Rectangle(
                dc,
                m_displayRect.left(),
                m_displayRect.top(),
                m_displayRect.right() + 1,
                m_displayRect.bottom() + 1);

        ::DeleteObject(pen);
        ::DeleteObject(brush);
        ::EndPaint(HWND(m_windowId), &paint);
    }
}

QSize Evr9VideoWindowControl::nativeSize() const
{
    QSize size;
    if (m_displayControl) {
        SIZE sourceSize;
        if (SUCCEEDED(m_displayControl->GetNativeVideoSize(&sourceSize, 0)))
            size = QSize(sourceSize.cx, sourceSize.cy);
    }
    return size;
}

Qt::AspectRatioMode Evr9VideoWindowControl::aspectRatioMode() const
{
    return m_aspectRatioMode;
}

void Evr9VideoWindowControl::setAspectRatioMode(Qt::AspectRatioMode mode)
{
    m_aspectRatioMode = mode;

    if (m_displayControl) {
        switch (mode) {
        case Qt::IgnoreAspectRatio:
            //comment from MSDN: Do not maintain the aspect ratio of the video. Stretch the video to fit the output rectangle.
            m_displayControl->SetAspectRatioMode(MFVideoARMode_None);
            break;
        case Qt::KeepAspectRatio:
            //comment from MSDN: Preserve the aspect ratio of the video by letterboxing or within the output rectangle.
            m_displayControl->SetAspectRatioMode(MFVideoARMode_PreservePicture);
            break;
        case Qt::KeepAspectRatioByExpanding:
            //for this mode, more adjustment will be done in setDisplayRect
            m_displayControl->SetAspectRatioMode(MFVideoARMode_PreservePicture);
            break;
        default:
            break;
        }
        setDisplayRect(m_displayRect);
    }
}

int Evr9VideoWindowControl::brightness() const
{
    return m_brightness;
}

void Evr9VideoWindowControl::setBrightness(int brightness)
{
    if (m_brightness == brightness)
        return;

    m_brightness = brightness;

    m_dirtyValues |= DXVA2_ProcAmp_Brightness;

    setProcAmpValues();

    emit brightnessChanged(brightness);
}

int Evr9VideoWindowControl::contrast() const
{
    return m_contrast;
}

void Evr9VideoWindowControl::setContrast(int contrast)
{
    if (m_contrast == contrast)
        return;

    m_contrast = contrast;

    m_dirtyValues |= DXVA2_ProcAmp_Contrast;

    setProcAmpValues();

    emit contrastChanged(contrast);
}

int Evr9VideoWindowControl::hue() const
{
    return m_hue;
}

void Evr9VideoWindowControl::setHue(int hue)
{
    if (m_hue == hue)
        return;

    m_hue = hue;

    m_dirtyValues |= DXVA2_ProcAmp_Hue;

    setProcAmpValues();

    emit hueChanged(hue);
}

int Evr9VideoWindowControl::saturation() const
{
    return m_saturation;
}

void Evr9VideoWindowControl::setSaturation(int saturation)
{
    if (m_saturation == saturation)
        return;

    m_saturation = saturation;

    m_dirtyValues |= DXVA2_ProcAmp_Saturation;

    setProcAmpValues();

    emit saturationChanged(saturation);
}

IMFActivate* Evr9VideoWindowControl::currentActivate() const
{
    return m_currentActivate;
}

void Evr9VideoWindowControl::setProcAmpValues()
{
    if (m_processor) {
        DXVA2_ProcAmpValues values;
        if (m_dirtyValues & DXVA2_ProcAmp_Brightness) {
            values.Brightness = scaleProcAmpValue(DXVA2_ProcAmp_Brightness, m_brightness);
        }
        if (m_dirtyValues & DXVA2_ProcAmp_Contrast) {
            values.Contrast = scaleProcAmpValue(DXVA2_ProcAmp_Contrast, m_contrast);
        }
        if (m_dirtyValues & DXVA2_ProcAmp_Hue) {
            values.Hue = scaleProcAmpValue(DXVA2_ProcAmp_Hue, m_hue);
        }
        if (m_dirtyValues & DXVA2_ProcAmp_Saturation) {
            values.Saturation = scaleProcAmpValue(DXVA2_ProcAmp_Saturation, m_saturation);
        }

        if (SUCCEEDED(m_processor->SetProcAmpValues(0, &values))) {
            m_dirtyValues = 0;
        }
    }
}

DXVA2_Fixed32 Evr9VideoWindowControl::scaleProcAmpValue(DWORD prop, int value) const
{
    float scaledValue = 0.0;

    DXVA2_ValueRange  range;
    if (SUCCEEDED(m_processor->GetProcAmpRange(prop, &range))) {
        scaledValue = DXVA2FixedToFloat(range.DefaultValue);
        if (value > 0)
            scaledValue += float(value) * (DXVA2FixedToFloat(range.MaxValue) - DXVA2FixedToFloat(range.DefaultValue)) / 100;
        else if (value < 0)
            scaledValue -= float(value) * (DXVA2FixedToFloat(range.MinValue) - DXVA2FixedToFloat(range.DefaultValue)) / 100;
    }

    return DXVA2FloatToFixed(scaledValue);
}
<commit_msg>WMF: Fixed color adjustment when using the EVR window control.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "evr9videowindowcontrol.h"
#include <QtWidgets/qwidget.h>
#include <QtCore/qdebug.h>
#include <QtCore/qglobal.h>

Evr9VideoWindowControl::Evr9VideoWindowControl(QObject *parent)
    : QVideoWindowControl(parent)
    , m_windowId(0)
    , m_dirtyValues(0)
    , m_aspectRatioMode(Qt::KeepAspectRatio)
    , m_brightness(0)
    , m_contrast(0)
    , m_hue(0)
    , m_saturation(0)
    , m_fullScreen(false)
    , m_currentActivate(0)
    , m_evrSink(0)
    , m_displayControl(0)
{
    if (FAILED(MFCreateVideoRendererActivate(0, &m_currentActivate))) {
        qWarning() << "Failed to create evr video renderer activate!";
        return;
    }
    if (FAILED(m_currentActivate->ActivateObject(IID_IMFMediaSink, (LPVOID*)(&m_evrSink)))) {
        qWarning() << "Failed to activate evr media sink!";
        return;
    }
    if (FAILED(MFGetService(m_evrSink, MR_VIDEO_RENDER_SERVICE, IID_PPV_ARGS(&m_displayControl)))) {
        qWarning() << "Failed to get display control from evr media sink!";
        return;
    }
    if (FAILED(MFGetService(m_evrSink,  MR_VIDEO_MIXER_SERVICE, IID_PPV_ARGS(&m_processor)))) {
        qWarning() << "Failed to get video processor from evr media sink!";
        return;
    }
}

Evr9VideoWindowControl::~Evr9VideoWindowControl()
{
    if (m_processor)
        m_processor->Release();
    if (m_displayControl)
        m_displayControl->Release();
    if (m_evrSink)
        m_evrSink->Release();
    if (m_currentActivate) {
        m_currentActivate->ShutdownObject();
        m_currentActivate->Release();
    }
}

WId Evr9VideoWindowControl::winId() const
{
    return m_windowId;
}

void Evr9VideoWindowControl::setWinId(WId id)
{
    m_windowId = id;

    if (QWidget *widget = QWidget::find(m_windowId)) {
        const QColor color = widget->palette().color(QPalette::Window);

        m_windowColor = RGB(color.red(), color.green(), color.blue());
    }

    if (m_displayControl) {
        m_displayControl->SetVideoWindow(HWND(m_windowId));
    }
}

QRect Evr9VideoWindowControl::displayRect() const
{
    return m_displayRect;
}

void Evr9VideoWindowControl::setDisplayRect(const QRect &rect)
{
    m_displayRect = rect;

    if (m_displayControl) {
        RECT displayRect = { rect.left(), rect.top(), rect.right() + 1, rect.bottom() + 1 };
        QSize sourceSize = nativeSize();

        RECT sourceRect = { 0, 0, sourceSize.width(), sourceSize.height() };

        if (m_aspectRatioMode == Qt::KeepAspectRatioByExpanding) {
            QSize clippedSize = rect.size();
            clippedSize.scale(sourceRect.right, sourceRect.bottom, Qt::KeepAspectRatio);

            sourceRect.left = (sourceRect.right - clippedSize.width()) / 2;
            sourceRect.top = (sourceRect.bottom - clippedSize.height()) / 2;
            sourceRect.right = sourceRect.left + clippedSize.width();
            sourceRect.bottom = sourceRect.top + clippedSize.height();
        }

        if (sourceSize.width() > 0 && sourceSize.height() > 0) {
            MFVideoNormalizedRect sourceNormRect;
            sourceNormRect.left = float(sourceRect.left) / float(sourceRect.right);
            sourceNormRect.top = float(sourceRect.top) / float(sourceRect.bottom);
            sourceNormRect.right = float(sourceRect.right) / float(sourceRect.right);
            sourceNormRect.bottom = float(sourceRect.bottom) / float(sourceRect.bottom);
            m_displayControl->SetVideoPosition(&sourceNormRect, &displayRect);
        } else {
            m_displayControl->SetVideoPosition(NULL, &displayRect);
        }
    }
}

bool Evr9VideoWindowControl::isFullScreen() const
{
    return m_fullScreen;
}

void Evr9VideoWindowControl::setFullScreen(bool fullScreen)
{
    if (m_fullScreen == fullScreen)
        return;
    emit fullScreenChanged(m_fullScreen = fullScreen);
}

void Evr9VideoWindowControl::repaint()
{
    QSize size = nativeSize();
    if (size.width() > 0 && size.height() > 0
        && m_displayControl
        && SUCCEEDED(m_displayControl->RepaintVideo())) {
        return;
    }

    PAINTSTRUCT paint;
    if (HDC dc = ::BeginPaint(HWND(m_windowId), &paint)) {
        HPEN pen = ::CreatePen(PS_SOLID, 1, m_windowColor);
        HBRUSH brush = ::CreateSolidBrush(m_windowColor);
        ::SelectObject(dc, pen);
        ::SelectObject(dc, brush);

        ::Rectangle(
                dc,
                m_displayRect.left(),
                m_displayRect.top(),
                m_displayRect.right() + 1,
                m_displayRect.bottom() + 1);

        ::DeleteObject(pen);
        ::DeleteObject(brush);
        ::EndPaint(HWND(m_windowId), &paint);
    }
}

QSize Evr9VideoWindowControl::nativeSize() const
{
    QSize size;
    if (m_displayControl) {
        SIZE sourceSize;
        if (SUCCEEDED(m_displayControl->GetNativeVideoSize(&sourceSize, 0)))
            size = QSize(sourceSize.cx, sourceSize.cy);
    }
    return size;
}

Qt::AspectRatioMode Evr9VideoWindowControl::aspectRatioMode() const
{
    return m_aspectRatioMode;
}

void Evr9VideoWindowControl::setAspectRatioMode(Qt::AspectRatioMode mode)
{
    m_aspectRatioMode = mode;

    if (m_displayControl) {
        switch (mode) {
        case Qt::IgnoreAspectRatio:
            //comment from MSDN: Do not maintain the aspect ratio of the video. Stretch the video to fit the output rectangle.
            m_displayControl->SetAspectRatioMode(MFVideoARMode_None);
            break;
        case Qt::KeepAspectRatio:
            //comment from MSDN: Preserve the aspect ratio of the video by letterboxing or within the output rectangle.
            m_displayControl->SetAspectRatioMode(MFVideoARMode_PreservePicture);
            break;
        case Qt::KeepAspectRatioByExpanding:
            //for this mode, more adjustment will be done in setDisplayRect
            m_displayControl->SetAspectRatioMode(MFVideoARMode_PreservePicture);
            break;
        default:
            break;
        }
        setDisplayRect(m_displayRect);
    }
}

int Evr9VideoWindowControl::brightness() const
{
    return m_brightness;
}

void Evr9VideoWindowControl::setBrightness(int brightness)
{
    if (m_brightness == brightness)
        return;

    m_brightness = brightness;

    m_dirtyValues |= DXVA2_ProcAmp_Brightness;

    setProcAmpValues();

    emit brightnessChanged(brightness);
}

int Evr9VideoWindowControl::contrast() const
{
    return m_contrast;
}

void Evr9VideoWindowControl::setContrast(int contrast)
{
    if (m_contrast == contrast)
        return;

    m_contrast = contrast;

    m_dirtyValues |= DXVA2_ProcAmp_Contrast;

    setProcAmpValues();

    emit contrastChanged(contrast);
}

int Evr9VideoWindowControl::hue() const
{
    return m_hue;
}

void Evr9VideoWindowControl::setHue(int hue)
{
    if (m_hue == hue)
        return;

    m_hue = hue;

    m_dirtyValues |= DXVA2_ProcAmp_Hue;

    setProcAmpValues();

    emit hueChanged(hue);
}

int Evr9VideoWindowControl::saturation() const
{
    return m_saturation;
}

void Evr9VideoWindowControl::setSaturation(int saturation)
{
    if (m_saturation == saturation)
        return;

    m_saturation = saturation;

    m_dirtyValues |= DXVA2_ProcAmp_Saturation;

    setProcAmpValues();

    emit saturationChanged(saturation);
}

IMFActivate* Evr9VideoWindowControl::currentActivate() const
{
    return m_currentActivate;
}

void Evr9VideoWindowControl::setProcAmpValues()
{
    if (m_processor) {
        DXVA2_ProcAmpValues values;
        if (m_dirtyValues & DXVA2_ProcAmp_Brightness) {
            values.Brightness = scaleProcAmpValue(DXVA2_ProcAmp_Brightness, m_brightness);
        }
        if (m_dirtyValues & DXVA2_ProcAmp_Contrast) {
            values.Contrast = scaleProcAmpValue(DXVA2_ProcAmp_Contrast, m_contrast);
        }
        if (m_dirtyValues & DXVA2_ProcAmp_Hue) {
            values.Hue = scaleProcAmpValue(DXVA2_ProcAmp_Hue, m_hue);
        }
        if (m_dirtyValues & DXVA2_ProcAmp_Saturation) {
            values.Saturation = scaleProcAmpValue(DXVA2_ProcAmp_Saturation, m_saturation);
        }

        if (SUCCEEDED(m_processor->SetProcAmpValues(m_dirtyValues, &values))) {
            m_dirtyValues = 0;
        }
    }
}

DXVA2_Fixed32 Evr9VideoWindowControl::scaleProcAmpValue(DWORD prop, int value) const
{
    float scaledValue = 0.0;

    DXVA2_ValueRange  range;
    if (SUCCEEDED(m_processor->GetProcAmpRange(prop, &range))) {
        scaledValue = DXVA2FixedToFloat(range.DefaultValue);
        if (value > 0)
            scaledValue += float(value) * (DXVA2FixedToFloat(range.MaxValue) - DXVA2FixedToFloat(range.DefaultValue)) / 100;
        else if (value < 0)
            scaledValue -= float(value) * (DXVA2FixedToFloat(range.MinValue) - DXVA2FixedToFloat(range.DefaultValue)) / 100;
    }

    return DXVA2FloatToFixed(scaledValue);
}
<|endoftext|>


<commit_before>//
// C++ Implementation: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//

/* Loads all builtin functions */

/* Loads a builtin function */
#include "BuiltinFuncs.hpp"
#include <string>
#include <iostream>
#include "fatal.h"

std::map<std::string, Func*> BuiltinFuncs::builtin_func_tree;

int BuiltinFuncs::load_builtin_func(const std::string & name, float (*func_ptr)(float*), int num_args) {

  Func * func;
  int retval;

  /* Create new function */
  func = new Func(name, func_ptr, num_args);

  if (func == 0)
    return PROJECTM_OUTOFMEM_ERROR;

  retval = insert_func( func );

  return retval;

}

Func * BuiltinFuncs::find_func(const std::string & name) {

  std::map<std::string, Func*>::iterator pos = builtin_func_tree.find(name);

  // Case: function not found, return null
  if (pos == builtin_func_tree.end())
	return 0;

  // Case: function found, return a pointer to it
  return pos->second;

}

int BuiltinFuncs::load_all_builtin_func() {

  if (load_builtin_func("int", FuncWrappers::int_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("abs", FuncWrappers::abs_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sin", FuncWrappers::sin_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("cos", FuncWrappers::cos_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("tan", FuncWrappers::tan_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("asin", FuncWrappers::asin_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("acos", FuncWrappers::acos_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("atan", FuncWrappers::atan_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sqr", FuncWrappers::sqr_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sqrt", FuncWrappers::sqrt_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("pow", FuncWrappers::pow_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("exp", FuncWrappers::exp_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("log", FuncWrappers::log_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("log10", FuncWrappers::log10_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sign", FuncWrappers::sign_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("min", FuncWrappers::min_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("max", FuncWrappers::max_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sigmoid", FuncWrappers::sigmoid_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("atan2", FuncWrappers::atan2_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("rand", FuncWrappers::rand_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("band", FuncWrappers::band_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("bor", FuncWrappers::bor_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("bnot", FuncWrappers::bnot_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("if", FuncWrappers::if_wrapper, 3) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("equal", FuncWrappers::equal_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("above", FuncWrappers::above_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("below", FuncWrappers::below_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("nchoosek", FuncWrappers::nchoosek_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("fact", FuncWrappers::fact_wrapper, 1) < 0)
    return PROJECTM_ERROR;

  return PROJECTM_SUCCESS;
}

volatile bool BuiltinFuncs::initialized = false;

/* Initialize the builtin function database.
   Should only be necessary once */
int BuiltinFuncs::init_builtin_func_db() {
  int retval;

  if (initialized) {
    return 0;
  } else
    initialized = true;

  retval = load_all_builtin_func();
  return retval;
}

/* Destroy the builtin function database.
   Generally, do this on projectm exit */
int BuiltinFuncs::destroy_builtin_func_db() {

traverse<TraverseFunctors::Delete<Func> >(builtin_func_tree);

builtin_func_tree.clear();
initialized = false;
return PROJECTM_SUCCESS;
}

/* Insert a function into the database */
int BuiltinFuncs::insert_func( Func *func ) {

  assert(func);
  if (func == 0) {
      std::cerr << "Received a null function object, ignoring...." << std::endl;
      return PROJECTM_ERROR;
  }

  std::cout << "inserting function " << func->getName() << std::endl;

  const std::pair<std::string, Func*> pair = std::make_pair(std::string(func->getName()), func);

  assert(pair.second);

  const std::pair<std::map<std::string, Func*>::iterator, bool> inserteePair =
  	builtin_func_tree.insert(pair);

  if (!inserteePair.second) {
	std::cerr << "Failed to insert builtin function \"" << func->getName() << "\" into collection! Bailing..." << std::endl;
	abort();

  }

  return PROJECTM_SUCCESS;
}

<commit_msg>removed debugging<commit_after>//
// C++ Implementation: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//

/* Loads all builtin functions */

/* Loads a builtin function */
#include "BuiltinFuncs.hpp"
#include <string>
#include <iostream>
#include "fatal.h"

std::map<std::string, Func*> BuiltinFuncs::builtin_func_tree;

int BuiltinFuncs::load_builtin_func(const std::string & name, float (*func_ptr)(float*), int num_args) {

  Func * func;
  int retval;

  /* Create new function */
  func = new Func(name, func_ptr, num_args);

  if (func == 0)
    return PROJECTM_OUTOFMEM_ERROR;

  retval = insert_func( func );

  return retval;

}

Func * BuiltinFuncs::find_func(const std::string & name) {

  std::map<std::string, Func*>::iterator pos = builtin_func_tree.find(name);

  // Case: function not found, return null
  if (pos == builtin_func_tree.end())
	return 0;

  // Case: function found, return a pointer to it
  return pos->second;

}

int BuiltinFuncs::load_all_builtin_func() {

  if (load_builtin_func("int", FuncWrappers::int_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("abs", FuncWrappers::abs_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sin", FuncWrappers::sin_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("cos", FuncWrappers::cos_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("tan", FuncWrappers::tan_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("asin", FuncWrappers::asin_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("acos", FuncWrappers::acos_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("atan", FuncWrappers::atan_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sqr", FuncWrappers::sqr_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sqrt", FuncWrappers::sqrt_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("pow", FuncWrappers::pow_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("exp", FuncWrappers::exp_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("log", FuncWrappers::log_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("log10", FuncWrappers::log10_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sign", FuncWrappers::sign_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("min", FuncWrappers::min_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("max", FuncWrappers::max_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("sigmoid", FuncWrappers::sigmoid_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("atan2", FuncWrappers::atan2_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("rand", FuncWrappers::rand_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("band", FuncWrappers::band_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("bor", FuncWrappers::bor_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("bnot", FuncWrappers::bnot_wrapper, 1) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("if", FuncWrappers::if_wrapper, 3) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("equal", FuncWrappers::equal_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("above", FuncWrappers::above_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("below", FuncWrappers::below_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("nchoosek", FuncWrappers::nchoosek_wrapper, 2) < 0)
    return PROJECTM_ERROR;
  if (load_builtin_func("fact", FuncWrappers::fact_wrapper, 1) < 0)
    return PROJECTM_ERROR;

  return PROJECTM_SUCCESS;
}

volatile bool BuiltinFuncs::initialized = false;

/* Initialize the builtin function database.
   Should only be necessary once */
int BuiltinFuncs::init_builtin_func_db() {
  int retval;

  if (initialized) {
    return 0;
  } else
    initialized = true;

  retval = load_all_builtin_func();
  return retval;
}

/* Destroy the builtin function database.
   Generally, do this on projectm exit */
int BuiltinFuncs::destroy_builtin_func_db() {

traverse<TraverseFunctors::Delete<Func> >(builtin_func_tree);

builtin_func_tree.clear();
initialized = false;
return PROJECTM_SUCCESS;
}

/* Insert a function into the database */
int BuiltinFuncs::insert_func( Func *func ) {

  assert(func);

  if (func == 0) {
      std::cerr << "Received a null function object, ignoring...." << std::endl;
      return PROJECTM_ERROR;
  }

//   //std::cout << "inserting function " << func->getName() << std::endl;

  const std::pair<std::string, Func*> pair = std::make_pair(std::string(func->getName()), func);

  assert(pair.second);

  const std::pair<std::map<std::string, Func*>::iterator, bool> inserteePair =
  	builtin_func_tree.insert(pair);

  if (!inserteePair.second) {
	std::cerr << "Failed to insert builtin function \"" << func->getName() << "\" into collection! Bailing..." << std::endl;
	abort();
  }

  return PROJECTM_SUCCESS;
}

<|endoftext|>


<commit_before>#include "NFfunction.hh"

using namespace std;
using namespace NFcore;
using namespace mu;

GlobalFunction::GlobalFunction(string name,
		string funcExpression,
		vector <string> &varRefNames,
		vector <string> &varRefTypes,
		vector <string> &paramNames,
		System *s)
{
	if(varRefNames.size()!=varRefTypes.size()) {
		cerr<<"Trying to create a global function, but your variable reference vectors don't match up in size!"<<endl;
		cerr<<"Quitting!"<<endl;
		exit(1);
	}

	this->name = name;
	this->funcExpression = funcExpression;

	this->n_varRefs=varRefNames.size();
	this->varRefNames = new string[n_varRefs];
	this->varRefTypes = new string[n_varRefs];
	for(unsigned int vr=0; vr<n_varRefs; vr++) {
		this->varRefNames[vr]=varRefNames.at(vr);
		this->varRefTypes[vr]=varRefTypes.at(vr);
	}

	this->n_params=paramNames.size();
	this->paramNames = new string[n_params];
	for(unsigned int i=0; i<n_params; i++) {
		this->paramNames[i]=paramNames.at(i);
	}
	p=0;
}

GlobalFunction::~GlobalFunction()
{
	delete [] varRefNames;
	delete [] varRefTypes;
	delete [] paramNames;
	if(p!=NULL) delete p;
}

void GlobalFunction::prepareForSimulation(System *s)
{
	try {
		p=FuncFactory::create();
		for(unsigned int vr=0; vr<n_varRefs; vr++)
		{
			if(varRefTypes[vr]=="Observable") {
				Observable *obs = s->getObservableByName(varRefNames[vr]);
				if(obs==NULL) {
					cout<<"When creating global function: "<<this->name<<endl<<" could not find the observable: ";
					cout<<varRefNames[vr]<<" of type "<<varRefTypes[vr]<<endl;
					cout<<"Quitting."<<endl;
					exit(1);
				}
				obs->addReferenceToMyself(p);
			} else {
				cout<<"here"<<endl;
				cout<<"Uh oh, an unrecognized argType ("<<varRefTypes[vr]<<") for a function! "<<varRefNames[vr]<<endl;
				cout<<"Try using the type: \"MoleculeObservable\""<<endl;
				cout<<"Quitting because this will give unpredicatable results, or just crash."<<endl;
				exit(1);
			}
		}

		for(unsigned int i=0; i<n_params; i++) {
			p->DefineConst(paramNames[i],s->getParameter(paramNames[i]));
		}
		p->SetExpr(this->funcExpression);

	}
	catch (mu::Parser::exception_type &e)
	{
		cout<<"Error preparing function "<<name<<" in class GlobalFunction!!  This is what happened:"<<endl;
		cout<< "  "<<e.GetMsg() << endl;
		cout<<"Quitting."<<endl;
		exit(1);
	}
}

void GlobalFunction::updateParameters(System *s) {
	//cout<<"Updating parameters for function: "<<name<<endl;
	for(unsigned int i=0; i<n_params; i++) {
		p->DefineConst(paramNames[i],s->getParameter(paramNames[i]));
	}

}

void GlobalFunction::attatchRxn(ReactionClass *r)
{
	//unsigned int n_rxns;
	//ReactionClass *rxns;

}

void GlobalFunction::printDetails()
{
	cout<<"Global Function: '"<< this->name << "()'"<<endl;
	cout<<" ="<<funcExpression<<endl;
	cout<<"   -Variable References:"<<endl;
	for(unsigned int vr=0; vr<n_varRefs; vr++) {
		cout<<"         "<<varRefTypes[vr]<<":  "<<varRefNames[vr]<<" = " << ""<<endl;
	}
	cout<<"   -Constant Parameters:"<<endl;
	for(unsigned int i=0; i<n_params; i++) {
		cout<<"         "<<paramNames[i]<<endl;
	}

//	// Get the map with the variables
//	mu::Parser::varmap_type variables = p->GetVar();
//	cout << (int)variables.size() << " variables."<<endl;
//	mu::Parser::varmap_type::const_iterator item = variables.begin();
//	// Query the variables
//	for (; item!=variables.end(); ++item)
//	{
//	  cout << "  Name: " << item->first << " Address: [0x" << item->second << "]  Value: "<< *(item->second)<<"\n";
//	}

	if(p!=0) {
		// AS-2021
		if (this->fileFunc) {
			cout<<"   Function currently evaluates to: "<<this->fileEval()<<endl;
		} else {
			cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		}
		// cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		// AS-2021
	}
}

// AS-2021
void GlobalFunction::loadParamFile(string filePath)
{
	// cout<<"######## loading file: "<<filePath<<endl;
	// cout<<"######## for function: "<<paramName<<endl;
	// setup our vectors
	vector <double> time;
	vector <double> values;
	// open file for reading
	// TODO: Err out if it doesn't open
	try {
		ifstream file(filePath.c_str());
		// strings for looping over the file
		string line, word, content;
		string a,b;
		// TODO: Err out if the format is wrong
		while (file >> a >> b) {
			// convert a to double
			istringstream aos(a);
			double d;
			aos >> d;
			// add it to time
			time.push_back(d);
			// convert b to double
			istringstream bos(b);
			bos >> d;
			// add it to values
			values.push_back(d);
		}
		// put the vectors into data vector
		this->data.push_back(time);
		this->data.push_back(values);
	} catch (exception const & e) {
		cout<<"Error preparing function "<<name<<" in class GlobalFunction!!"<<endl;
		cout<<"Failed to either open or read the file."<<endl;
		cout<<"Quitting."<<endl;
		exit(1);
	};
	return;
};

void GlobalFunction::addCounterPointer(double *counter){
	this->counter = counter;
}

void GlobalFunction::enableFileDependency(string filePath) {
	// load file
	// TODO: Err out if this fails
	try {
		this->loadParamFile(filePath);
	} catch (exception const & e) {
		cout<<"Error preparing function "<<name<<" in class GlobalFunction!!"<<endl;
		cout<<"Quitting."<<endl;
		exit(1);
	};
	// we just want to keep a record of this
	this->filePath = filePath;
	// this sets it up so that this function knows it's supposed
	// to be pulling values from a file
	this->fileFunc = true;
	// set this up to give max value error once
	this->maxErrRaised = false;
}

double GlobalFunction::fileEval() {
	// TODO: Error checking and reporting
	// initialize index
	int ctrInd = 0;
	// distance from current value
	double cdist;
	// distance from new value to compare to current
	double ndist;
	// counter val
	double ctrVal = (*this->counter);
	// find the index closest in time
	for (int i=0;i<this->data[0].size();i++) {
		// if it's the first value, calculate and move on
		if(i==0) {
			cdist = abs(ctrVal-this->data[0][i]);
		} else {
			// calculate the new distance
			ndist = abs(ctrVal-this->data[0][i]);
			// if the distance is increasing, we are done
			// this relies on the assumption that the original
			// time series is ordered
			if(ndist>cdist) {
				break;
			} else {
				// we are getting closer to the value we want
				// so we keep going
				cdist = ndist;
				ctrInd += 1;
			}
		}
	}
	// index can't be larger than the array size
	// TODO: warn if we get past our given array
	if (ctrInd>=this->data[0].size()) {
		if(!this->maxErrRaised) {
			cerr<<"Warning!! The array provided by the file "<<
					this->filePath<<"doesn't contain data for counter observable"<<
					this->varRefNames[0]<<" with value "<<ctrVal<<
					" using the final value in the array"<<endl;
			this->maxErrRaised = true;
		};
		ctrInd = this->data[0].size()-1;
	}
	// debug stuff
	// cout<<"counter value was: "<<ctrVal<<endl;
	// cout<<"ctr array result was: "<<data[0][ctrInd]<<endl;
	// cout<<"value array result was: "<<data[1][ctrInd]<<endl;
	// return value from the value array
	return this->data[1][ctrInd];
}
// AS-2021

void GlobalFunction::printDetails(System *s)
{
	cout<<"Global Function: '"<< this->name << "()'"<<endl;
	cout<<" ="<<funcExpression<<endl;
	cout<<"   -Variable References:"<<endl;
	for(unsigned int vr=0; vr<n_varRefs; vr++) {
		cout<<"         "<<varRefTypes[vr]<<":  "<<varRefNames[vr]<<" = " << s->getObservableByName(varRefNames[vr])->getCount()<<endl;
	}
	cout<<"   -Constant Parameters:"<<endl;
	for(unsigned int i=0; i<n_params; i++) {
		cout<<"         "<<paramNames[i]<<" = " << s->getParameter(paramNames[i])<<endl;
	}

	if(p!=0) {
		// AS-2021
		if (this->fileFunc) {
			cout<<"   Function relies on file: "<<this->filePath<<endl;
			cout<<"   Function currently evaluates to: "<<this->fileEval()<<endl;
		} else {
			cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		}
		// cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		// AS-2021
	}
}

StateCounter::StateCounter(string name, MoleculeType *mt, string stateName) {
	this->name=name;
	this->mt = mt;
	this->stateIndex = mt->getCompIndexFromName(stateName);
	this->value=0;

	//Make sure this is a state we can count on!
	if(!mt->isIntegerComponent(stateName)) {
		//if it is not an integer component state, we must abort because
		//we can not evaluate the sum of a non integer component
		cerr<<"Trying to create a stateCounter: '"<<name<<"' on the state: '"<<stateName<<"'\n";
		cerr<<"of MoleculeType: '"<<mt->getName()<<"', but the state you have selected cannot\n";
		cerr<<"have integer values, so summations on this state are undefined.  I am quitting."<<endl;
		exit(1);
	}
}
StateCounter::~StateCounter() {
	mt=0;
}

void StateCounter::add(Molecule *m) {
	if(m->getMoleculeType()==mt) {

	//	cout<<"matched moleculeType"<<endl;
		value+=m->getComponentState(stateIndex);
	//	cout<<"found component state: "<<m->getComponentState(stateIndex)<<endl;
	//	cout<<"updating v`alue to: "<< value<<endl;
	}
}
<commit_msg>step function implementation<commit_after>#include "NFfunction.hh"

using namespace std;
using namespace NFcore;
using namespace mu;

GlobalFunction::GlobalFunction(string name,
		string funcExpression,
		vector <string> &varRefNames,
		vector <string> &varRefTypes,
		vector <string> &paramNames,
		System *s)
{
	if(varRefNames.size()!=varRefTypes.size()) {
		cerr<<"Trying to create a global function, but your variable reference vectors don't match up in size!"<<endl;
		cerr<<"Quitting!"<<endl;
		exit(1);
	}

	this->name = name;
	this->funcExpression = funcExpression;

	this->n_varRefs=varRefNames.size();
	this->varRefNames = new string[n_varRefs];
	this->varRefTypes = new string[n_varRefs];
	for(unsigned int vr=0; vr<n_varRefs; vr++) {
		this->varRefNames[vr]=varRefNames.at(vr);
		this->varRefTypes[vr]=varRefTypes.at(vr);
	}

	this->n_params=paramNames.size();
	this->paramNames = new string[n_params];
	for(unsigned int i=0; i<n_params; i++) {
		this->paramNames[i]=paramNames.at(i);
	}
	p=0;
}

GlobalFunction::~GlobalFunction()
{
	delete [] varRefNames;
	delete [] varRefTypes;
	delete [] paramNames;
	if(p!=NULL) delete p;
}

void GlobalFunction::prepareForSimulation(System *s)
{
	try {
		p=FuncFactory::create();
		for(unsigned int vr=0; vr<n_varRefs; vr++)
		{
			if(varRefTypes[vr]=="Observable") {
				Observable *obs = s->getObservableByName(varRefNames[vr]);
				if(obs==NULL) {
					cout<<"When creating global function: "<<this->name<<endl<<" could not find the observable: ";
					cout<<varRefNames[vr]<<" of type "<<varRefTypes[vr]<<endl;
					cout<<"Quitting."<<endl;
					exit(1);
				}
				obs->addReferenceToMyself(p);
			} else {
				cout<<"here"<<endl;
				cout<<"Uh oh, an unrecognized argType ("<<varRefTypes[vr]<<") for a function! "<<varRefNames[vr]<<endl;
				cout<<"Try using the type: \"MoleculeObservable\""<<endl;
				cout<<"Quitting because this will give unpredicatable results, or just crash."<<endl;
				exit(1);
			}
		}

		for(unsigned int i=0; i<n_params; i++) {
			p->DefineConst(paramNames[i],s->getParameter(paramNames[i]));
		}
		p->SetExpr(this->funcExpression);

	}
	catch (mu::Parser::exception_type &e)
	{
		cout<<"Error preparing function "<<name<<" in class GlobalFunction!!  This is what happened:"<<endl;
		cout<< "  "<<e.GetMsg() << endl;
		cout<<"Quitting."<<endl;
		exit(1);
	}
}

void GlobalFunction::updateParameters(System *s) {
	//cout<<"Updating parameters for function: "<<name<<endl;
	for(unsigned int i=0; i<n_params; i++) {
		p->DefineConst(paramNames[i],s->getParameter(paramNames[i]));
	}

}

void GlobalFunction::attatchRxn(ReactionClass *r)
{
	//unsigned int n_rxns;
	//ReactionClass *rxns;

}

void GlobalFunction::printDetails()
{
	cout<<"Global Function: '"<< this->name << "()'"<<endl;
	cout<<" ="<<funcExpression<<endl;
	cout<<"   -Variable References:"<<endl;
	for(unsigned int vr=0; vr<n_varRefs; vr++) {
		cout<<"         "<<varRefTypes[vr]<<":  "<<varRefNames[vr]<<" = " << ""<<endl;
	}
	cout<<"   -Constant Parameters:"<<endl;
	for(unsigned int i=0; i<n_params; i++) {
		cout<<"         "<<paramNames[i]<<endl;
	}

//	// Get the map with the variables
//	mu::Parser::varmap_type variables = p->GetVar();
//	cout << (int)variables.size() << " variables."<<endl;
//	mu::Parser::varmap_type::const_iterator item = variables.begin();
//	// Query the variables
//	for (; item!=variables.end(); ++item)
//	{
//	  cout << "  Name: " << item->first << " Address: [0x" << item->second << "]  Value: "<< *(item->second)<<"\n";
//	}

	if(p!=0) {
		// AS-2021
		if (this->fileFunc) {
			cout<<"   Function currently evaluates to: "<<this->fileEval()<<endl;
		} else {
			cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		}
		// cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		// AS-2021
	}
}

// AS-2021
void GlobalFunction::loadParamFile(string filePath)
{
	// cout<<"######## loading file: "<<filePath<<endl;
	// cout<<"######## for function: "<<paramName<<endl;
	// setup our vectors
	vector <double> time;
	vector <double> values;
	// open file for reading
	// TODO: Err out if it doesn't open
	try {
		ifstream file(filePath.c_str());
		// strings for looping over the file
		string line, word, content;
		string a,b;
		// TODO: Err out if the format is wrong
		while (file >> a >> b) {
			// convert a to double
			istringstream aos(a);
			double d;
			aos >> d;
			// add it to time
			time.push_back(d);
			// convert b to double
			istringstream bos(b);
			bos >> d;
			// add it to values
			values.push_back(d);
		}
		// put the vectors into data vector
		this->data.push_back(time);
		this->data.push_back(values);
	} catch (exception const & e) {
		cout<<"Error preparing function "<<name<<" in class GlobalFunction!!"<<endl;
		cout<<"Failed to either open or read the file."<<endl;
		cout<<"Quitting."<<endl;
		exit(1);
	};
	return;
};

void GlobalFunction::addCounterPointer(double *counter){
	this->counter = counter;
}

void GlobalFunction::enableFileDependency(string filePath) {
	// load file
	// TODO: Err out if this fails
	try {
		this->loadParamFile(filePath);
	} catch (exception const & e) {
		cout<<"Error preparing function "<<name<<" in class GlobalFunction!!"<<endl;
		cout<<"Quitting."<<endl;
		exit(1);
	};
	// we just want to keep a record of this
	this->filePath = filePath;
	// this sets it up so that this function knows it's supposed
	// to be pulling values from a file
	this->fileFunc = true;
	// set this up to give max value error once
	this->maxErrRaised = false;
}

double GlobalFunction::fileEval() {
	// TODO: Error checking and reporting
	// initialize index
	int ctrInd = 0;
	// counter val
	double ctrVal = (*this->counter);
	// basic step function implementation
	for (int i=0;i<this->data[0].size();i++) {
		// if it's the first value, calculate and move on
		if(data[0][i]>ctrVal) {
			break;
		} else {
			ctrInd = i;
		}
	}

	// // Closest in time implementation
	// // distance from current value
	// double cdist;
	// // distance from new value to compare to current
	// double ndist;
	// // find the index closest in time
	// for (int i=0;i<this->data[0].size();i++) {
	// 	// if it's the first value, calculate and move on
	// 	if(i==0) {
	// 		cdist = abs(ctrVal-this->data[0][i]);
	// 	} else {
	// 		// calculate the new distance
	// 		ndist = abs(ctrVal-this->data[0][i]);
	// 		// if the distance is increasing, we are done
	// 		// this relies on the assumption that the original
	// 		// time series is ordered
	// 		if(ndist>cdist) {
	// 			break;
	// 		} else {
	// 			// we are getting closer to the value we want
	// 			// so we keep going
	// 			cdist = ndist;
	// 			ctrInd = i;
	// 		}
	// 	}
	// }

	// // debug stuff
	// cout<<"counter value was: "<<ctrVal<<endl;
	// cout<<"ctr array result was: "<<data[0][ctrInd]<<endl;
	// cout<<"value array result was: "<<data[1][ctrInd]<<endl;
	// return value from the value array
	return this->data[1][ctrInd];
}
// AS-2021

void GlobalFunction::printDetails(System *s)
{
	cout<<"Global Function: '"<< this->name << "()'"<<endl;
	cout<<" ="<<funcExpression<<endl;
	cout<<"   -Variable References:"<<endl;
	for(unsigned int vr=0; vr<n_varRefs; vr++) {
		cout<<"         "<<varRefTypes[vr]<<":  "<<varRefNames[vr]<<" = " << s->getObservableByName(varRefNames[vr])->getCount()<<endl;
	}
	cout<<"   -Constant Parameters:"<<endl;
	for(unsigned int i=0; i<n_params; i++) {
		cout<<"         "<<paramNames[i]<<" = " << s->getParameter(paramNames[i])<<endl;
	}

	if(p!=0) {
		// AS-2021
		if (this->fileFunc) {
			cout<<"   Function relies on file: "<<this->filePath<<endl;
			cout<<"   Function currently evaluates to: "<<this->fileEval()<<endl;
		} else {
			cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		}
		// cout<<"   Function currently evaluates to: "<<FuncFactory::Eval(p)<<endl;
		// AS-2021
	}
}

StateCounter::StateCounter(string name, MoleculeType *mt, string stateName) {
	this->name=name;
	this->mt = mt;
	this->stateIndex = mt->getCompIndexFromName(stateName);
	this->value=0;

	//Make sure this is a state we can count on!
	if(!mt->isIntegerComponent(stateName)) {
		//if it is not an integer component state, we must abort because
		//we can not evaluate the sum of a non integer component
		cerr<<"Trying to create a stateCounter: '"<<name<<"' on the state: '"<<stateName<<"'\n";
		cerr<<"of MoleculeType: '"<<mt->getName()<<"', but the state you have selected cannot\n";
		cerr<<"have integer values, so summations on this state are undefined.  I am quitting."<<endl;
		exit(1);
	}
}
StateCounter::~StateCounter() {
	mt=0;
}

void StateCounter::add(Molecule *m) {
	if(m->getMoleculeType()==mt) {

	//	cout<<"matched moleculeType"<<endl;
		value+=m->getComponentState(stateIndex);
	//	cout<<"found component state: "<<m->getComponentState(stateIndex)<<endl;
	//	cout<<"updating v`alue to: "<< value<<endl;
	}
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 SRG Technology, LLC
//
// 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, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "anyrpc/api.h"
#include "anyrpc/logger.h"
#include "anyrpc/error.h"
#include "anyrpc/value.h"
#include "anyrpc/method.h"

namespace anyrpc
{

void ListMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->ListMethods(params, result);
}

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

void HelpMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->FindHelpMethod(params, result);
}

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

MethodManager::MethodManager()
{
    methods_[LIST_METHODS] = new ListMethod(this,LIST_METHODS,LIST_METHODS_HELP);
    methods_[METHOD_HELP] = new HelpMethod(this,METHOD_HELP,METHOD_HELP_HELP);
}

MethodManager::~MethodManager()
{
    MethodMap::iterator it = methods_.begin();
    for (MethodMap::iterator it = methods_.begin(); it != methods_.end(); it++)
    {
        if (it->second->DeleteOnRemove())
            delete it->second;  // free the method pointer data
    }
    methods_.clear();
}

void MethodManager::AddFunction(Function* function, std::string const& name, std::string const& help)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[name] = new MethodFunction(function,name,help);
    }
    else
    {
        // function already defined, throw exception
        // the user can catch and ignore the exception if this behavior is desired
        anyrpc_throw(AnyRpcErrorFunctionRedefine, "Attempt to redefine function name: " + name);
    }
}

void MethodManager::AddMethod(Method* method)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(method->Name());
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[method->Name()] = method;
    }
    else
    {
		std::string nameStr = method->Name();
        // method already defined, clean up then throw exception
        // the user can catch and ignore the exception if this behavior is desired
        if (method->DeleteOnRemove())
            delete method;
        anyrpc_throw(AnyRpcErrorMethodRedefine, "Attempt to redefine method name: " + nameStr);
    }
}

bool MethodManager::RemoveMethod(std::string const& name, bool WaitForDelayedRemove /* = false */)
{
    std::unique_lock<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
        return false; // no such method exists

    Method *method = it->second;
    if (method->ActiveThreads() > 0)
    {
        method->SetDelayedRemove();
        if (WaitForDelayedRemove)
        {
            // wait for method "name" being actually deleted
            while (methods_.find(name) != methods_.end())
                condVarDelayedRemove_.wait(lock);
        }
    }
    else
    {
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
    }
    return true;
}

bool MethodManager::ExecuteMethod(std::string const& name, Value& params, Value& result)
{
    std::unique_lock<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if ((it == methods_.end()) || it->second->DelayedRemove())
        return false;
    // Add this thread to the list of users for this method
    Method *method = it->second;
    method->AddThread();
    lock.unlock();

    try
    {
        it->second->Execute(params, result);
    }
    catch (...)
    {
        ExecuteMethod_FollowUpOperations(method);
        throw; // rethrow exception
    }

    ExecuteMethod_FollowUpOperations(method);

    return true;
}

void MethodManager::ExecuteMethod_FollowUpOperations(Method *method)
{
    std::lock_guard<std::mutex> lock(mutex_);
    // Finish with this thread using this method
    method->RemoveThread();
    // Check if we should remove the method - must have no active threads
    if (method->DelayedRemove() && (method->ActiveThreads() == 0))
    {
        // Find the method again in case other changes to the list have occurred
        MethodMap::const_iterator it = methods_.find(method->Name());
        if (it == methods_.end())
            anyrpc_throw(AnyRpcErrorInternalError, "Method not found for delayed remove: " + method->Name());
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
        condVarDelayedRemove_.notify_all(); // notify waiting calls of remove method (if any)
    }
}

void MethodManager::ListMethods(Value& params, Value& result)
{
    int i=0;
    result.SetArray();
    std::lock_guard<std::mutex> lock(mutex_);
    result.SetSize(methods_.size());
    for (MethodMap::const_iterator it = methods_.begin(); it != methods_.end(); ++it)
        result[i++] = it->first;
}

void MethodManager::FindHelpMethod(Value& params, Value& result)
{
    if (!params.IsArray() || (params.Size() != 1) || !params[0].IsString())
        anyrpc_throw(AnyRpcErrorInvalidParams, "Invalid parameters");

    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(params[0].GetString());
    if (it == methods_.end())
        anyrpc_throw(AnyRpcErrorMethodNotFound, "Unknown method name: " + std::string(params[0].GetString()));

    result = it->second->Help();
}

}
<commit_msg>Use space instead of tab<commit_after>// Copyright (C) 2015 SRG Technology, LLC
//
// 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, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "anyrpc/api.h"
#include "anyrpc/logger.h"
#include "anyrpc/error.h"
#include "anyrpc/value.h"
#include "anyrpc/method.h"

namespace anyrpc
{

void ListMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->ListMethods(params, result);
}

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

void HelpMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->FindHelpMethod(params, result);
}

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

MethodManager::MethodManager()
{
    methods_[LIST_METHODS] = new ListMethod(this,LIST_METHODS,LIST_METHODS_HELP);
    methods_[METHOD_HELP] = new HelpMethod(this,METHOD_HELP,METHOD_HELP_HELP);
}

MethodManager::~MethodManager()
{
    MethodMap::iterator it = methods_.begin();
    for (MethodMap::iterator it = methods_.begin(); it != methods_.end(); it++)
    {
        if (it->second->DeleteOnRemove())
            delete it->second;  // free the method pointer data
    }
    methods_.clear();
}

void MethodManager::AddFunction(Function* function, std::string const& name, std::string const& help)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[name] = new MethodFunction(function,name,help);
    }
    else
    {
        // function already defined, throw exception
        // the user can catch and ignore the exception if this behavior is desired
        anyrpc_throw(AnyRpcErrorFunctionRedefine, "Attempt to redefine function name: " + name);
    }
}

void MethodManager::AddMethod(Method* method)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(method->Name());
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[method->Name()] = method;
    }
    else
    {
        std::string nameStr = method->Name();
        // method already defined, clean up then throw exception
        // the user can catch and ignore the exception if this behavior is desired
        if (method->DeleteOnRemove())
            delete method;
        anyrpc_throw(AnyRpcErrorMethodRedefine, "Attempt to redefine method name: " + nameStr);
    }
}

bool MethodManager::RemoveMethod(std::string const& name, bool WaitForDelayedRemove /* = false */)
{
    std::unique_lock<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
        return false; // no such method exists

    Method *method = it->second;
    if (method->ActiveThreads() > 0)
    {
        method->SetDelayedRemove();
        if (WaitForDelayedRemove)
        {
            // wait for method "name" being actually deleted
            while (methods_.find(name) != methods_.end())
                condVarDelayedRemove_.wait(lock);
        }
    }
    else
    {
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
    }
    return true;
}

bool MethodManager::ExecuteMethod(std::string const& name, Value& params, Value& result)
{
    std::unique_lock<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if ((it == methods_.end()) || it->second->DelayedRemove())
        return false;
    // Add this thread to the list of users for this method
    Method *method = it->second;
    method->AddThread();
    lock.unlock();

    try
    {
        it->second->Execute(params, result);
    }
    catch (...)
    {
        ExecuteMethod_FollowUpOperations(method);
        throw; // rethrow exception
    }

    ExecuteMethod_FollowUpOperations(method);

    return true;
}

void MethodManager::ExecuteMethod_FollowUpOperations(Method *method)
{
    std::lock_guard<std::mutex> lock(mutex_);
    // Finish with this thread using this method
    method->RemoveThread();
    // Check if we should remove the method - must have no active threads
    if (method->DelayedRemove() && (method->ActiveThreads() == 0))
    {
        // Find the method again in case other changes to the list have occurred
        MethodMap::const_iterator it = methods_.find(method->Name());
        if (it == methods_.end())
            anyrpc_throw(AnyRpcErrorInternalError, "Method not found for delayed remove: " + method->Name());
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
        condVarDelayedRemove_.notify_all(); // notify waiting calls of remove method (if any)
    }
}

void MethodManager::ListMethods(Value& params, Value& result)
{
    int i=0;
    result.SetArray();
    std::lock_guard<std::mutex> lock(mutex_);
    result.SetSize(methods_.size());
    for (MethodMap::const_iterator it = methods_.begin(); it != methods_.end(); ++it)
        result[i++] = it->first;
}

void MethodManager::FindHelpMethod(Value& params, Value& result)
{
    if (!params.IsArray() || (params.Size() != 1) || !params[0].IsString())
        anyrpc_throw(AnyRpcErrorInvalidParams, "Invalid parameters");

    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(params[0].GetString());
    if (it == methods_.end())
        anyrpc_throw(AnyRpcErrorMethodNotFound, "Unknown method name: " + std::string(params[0].GetString()));

    result = it->second->Help();
}

}
<|endoftext|>


<commit_before>// SwiftShader Software Renderer
//
// Copyright(c) 2005-2012 TransGaming Inc.
//
// All rights reserved. No part of this software may be copied, distributed, transmitted,
// transcribed, stored in a retrieval system, translated into any human or computer
// language by any means, or disclosed to third parties without the explicit written
// agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express
// or implied, including but not limited to any patent rights, are granted to you.
//

// debug.cpp: Debugging utilities.

#include "common/debug.h"

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

namespace es
{
	static void output(const char *format, va_list vararg)
	{
		if(false)
		{
			FILE* file = fopen(TRACE_OUTPUT_FILE, "a");

			if(file)
			{
				vfprintf(file, format, vararg);
				fclose(file);
			}
		}
	}

	void trace(const char *format, ...)
	{
		va_list vararg;
		va_start(vararg, format);
		output(format, vararg);
		va_end(vararg);
	}
}
<commit_msg>Replaced fopen every trace call by a single fopen when tracing/dumping data<commit_after>// SwiftShader Software Renderer
//
// Copyright(c) 2005-2012 TransGaming Inc.
//
// All rights reserved. No part of this software may be copied, distributed, transmitted,
// transcribed, stored in a retrieval system, translated into any human or computer
// language by any means, or disclosed to third parties without the explicit written
// agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express
// or implied, including but not limited to any patent rights, are granted to you.
//

// debug.cpp: Debugging utilities.

#include "common/debug.h"

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

namespace es
{
	static void output(const char *format, va_list vararg)
	{
		if(false)
		{
			static FILE* file = nullptr;
			if(!file)
			{
				file = fopen(TRACE_OUTPUT_FILE, "w");
			}

			if(file)
			{
				vfprintf(file, format, vararg);
			}
		}
	}

	void trace(const char *format, ...)
	{
		va_list vararg;
		va_start(vararg, format);
		output(format, vararg);
		va_end(vararg);
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebSockets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "gameserver.h"
#include "QtWebSockets/QWebSocketServer"
#include "QtWebSockets/QWebSocket"
#include <QtCore/QDebug>
#include <QPoint>
#include <QJsonDocument>
#include <QJsonObject>

QT_USE_NAMESPACE

GameServer::GameServer(quint16 port, QObject *parent)
    : QObject(parent)
    , m_wsServer(nullptr)
{
    m_wsServer = new QWebSocketServer(QStringLiteral("Game Server"),
        QWebSocketServer::NonSecureMode, this);
    if (m_wsServer->listen(QHostAddress::Any, port)) {
        qDebug() << "Game Server listening on port" << port;
        connect(m_wsServer, &QWebSocketServer::newConnection, this, &GameServer::onNewConnection);
    }
}

GameServer::~GameServer()
{
    m_wsServer->close();
    QList<QWebSocket *> sockets = m_socketPlayerMap.keys();
    qDeleteAll(sockets.begin(), sockets.end());
}

void GameServer::onNewConnection()
{
    QWebSocket *socket = m_wsServer->nextPendingConnection();

    connect(socket, &QWebSocket::textMessageReceived, this, &GameServer::processMessage);
    connect(socket, &QWebSocket::disconnected, this, &GameServer::socketDisconnected);

    std::shared_ptr<PlayerModel> player = std::make_shared<PlayerModel>();
    m_socketPlayerMap[socket] = player;
    emit playerConnected(qVariantFromValue(player.get()));
}

void GameServer::processMessage(const QString &message)
{
    PlayerModel *player = m_socketPlayerMap[static_cast<QWebSocket *>(sender())].get();
    if (!player)
        return;

    QJsonObject jsonMsg = QJsonDocument::fromJson(message.toLatin1()).object();
    if (jsonMsg.value("type").toString() == QStringLiteral("move"))
        emit player->touchMove(jsonMsg.value("x").toInt(), jsonMsg.value("y").toInt(), jsonMsg.value("t").toInt());
    else if (jsonMsg.value("type").toString() == QStringLiteral("start"))
        emit player->touchStart();
    else if (jsonMsg.value("type").toString() == QStringLiteral("end"))
        emit player->touchEnd();
}

void GameServer::socketDisconnected()
{
    QWebSocket *socket = qobject_cast<QWebSocket *>(sender());
    if (socket)
    {
        std::shared_ptr<PlayerModel> player = m_socketPlayerMap.take(socket);
        emit playerDisconnected(qVariantFromValue(player.get()));

        m_socketPlayerMap.remove(socket);
        socket->deleteLater();
    }
}
<commit_msg>Handle floating point move coords<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebSockets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "gameserver.h"
#include "QtWebSockets/QWebSocketServer"
#include "QtWebSockets/QWebSocket"
#include <QtCore/QDebug>
#include <QPoint>
#include <QJsonDocument>
#include <QJsonObject>

QT_USE_NAMESPACE

GameServer::GameServer(quint16 port, QObject *parent)
    : QObject(parent)
    , m_wsServer(nullptr)
{
    m_wsServer = new QWebSocketServer(QStringLiteral("Game Server"),
        QWebSocketServer::NonSecureMode, this);
    if (m_wsServer->listen(QHostAddress::Any, port)) {
        qDebug() << "Game Server listening on port" << port;
        connect(m_wsServer, &QWebSocketServer::newConnection, this, &GameServer::onNewConnection);
    }
}

GameServer::~GameServer()
{
    m_wsServer->close();
    QList<QWebSocket *> sockets = m_socketPlayerMap.keys();
    qDeleteAll(sockets.begin(), sockets.end());
}

void GameServer::onNewConnection()
{
    QWebSocket *socket = m_wsServer->nextPendingConnection();

    connect(socket, &QWebSocket::textMessageReceived, this, &GameServer::processMessage);
    connect(socket, &QWebSocket::disconnected, this, &GameServer::socketDisconnected);

    std::shared_ptr<PlayerModel> player = std::make_shared<PlayerModel>();
    m_socketPlayerMap[socket] = player;
    emit playerConnected(qVariantFromValue(player.get()));
}

void GameServer::processMessage(const QString &message)
{
    PlayerModel *player = m_socketPlayerMap[static_cast<QWebSocket *>(sender())].get();
    if (!player)
        return;

    QJsonObject jsonMsg = QJsonDocument::fromJson(message.toLatin1()).object();
    if (jsonMsg.value("type").toString() == QStringLiteral("move"))
        emit player->touchMove(jsonMsg.value("x").toDouble(), jsonMsg.value("y").toDouble(), jsonMsg.value("t").toInt());
    else if (jsonMsg.value("type").toString() == QStringLiteral("start"))
        emit player->touchStart();
    else if (jsonMsg.value("type").toString() == QStringLiteral("end"))
        emit player->touchEnd();
}

void GameServer::socketDisconnected()
{
    QWebSocket *socket = qobject_cast<QWebSocket *>(sender());
    if (socket)
    {
        std::shared_ptr<PlayerModel> player = m_socketPlayerMap.take(socket);
        emit playerDisconnected(qVariantFromValue(player.get()));

        m_socketPlayerMap.remove(socket);
        socket->deleteLater();
    }
}
<|endoftext|>


<commit_before>/* Copyright 2016 The TensorFlow 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.
==============================================================================*/

#include "tensorflow/core/lib/monitoring/collection_registry.h"

#include "tensorflow/core/lib/monitoring/counter.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace monitoring {

namespace test_util {

class CollectionRegistryTestAccess {
 public:
  static std::unique_ptr<CollectionRegistry> CreateRegistry(Env* const env) {
    return std::unique_ptr<CollectionRegistry>(new CollectionRegistry(env));
  }
};

}  // namespace test_util

namespace {

void EmptyCollectionFunction(MetricCollectorGetter getter) {}

TEST(CollectionRegistryTest, RegistrationUnregistration) {
  auto* collection_registry = CollectionRegistry::Default();
  const MetricDef<MetricKind::kCumulative, int64, 0> metric_def0(
      "/tensorflow/metric0", "An example metric with no labels.");
  const MetricDef<MetricKind::kGauge, double, 1> metric_def1(
      "/tensorflow/metric1", "An example metric with one label.", "LabelName");

  {
    // Enclosed in a scope so that we unregister before the stack variables
    // above are destroyed.

    std::unique_ptr<CollectionRegistry::RegistrationHandle> handle0 =
        collection_registry->Register(&metric_def0, EmptyCollectionFunction);
    std::unique_ptr<CollectionRegistry::RegistrationHandle> handle1 =
        collection_registry->Register(&metric_def1, EmptyCollectionFunction);

    handle0.reset();

    // Able to register again because it was unregistered earlier.
    handle0 =
        collection_registry->Register(&metric_def0, EmptyCollectionFunction);
  }
}

TEST(CollectionRegistryDeathTest, DuplicateRegistration) {
  auto* collection_registry = CollectionRegistry::Default();
  const MetricDef<MetricKind::kCumulative, int64, 0> metric_def(
      "/tensorflow/metric", "An example metric with no labels.");

  auto handle =
      collection_registry->Register(&metric_def, EmptyCollectionFunction);
  EXPECT_DEATH(
      {
        auto duplicate_handle =
            collection_registry->Register(&metric_def, EmptyCollectionFunction);
      },
      "/tensorflow/metric");
}

auto* counter_with_labels =
    Counter<2>::New("/tensorflow/test/counter_with_labels",
                    "Counter with one label.", "MyLabel0", "MyLabel1");
auto* counter_without_labels = Counter<0>::New(
    "/tensorflow/test/counter_without_labels", "Counter without any labels.");
TEST(CollectMetricsTest, Counter) {
  counter_with_labels->GetCell("Label00", "Label10")->IncrementBy(42);
  counter_with_labels->GetCell("Label01", "Label11")->IncrementBy(58);
  counter_without_labels->GetCell()->IncrementBy(7);

  for (const bool collect_metric_descriptors : {true, false}) {
    SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ",
                                 collect_metric_descriptors));

    auto* collection_registry = CollectionRegistry::Default();
    CollectionRegistry::CollectMetricsOptions options;
    options.collect_metric_descriptors = collect_metric_descriptors;
    const std::unique_ptr<CollectedMetrics> collected_metrics =
        collection_registry->CollectMetrics(options);

    if (collect_metric_descriptors) {
      ASSERT_EQ(2, collected_metrics->metric_descriptor_map.size());

      const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at(
          "/tensorflow/test/counter_with_labels");
      EXPECT_EQ("/tensorflow/test/counter_with_labels", ld.name);
      EXPECT_EQ("Counter with one label.", ld.description);
      ASSERT_EQ(2, ld.label_names.size());
      EXPECT_EQ("MyLabel0", ld.label_names[0]);
      EXPECT_EQ("MyLabel1", ld.label_names[1]);
      EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind);
      EXPECT_EQ(ValueType::kInt64, ld.value_type);

      const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at(
          "/tensorflow/test/counter_without_labels");
      EXPECT_EQ("/tensorflow/test/counter_without_labels", ud.name);
      EXPECT_EQ("Counter without any labels.", ud.description);
      ASSERT_EQ(0, ud.label_names.size());
      EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind);
      EXPECT_EQ(ValueType::kInt64, ud.value_type);
    } else {
      EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size());
    }

    ASSERT_EQ(2, collected_metrics->point_set_map.size());

    const PointSet& lps = *collected_metrics->point_set_map.at(
        "/tensorflow/test/counter_with_labels");
    EXPECT_EQ("/tensorflow/test/counter_with_labels", lps.metric_name);
    ASSERT_EQ(2, lps.points.size());
    ASSERT_EQ(2, lps.points[0]->labels.size());
    EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name);
    EXPECT_EQ("Label00", lps.points[0]->labels[0].value);
    EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name);
    EXPECT_EQ("Label10", lps.points[0]->labels[1].value);
    EXPECT_EQ(ValueType::kInt64, lps.points[0]->value_type);
    EXPECT_EQ(42, lps.points[0]->int64_value);
    EXPECT_LT(0, lps.points[0]->start_timestamp_millis);
    EXPECT_LT(0, lps.points[0]->end_timestamp_millis);
    EXPECT_GE(lps.points[0]->end_timestamp_millis,
              lps.points[0]->start_timestamp_millis);
    ASSERT_EQ(2, lps.points[1]->labels.size());
    EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name);
    EXPECT_EQ("Label01", lps.points[1]->labels[0].value);
    EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name);
    EXPECT_EQ("Label11", lps.points[1]->labels[1].value);
    EXPECT_EQ(ValueType::kInt64, lps.points[1]->value_type);
    EXPECT_EQ(58, lps.points[1]->int64_value);
    EXPECT_LT(0, lps.points[1]->start_timestamp_millis);
    EXPECT_LT(0, lps.points[1]->end_timestamp_millis);
    EXPECT_GE(lps.points[1]->end_timestamp_millis,
              lps.points[1]->start_timestamp_millis);

    const PointSet& ups = *collected_metrics->point_set_map.at(
        "/tensorflow/test/counter_without_labels");
    EXPECT_EQ("/tensorflow/test/counter_without_labels", ups.metric_name);
    ASSERT_EQ(1, ups.points.size());
    EXPECT_EQ(0, ups.points[0]->labels.size());
    EXPECT_EQ(ValueType::kInt64, ups.points[0]->value_type);
    EXPECT_EQ(7, ups.points[0]->int64_value);
    EXPECT_LT(0, ups.points[0]->start_timestamp_millis);
    EXPECT_LT(0, ups.points[0]->end_timestamp_millis);
    EXPECT_GE(ups.points[0]->end_timestamp_millis,
              ups.points[0]->start_timestamp_millis);
  }
}

// A FakeClockEnv to manually advance time.
class FakeClockEnv : public EnvWrapper {
 public:
  FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {}

  // Manually advance the current time by 'millis' milliseconds.
  void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; }

  // Method that this environment specifically overrides.
  uint64 NowMicros() override { return current_millis_ * 1000; }

 private:
  uint64 current_millis_;
};

TEST(CollectionRegistryTest, WriteTimestamps) {
  FakeClockEnv fake_clock_env;
  auto collection_registry =
      test_util::CollectionRegistryTestAccess::CreateRegistry(&fake_clock_env);

  fake_clock_env.AdvanceByMillis(25);
  {
    const MetricDef<MetricKind::kCumulative, int64, 0> cumulative_metric(
        "/tensorflow/cumulative/metric", "An example metric with no labels.");
    auto handle = collection_registry->Register(
        &cumulative_metric, [&](MetricCollectorGetter getter) {
          auto metric_collector = getter.Get(&cumulative_metric);
          metric_collector.CollectValue({}, 42);
        });
    fake_clock_env.AdvanceByMillis(75);
    const std::unique_ptr<CollectedMetrics> collected_metrics =
        collection_registry->CollectMetrics({});
    const PointSet& point_set =
        *collected_metrics->point_set_map.at("/tensorflow/cumulative/metric");
    ASSERT_EQ(1, point_set.points.size());
    EXPECT_EQ(25, point_set.points[0]->start_timestamp_millis);
    EXPECT_EQ(100, point_set.points[0]->end_timestamp_millis);
  }
  {
    const MetricDef<MetricKind::kGauge, int64, 0> gauge_metric(
        "/tensorflow/gauge/metric", "An example metric with no labels.");
    auto handle = collection_registry->Register(
        &gauge_metric, [&](MetricCollectorGetter getter) {
          auto metric_collector = getter.Get(&gauge_metric);
          metric_collector.CollectValue({}, 42);
        });
    fake_clock_env.AdvanceByMillis(75);
    const std::unique_ptr<CollectedMetrics> collected_metrics =
        collection_registry->CollectMetrics({});
    const PointSet& point_set =
        *collected_metrics->point_set_map.at("/tensorflow/gauge/metric");
    ASSERT_EQ(1, point_set.points.size());
    EXPECT_EQ(175, point_set.points[0]->start_timestamp_millis);
    EXPECT_EQ(175, point_set.points[0]->end_timestamp_millis);
  }
}

}  // namespace
}  // namespace monitoring
}  // namespace tensorflow
<commit_msg>Adds another testcase for CollectionRegistryTest. Change: 130560709<commit_after>/* Copyright 2016 The TensorFlow 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.
==============================================================================*/

#include "tensorflow/core/lib/monitoring/collection_registry.h"

#include "tensorflow/core/lib/monitoring/counter.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace monitoring {

namespace test_util {

class CollectionRegistryTestAccess {
 public:
  static std::unique_ptr<CollectionRegistry> CreateRegistry(Env* const env) {
    return std::unique_ptr<CollectionRegistry>(new CollectionRegistry(env));
  }
};

}  // namespace test_util

namespace {

void EmptyCollectionFunction(MetricCollectorGetter getter) {}

TEST(CollectionRegistryTest, RegistrationUnregistration) {
  auto* collection_registry = CollectionRegistry::Default();
  const MetricDef<MetricKind::kCumulative, int64, 0> metric_def0(
      "/tensorflow/metric0", "An example metric with no labels.");
  const MetricDef<MetricKind::kGauge, double, 1> metric_def1(
      "/tensorflow/metric1", "An example metric with one label.", "LabelName");

  {
    // Enclosed in a scope so that we unregister before the stack variables
    // above are destroyed.

    std::unique_ptr<CollectionRegistry::RegistrationHandle> handle0 =
        collection_registry->Register(&metric_def0, EmptyCollectionFunction);
    std::unique_ptr<CollectionRegistry::RegistrationHandle> handle1 =
        collection_registry->Register(&metric_def1, EmptyCollectionFunction);

    handle0.reset();

    // Able to register again because it was unregistered earlier.
    handle0 =
        collection_registry->Register(&metric_def0, EmptyCollectionFunction);
  }
}

TEST(CollectionRegistryDeathTest, DuplicateRegistration) {
  auto* collection_registry = CollectionRegistry::Default();
  const MetricDef<MetricKind::kCumulative, int64, 0> metric_def(
      "/tensorflow/metric", "An example metric with no labels.");

  auto handle =
      collection_registry->Register(&metric_def, EmptyCollectionFunction);
  EXPECT_DEATH(
      {
        auto duplicate_handle =
            collection_registry->Register(&metric_def, EmptyCollectionFunction);
      },
      "/tensorflow/metric");
}

TEST(CollectMetricsTest, NoMetrics) {
  auto* collection_registry = CollectionRegistry::Default();
  const std::unique_ptr<CollectedMetrics> collected_metrics =
      collection_registry->CollectMetrics({});
  EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size());
  EXPECT_EQ(0, collected_metrics->point_set_map.size());
}

TEST(CollectMetricsTest, Counter) {
  auto counter_with_labels = std::unique_ptr<Counter<2>>(
      Counter<2>::New("/tensorflow/test/counter_with_labels",
                      "Counter with labels.", "MyLabel0", "MyLabel1"));
  auto counter_without_labels = std::unique_ptr<Counter<0>>(Counter<0>::New(
      "/tensorflow/test/counter_without_labels", "Counter without labels."));

  counter_with_labels->GetCell("Label00", "Label10")->IncrementBy(42);
  counter_with_labels->GetCell("Label01", "Label11")->IncrementBy(58);
  counter_without_labels->GetCell()->IncrementBy(7);

  for (const bool collect_metric_descriptors : {true, false}) {
    SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ",
                                 collect_metric_descriptors));

    auto* collection_registry = CollectionRegistry::Default();
    CollectionRegistry::CollectMetricsOptions options;
    options.collect_metric_descriptors = collect_metric_descriptors;
    const std::unique_ptr<CollectedMetrics> collected_metrics =
        collection_registry->CollectMetrics(options);

    if (collect_metric_descriptors) {
      ASSERT_EQ(2, collected_metrics->metric_descriptor_map.size());

      const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at(
          "/tensorflow/test/counter_with_labels");
      EXPECT_EQ("/tensorflow/test/counter_with_labels", ld.name);
      EXPECT_EQ("Counter with labels.", ld.description);
      ASSERT_EQ(2, ld.label_names.size());
      EXPECT_EQ("MyLabel0", ld.label_names[0]);
      EXPECT_EQ("MyLabel1", ld.label_names[1]);
      EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind);
      EXPECT_EQ(ValueType::kInt64, ld.value_type);

      const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at(
          "/tensorflow/test/counter_without_labels");
      EXPECT_EQ("/tensorflow/test/counter_without_labels", ud.name);
      EXPECT_EQ("Counter without labels.", ud.description);
      ASSERT_EQ(0, ud.label_names.size());
      EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind);
      EXPECT_EQ(ValueType::kInt64, ud.value_type);
    } else {
      EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size());
    }

    ASSERT_EQ(2, collected_metrics->point_set_map.size());

    const PointSet& lps = *collected_metrics->point_set_map.at(
        "/tensorflow/test/counter_with_labels");
    EXPECT_EQ("/tensorflow/test/counter_with_labels", lps.metric_name);
    ASSERT_EQ(2, lps.points.size());
    ASSERT_EQ(2, lps.points[0]->labels.size());
    EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name);
    EXPECT_EQ("Label00", lps.points[0]->labels[0].value);
    EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name);
    EXPECT_EQ("Label10", lps.points[0]->labels[1].value);
    EXPECT_EQ(ValueType::kInt64, lps.points[0]->value_type);
    EXPECT_EQ(42, lps.points[0]->int64_value);
    EXPECT_LT(0, lps.points[0]->start_timestamp_millis);
    EXPECT_LT(0, lps.points[0]->end_timestamp_millis);
    EXPECT_GE(lps.points[0]->end_timestamp_millis,
              lps.points[0]->start_timestamp_millis);
    ASSERT_EQ(2, lps.points[1]->labels.size());
    EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name);
    EXPECT_EQ("Label01", lps.points[1]->labels[0].value);
    EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name);
    EXPECT_EQ("Label11", lps.points[1]->labels[1].value);
    EXPECT_EQ(ValueType::kInt64, lps.points[1]->value_type);
    EXPECT_EQ(58, lps.points[1]->int64_value);
    EXPECT_LT(0, lps.points[1]->start_timestamp_millis);
    EXPECT_LT(0, lps.points[1]->end_timestamp_millis);
    EXPECT_GE(lps.points[1]->end_timestamp_millis,
              lps.points[1]->start_timestamp_millis);

    const PointSet& ups = *collected_metrics->point_set_map.at(
        "/tensorflow/test/counter_without_labels");
    EXPECT_EQ("/tensorflow/test/counter_without_labels", ups.metric_name);
    ASSERT_EQ(1, ups.points.size());
    EXPECT_EQ(0, ups.points[0]->labels.size());
    EXPECT_EQ(ValueType::kInt64, ups.points[0]->value_type);
    EXPECT_EQ(7, ups.points[0]->int64_value);
    EXPECT_LT(0, ups.points[0]->start_timestamp_millis);
    EXPECT_LT(0, ups.points[0]->end_timestamp_millis);
    EXPECT_GE(ups.points[0]->end_timestamp_millis,
              ups.points[0]->start_timestamp_millis);
  }
}

// A FakeClockEnv to manually advance time.
class FakeClockEnv : public EnvWrapper {
 public:
  FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {}

  // Manually advance the current time by 'millis' milliseconds.
  void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; }

  // Method that this environment specifically overrides.
  uint64 NowMicros() override { return current_millis_ * 1000; }

 private:
  uint64 current_millis_;
};

TEST(CollectionRegistryTest, WriteTimestamps) {
  FakeClockEnv fake_clock_env;
  auto collection_registry =
      test_util::CollectionRegistryTestAccess::CreateRegistry(&fake_clock_env);

  fake_clock_env.AdvanceByMillis(25);
  {
    const MetricDef<MetricKind::kCumulative, int64, 0> cumulative_metric(
        "/tensorflow/cumulative/metric", "An example metric with no labels.");
    auto handle = collection_registry->Register(
        &cumulative_metric, [&](MetricCollectorGetter getter) {
          auto metric_collector = getter.Get(&cumulative_metric);
          metric_collector.CollectValue({}, 42);
        });
    fake_clock_env.AdvanceByMillis(75);
    const std::unique_ptr<CollectedMetrics> collected_metrics =
        collection_registry->CollectMetrics({});
    const PointSet& point_set =
        *collected_metrics->point_set_map.at("/tensorflow/cumulative/metric");
    ASSERT_EQ(1, point_set.points.size());
    EXPECT_EQ(25, point_set.points[0]->start_timestamp_millis);
    EXPECT_EQ(100, point_set.points[0]->end_timestamp_millis);
  }
  {
    const MetricDef<MetricKind::kGauge, int64, 0> gauge_metric(
        "/tensorflow/gauge/metric", "An example metric with no labels.");
    auto handle = collection_registry->Register(
        &gauge_metric, [&](MetricCollectorGetter getter) {
          auto metric_collector = getter.Get(&gauge_metric);
          metric_collector.CollectValue({}, 42);
        });
    fake_clock_env.AdvanceByMillis(75);
    const std::unique_ptr<CollectedMetrics> collected_metrics =
        collection_registry->CollectMetrics({});
    const PointSet& point_set =
        *collected_metrics->point_set_map.at("/tensorflow/gauge/metric");
    ASSERT_EQ(1, point_set.points.size());
    EXPECT_EQ(175, point_set.points[0]->start_timestamp_millis);
    EXPECT_EQ(175, point_set.points[0]->end_timestamp_millis);
  }
}

}  // namespace
}  // namespace monitoring
}  // namespace tensorflow
<|endoftext|>


<commit_before>//
// YaPB - Counter-Strike Bot based on PODBot by Markus Klinge.
// Copyright  2004-2020 YaPB Project <yapb@jeefo.net>.
//
// SPDX-License-Identifier: MIT
//

#include <yapb.h>

// module interface implementation
class YaPBModule : public IYaPBModule, public Singleton <YaPBModule> {
private:
   Bot *getBot (int index) {
      if (index < 1) {
         return nullptr;
      }
      return bots[game.playerOfIndex (index - 1)];
   }

public:
   // get the bot version string
   virtual const char *getBotVersion () override {
      return product.version.chars ();
   }

   // checks if bots are currently in game
   virtual bool isBotsInGame () override {
      return bots.getBotCount () > 0 ;
   }

   // checks whether specified players is a yapb bot
   virtual bool isBot (int entity) override {
      return getBot (entity) != nullptr;
   }

   // gets the node nearest to origin
   virtual int getNearestNode (float *origin) override {
      if (graph.length () > 0) {
         return graph.getNearestNoBuckets (origin);
      }
      return kInvalidNodeIndex;
   }

   // checks wether node is valid
   virtual bool isNodeValid (int node) override {
      return graph.exists (node);
   }

   // gets the node origin
   virtual float *getNodeOrigin (int node) override {
      if (!graph.exists (node)) {
         return nullptr;
      }
      return graph[node].origin;
   }

   // get the bots current active node
   virtual int getCurrentNodeId (int entity) override {
      auto bot = getBot (entity);

      if (bot) {
         return bot->getCurrentNodeIndex ();
      }
      return kInvalidNodeIndex;
   }

   // force bot to go to the selected node
   virtual void setBotGoal (int entity, int node) {
      if (!graph.exists (node)) {
         return;
      }
      auto bot = getBot (entity);

      if (bot) {
         return bot->sendBotToOrigin (graph[node].origin);
      }
   }

   // force bot to go to selected origin
   virtual void setBotGoalOrigin (int entity, float *origin) {
      auto bot = getBot (entity);

      if (bot) {
         return bot->sendBotToOrigin (origin);
      }
   }
};

CR_EXPOSE_GLOBAL_SINGLETON (YaPBModule, botModule);

// export all the stuff, maybe add versioned interface ?
CR_EXPORT IYaPBModule *GetBotAPI (int version) {
   if (version != kYaPBModuleVersion) {
      return nullptr;
   }
   return &botModule;
}
<commit_msg>fix build<commit_after>//
// YaPB - Counter-Strike Bot based on PODBot by Markus Klinge.
// Copyright  2004-2020 YaPB Project <yapb@jeefo.net>.
//
// SPDX-License-Identifier: MIT
//

#include <yapb.h>

// module interface implementation
class YaPBModule : public IYaPBModule {
private:
   Bot *getBot (int index) {
      if (index < 1) {
         return nullptr;
      }
      return bots[game.playerOfIndex (index - 1)];
   }

public:
   // get the bot version string
   virtual const char *getBotVersion () override {
      return product.version.chars ();
   }

   // checks if bots are currently in game
   virtual bool isBotsInGame () override {
      return bots.getBotCount () > 0;
   }

   // checks whether specified players is a yapb bot
   virtual bool isBot (int entity) override {
      return getBot (entity) != nullptr;
   }

   // gets the node nearest to origin
   virtual int getNearestNode (float *origin) override {
      if (graph.length () > 0) {
         return graph.getNearestNoBuckets (origin);
      }
      return kInvalidNodeIndex;
   }

   // checks wether node is valid
   virtual bool isNodeValid (int node) override {
      return graph.exists (node);
   }

   // gets the node origin
   virtual float *getNodeOrigin (int node) override {
      if (!graph.exists (node)) {
         return nullptr;
      }
      return graph[node].origin;
   }

   // get the bots current active node
   virtual int getCurrentNodeId (int entity) override {
      auto bot = getBot (entity);

      if (bot) {
         return bot->getCurrentNodeIndex ();
      }
      return kInvalidNodeIndex;
   }

   // force bot to go to the selected node
   virtual void setBotGoal (int entity, int node) override {
      if (!graph.exists (node)) {
         return;
      }
      auto bot = getBot (entity);

      if (bot) {
         return bot->sendBotToOrigin (graph[node].origin);
      }
   }

   // force bot to go to selected origin
   virtual void setBotGoalOrigin (int entity, float *origin) override {
      auto bot = getBot (entity);

      if (bot) {
         return bot->sendBotToOrigin (origin);
      }
   }
};

// export all the stuff, maybe add versioned interface ?
CR_EXPORT IYaPBModule *GetBotAPI (int version) {
   if (version != kYaPBModuleVersion) {
      return nullptr;
   }
   static YaPBModule botModule;

   return &botModule;
}
<|endoftext|>