<commit_before>#include "PhosphorRender.h"
#include <cmath>

#include <QtQuick/qsgnode.h>
#include <QtQuick/qsgflatcolormaterial.h>
#include <iostream>

class Shader : public QSGMaterialShader
{
public:
    const char *vertexShader() const {
        return
        "attribute highp vec4 vertex;          \n"
        "uniform highp mat4 matrix;            \n"
        "void main() {                         \n"
        "    gl_Position = matrix * vertex;    \n"
        "}";
    }

    const char *fragmentShader() const {
        return
        "#version 120 \n"
        "uniform lowp float opacity;"
        "void main() {"
        "    float dist = length(gl_PointCoord - vec2(0.5))*2;"
        "    gl_FragColor = vec4(0.03, 0.3, 0.03, 1) * opacity * (1-dist);"
       //"    if(dist > 1)"
       //"        discard;"
        "}";
    }

    char const *const *attributeNames() const
    {
        static char const *const names[] = { "vertex", 0 };
        return names;
    }

    void initialize()
    {
        QSGMaterialShader::initialize();
        m_id_matrix = program()->uniformLocation("matrix");
        m_id_opacity = program()->uniformLocation("opacity");
    }

    void updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial);

    void deactivate() {
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

private:
    int m_id_matrix;
    int m_id_opacity;
};

class Material : public QSGMaterial
{
public:
    QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
    QSGMaterialShader *createShader() const { return new Shader; }
    QSGMaterial::Flags  flags() const { return QSGMaterial::Blending; }

    QMatrix4x4 transformation;
    float pointSize;
};

void Shader::updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial)
{
    Q_ASSERT(program()->isLinked());

    Material* m = static_cast<Material*>(newMaterial);
    program()->setUniformValue(m_id_matrix, state.combinedMatrix()*m->transformation);

    if (state.isOpacityDirty()) {
        program()->setUniformValue(m_id_opacity, state.opacity());
    }

    glBlendFunc(GL_ONE, GL_ONE);
    glPointSize(m->pointSize);
}

PhosphorRender::PhosphorRender(QQuickItem *parent)
    : QQuickItem(parent)
{
    setFlag(ItemHasContents, true);
}

PhosphorRender::~PhosphorRender()
{
}

QSGNode *PhosphorRender::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    if (!m_buffer) {
        return 0;
    }

    QSGGeometryNode *node = 0;
    QSGGeometry *geometry = 0;
    Material *material = 0;

    unsigned n_points = m_buffer->countPointsBetween(m_xmin, m_xmax);

    if (!oldNode) {
        node = new QSGGeometryNode;
        geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), n_points);
        geometry->setLineWidth(2);
        geometry->setDrawingMode(GL_POINTS);
        node->setGeometry(geometry);
        node->setFlag(QSGNode::OwnsGeometry);
        material = new Material;
        material->setFlag(QSGMaterial::Blending);
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);
    } else {
        node = static_cast<QSGGeometryNode *>(oldNode);
        geometry = node->geometry();
        geometry->allocate(n_points);
        material = static_cast<Material*>(node->material());
    }

    QRectF bounds = boundingRect();

    material->transformation.setToIdentity();
    material->transformation.scale(bounds.width()/(m_xmax - m_xmin), bounds.height()/(m_ymin - m_ymax));
    material->transformation.translate(-m_xmin, -m_ymax);

    material->pointSize = m_pointSize;

    m_buffer->toVertexData(m_xmin, m_xmax, geometry->vertexDataAsPoint2D(), n_points);
    node->markDirty(QSGNode::DirtyGeometry);

    return node;
}
<commit_msg>Fix uninitialized property<commit_after>#include "PhosphorRender.h"
#include <cmath>

#include <QtQuick/qsgnode.h>
#include <QtQuick/qsgflatcolormaterial.h>
#include <iostream>

class Shader : public QSGMaterialShader
{
public:
    const char *vertexShader() const {
        return
        "attribute highp vec4 vertex;          \n"
        "uniform highp mat4 matrix;            \n"
        "void main() {                         \n"
        "    gl_Position = matrix * vertex;    \n"
        "}";
    }

    const char *fragmentShader() const {
        return
        "#version 120 \n"
        "uniform lowp float opacity;"
        "void main() {"
        "    float dist = length(gl_PointCoord - vec2(0.5))*2;"
        "    gl_FragColor = vec4(0.03, 0.3, 0.03, 1) * opacity * (1-dist);"
       //"    if(dist > 1)"
       //"        discard;"
        "}";
    }

    char const *const *attributeNames() const
    {
        static char const *const names[] = { "vertex", 0 };
        return names;
    }

    void initialize()
    {
        QSGMaterialShader::initialize();
        m_id_matrix = program()->uniformLocation("matrix");
        m_id_opacity = program()->uniformLocation("opacity");
    }

    void updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial);

    void deactivate() {
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

private:
    int m_id_matrix;
    int m_id_opacity;
};

class Material : public QSGMaterial
{
public:
    QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
    QSGMaterialShader *createShader() const { return new Shader; }
    QSGMaterial::Flags  flags() const { return QSGMaterial::Blending; }

    QMatrix4x4 transformation;
    float pointSize;
};

void Shader::updateState(const RenderState &state, QSGMaterial *newMaterial, QSGMaterial *oldMaterial)
{
    Q_ASSERT(program()->isLinked());

    Material* m = static_cast<Material*>(newMaterial);
    program()->setUniformValue(m_id_matrix, state.combinedMatrix()*m->transformation);

    if (state.isOpacityDirty()) {
        program()->setUniformValue(m_id_opacity, state.opacity());
    }

    glBlendFunc(GL_ONE, GL_ONE);
    glPointSize(m->pointSize);
}

PhosphorRender::PhosphorRender(QQuickItem *parent)
    : QQuickItem(parent), m_buffer(NULL), m_xmin(0), m_xmax(1), m_ymin(0), m_ymax(1), m_pointSize(0)
{
    setFlag(ItemHasContents, true);
}

PhosphorRender::~PhosphorRender()
{
}

QSGNode *PhosphorRender::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    if (!m_buffer) {
        return 0;
    }

    QSGGeometryNode *node = 0;
    QSGGeometry *geometry = 0;
    Material *material = 0;

    unsigned n_points = m_buffer->countPointsBetween(m_xmin, m_xmax);

    if (!oldNode) {
        node = new QSGGeometryNode;
        geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), n_points);
        geometry->setLineWidth(2);
        geometry->setDrawingMode(GL_POINTS);
        node->setGeometry(geometry);
        node->setFlag(QSGNode::OwnsGeometry);
        material = new Material;
        material->setFlag(QSGMaterial::Blending);
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);
    } else {
        node = static_cast<QSGGeometryNode *>(oldNode);
        geometry = node->geometry();
        geometry->allocate(n_points);
        material = static_cast<Material*>(node->material());
    }

    QRectF bounds = boundingRect();

    material->transformation.setToIdentity();
    material->transformation.scale(bounds.width()/(m_xmax - m_xmin), bounds.height()/(m_ymin - m_ymax));
    material->transformation.translate(-m_xmin, -m_ymax);

    material->pointSize = m_pointSize;

    m_buffer->toVertexData(m_xmin, m_xmax, geometry->vertexDataAsPoint2D(), n_points);
    node->markDirty(QSGNode::DirtyGeometry);

    return node;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "ConnectorDAImpl.h"

//--- project modules used -----------------------------------------------------

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "SSLSocket.h"
#include "SysLog.h"
#include "SocketStream.h"
#include "Timers.h"

//--- c-modules used -----------------------------------------------------------
#if defined(WIN32)
#include <io.h>				// for SO_ERROR
#else
#include <sys/socket.h>		// for SO_ERROR
#endif

//--- ConnectorDAImpl -----------------------------------------------------
RegisterDataAccessImpl(ConnectorDAImpl);

ConnectorDAImpl::ConnectorDAImpl(const char *name) : DataAccessImpl(name)
{
}

ConnectorDAImpl::~ConnectorDAImpl()
{
}

IFAObject *ConnectorDAImpl::Clone() const
{
	return new ConnectorDAImpl(fName);
}

bool ConnectorDAImpl::Exec( Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.Exec);

	bool bCloseSocket = true, bRetCode = false, bRecreate = false;
	Anything anySocketParams;
	Connector *pConnector = NULL;
	Socket *pSocket = NULL;
	in->Get("CloseSocket", bCloseSocket, context);
	TraceAny(context.GetTmpStore(), "TempStore");
	if ( in->Get("SocketParams", anySocketParams, context) ) {
		TraceAny(anySocketParams, "SocketParams");
		if ( (pSocket = RecreateSocket(anySocketParams, context, in, out)) != NULL ) {
			bRecreate = true;
		} else {
			// remove SocketParams from TmpStore
			context.GetTmpStore().Remove("SocketParams");
			anySocketParams = Anything();
		}
	}
	if ( pSocket == NULL ) {
		// create new connector
		pConnector = DoMakeConnector(context, in, out);
		if ( pConnector ) {
			pSocket = DoConnect(pConnector, context, in, out);
			if ( pSocket ) {
				// store params
				anySocketParams = pSocket->ClientInfo();
				anySocketParams["SocketFd"] = pSocket->GetFd();
				TraceAny(anySocketParams, "SocketParams");
				out->Put("SocketParams", anySocketParams, context);
			}
		} else {
			SYSWARNING("failed to create Connector");
		}
	}

	if ( pSocket ) {
		// set socket option not to close the filedescriptor when Socket gets destructed
		Trace("closeflag : " << (bCloseSocket ? "true" : "false"));
		pSocket->CloseOnDelete(bCloseSocket);
		bRetCode = DoExec(pSocket, context, in, out);
		Trace("bRetCode : " << (bRetCode ? "true" : "false"));
	} else {
		SYSWARNING("Socket not valid!");
	}
	if ( bRecreate && pSocket ) {
		Trace("deleting recreated socket");
		delete pSocket;
	}

	// delete Connector object -> also deletes socket!
	delete pConnector;
	pSocket = NULL;
	if ( bCloseSocket ) {
		// remove SocketParams from TmpStore
		context.GetTmpStore().Remove("SocketParams");
	}
	return bRetCode;
}

Connector *ConnectorDAImpl::DoMakeConnector( Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.DoMakeConnector);
	Connector *pConnector = NULL;
	String strAddress;
	long lPort = 0L, lConnTimeout = 10L;
	bool bUseSSL = false;
	if ( !in->Get("Address", strAddress, context) ) {
		strAddress = EndPoint::GetLocalHost();
		SYSINFO("address set to " << strAddress);
	}
	if ( !in->Get("Port", lPort, context) ) {
		SYSERROR("Port not given!");
		return NULL;
	}
	in->Get("UseSSL", bUseSSL, context);
	in->Get("ConnectTimeout", lConnTimeout, context);
	lConnTimeout *= 1000L;
	Trace( "Address<" << strAddress << "> Port[" << lPort << "] " << (bUseSSL ? "SSL" : "") << " ConnectTimeout: " << lConnTimeout << "ms");
	if ( bUseSSL ) {
		pConnector = new SSLConnector(strAddress, lPort, lConnTimeout, (SSL_CTX *)context.Lookup("SSLContext").AsIFAObject(0));
	} else {
		pConnector = new Connector(strAddress, lPort, lConnTimeout);
	}
	return pConnector;
}

Socket *ConnectorDAImpl::DoConnect(Connector *csc, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.DoConnect);
	Socket *s = NULL;
	DAAccessTimer(ConnectorDAImpl.DoConnect, "connecting <" << fName << ">", context);
	s = csc->Use();
	// error message here in case of failure
	return s;
}

Socket *ConnectorDAImpl::RecreateSocket(Anything &anyParams, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.RecreateSocket);
	Socket *s = NULL;
	long socketFd = 0L;
	bool bUseSSL = false;
	ROAnything roaParams = anyParams;
	socketFd = roaParams["SocketFd"].AsLong(0L);

	if ( socketFd != 0L ) {
		int error = 0;
		bool bSuccess = Socket::GetSockOptInt(socketFd, SO_ERROR, error);
		if ( bSuccess ) {
			// recreate socket using the params
			in->Get("UseSSL", bUseSSL, context);
			if ( roaParams["HTTPS"].AsBool() || bUseSSL ) {
				s = new (Storage::Global()) SSLClientSocket((SSL_CTX *)context.Lookup("SSLContext").AsIFAObject(0), socketFd, anyParams, true);
			} else {
				s = new (Storage::Global()) Socket(socketFd, anyParams, true);
			}
		}
	}
	return s;
}

bool ConnectorDAImpl::DoExec(Socket *pSocket, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.DoExec);
	long lSocketStreamTimeout = 30L, lCheckReadyTimeout = 30L, lSocketTimeout = 300L;
	bool bTcpNoDelay = true;
	in->Get("SocketTimeout", lSocketTimeout, context);
	in->Get("SocketStreamTimeout", lSocketStreamTimeout, context);
	in->Get("CheckReadyTimeout", lCheckReadyTimeout, context);
	in->Get("TcpNoDelay", bTcpNoDelay, context);
	lSocketTimeout *= 1000L;
	lSocketStreamTimeout *= 1000L;
	lCheckReadyTimeout *= 1000L;
	iostream *pIos = NULL;
	if ( pSocket ) {
		if ( bTcpNoDelay ) {
			pSocket->SetNoDelay();
		}
		pSocket->SetTimeout(lSocketTimeout);
		pIos = pSocket->GetStream();
	}
	if ( pIos == NULL ) {
		return HandleError(pSocket, "connection to: ", context, in, out);
	}
	{
		DAAccessTimer(ConnectorDAImpl.DoExec, "writing", context);
		if ( !SendInput(pIos, pSocket, lCheckReadyTimeout, lSocketStreamTimeout, context, in, out) || !(*pIos)) {
			return false;
		}
	}
	{
		DAAccessTimer(ConnectorDAImpl.DoExec, "reading", context);
		long lRetCode = 0L;
		if ( pSocket->IsReadyForReading(lCheckReadyTimeout, lRetCode) ) {
			Trace("waiting on output from other party");
			DiffTimer aReadTimer;
			TimeoutModifier aTimeoutModifier((SocketStream *) pIos, lSocketStreamTimeout);
			aTimeoutModifier.Use();
			if ( out->Put("Output", *pIos, context) ) {
				return true;
			} else {
				String strError("put into Output slot took ");
				strError << (long)aReadTimer.Diff() << "ms from: ";
				HandleError(pSocket, strError, context, in, out);
			}
		} else {
			String strError("not ready for reading");
			if ( lRetCode == 0 ) {
				strError << " after " << lCheckReadyTimeout << "s";
			}
			strError << " from: ";
			HandleError(pSocket, strError, context, in, out);
		}
	}
	return false;
}

bool ConnectorDAImpl::SendInput(iostream *pIos, Socket *s, long lCheckReadyTimeout, long lSocketStreamTimeout, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.SendInput);

	if ( pIos ) {
		long lRetCode = 0L;
		if ( s->IsReadyForWriting(lCheckReadyTimeout, lRetCode) ) {
			Trace("writing input to other party");
			TimeoutModifier aTimeoutModifier((SocketStream *) pIos, lSocketStreamTimeout);
			aTimeoutModifier.Use();
			bool retCode = in->Get("Input", *pIos, context);
			pIos->flush();
			Trace("input sent and stream flushed");
			if (retCode) {
				Trace("returning true");
				return true;
			}
			HandleError(s, "sending request to: ", context, in, out);
		} else {
			String strError("not ready for writing");
			if ( lRetCode == 0 ) {
				strError << " after " << lCheckReadyTimeout << "s";
			}
			strError << " to: ";
			HandleError(s, strError, context, in, out);
		}
	}
	return false;
}

bool ConnectorDAImpl::HandleError( Socket *s, const char *streamText, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.HandleError);
	Trace(" Errortext to use : " << streamText);

	String strBuf;
	{
		OStringStream stream(strBuf);
		stream << streamText;
		s->ClientInfo().PrintOn(stream) << " failed!";
		stream.flush();
	}
	out->Put("Error", strBuf, context);
	SYSERROR(strBuf);

	return false;
}
<commit_msg>added more trace info<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "ConnectorDAImpl.h"

//--- project modules used -----------------------------------------------------

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "SSLSocket.h"
#include "SysLog.h"
#include "SocketStream.h"
#include "Timers.h"

//--- c-modules used -----------------------------------------------------------
#if defined(WIN32)
#include <io.h>				// for SO_ERROR
#else
#include <sys/socket.h>		// for SO_ERROR
#endif

//--- ConnectorDAImpl -----------------------------------------------------
RegisterDataAccessImpl(ConnectorDAImpl);

ConnectorDAImpl::ConnectorDAImpl(const char *name) : DataAccessImpl(name)
{
}

ConnectorDAImpl::~ConnectorDAImpl()
{
}

IFAObject *ConnectorDAImpl::Clone() const
{
	return new ConnectorDAImpl(fName);
}

bool ConnectorDAImpl::Exec( Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.Exec);

	bool bCloseSocket = true, bRetCode = false, bRecreate = false;
	Anything anySocketParams;
	Connector *pConnector = NULL;
	Socket *pSocket = NULL;
	in->Get("CloseSocket", bCloseSocket, context);
	TraceAny(context.GetTmpStore(), "TempStore");
	if ( in->Get("SocketParams", anySocketParams, context) ) {
		TraceAny(anySocketParams, "SocketParams");
		if ( (pSocket = RecreateSocket(anySocketParams, context, in, out)) != NULL ) {
			bRecreate = true;
		} else {
			// remove SocketParams from TmpStore
			context.GetTmpStore().Remove("SocketParams");
			anySocketParams = Anything();
		}
	}
	if ( pSocket == NULL ) {
		// create new connector
		pConnector = DoMakeConnector(context, in, out);
		if ( pConnector ) {
			pSocket = DoConnect(pConnector, context, in, out);
			if ( pSocket ) {
				// store params
				anySocketParams = pSocket->ClientInfo();
				anySocketParams["SocketFd"] = pSocket->GetFd();
				TraceAny(anySocketParams, "SocketParams");
				out->Put("SocketParams", anySocketParams, context);
			}
		} else {
			SYSWARNING("failed to create Connector");
		}
	}

	if ( pSocket ) {
		// set socket option not to close the filedescriptor when Socket gets destructed
		Trace("closeflag : " << (bCloseSocket ? "true" : "false"));
		pSocket->CloseOnDelete(bCloseSocket);
		bRetCode = DoExec(pSocket, context, in, out);
		Trace("bRetCode : " << (bRetCode ? "true" : "false"));
	} else {
		SYSWARNING("Socket not valid!");
	}
	if ( bRecreate && pSocket ) {
		Trace("deleting recreated socket");
		delete pSocket;
	}

	// delete Connector object -> also deletes socket!
	delete pConnector;
	pSocket = NULL;
	if ( bCloseSocket ) {
		// remove SocketParams from TmpStore
		context.GetTmpStore().Remove("SocketParams");
	}
	return bRetCode;
}

Connector *ConnectorDAImpl::DoMakeConnector( Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.DoMakeConnector);
	Connector *pConnector = NULL;
	String strAddress;
	long lPort = 0L, lConnTimeout = 10L;
	bool bUseSSL = false;
	if ( !in->Get("Address", strAddress, context) ) {
		strAddress = EndPoint::GetLocalHost();
		SYSINFO("address set to " << strAddress);
	}
	if ( !in->Get("Port", lPort, context) ) {
		SYSERROR("Port not given!");
		return NULL;
	}
	in->Get("UseSSL", bUseSSL, context);
	in->Get("ConnectTimeout", lConnTimeout, context);
	lConnTimeout *= 1000L;
	Trace( "Address<" << strAddress << "> Port[" << lPort << "] " << (bUseSSL ? "SSL" : "") << " ConnectTimeout: " << lConnTimeout << "ms");
	if ( bUseSSL ) {
		pConnector = new SSLConnector(strAddress, lPort, lConnTimeout, (SSL_CTX *)context.Lookup("SSLContext").AsIFAObject(0));
	} else {
		pConnector = new Connector(strAddress, lPort, lConnTimeout);
	}
	return pConnector;
}

Socket *ConnectorDAImpl::DoConnect(Connector *csc, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.DoConnect);
	Socket *s = NULL;
	DAAccessTimer(ConnectorDAImpl.DoConnect, "connecting <" << fName << ">", context);
	s = csc->Use();
	// error message here in case of failure
	return s;
}

Socket *ConnectorDAImpl::RecreateSocket(Anything &anyParams, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.RecreateSocket);
	Socket *s = NULL;
	long socketFd = 0L;
	bool bUseSSL = false;
	ROAnything roaParams = anyParams;
	socketFd = roaParams["SocketFd"].AsLong(0L);

	if ( socketFd != 0L ) {
		int error = 0;
		bool bSuccess = Socket::GetSockOptInt(socketFd, SO_ERROR, error);
		if ( bSuccess ) {
			// recreate socket using the params
			in->Get("UseSSL", bUseSSL, context);
			if ( roaParams["HTTPS"].AsBool() || bUseSSL ) {
				s = new (Storage::Global()) SSLClientSocket((SSL_CTX *)context.Lookup("SSLContext").AsIFAObject(0), socketFd, anyParams, true);
			} else {
				s = new (Storage::Global()) Socket(socketFd, anyParams, true);
			}
		}
	}
	return s;
}

bool ConnectorDAImpl::DoExec(Socket *pSocket, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.DoExec);
	long lSocketStreamTimeout = 30L, lCheckReadyTimeout = 30L, lSocketTimeout = 300L;
	bool bTcpNoDelay = true;
	in->Get("SocketTimeout", lSocketTimeout, context);
	in->Get("SocketStreamTimeout", lSocketStreamTimeout, context);
	in->Get("CheckReadyTimeout", lCheckReadyTimeout, context);
	in->Get("TcpNoDelay", bTcpNoDelay, context);
	lSocketTimeout *= 1000L;
	lSocketStreamTimeout *= 1000L;
	lCheckReadyTimeout *= 1000L;
	iostream *pIos = NULL;
	if ( pSocket ) {
		if ( bTcpNoDelay ) {
			pSocket->SetNoDelay();
		}
		pSocket->SetTimeout(lSocketTimeout);
		pIos = pSocket->GetStream();
	}
	if ( pIos == NULL ) {
		return HandleError(pSocket, "connection to: ", context, in, out);
	}
	{
		DAAccessTimer(ConnectorDAImpl.DoExec, "writing", context);
		if ( !SendInput(pIos, pSocket, lCheckReadyTimeout, lSocketStreamTimeout, context, in, out) || !(*pIos)) {
			return false;
		}
	}
	{
		DAAccessTimer(ConnectorDAImpl.DoExec, "reading", context);
		long lRetCode = 0L;
		Trace("waiting on ReadyForReading, CheckReadyTimeout:" << lCheckReadyTimeout);
		if ( pSocket->IsReadyForReading(lCheckReadyTimeout, lRetCode) ) {
			Trace("waiting on output from other party, SocketStreamTimeout:" << lSocketStreamTimeout);
			DiffTimer aReadTimer;
			TimeoutModifier aTimeoutModifier((SocketStream *) pIos, lSocketStreamTimeout);
			aTimeoutModifier.Use();
			if ( out->Put("Output", *pIos, context) ) {
				return true;
			} else {
				String strError("put into Output slot took ");
				strError << (long)aReadTimer.Diff() << "ms from: ";
				HandleError(pSocket, strError, context, in, out);
			}
		} else {
			String strError("not ready for reading");
			if ( lRetCode == 0 ) {
				strError << " after " << lCheckReadyTimeout << "s";
			}
			strError << " from: ";
			HandleError(pSocket, strError, context, in, out);
		}
	}
	return false;
}

bool ConnectorDAImpl::SendInput(iostream *pIos, Socket *s, long lCheckReadyTimeout, long lSocketStreamTimeout, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.SendInput);

	if ( pIos ) {
		long lRetCode = 0L;
		Trace("waiting on ReadyForWriting, CheckReadyTimeout:" << lCheckReadyTimeout);
		if ( s->IsReadyForWriting(lCheckReadyTimeout, lRetCode) ) {
			Trace("writing input to other party, SocketStreamTimeout:" << lSocketStreamTimeout);
			TimeoutModifier aTimeoutModifier((SocketStream *) pIos, lSocketStreamTimeout);
			aTimeoutModifier.Use();
			bool retCode = in->Get("Input", *pIos, context);
			pIos->flush();
			Trace("input sent and stream flushed");
			if (retCode) {
				Trace("returning true");
				return true;
			}
			HandleError(s, "sending request to: ", context, in, out);
		} else {
			String strError("not ready for writing");
			if ( lRetCode == 0 ) {
				strError << " after " << lCheckReadyTimeout << "s";
			}
			strError << " to: ";
			HandleError(s, strError, context, in, out);
		}
	}
	return false;
}

bool ConnectorDAImpl::HandleError( Socket *s, const char *streamText, Context &context, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(ConnectorDAImpl.HandleError);
	Trace(" Errortext to use : " << streamText);

	String strBuf;
	{
		OStringStream stream(strBuf);
		stream << streamText;
		s->ClientInfo().PrintOn(stream) << " failed!";
		stream.flush();
	}
	out->Put("Error", strBuf, context);
	SYSERROR(strBuf);

	return false;
}
<|endoftext|>


<commit_before>/* Copyright 2018 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/compiler/xla/service/gpu/cudnn_conv_pad_for_tensor_cores.h"

#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/tests/hlo_verified_test_base.h"
#include "tensorflow/compiler/xla/util.h"

namespace xla {
namespace gpu {
namespace {

namespace op = xla::testing::opcode_matchers;
using ::testing::_;

class CudnnConvPadForTensorCoresTest : public HloVerifiedTestBase {};

TEST_F(CudnnConvPadForTensorCoresTest, PadF16ForwardConvInputChannels) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,41] parameter(0)
    filter = f16[2,2,41,40] parameter(1)
    ROOT result = (f16[10,20,30,40], u8[0]) custom-call(input, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convForward"
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();

  SCOPED_TRACE(module().ToString());
  EXPECT_THAT(root, op::CustomCall(kCudnnConvForwardCallTarget,
                                   op::Pad(op::Parameter(0), _),
                                   op::Pad(op::Parameter(1), _)));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(0)->shape(),
                               ShapeUtil::MakeShape(F16, {10, 20, 30, 48})));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(1)->shape(),
                               ShapeUtil::MakeShape(F16, {2, 2, 48, 40})));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardInputConvOutputChannels) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    output = f16[10,20,30,41] parameter(0)
    filter = f16[2,2,40,41] parameter(1)
    ROOT result = (f16[10,20,30,40], u8[0]) custom-call(output, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convBackwardInput"
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();
  EXPECT_THAT(root, op::CustomCall(kCudnnConvBackwardInputCallTarget,
                                   op::Pad(op::Parameter(0), _),
                                   op::Pad(op::Parameter(1), _)));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(0)->shape(),
                               ShapeUtil::MakeShape(F16, {10, 20, 30, 48})));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(1)->shape(),
                               ShapeUtil::MakeShape(F16, {2, 2, 40, 48})));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16ForwardConvOutputChannels) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,40] parameter(0)
    filter = f16[2,2,40,41] parameter(1)
    ROOT result = (f16[10,20,30,41], u8[0]) custom-call(input, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convForward"
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();
  EXPECT_THAT(root, op::Tuple(op::Slice(op::GetTupleElement(op::CustomCall(
                                  kCudnnConvForwardCallTarget, op::Parameter(0),
                                  op::Pad(op::Parameter(1), _)))),
                              _));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardInputConvInputChannels) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    output = f16[10,20,30,40] parameter(0)
    filter = f16[2,2,41,40] parameter(1)
    result = (f16[10,20,30,41], u8[0]) custom-call(output, filter),
              window={size=2x2}, dim_labels=b01f_01io->b01f,
              custom_call_target="__cudnn$convBackwardInput"
    ROOT gte = f16[10,20,30,41] get-tuple-element(result), index=0
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();
  EXPECT_THAT(root, op::GetTupleElement(op::Tuple(
                        op::Slice(op::GetTupleElement(op::CustomCall(
                            kCudnnConvBackwardInputCallTarget, op::Parameter(0),
                            op::Pad(op::Parameter(1), _)))),
                        _)));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardFilterConvInputChannels) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,41] parameter(0)
    output = f16[10,20,30,40] parameter(1)
    result = (f16[2,2,41,40], u8[0]) custom-call(input, output),
              window={size=2x2}, dim_labels=b01f_01io->b01f,
              custom_call_target="__cudnn$convBackwardFilter"
    ROOT gte = f16[2,2,41,40] get-tuple-element(result), index=0
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();
  EXPECT_THAT(root, op::GetTupleElement(op::Tuple(
                        op::Slice(op::GetTupleElement(op::CustomCall(
                            kCudnnConvBackwardFilterCallTarget,
                            op::Pad(op::Parameter(0), _), op::Parameter(1)))),
                        _)));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardFilterConvOutputChannels) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,40] parameter(0)
    output = f16[10,20,30,41] parameter(1)
    result = (f16[2,2,40,41], u8[0]) custom-call(input, output),
              window={size=2x2}, dim_labels=b01f_01io->b01f,
              custom_call_target="__cudnn$convBackwardFilter"
    ROOT gte = f16[2,2,40,41] get-tuple-element(result), index=0
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();
  EXPECT_THAT(root, op::GetTupleElement(op::Tuple(
                        op::Slice(op::GetTupleElement(op::CustomCall(
                            kCudnnConvBackwardFilterCallTarget,
                            op::Parameter(0), op::Pad(op::Parameter(1), _)))),
                        _)));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadInputFeatures3To4) {
  ParseAndVerifyModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,3] parameter(0)
    filter = f16[2,2,3,32] parameter(1)
    ROOT result = (f16[10,20,30,32], u8[0]) custom-call(input, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convForward"
  })");
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(&module()).ValueOrDie());
  auto* root = module().entry_computation()->root_instruction();

  SCOPED_TRACE(module().ToString());
  EXPECT_THAT(root, op::CustomCall(kCudnnConvForwardCallTarget,
                                   op::Pad(op::Parameter(0), _),
                                   op::Pad(op::Parameter(1), _)));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(0)->shape(),
                               ShapeUtil::MakeShape(F16, {10, 20, 30, 4})));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(1)->shape(),
                               ShapeUtil::MakeShape(F16, {2, 2, 4, 32})));
}

}  // anonymous namespace
}  // namespace gpu
}  // namespace xla
<commit_msg>[XLA:GPU] Use HloVerifiedModule in cudnn_conv_pad_for_tensor_cores_test.<commit_after>/* Copyright 2018 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/compiler/xla/service/gpu/cudnn_conv_pad_for_tensor_cores.h"

#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/tests/hlo_verified_test_base.h"
#include "tensorflow/compiler/xla/util.h"

namespace xla {
namespace gpu {
namespace {

namespace op = xla::testing::opcode_matchers;
using ::testing::_;

class CudnnConvPadForTensorCoresTest : public HloVerifiedTestBase {};

TEST_F(CudnnConvPadForTensorCoresTest, PadF16ForwardConvInputChannels) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,41] parameter(0)
    filter = f16[2,2,41,40] parameter(1)
    ROOT result = (f16[10,20,30,40], u8[0]) custom-call(input, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convForward"
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();

  SCOPED_TRACE(module->ToString());
  EXPECT_THAT(root, op::CustomCall(kCudnnConvForwardCallTarget,
                                   op::Pad(op::Parameter(0), _),
                                   op::Pad(op::Parameter(1), _)));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(0)->shape(),
                               ShapeUtil::MakeShape(F16, {10, 20, 30, 48})));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(1)->shape(),
                               ShapeUtil::MakeShape(F16, {2, 2, 48, 40})));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardInputConvOutputChannels) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    output = f16[10,20,30,41] parameter(0)
    filter = f16[2,2,40,41] parameter(1)
    ROOT result = (f16[10,20,30,40], u8[0]) custom-call(output, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convBackwardInput"
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();
  EXPECT_THAT(root, op::CustomCall(kCudnnConvBackwardInputCallTarget,
                                   op::Pad(op::Parameter(0), _),
                                   op::Pad(op::Parameter(1), _)));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(0)->shape(),
                               ShapeUtil::MakeShape(F16, {10, 20, 30, 48})));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(1)->shape(),
                               ShapeUtil::MakeShape(F16, {2, 2, 40, 48})));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16ForwardConvOutputChannels) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,40] parameter(0)
    filter = f16[2,2,40,41] parameter(1)
    ROOT result = (f16[10,20,30,41], u8[0]) custom-call(input, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convForward"
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();
  EXPECT_THAT(root, op::Tuple(op::Slice(op::GetTupleElement(op::CustomCall(
                                  kCudnnConvForwardCallTarget, op::Parameter(0),
                                  op::Pad(op::Parameter(1), _)))),
                              _));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardInputConvInputChannels) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    output = f16[10,20,30,40] parameter(0)
    filter = f16[2,2,41,40] parameter(1)
    result = (f16[10,20,30,41], u8[0]) custom-call(output, filter),
              window={size=2x2}, dim_labels=b01f_01io->b01f,
              custom_call_target="__cudnn$convBackwardInput"
    ROOT gte = f16[10,20,30,41] get-tuple-element(result), index=0
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();
  EXPECT_THAT(root, op::GetTupleElement(op::Tuple(
                        op::Slice(op::GetTupleElement(op::CustomCall(
                            kCudnnConvBackwardInputCallTarget, op::Parameter(0),
                            op::Pad(op::Parameter(1), _)))),
                        _)));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardFilterConvInputChannels) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,41] parameter(0)
    output = f16[10,20,30,40] parameter(1)
    result = (f16[2,2,41,40], u8[0]) custom-call(input, output),
              window={size=2x2}, dim_labels=b01f_01io->b01f,
              custom_call_target="__cudnn$convBackwardFilter"
    ROOT gte = f16[2,2,41,40] get-tuple-element(result), index=0
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();
  EXPECT_THAT(root, op::GetTupleElement(op::Tuple(
                        op::Slice(op::GetTupleElement(op::CustomCall(
                            kCudnnConvBackwardFilterCallTarget,
                            op::Pad(op::Parameter(0), _), op::Parameter(1)))),
                        _)));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadF16BackwardFilterConvOutputChannels) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,40] parameter(0)
    output = f16[10,20,30,41] parameter(1)
    result = (f16[2,2,40,41], u8[0]) custom-call(input, output),
              window={size=2x2}, dim_labels=b01f_01io->b01f,
              custom_call_target="__cudnn$convBackwardFilter"
    ROOT gte = f16[2,2,40,41] get-tuple-element(result), index=0
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();
  EXPECT_THAT(root, op::GetTupleElement(op::Tuple(
                        op::Slice(op::GetTupleElement(op::CustomCall(
                            kCudnnConvBackwardFilterCallTarget,
                            op::Parameter(0), op::Pad(op::Parameter(1), _)))),
                        _)));
}

TEST_F(CudnnConvPadForTensorCoresTest, PadInputFeatures3To4) {
  auto module = ParseAndReturnVerifiedModule(R"(
  HloModule TestModule

  ENTRY TestComputation {
    input = f16[10,20,30,3] parameter(0)
    filter = f16[2,2,3,32] parameter(1)
    ROOT result = (f16[10,20,30,32], u8[0]) custom-call(input, filter),
                  window={size=2x2}, dim_labels=b01f_01io->b01f,
                  custom_call_target="__cudnn$convForward"
  })")
                    .ValueOrDie();
  EXPECT_TRUE(CudnnConvPadForTensorCores().Run(module.get()).ValueOrDie());
  auto* root = module->entry_computation()->root_instruction();

  SCOPED_TRACE(module->ToString());
  EXPECT_THAT(root, op::CustomCall(kCudnnConvForwardCallTarget,
                                   op::Pad(op::Parameter(0), _),
                                   op::Pad(op::Parameter(1), _)));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(0)->shape(),
                               ShapeUtil::MakeShape(F16, {10, 20, 30, 4})));
  EXPECT_TRUE(ShapeUtil::Equal(root->operand(1)->shape(),
                               ShapeUtil::MakeShape(F16, {2, 2, 4, 32})));
}

}  // anonymous namespace
}  // namespace gpu
}  // namespace xla
<|endoftext|>


<commit_before>/* Copyright 2022 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_lite_support/cc/task/audio/audio_embedder.h"

#include "pybind11/pybind11.h"
#include "pybind11_abseil/status_casters.h"  // from @pybind11_abseil
#include "pybind11_protobuf/native_proto_caster.h"  // from @pybind11_protobuf
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/cc/task/audio/core/audio_buffer.h"
#include "tensorflow_lite_support/python/task/core/pybinds/task_utils.h"

namespace tflite {
namespace task {
namespace audio {

namespace {
namespace py = ::pybind11;
using PythonBaseOptions = ::tflite::python::task::core::BaseOptions;
using CppBaseOptions = ::tflite::task::core::BaseOptions;
}  // namespace

PYBIND11_MODULE(_pywrap_audio_embedder, m) {
  // python wrapper for C++ AudioEmbedder class which shouldn't be directly used
  // by the users.
  pybind11::google::ImportStatusModule();
  pybind11_protobuf::ImportNativeProtoCasters();

  py::class_<AudioEmbedder>(m, "AudioEmbedder")
      .def_static(
          "create_from_options",
		  [](const PythonBaseOptions& base_options,
		     const processor::EmbeddingOptions& embedding_options) {
		      AudioEmbedderOptions options;
		      auto cpp_base_options =
		          core::convert_to_cpp_base_options(base_options);

		      options.set_allocated_base_options(cpp_base_options.release());
		      options.add_embedding_options()->CopyFrom(embedding_options);
		      return AudioEmbedder::CreateFromOptions(options);
		  })
      .def_static("cosine_similarity", &AudioEmbedder::CosineSimilarity)
      .def("embed",
          [](AudioEmbedder& self, const AudioBuffer& audio)
              -> tflite::support::StatusOr<
                           tflite::task::processor::EmbeddingResult> {
               return self.Embed(audio);
           })
      .def("get_embedding_dimension", &AudioEmbedder::GetEmbeddingDimension)
      .def("get_number_of_output_layers",
           &AudioEmbedder::GetNumberOfOutputLayers)
      .def("get_required_audio_format",
           &AudioEmbedder::GetRequiredAudioFormat)
      .def("get_required_input_buffer_size",
           &AudioEmbedder::GetRequiredInputBufferSize);
}

}  // namespace vision
}  // namespace task
}  // namespace tflite
<commit_msg>Simplified a binding in pybinds<commit_after>/* Copyright 2022 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_lite_support/cc/task/audio/audio_embedder.h"

#include "pybind11/pybind11.h"
#include "pybind11_abseil/status_casters.h"  // from @pybind11_abseil
#include "pybind11_protobuf/native_proto_caster.h"  // from @pybind11_protobuf
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/cc/task/audio/core/audio_buffer.h"
#include "tensorflow_lite_support/python/task/core/pybinds/task_utils.h"

namespace tflite {
namespace task {
namespace audio {

namespace {
namespace py = ::pybind11;
using PythonBaseOptions = ::tflite::python::task::core::BaseOptions;
using CppBaseOptions = ::tflite::task::core::BaseOptions;
}  // namespace

PYBIND11_MODULE(_pywrap_audio_embedder, m) {
  // python wrapper for C++ AudioEmbedder class which shouldn't be directly used
  // by the users.
  pybind11::google::ImportStatusModule();
  pybind11_protobuf::ImportNativeProtoCasters();

  py::class_<AudioEmbedder>(m, "AudioEmbedder")
      .def_static(
          "create_from_options",
		  [](const PythonBaseOptions& base_options,
		     const processor::EmbeddingOptions& embedding_options) {
		      AudioEmbedderOptions options;
		      auto cpp_base_options =
		          core::convert_to_cpp_base_options(base_options);

		      options.set_allocated_base_options(cpp_base_options.release());
		      options.add_embedding_options()->CopyFrom(embedding_options);
		      return AudioEmbedder::CreateFromOptions(options);
		  })
      .def_static("cosine_similarity", &AudioEmbedder::CosineSimilarity)
      .def("embed", &AudioEmbedder::Embed)
      .def("get_embedding_dimension", &AudioEmbedder::GetEmbeddingDimension)
      .def("get_number_of_output_layers",
           &AudioEmbedder::GetNumberOfOutputLayers)
      .def("get_required_audio_format",
           &AudioEmbedder::GetRequiredAudioFormat)
      .def("get_required_input_buffer_size",
           &AudioEmbedder::GetRequiredInputBufferSize);
}

}  // namespace vision
}  // namespace task
}  // namespace tflite
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "code/ylikuutio/geometry/line2D.hpp"
#include "code/ylikuutio/linear_algebra/matrix.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector>   // std::vector

TEST(line2D_must_be_defined_as_expected, line2D_std_vector_float_x1_0_y1_0_x2_1_y2_1)
{
    std::vector<float> point1;
    point1.push_back(0.0f); // x = 0.0
    point1.push_back(0.0f); // y = 0.0

    std::vector<float> point2;
    point2.push_back(1.0f); // x = 1.0
    point2.push_back(1.0f); // y = 1.0

    geometry::Line2D line1 = geometry::Line2D(point1, point2);
    ASSERT_EQ(line1.x1, 0.0f);
    ASSERT_EQ(line1.y1, 0.0f);
    ASSERT_EQ(line1.x2, 1.0f);
    ASSERT_EQ(line1.y2, 1.0f);
    ASSERT_EQ(line1.x1_minus_x2, -1.0f);
    ASSERT_EQ(line1.y1_minus_y2, -1.0f);
    ASSERT_EQ(line1.determinant, 0.0f);

    geometry::Line2D line2 = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
    ASSERT_EQ(line2.determinant, 0.0f);
}
TEST(line2D_must_be_defined_as_expected, line2D_glm_vec2_x1_0_y1_0_x2_1_y2_1)
{
    glm::vec2 point1 = glm::vec2(0.0f, 0.0f); // x = 0.0, y = 0.0
    glm::vec2 point2 = glm::vec2(1.0f, 1.0f); // x = 1.0, y = 1.0

    geometry::Line2D line1 = geometry::Line2D(point1, point2);
    ASSERT_EQ(line1.x1, 0.0f);
    ASSERT_EQ(line1.y1, 0.0f);
    ASSERT_EQ(line1.x2, 1.0f);
    ASSERT_EQ(line1.y2, 1.0f);
    ASSERT_EQ(line1.x1_minus_x2, -1.0f);
    ASSERT_EQ(line1.y1_minus_y2, -1.0f);
    ASSERT_EQ(line1.determinant, 0.0f);
}
TEST(lines2D_defined_with_std_vector_float_and_glm_vec2_must_be_identical, x1_0_y1_0_x2_1_y2_1)
{
    geometry::Line2D line_std_vector_float = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
    geometry::Line2D line_glm_vec2 = geometry::Line2D(glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f));
    ASSERT_TRUE(line_std_vector_float.is_identical_with(&line_glm_vec2));
    ASSERT_TRUE(line_glm_vec2.is_identical_with(&line_std_vector_float));
}
TEST(line2D_must_be_defined_as_expected, line2D_x1_340_y1_150_x2_100_y2_50)
{
    std::vector<float> point1;
    float x1 = 340.0f;
    float y1 = 150.0f;
    point1.push_back(x1); // x = 340.0
    point1.push_back(y1); // y = 150.0

    std::vector<float> point2;
    float x2 = 100.0f;
    float y2 = 50.0f;
    point2.push_back(x2); // x = 100.0
    point2.push_back(y2); // y = 50.0

    geometry::Line2D* line1 = new geometry::Line2D(point1, point2);
    geometry::Line2D* line2 = new geometry::Line2D(std::vector<float>{ x1, y1 }, std::vector<float>{ x2, y2 });
    ASSERT_TRUE(line1->is_identical_with(line2));
    ASSERT_EQ(line1->determinant, 2000.0f);
    delete line1;
    delete line2;
}
<commit_msg>`test_line2D.cpp`: more tests.<commit_after>#include "gtest/gtest.h"
#include "code/ylikuutio/geometry/line2D.hpp"
#include "code/ylikuutio/linear_algebra/matrix.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector>   // std::vector

TEST(line2D_must_be_defined_as_expected, line2D_std_vector_float_x1_0_y1_0_x2_1_y2_1)
{
    std::vector<float> point1;
    point1.push_back(0.0f); // x = 0.0
    point1.push_back(0.0f); // y = 0.0

    std::vector<float> point2;
    point2.push_back(1.0f); // x = 1.0
    point2.push_back(1.0f); // y = 1.0

    geometry::Line2D line1 = geometry::Line2D(point1, point2);
    ASSERT_EQ(line1.x1, 0.0f);
    ASSERT_EQ(line1.y1, 0.0f);
    ASSERT_EQ(line1.x2, 1.0f);
    ASSERT_EQ(line1.y2, 1.0f);
    ASSERT_EQ(line1.x1_minus_x2, -1.0f);
    ASSERT_EQ(line1.y1_minus_y2, -1.0f);
    ASSERT_EQ(line1.determinant, 0.0f);

    geometry::Line2D line2 = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
    ASSERT_EQ(line2.determinant, 0.0f);
}
TEST(line2D_must_be_defined_as_expected, line2D_glm_vec2_x1_0_y1_0_x2_1_y2_1)
{
    glm::vec2 point1 = glm::vec2(0.0f, 0.0f); // x = 0.0, y = 0.0
    glm::vec2 point2 = glm::vec2(1.0f, 1.0f); // x = 1.0, y = 1.0

    geometry::Line2D line1 = geometry::Line2D(point1, point2);
    ASSERT_EQ(line1.x1, 0.0f);
    ASSERT_EQ(line1.y1, 0.0f);
    ASSERT_EQ(line1.x2, 1.0f);
    ASSERT_EQ(line1.y2, 1.0f);
    ASSERT_EQ(line1.x1_minus_x2, -1.0f);
    ASSERT_EQ(line1.y1_minus_y2, -1.0f);
    ASSERT_EQ(line1.determinant, 0.0f);
}
TEST(lines2D_defined_with_std_vector_float_and_glm_vec2_must_be_identical, x1_0_y1_0_x2_0_y2_1)
{
    geometry::Line2D line_std_vector_float = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 0.0f, 1.0f });
    geometry::Line2D line_glm_vec2 = geometry::Line2D(glm::vec2(0.0f, 0.0f), glm::vec2(0.0f, 1.0f));
    ASSERT_TRUE(line_std_vector_float.is_identical_with(&line_glm_vec2));
    ASSERT_TRUE(line_glm_vec2.is_identical_with(&line_std_vector_float));
}
TEST(lines2D_defined_with_std_vector_float_and_glm_vec2_must_be_identical, x1_0_y1_0_x2_1_y2_0)
{
    geometry::Line2D line_std_vector_float = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 0.0f });
    geometry::Line2D line_glm_vec2 = geometry::Line2D(glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 0.0f));
    ASSERT_TRUE(line_std_vector_float.is_identical_with(&line_glm_vec2));
    ASSERT_TRUE(line_glm_vec2.is_identical_with(&line_std_vector_float));
}
TEST(lines2D_defined_with_std_vector_float_and_glm_vec2_must_be_identical, x1_0_y1_0_x2_1_y2_1)
{
    geometry::Line2D line_std_vector_float = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
    geometry::Line2D line_glm_vec2 = geometry::Line2D(glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f));
    ASSERT_TRUE(line_std_vector_float.is_identical_with(&line_glm_vec2));
    ASSERT_TRUE(line_glm_vec2.is_identical_with(&line_std_vector_float));
}
TEST(line2D_must_be_defined_as_expected, line2D_x1_340_y1_150_x2_100_y2_50)
{
    std::vector<float> point1;
    float x1 = 340.0f;
    float y1 = 150.0f;
    point1.push_back(x1); // x = 340.0
    point1.push_back(y1); // y = 150.0

    std::vector<float> point2;
    float x2 = 100.0f;
    float y2 = 50.0f;
    point2.push_back(x2); // x = 100.0
    point2.push_back(y2); // y = 50.0

    geometry::Line2D* line1 = new geometry::Line2D(point1, point2);
    geometry::Line2D* line2 = new geometry::Line2D(std::vector<float>{ x1, y1 }, std::vector<float>{ x2, y2 });
    ASSERT_TRUE(line1->is_identical_with(line2));
    ASSERT_EQ(line1->determinant, 2000.0f);
    delete line1;
    delete line2;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: weakeventlistener.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef COMPHELPER_WEAKEVENTLISTENER_HXX
#define COMPHELPER_WEAKEVENTLISTENER_HXX

#include <cppuhelper/compbase1.hxx>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/uno/XWeak.hpp>
#include <cppuhelper/weakref.hxx>
#include <comphelper/broadcasthelper.hxx>
#include "comphelper/comphelperdllapi.h"

//.........................................................................
namespace comphelper
{
//.........................................................................

    //=====================================================================
    //= OWeakListenerAdapterBase
    //=====================================================================
    /** (the base for) an adapter which allows to add as listener to a foreign component, without
        being held hard.

The idea is that this adapter is added as listener to a foreign component, which usually
        holds it's listener hard. The adapter itself knows the real listener as weak reference,
        thus not affecting it's life time.

    */
    class OWeakListenerAdapterBase : public OBaseMutex
    {
    private:
        ::com::sun::star::uno::WeakReference< ::com::sun::star::uno::XInterface >
                m_aListener;
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                m_xBroadcaster;

    protected:
        inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                getListener( ) const
        {
            return m_aListener.get();
        }

        inline const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >&
                getBroadcaster( ) const
        {
            return m_xBroadcaster;
        }

        inline void resetListener( )
        {
            m_aListener = ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >();
        }

    protected:
        inline OWeakListenerAdapterBase(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak >& _rxListener,
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxBroadcaster
        )
            :m_aListener    (  _rxListener )
            ,m_xBroadcaster ( _rxBroadcaster )
        {
        }

    protected:
        virtual ~OWeakListenerAdapterBase();
    };

    //=====================================================================
    //= OWeakListenerAdapter
    //=====================================================================
    template< class BROADCASTER, class LISTENER >
    /** yet another base for weak listener adapters, this time with some type safety

Note that derived classes need to overwrite all virtual methods of their interface
        except XEventListener::disposing, and forward it to their master listener.

Addtionally, derived classes need to add themself as listener to the broadcaster,
        as this can't be done in a generic way

    */
    class OWeakListenerAdapter
            :public ::cppu::WeakComponentImplHelper1 < LISTENER >
            ,public OWeakListenerAdapterBase
    {
    protected:
        /** ctor

Note that derived classes still need to add themself as listener to the broadcaster,
            as this can't be done in a generic way

        */
        OWeakListenerAdapter(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak >& _rxListener,
            const ::com::sun::star::uno::Reference< BROADCASTER >& _rxBroadcaster
        );

    protected:
        inline  ::com::sun::star::uno::Reference< LISTENER > getListener( ) const
        {
            return  ::com::sun::star::uno::Reference< LISTENER >( OWeakListenerAdapterBase::getListener(), ::com::sun::star::uno::UNO_QUERY );
        }

        // XEventListener overridables
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    protected:
        // OComponentHelper overridables
        // to be overridden, again - the derived class should revoke the listener from the broadcaster
        virtual void SAL_CALL disposing( ) = 0;
    };

    //=====================================================================
    //= OWeakEventListenerAdapter
    //=====================================================================
    typedef OWeakListenerAdapter    <   ::com::sun::star::lang::XComponent
                                    ,   ::com::sun::star::lang::XEventListener
                                    >   OWeakEventListenerAdapter_Base;
    /** the most simple listener adapter: for XEventListeners at XComponents
    */
    class COMPHELPER_DLLPUBLIC OWeakEventListenerAdapter : public OWeakEventListenerAdapter_Base
    {
    public:
        OWeakEventListenerAdapter(
            ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak > _rxListener,
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > _rxBroadcaster
        );

        // nothing to do except an own ctor - the forwarding of the "disposing" is already done
        // in the base class

    protected:
        using OWeakEventListenerAdapter_Base::disposing;
        virtual void SAL_CALL disposing( );
    };

    //=====================================================================
    //= OWeakListenerAdapter
    //=====================================================================
    //---------------------------------------------------------------------
    template< class BROADCASTER, class LISTENER >
    OWeakListenerAdapter< BROADCASTER, LISTENER >::OWeakListenerAdapter(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak >& _rxListener,
        const ::com::sun::star::uno::Reference< BROADCASTER >& _rxBroadcaster
    )
        : ::cppu::WeakComponentImplHelper1< LISTENER >( m_aMutex )
        , OWeakListenerAdapterBase( _rxListener, _rxBroadcaster )
    {
    }

    //---------------------------------------------------------------------
    template< class BROADCASTER, class LISTENER >
    void SAL_CALL OWeakListenerAdapter< BROADCASTER, LISTENER >::disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException)
    {
        ::com::sun::star::uno::Reference< LISTENER > xListener( getListener() );
        if ( xListener.is() )
            xListener->disposing( _rSource );
    }

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif// COMPHELPER_WEAKEVENTLISTENER_HXX

<commit_msg>swunolocking1: #i108161#: WeakReferenceHelper:  Apple g++ 4.0.1 erroneously believes that it is ambiguous to use  WeakReference<XInterface>::operator=(Reference<XInterface>).  as a workaround, introduce WeakReferenceHelper::clear(), and fix all users.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: weakeventlistener.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef COMPHELPER_WEAKEVENTLISTENER_HXX
#define COMPHELPER_WEAKEVENTLISTENER_HXX

#include <cppuhelper/compbase1.hxx>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/uno/XWeak.hpp>
#include <cppuhelper/weakref.hxx>
#include <comphelper/broadcasthelper.hxx>
#include "comphelper/comphelperdllapi.h"

//.........................................................................
namespace comphelper
{
//.........................................................................

    //=====================================================================
    //= OWeakListenerAdapterBase
    //=====================================================================
    /** (the base for) an adapter which allows to add as listener to a foreign component, without
        being held hard.

The idea is that this adapter is added as listener to a foreign component, which usually
        holds it's listener hard. The adapter itself knows the real listener as weak reference,
        thus not affecting it's life time.

    */
    class OWeakListenerAdapterBase : public OBaseMutex
    {
    private:
        ::com::sun::star::uno::WeakReference< ::com::sun::star::uno::XInterface >
                m_aListener;
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                m_xBroadcaster;

    protected:
        inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                getListener( ) const
        {
            return m_aListener.get();
        }

        inline const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >&
                getBroadcaster( ) const
        {
            return m_xBroadcaster;
        }

        inline void resetListener( )
        {
            m_aListener.clear();
        }

    protected:
        inline OWeakListenerAdapterBase(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak >& _rxListener,
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxBroadcaster
        )
            :m_aListener    (  _rxListener )
            ,m_xBroadcaster ( _rxBroadcaster )
        {
        }

    protected:
        virtual ~OWeakListenerAdapterBase();
    };

    //=====================================================================
    //= OWeakListenerAdapter
    //=====================================================================
    template< class BROADCASTER, class LISTENER >
    /** yet another base for weak listener adapters, this time with some type safety

Note that derived classes need to overwrite all virtual methods of their interface
        except XEventListener::disposing, and forward it to their master listener.

Addtionally, derived classes need to add themself as listener to the broadcaster,
        as this can't be done in a generic way

    */
    class OWeakListenerAdapter
            :public ::cppu::WeakComponentImplHelper1 < LISTENER >
            ,public OWeakListenerAdapterBase
    {
    protected:
        /** ctor

Note that derived classes still need to add themself as listener to the broadcaster,
            as this can't be done in a generic way

        */
        OWeakListenerAdapter(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak >& _rxListener,
            const ::com::sun::star::uno::Reference< BROADCASTER >& _rxBroadcaster
        );

    protected:
        inline  ::com::sun::star::uno::Reference< LISTENER > getListener( ) const
        {
            return  ::com::sun::star::uno::Reference< LISTENER >( OWeakListenerAdapterBase::getListener(), ::com::sun::star::uno::UNO_QUERY );
        }

        // XEventListener overridables
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    protected:
        // OComponentHelper overridables
        // to be overridden, again - the derived class should revoke the listener from the broadcaster
        virtual void SAL_CALL disposing( ) = 0;
    };

    //=====================================================================
    //= OWeakEventListenerAdapter
    //=====================================================================
    typedef OWeakListenerAdapter    <   ::com::sun::star::lang::XComponent
                                    ,   ::com::sun::star::lang::XEventListener
                                    >   OWeakEventListenerAdapter_Base;
    /** the most simple listener adapter: for XEventListeners at XComponents
    */
    class COMPHELPER_DLLPUBLIC OWeakEventListenerAdapter : public OWeakEventListenerAdapter_Base
    {
    public:
        OWeakEventListenerAdapter(
            ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak > _rxListener,
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > _rxBroadcaster
        );

        // nothing to do except an own ctor - the forwarding of the "disposing" is already done
        // in the base class

    protected:
        using OWeakEventListenerAdapter_Base::disposing;
        virtual void SAL_CALL disposing( );
    };

    //=====================================================================
    //= OWeakListenerAdapter
    //=====================================================================
    //---------------------------------------------------------------------
    template< class BROADCASTER, class LISTENER >
    OWeakListenerAdapter< BROADCASTER, LISTENER >::OWeakListenerAdapter(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XWeak >& _rxListener,
        const ::com::sun::star::uno::Reference< BROADCASTER >& _rxBroadcaster
    )
        : ::cppu::WeakComponentImplHelper1< LISTENER >( m_aMutex )
        , OWeakListenerAdapterBase( _rxListener, _rxBroadcaster )
    {
    }

    //---------------------------------------------------------------------
    template< class BROADCASTER, class LISTENER >
    void SAL_CALL OWeakListenerAdapter< BROADCASTER, LISTENER >::disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException)
    {
        ::com::sun::star::uno::Reference< LISTENER > xListener( getListener() );
        if ( xListener.is() )
            xListener->disposing( _rSource );
    }

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif// COMPHELPER_WEAKEVENTLISTENER_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AnyCompareFactory.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 17:05:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"

#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XCOLLATOR_HPP_
#include <com/sun/star/i18n/XCollator.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef __SGI_STL_MAP
#include <map>
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace com::sun::star::lang;
using namespace com::sun::star::i18n;
using namespace rtl;

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

class AnyCompare : public ::cppu::WeakImplHelper1< XAnyCompare >
{
    Reference< XCollator > m_rCollator;

public:
    AnyCompare( Reference< XMultiServiceFactory > xFactory, const Locale& rLocale ) throw()
    {
        m_rCollator = Reference< XCollator >(
                        xFactory->createInstance( OUString::createFromAscii( "com.sun.star.i18n.Collator" ) ),
                        UNO_QUERY );

        m_rCollator->loadDefaultCollator( rLocale,
                                          0 ); //???

    }

    virtual sal_Int16 SAL_CALL compare( const Any& any1, const Any& any2 ) throw(RuntimeException);
};

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

Sequence< rtl::OUString > SAL_CALL AnyCompareFactory_getSupportedServiceNames() throw();
rtl::OUString SAL_CALL AnyCompareFactory_getImplementationName() throw();
Reference< XInterface > SAL_CALL AnyCompareFactory_createInstance(
                const Reference< XMultiServiceFactory > & rSMgr ) throw( Exception );

class AnyCompareFactory : public cppu::WeakImplHelper3< XAnyCompareFactory, XInitialization, XServiceInfo >
{
    Reference< XAnyCompare >            m_rAnyCompare;
    Reference< XMultiServiceFactory >   m_rFactory;
    Locale                              m_Locale;

public:
    AnyCompareFactory( Reference< XMultiServiceFactory > xFactory ) : m_rFactory( xFactory )
    {
    }

    // XAnyCompareFactory
    virtual Reference< XAnyCompare > SAL_CALL createAnyCompareByName ( const OUString& aPropertyName ) throw(::com::sun::star::uno::RuntimeException);

    // XInitialization
    virtual void SAL_CALL initialize( const Sequence< Any >& aArguments )
            throw ( Exception, RuntimeException );

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName(  ) throw(RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(  ) throw(RuntimeException);
};

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

sal_Int16 SAL_CALL AnyCompare::compare( const Any& any1, const Any& any2 ) throw(::com::sun::star::uno::RuntimeException)
{
    sal_Int16 aResult = 0;

    if( m_rCollator.is() )
    {
        OUString aStr1;
        OUString aStr2;

        any1 >>= aStr1;
        any2 >>= aStr2;

        aResult = ( sal_Int16 )m_rCollator->compareString( aStr1, aStr2 );
    }

    return aResult;
}

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

Reference< XAnyCompare > SAL_CALL AnyCompareFactory::createAnyCompareByName( const OUString& aPropertyName ) throw(::com::sun::star::uno::RuntimeException)
{
    // for now only OUString properties compare is implemented
    // so no check for the property name is done

    if( aPropertyName.equals( OUString::createFromAscii( "Title" ) ) )
        return m_rAnyCompare;

    return Reference< XAnyCompare >();
}

void SAL_CALL AnyCompareFactory::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    if( aArguments.getLength() )
    {
        if( aArguments[0] >>= m_Locale )
        {
            m_rAnyCompare = new AnyCompare( m_rFactory, m_Locale );
            return;
        }
    }

    throw IllegalArgumentException( OUString::createFromAscii( "The Any object does not contain Locale!\n" ),
                                    Reference< XInterface >(),
                                    1 );
}

OUString SAL_CALL AnyCompareFactory::getImplementationName(  ) throw( RuntimeException )
{
    return AnyCompareFactory_getImplementationName();
}

sal_Bool SAL_CALL AnyCompareFactory::supportsService( const OUString& ServiceName ) throw(RuntimeException)
{
    rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.NamedPropertyValues" ) );
    return aServiceName == ServiceName;
}

Sequence< OUString > SAL_CALL AnyCompareFactory::getSupportedServiceNames(  ) throw(RuntimeException)
{
    return AnyCompareFactory_getSupportedServiceNames();
}

Sequence< rtl::OUString > SAL_CALL AnyCompareFactory_getSupportedServiceNames() throw()
{
    const rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ucb.AnyCompareFactory" ) );
    const Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
    return aSeq;
}

rtl::OUString SAL_CALL AnyCompareFactory_getImplementationName() throw()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "AnyCompareFactory" ) );
}

Reference< XInterface > SAL_CALL AnyCompareFactory_createInstance(
                const Reference< XMultiServiceFactory > & rSMgr ) throw( Exception )
{
    return (cppu::OWeakObject*)new AnyCompareFactory( rSMgr );
}

<commit_msg>INTEGRATION: CWS fwk77 (1.5.116); FILE MERGED 2007/11/24 10:28:22 pb 1.5.116.2: fix: #i81435# syntax fixed 2007/10/18 12:48:28 mav 1.5.116.1: #i81435# introduce SeekableOutputStream implementation; use new registration<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AnyCompareFactory.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-04 16:36:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"

#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XCOLLATOR_HPP_
#include <com/sun/star/i18n/XCollator.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef __SGI_STL_MAP
#include <map>
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace com::sun::star::lang;
using namespace com::sun::star::i18n;
using namespace rtl;

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

class AnyCompare : public ::cppu::WeakImplHelper1< XAnyCompare >
{
    Reference< XCollator > m_rCollator;

public:
    AnyCompare( Reference< XComponentContext > xContext, const Locale& rLocale ) throw()
    {
        Reference< XMultiComponentFactory > xFactory = xContext->getServiceManager();
        if ( xFactory.is() )
    {
        m_rCollator = Reference< XCollator >(
                xFactory->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.i18n.Collator" ), xContext ),
                        UNO_QUERY );
        m_rCollator->loadDefaultCollator( rLocale,
                                          0 ); //???
        }

    }

    virtual sal_Int16 SAL_CALL compare( const Any& any1, const Any& any2 ) throw(RuntimeException);
};

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

Sequence< rtl::OUString > SAL_CALL AnyCompareFactory_getSupportedServiceNames() throw();
rtl::OUString SAL_CALL AnyCompareFactory_getImplementationName() throw();
Reference< XInterface > SAL_CALL AnyCompareFactory_createInstance(
                const Reference< XComponentContext >& rxContext ) throw( Exception );

class AnyCompareFactory : public cppu::WeakImplHelper3< XAnyCompareFactory, XInitialization, XServiceInfo >
{
    Reference< XAnyCompare >            m_rAnyCompare;
    Reference< XComponentContext >      m_rContext;
    Locale                              m_Locale;

public:
    AnyCompareFactory( Reference< XComponentContext > xContext ) : m_rContext( xContext )
    {}

    // XAnyCompareFactory
    virtual Reference< XAnyCompare > SAL_CALL createAnyCompareByName ( const OUString& aPropertyName ) throw(::com::sun::star::uno::RuntimeException);

    // XInitialization
    virtual void SAL_CALL initialize( const Sequence< Any >& aArguments )
            throw ( Exception, RuntimeException );

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName(  ) throw(RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(  ) throw(RuntimeException);
};

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

sal_Int16 SAL_CALL AnyCompare::compare( const Any& any1, const Any& any2 ) throw(::com::sun::star::uno::RuntimeException)
{
    sal_Int16 aResult = 0;

    if( m_rCollator.is() )
    {
        OUString aStr1;
        OUString aStr2;

        any1 >>= aStr1;
        any2 >>= aStr2;

        aResult = ( sal_Int16 )m_rCollator->compareString( aStr1, aStr2 );
    }

    return aResult;
}

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

Reference< XAnyCompare > SAL_CALL AnyCompareFactory::createAnyCompareByName( const OUString& aPropertyName ) throw(::com::sun::star::uno::RuntimeException)
{
    // for now only OUString properties compare is implemented
    // so no check for the property name is done

    if( aPropertyName.equals( OUString::createFromAscii( "Title" ) ) )
        return m_rAnyCompare;

    return Reference< XAnyCompare >();
}

void SAL_CALL AnyCompareFactory::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    if( aArguments.getLength() )
    {
        if( aArguments[0] >>= m_Locale )
        {
            m_rAnyCompare = new AnyCompare( m_rContext, m_Locale );
            return;
        }
    }

}

OUString SAL_CALL AnyCompareFactory::getImplementationName(  ) throw( RuntimeException )
{
    return AnyCompareFactory_getImplementationName();
}

sal_Bool SAL_CALL AnyCompareFactory::supportsService( const OUString& ServiceName ) throw(RuntimeException)
{
    rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.NamedPropertyValues" ) );
    return aServiceName == ServiceName;
}

Sequence< OUString > SAL_CALL AnyCompareFactory::getSupportedServiceNames(  ) throw(RuntimeException)
{
    return AnyCompareFactory_getSupportedServiceNames();
}

Sequence< rtl::OUString > SAL_CALL AnyCompareFactory_getSupportedServiceNames() throw()
{
    const rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ucb.AnyCompareFactory" ) );
    const Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
    return aSeq;
}

rtl::OUString SAL_CALL AnyCompareFactory_getImplementationName() throw()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "AnyCompareFactory" ) );
}

Reference< XInterface > SAL_CALL AnyCompareFactory_createInstance(
                const Reference< XComponentContext >& rxContext ) throw( Exception )
{
    return (cppu::OWeakObject*)new AnyCompareFactory( rxContext );
}
<|endoftext|>