<commit_before>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.8, packaged on January, 2008.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_product.cpp implementation of the GLC_Product class.

#include "glc_product.h"
#include "glc_part.h"

GLC_Product::GLC_Product(GLC_World *pWorld)
: GLC_Node(pWorld)
{
}

GLC_Product::~GLC_Product()
{
	// Delete Child product
 	QHashIterator<GLC_uint, GLC_Product*> productIterator(m_ChildProducts);
 	while (productIterator.hasNext())
 	{
     	productIterator.next();
     	delete productIterator.value();
 	}
 	m_ChildProducts.clear();

	// Delete Child part
 	QHashIterator<GLC_uint, GLC_Part*> partIterator(m_ChildParts);
 	while (partIterator.hasNext())
 	{
     	partIterator.next();
     	delete partIterator.value();
 	}
 	m_ChildParts.clear();

}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

// return true if product is parent of node
bool GLC_Product::isParentOf(const GLC_uint key) const
{
	return m_ChildProducts.contains(key) || m_ChildParts.contains(key);
}

// Return the child product associated with the key
GLC_Product* GLC_Product::childProduct(const GLC_uint key)
{
	if (m_ChildProducts.contains(key))
	{
		return m_ChildProducts[key];
	}
	else
	{
		return NULL;
	}
}
// Return the child part associated with the key
GLC_Part* GLC_Product::childPart(const GLC_uint key)
{
	if (m_ChildParts.contains(key))
	{
		return m_ChildParts[key];
	}
	else
	{
		return NULL;
	}
}

//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Move the Product with specified matrix
void GLC_Product::move(const GLC_Matrix4x4& matrix)
{
	m_RelativeMatrix= matrix * m_RelativeMatrix;
	m_AbsoluteMatrix= matrix * m_AbsoluteMatrix;

	// Update Childe product Matrix
 	QHashIterator<GLC_uint, GLC_Product*> productIterator(m_ChildProducts);
 	while (productIterator.hasNext())
 	{
     	productIterator.next();
     	productIterator.value()->updateAbsoluteMatrix();
 	}
	// Update Childe part Matrix
 	QHashIterator<GLC_uint, GLC_Part*> partIterator(m_ChildParts);
 	while (partIterator.hasNext())
 	{
     	partIterator.next();
     	partIterator.value()->updateAbsoluteMatrix();
 	}
}

// Add a child product
GLC_Product* GLC_Product::addChildProduct()
{
	GLC_Product* pChild= new GLC_Product(m_pWorld);
	m_ChildProducts.insert(pChild->getID(), pChild);
	pChild->setParent(this);
	return pChild;
}

// Add child part containing specified instance
 GLC_Part* GLC_Product::addChildPart(GLC_Instance& instance)
 {
 	GLC_Part* pChild= new GLC_Part(m_pWorld, instance);
	m_ChildParts.insert(pChild->getID(), pChild);
	pChild->setParent(this);
	return pChild;
 }

 // Remove a child with the specified UID
 bool GLC_Product::removeChild(const GLC_uint id)
 {
 	if (m_ChildProducts.contains(id))
 	{
 		delete m_ChildProducts.take(id);
 		return true;
 	}
 	else if (m_ChildParts.contains(id))
 	{
 		delete m_ChildParts.take(id);
 		return true;

 	}
 	else return false;
 }

// Update Product absolute matrix
void GLC_Product::updateAbsoluteMatrix()
{
	if (NULL != m_pParent)
	{
		m_AbsoluteMatrix= m_pParent->absoluteMatrix() * m_RelativeMatrix;
	}
}

<commit_msg>Add methods to add a list of Childs Product or par part. Add clone method<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.8, packaged on January, 2008.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_product.cpp implementation of the GLC_Product class.

#include "glc_product.h"
#include "glc_part.h"

GLC_Product::GLC_Product(GLC_World *pWorld)
: GLC_Node(pWorld)
{
}

GLC_Product::~GLC_Product()
{
	// Delete Child product
 	QHashIterator<GLC_uint, GLC_Product*> productIterator(m_ChildProducts);
 	while (productIterator.hasNext())
 	{
     	productIterator.next();
     	delete productIterator.value();
 	}
 	m_ChildProducts.clear();

	// Delete Child part
 	QHashIterator<GLC_uint, GLC_Part*> partIterator(m_ChildParts);
 	while (partIterator.hasNext())
 	{
     	partIterator.next();
     	delete partIterator.value();
 	}
 	m_ChildParts.clear();

}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

// return true if product is parent of node
bool GLC_Product::isParentOf(const GLC_uint key) const
{
	return m_ChildProducts.contains(key) || m_ChildParts.contains(key);
}

// Clone the product
GLC_Product* GLC_Product::clone(GLC_World * pWorld) const
{
	GLC_Product* pResult= new GLC_Product(pWorld);
	pResult->setReference(this->m_Ref);
	pResult->addChildProducts(this->childProducts(), pWorld);
	pResult->addChildParts(this->childParts(), pWorld);
	return pResult;
}

// Return the child product associated with the key
GLC_Product* GLC_Product::childProduct(const GLC_uint key)
{
	if (m_ChildProducts.contains(key))
	{
		return m_ChildProducts[key];
	}
	else
	{
		return NULL;
	}
}
// Return the child part associated with the key
GLC_Part* GLC_Product::childPart(const GLC_uint key)
{
	if (m_ChildParts.contains(key))
	{
		return m_ChildParts[key];
	}
	else
	{
		return NULL;
	}
}

//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Move the Product with specified matrix
void GLC_Product::move(const GLC_Matrix4x4& matrix)
{
	m_RelativeMatrix= matrix * m_RelativeMatrix;
	m_AbsoluteMatrix= matrix * m_AbsoluteMatrix;

	// Update Childe product Matrix
 	QHashIterator<GLC_uint, GLC_Product*> productIterator(m_ChildProducts);
 	while (productIterator.hasNext())
 	{
     	productIterator.next();
     	productIterator.value()->updateAbsoluteMatrix();
 	}
	// Update Childe part Matrix
 	QHashIterator<GLC_uint, GLC_Part*> partIterator(m_ChildParts);
 	while (partIterator.hasNext())
 	{
     	partIterator.next();
     	partIterator.value()->updateAbsoluteMatrix();
 	}
}

// Add a new child product
GLC_Product* GLC_Product::addNewChildProduct()
{
	GLC_Product* pChild= new GLC_Product(m_pWorld);
	m_ChildProducts.insert(pChild->getID(), pChild);
	pChild->setParent(this);
	return pChild;
}

// Add child products
void GLC_Product::addChildProducts(QList<GLC_Product*> products, GLC_World* pWorld)
{
	const int max= products.size();
	for (int i= 0; i < max; ++i)
	{
		GLC_Product* pProduct= products[i]->clone(pWorld);
		m_ChildProducts.insert(pProduct->getID(), pProduct);
		pProduct->setParent(this);
	}
}

// Add child part containing specified instance
 GLC_Part* GLC_Product::addChildPart(GLC_Instance& instance)
 {
 	GLC_Part* pChild= new GLC_Part(m_pWorld, instance);
	m_ChildParts.insert(pChild->getID(), pChild);
	pChild->setParent(this);
	return pChild;
 }

 // Add child parts
void GLC_Product::addChildParts(QList<GLC_Part*> parts, GLC_World* pWorld)
{
	const int max= parts.size();
	for (int i= 0; i < max; ++i)
	{
		GLC_Part* pPart= parts[i]->clone(pWorld);
		m_ChildParts.insert(pPart->getID(), pPart);
		pPart->setParent(this);
	}
}

 // Remove a child with the specified UID
 bool GLC_Product::removeChild(const GLC_uint id)
 {
 	if (m_ChildProducts.contains(id))
 	{
 		delete m_ChildProducts.take(id);
 		return true;
 	}
 	else if (m_ChildParts.contains(id))
 	{
 		delete m_ChildParts.take(id);
 		return true;

 	}
 	else return false;
 }

// Update Product absolute matrix
void GLC_Product::updateAbsoluteMatrix()
{
	if (NULL != m_pParent)
	{
		m_AbsoluteMatrix= m_pParent->absoluteMatrix() * m_RelativeMatrix;
	}
}

<|endoftext|>


<commit_before>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.7, packaged on September, 2007.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_texture.cpp implementation of the GLC_Texture class.

#include <QtDebug>
#include "glc_texture.h"
#include "glc_exception.h"

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////

GLC_Texture::GLC_Texture(const QGLContext *pContext, const QString &Filename)
: m_pQGLContext(const_cast<QGLContext*>(pContext))
, m_File(Filename)
, m_TextureID(0)
, m_pTextureImage(new QImage(m_File.fileName()))
{
	if (m_pTextureImage->isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_File.fileName()).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}
}

GLC_Texture::GLC_Texture(const QGLContext *pContext, const QFile &file)
: m_pQGLContext(const_cast<QGLContext*>(pContext))
, m_File(file.fileName())
, m_TextureID(0)
, m_pTextureImage(new QImage(file.fileName()))
{
	if (m_pTextureImage->isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_File.fileName()).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}
}

GLC_Texture::GLC_Texture(const GLC_Texture &TextureToCopy)
: m_pQGLContext(TextureToCopy.m_pQGLContext)
, m_File(TextureToCopy.m_File.fileName())
, m_TextureID(0)
, m_pTextureImage(new QImage(*TextureToCopy.m_pTextureImage))

{
	if (m_pTextureImage->isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_File.fileName()).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}

}

GLC_Texture::~GLC_Texture()
{
	qDebug() << "GLC_Texture::~GLC_Texture Texture ID : " << m_TextureID;
	if (m_TextureID != 0)
	{
		m_pQGLContext->deleteTexture(m_TextureID);
		m_TextureID= 0;
	}
	else
	{
		delete m_pTextureImage;
		m_pTextureImage = NULL;
	}
}
// Load the texture
void GLC_Texture::glLoadTexture(void)
{
	if (m_TextureID == 0)
	{
		m_TextureID= m_pQGLContext->bindTexture(*m_pTextureImage);
		delete m_pTextureImage;
		m_pTextureImage= NULL;
		qDebug() << "GLC_Texture::glcBindTexture Texture ID = " << m_TextureID;
	}
}

// Bind texture in 2D mode
void GLC_Texture::glcBindTexture(void)
{
	if (m_TextureID != 0)
	{
		glBindTexture(GL_TEXTURE_2D, m_TextureID);
	}
	else
	{
		GLC_Exception e("GLC_Texture::glcBindTexture Texture not loaded");
		throw(e);
	}

}

<commit_msg>fix a bug in the copy contructor.<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.7, packaged on September, 2007.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_texture.cpp implementation of the GLC_Texture class.

#include <QtDebug>
#include "glc_texture.h"
#include "glc_exception.h"

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////

GLC_Texture::GLC_Texture(const QGLContext *pContext, const QString &Filename)
: m_pQGLContext(const_cast<QGLContext*>(pContext))
, m_File(Filename)
, m_TextureID(0)
, m_pTextureImage(new QImage(m_File.fileName()))
{
	if (m_pTextureImage->isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_File.fileName()).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}
}

GLC_Texture::GLC_Texture(const QGLContext *pContext, const QFile &file)
: m_pQGLContext(const_cast<QGLContext*>(pContext))
, m_File(file.fileName())
, m_TextureID(0)
, m_pTextureImage(new QImage(file.fileName()))
{
	if (m_pTextureImage->isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_File.fileName()).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}
}

GLC_Texture::GLC_Texture(const GLC_Texture &TextureToCopy)
: m_pQGLContext(TextureToCopy.m_pQGLContext)
, m_File(TextureToCopy.m_File.fileName())
, m_TextureID(0)
, m_pTextureImage(new QImage(TextureToCopy.m_File.fileName()))

{
	if (m_pTextureImage->isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_File.fileName()).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}

}

GLC_Texture::~GLC_Texture()
{
	qDebug() << "GLC_Texture::~GLC_Texture Texture ID : " << m_TextureID;
	if (m_TextureID != 0)
	{
		m_pQGLContext->deleteTexture(m_TextureID);
		m_TextureID= 0;
	}
	else
	{
		delete m_pTextureImage;
		m_pTextureImage = NULL;
	}
}
// Load the texture
void GLC_Texture::glLoadTexture(void)
{
	if (m_TextureID == 0)
	{
		m_TextureID= m_pQGLContext->bindTexture(*m_pTextureImage);
		delete m_pTextureImage;
		m_pTextureImage= NULL;
		qDebug() << "GLC_Texture::glcBindTexture Texture ID = " << m_TextureID;
	}
}

// Bind texture in 2D mode
void GLC_Texture::glcBindTexture(void)
{
	if (m_TextureID != 0)
	{
		glBindTexture(GL_TEXTURE_2D, m_TextureID);
	}
	else
	{
		GLC_Exception e("GLC_Texture::glcBindTexture Texture not loaded");
		throw(e);
	}

}

<|endoftext|>


<commit_before>//  File: tcLaunch.cpp
//      John Manferdelli
//
//  Description: Client for fileServer.
//
//  Copyright (c) 2011, Intel Corporation. Some contributions
//    (c) John Manferdelli.  All rights reserved.
//
// Use, duplication and disclosure of this file and derived works of
// this file are subject to and licensed under the Apache License dated
// January, 2004, (the "License").  This License is contained in the
// top level directory originally provided with the CloudProxy Project.
// Your right to use or distribute this file, or derived works thereof,
// is subject to your being bound by those terms and your use indicates
// consent to those terms.
//
// If you distribute this file (or portions derived therefrom), you must
// include License in or with the file and, in the event you do not include
// the entire License in the file, the file must contain a reference
// to the location of the License.

// ------------------------------------------------------------------------

#include "jlmTypes.h"
#include "logging.h"
#include "tcIO.h"
#include "tcServiceCodes.h"
#include "buffercoding.h"
#include "tinyxml.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <dirent.h>

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
using std::string;
using std::ifstream;
using std::ofstream;
using std::stringstream;
const char* szServerHostAddr= "127.0.0.1";

const char* g_tcioDDName;
int         g_myPid;

// ------------------------------------------------------------------------

void tcBufferprint(tcBuffer* p)
{
    fprintf(g_logFile,
           "Buffer: procid: %ld, req: %ld, size: %ld, status: %ld, orig proc: %ld\n",
           (long int)p->m_procid, (long int)p->m_reqID, (long int)p->m_reqSize,
           (long int)p->m_ustatus, (long int)p->m_origprocid);
}

bool gettcBuf(int fd, int* procid, u32* puReq, u32* pstatus, int* porigprocid,
                         int* paramsize, byte* params)
{
    byte            rgBuf[PADDEDREQ];
    tcBuffer*       pReq= (tcBuffer*) rgBuf;
    int             i;
    int             n;

#ifdef TEST
    fprintf(g_logFile, "gettcBuf outstanding %d\n", fd);
#endif
    n= *paramsize+sizeof(tcBuffer);
    if(n>PADDEDREQ) {
        fprintf(g_logFile, "Buffer too small\n");
        return false;
    }
    i= read(fd, rgBuf, n);
    if(i<0) {
        fprintf(g_logFile, "ReadBufRequest failed in gettcBuf %d %d\n", i, n);
        return false;
    }

#ifdef TEST
    fprintf(g_logFile, "gettcBuf succeeds %d\n", i);
    tcBufferprint((tcBuffer*) rgBuf);
    PrintBytes("Buffer: ", rgBuf, i);
#endif

#ifdef HEADERTEST
    fprintf(g_logFile, "gettcBuf: "); pReq->print();
#endif
    *procid= pReq->m_procid;
    *puReq= pReq->m_reqID;
    *pstatus= pReq->m_ustatus;
    *porigprocid= pReq->m_origprocid;
    i-= sizeof(tcBuffer);
    if(*paramsize<i)
        return false;
    *paramsize= i;
    memcpy(params, &rgBuf[sizeof(tcBuffer)], i);

    return true;
}

bool sendtcBuf(int fd, int procid, u32 uReq, u32 status, int origproc,
                          int paramsize, byte* params)
{
#if 1
    byte            rgBuf[PADDEDREQ];
    tcBuffer*       pReq= (tcBuffer*) rgBuf;
    int             i;
    int             n;

    if(paramsize>(PARAMSIZE)) {
        fprintf(g_logFile, "sendtcBuf buffer too small %d\n", paramsize);
        return false;
    }
    pReq->m_procid= procid;
    pReq->m_reqID= uReq;
    pReq->m_ustatus= status;
    pReq->m_origprocid= origproc;
    pReq->m_reqSize= paramsize;
#ifdef TEST
    fprintf(g_logFile, "sendtcBuf: "); tcBufferprint(pReq);
#endif
    n= paramsize+sizeof(tcBuffer);
    memcpy(&rgBuf[sizeof(tcBuffer)], params, paramsize);
    i= write(fd, rgBuf, n);
    if(i<0) {
        fprintf(g_logFile, "tcChannel::sendtcBuf: Write failed %d\n", i);
        return false;
    }
#endif
    return true;
}

bool startAppfromDeviceDriver(int fd, int* ppid, int argc, char **argv)
{
#if 1
    u32         ustatus;
    u32         ureq;
    int         procid= g_myPid;
    int         origprocid= g_myPid;
    int         size= PARAMSIZE;
    byte        rgBuf[PARAMSIZE];

    if(argc<1) {
        fprintf(g_logFile, "startAppfromDeviceDriver: no argument\n");
        return false;
    }
#ifdef TEST
    int i;
    fprintf(g_logFile, "startAppfromDeviceDriver, %d args\n", argc);
    for(i=0; i<argc;i++) {
        fprintf(g_logFile, "\t%s\n", argv[i]);
    }
    fprintf(g_logFile, "\n");
    fflush(g_logFile);
#endif

    size= encodeTCSERVICESTARTAPPFROMAPP(argv[0], argc-1, argv+1, PARAMSIZE, rgBuf);
    if(size<0) {
        fprintf(g_logFile, "startAppfromDeviceDriver: encodeTCSERVICESTARTAPPFROMAPP failed\n");
        return false;
    }
    if(!sendtcBuf(fd, g_myPid, TCSERVICESTARTAPPFROMAPP, 0, g_myPid, size, rgBuf)) {
        fprintf(g_logFile, "startAppfromDeviceDriver: sendtcBuf for TCSERVICESTARTAPPFROMAPP failed\n");
        return false;
    }
#ifdef TEST
    fprintf(g_logFile, "Sending request %s\n", rgBuf);
#endif
    size= PARAMSIZE;
    if(!gettcBuf(fd, &procid, &ureq, &ustatus, &origprocid, &size, rgBuf)) {
        fprintf(g_logFile, "startAppfromDeviceDriver: gettcBuf for TCSERVICESTARTAPPFROMAPP failed\n");
        return false;
    }
    if(!decodeTCSERVICESTARTAPPFROMTCSERVICE(ppid, rgBuf)) {
        fprintf(g_logFile, "startAppfromDeviceDriver: cant decode childproc\n");
        return false;
    }
#ifdef TEST
    fprintf(g_logFile, "Program created: %d by servicepid %d\n",
          *ppid, g_myPid);
#endif
#endif
    return true;
}

int initLinuxService()
{
#ifdef TEST
        fprintf(g_logFile, "initLinuxService device %s\n", g_tcioDDName);
#endif

    int fd= open(g_tcioDDName, O_RDWR);
        if(fd<0) {
            fprintf(g_logFile, "Can't open device driver %s\n", g_tcioDDName);
            return -1;
        }

#ifdef TEST
    fprintf(g_logFile, "initLinuxService returns %d\n", fd);
#endif
    return fd;
}

// -------------------------------------------------------------------------

#define MAXPROGNAME 512

char* programNamefromFileName(const char* fileName)
{
    char*   p= (char*) fileName;
    char*   q;
    char*   r;
    char    progNameBuf[MAXPROGNAME];

    if(fileName==NULL)
        return NULL;
#ifdef TEST
    fprintf(g_logFile, "fileName: %s\n", fileName);
#endif
    while(*p!='\0')
        p++;
    q= p-1;
    while((--p)!=fileName) {
        if(*p=='/') {
            break;
        }
        if(*p=='.') {
            break;
        }
    }

    if(*p=='/') {
        r= p+1;
    }
    else if(*p=='.') {
        q= p-1;
        r= q;
        while(r>=fileName) {
            if(*r=='/')
                break;
            r--;
        }
    }
    else {
        r= (char*)fileName-1;
    }
    if((q-r)>=(MAXPROGNAME-1))
        return NULL;
    r++;
    p= progNameBuf;
    while(r<=q)
        *(p++)= *(r++);
    *p= '\0';
    q= strdup(progNameBuf);
#ifdef TEST
    fprintf(g_logFile, "fileName: %s, progname: %s\n", fileName, q);
#endif
    return q;
}

int main(int an, char** av)
{
    int         i;
    int         newan= an;
    char**      newav= av;

    for(i=0;i<an;i++) {
      if(strcmp(av[i],"-help")==0) {
        fprintf(g_logFile,
         "tcLaunch.exe [-KVMHost |-KVMGuest | -LinuxHost]  KVNImage/ProcessImage remainingargs\n");
        return 0;
      }
      if(strcmp(av[i],"-KVMHost")==0) {
        // g_tcioDDName= "/dev/kvmtciodd0";
        g_tcioDDName= "/dev/tcioDD0";
        newan--;
        newav++;
      }
      else if(strcmp(av[i],"-KVMGuest")==0) {
        g_tcioDDName= "/dev/ktciodd0";
        newan--;
        newav++;
      }
      else if(strcmp(av[i],"-LinuxHost")==0) {
        g_tcioDDName= "/dev/tcioDD0";
        newan--;
        newav++;
      }
      else {
        g_tcioDDName= "/dev/tcioDD0";
      }
    }

    g_myPid= getpid();

#ifdef  TEST
    initLog(NULL);
    fprintf(g_logFile, "tcLaunch test %s, %d\n", g_tcioDDName, g_myPid);
    fflush(g_logFile);
#endif

    int fd= initLinuxService();
    if(fd<0) {
        fprintf(g_logFile, "tcLaunch: can't open tcio device driver\n");
        return 1;
    }

    if(newan<1) {
        fprintf(g_logFile, "tcLaunch: too few arguments\n");
        return 1;
    }
    newav[0]= newav[1];
    newav[1]= programNamefromFileName(newav[0]);
    newan= 2;

    int   handle= 0;
    if(startAppfromDeviceDriver(fd, &handle, newan, newav))
        fprintf(g_logFile, "tcLaunch: measured program started, id: %d, exiting\n",
                        handle);
    else
        fprintf(g_logFile, "tcLaunch: program not started due to error\n");
    fflush(g_logFile);
    close(fd);
    closeLog();
    return 0;
}

// ------------------------------------------------------------------------

<commit_msg>kvmtcService successfully starts kvm guest<commit_after>//  File: tcLaunch.cpp
//      John Manferdelli
//
//  Description: Client for fileServer.
//
//  Copyright (c) 2011, Intel Corporation. Some contributions
//    (c) John Manferdelli.  All rights reserved.
//
// Use, duplication and disclosure of this file and derived works of
// this file are subject to and licensed under the Apache License dated
// January, 2004, (the "License").  This License is contained in the
// top level directory originally provided with the CloudProxy Project.
// Your right to use or distribute this file, or derived works thereof,
// is subject to your being bound by those terms and your use indicates
// consent to those terms.
//
// If you distribute this file (or portions derived therefrom), you must
// include License in or with the file and, in the event you do not include
// the entire License in the file, the file must contain a reference
// to the location of the License.

// ------------------------------------------------------------------------

#include "jlmTypes.h"
#include "logging.h"
#include "tcIO.h"
#include "tcServiceCodes.h"
#include "buffercoding.h"
#include "tinyxml.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <dirent.h>

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
using std::string;
using std::ifstream;
using std::ofstream;
using std::stringstream;
const char* szServerHostAddr= "127.0.0.1";

const char* g_tcioDDName;
int         g_myPid;

// ------------------------------------------------------------------------

void tcBufferprint(tcBuffer* p)
{
    fprintf(g_logFile,
           "Buffer: procid: %ld, req: %ld, size: %ld, status: %ld, orig proc: %ld\n",
           (long int)p->m_procid, (long int)p->m_reqID, (long int)p->m_reqSize,
           (long int)p->m_ustatus, (long int)p->m_origprocid);
}

bool gettcBuf(int fd, int* procid, u32* puReq, u32* pstatus, int* porigprocid,
                         int* paramsize, byte* params)
{
    byte            rgBuf[PADDEDREQ];
    tcBuffer*       pReq= (tcBuffer*) rgBuf;
    int             i;
    int             n;

#ifdef TEST
    fprintf(g_logFile, "gettcBuf outstanding %d\n", fd);
#endif
    n= *paramsize+sizeof(tcBuffer);
    if(n>PADDEDREQ) {
        fprintf(g_logFile, "Buffer too small\n");
        return false;
    }
    i= read(fd, rgBuf, n);
    if(i<0) {
        fprintf(g_logFile, "ReadBufRequest failed in gettcBuf %d %d\n", i, n);
        return false;
    }

#ifdef TEST
    fprintf(g_logFile, "gettcBuf succeeds %d\n", i);
    tcBufferprint((tcBuffer*) rgBuf);
    PrintBytes("Buffer: ", rgBuf, i);
#endif

#ifdef HEADERTEST
    fprintf(g_logFile, "gettcBuf: "); pReq->print();
#endif
    *procid= pReq->m_procid;
    *puReq= pReq->m_reqID;
    *pstatus= pReq->m_ustatus;
    *porigprocid= pReq->m_origprocid;
    i-= sizeof(tcBuffer);
    if(*paramsize<i)
        return false;
    *paramsize= i;
    memcpy(params, &rgBuf[sizeof(tcBuffer)], i);

    return true;
}

bool sendtcBuf(int fd, int procid, u32 uReq, u32 status, int origproc,
                          int paramsize, byte* params)
{
#if 1
    byte            rgBuf[PADDEDREQ];
    tcBuffer*       pReq= (tcBuffer*) rgBuf;
    int             i;
    int             n;

    if(paramsize>(PARAMSIZE)) {
        fprintf(g_logFile, "sendtcBuf buffer too small %d\n", paramsize);
        return false;
    }
    pReq->m_procid= procid;
    pReq->m_reqID= uReq;
    pReq->m_ustatus= status;
    pReq->m_origprocid= origproc;
    pReq->m_reqSize= paramsize;
#ifdef TEST
    fprintf(g_logFile, "sendtcBuf: "); tcBufferprint(pReq);
#endif
    n= paramsize+sizeof(tcBuffer);
    memcpy(&rgBuf[sizeof(tcBuffer)], params, paramsize);
    i= write(fd, rgBuf, n);
    if(i<0) {
        fprintf(g_logFile, "tcChannel::sendtcBuf: Write failed %d\n", i);
        return false;
    }
#endif
    return true;
}

bool startAppfromDeviceDriver(int fd, int* ppid, int argc, char **argv)
{
#if 1
    u32         ustatus;
    u32         ureq;
    int         procid= g_myPid;
    int         origprocid= g_myPid;
    int         size= PARAMSIZE;
    byte        rgBuf[PARAMSIZE];

    if(argc<1) {
        fprintf(g_logFile, "startAppfromDeviceDriver: no argument\n");
        return false;
    }
#ifdef TEST
    int i;
    fprintf(g_logFile, "startAppfromDeviceDriver, %d args\n", argc);
    for(i=0; i<argc;i++) {
        fprintf(g_logFile, "\t%s\n", argv[i]);
    }
    fprintf(g_logFile, "\n");
    fflush(g_logFile);
#endif

    size= encodeTCSERVICESTARTAPPFROMAPP(argv[0], argc-1, argv+1, PARAMSIZE, rgBuf);
    if(size<0) {
        fprintf(g_logFile, "startAppfromDeviceDriver: encodeTCSERVICESTARTAPPFROMAPP failed\n");
        return false;
    }
    if(!sendtcBuf(fd, g_myPid, TCSERVICESTARTAPPFROMAPP, 0, g_myPid, size, rgBuf)) {
        fprintf(g_logFile, "startAppfromDeviceDriver: sendtcBuf for TCSERVICESTARTAPPFROMAPP failed\n");
        return false;
    }
#ifdef TEST
    fprintf(g_logFile, "Sending request %s\n", rgBuf);
#endif
    size= PARAMSIZE;
    if(!gettcBuf(fd, &procid, &ureq, &ustatus, &origprocid, &size, rgBuf)) {
        fprintf(g_logFile, "startAppfromDeviceDriver: gettcBuf for TCSERVICESTARTAPPFROMAPP failed\n");
        return false;
    }
    if(!decodeTCSERVICESTARTAPPFROMTCSERVICE(ppid, rgBuf)) {
        fprintf(g_logFile, "startAppfromDeviceDriver: cant decode childproc\n");
        return false;
    }
#ifdef TEST
    fprintf(g_logFile, "Program created: %d by servicepid %d\n",
          *ppid, g_myPid);
#endif
#endif
    return true;
}

int initLinuxService()
{
#ifdef TEST
        fprintf(g_logFile, "initLinuxService device %s\n", g_tcioDDName);
#endif

    int fd= open(g_tcioDDName, O_RDWR);
        if(fd<0) {
            fprintf(g_logFile, "Can't open device driver %s\n", g_tcioDDName);
            return -1;
        }

#ifdef TEST
    fprintf(g_logFile, "initLinuxService returns %d\n", fd);
#endif
    return fd;
}

// -------------------------------------------------------------------------

#define MAXPROGNAME 512

char* programNamefromFileName(const char* fileName)
{
    char*   p= (char*) fileName;
    char*   q;
    char*   r;
    char    progNameBuf[MAXPROGNAME];

    if(fileName==NULL)
        return NULL;
#ifdef TEST
    fprintf(g_logFile, "fileName: %s\n", fileName);
#endif
    while(*p!='\0')
        p++;
    q= p-1;
    while((--p)!=fileName) {
        if(*p=='/') {
            break;
        }
        if(*p=='.') {
            break;
        }
    }

    if(*p=='/') {
        r= p+1;
    }
    else if(*p=='.') {
        q= p-1;
        r= q;
        while(r>=fileName) {
            if(*r=='/')
                break;
            r--;
        }
    }
    else {
        r= (char*)fileName-1;
    }
    if((q-r)>=(MAXPROGNAME-1))
        return NULL;
    r++;
    p= progNameBuf;
    while(r<=q)
        *(p++)= *(r++);
    *p= '\0';
    q= strdup(progNameBuf);
#ifdef TEST
    fprintf(g_logFile, "fileName: %s, progname: %s\n", fileName, q);
#endif
    return q;
}

int main(int an, char** av)
{
    int         i;
    int         newan= an;
    char**      newav= av;
    bool        fSucceed= false;

    for(i=0;i<an;i++) {
      if(strcmp(av[i],"-help")==0) {
        fprintf(g_logFile,
         "tcLaunch.exe [-KVMHost |-KVMGuest | -LinuxHost]  KVNImage/ProcessImage remainingargs\n");
        return 0;
      }
      if(strcmp(av[i],"-KVMHost")==0) {
        // g_tcioDDName= "/dev/kvmtciodd0";
        g_tcioDDName= "/dev/tcioDD0";
        newan--;
        newav++;
        fSucceed= true;
      }
      else if(strcmp(av[i],"-KVMGuest")==0) {
        g_tcioDDName= "/dev/ktciodd0";
        newan--;
        newav++;
        fSucceed= true;
      }
      else if(strcmp(av[i],"-LinuxHost")==0) {
        g_tcioDDName= "/dev/tcioDD0";
        newan--;
        newav++;
        fSucceed= true;
      }
      else {
        g_tcioDDName= "/dev/tcioDD0";
      }
    }

    if(!fSucceed) {
        fprintf(g_logFile, "tcLaunch: error called with no flag\n");
        return 1;
    }

    g_myPid= getpid();

#ifdef  TEST
    initLog(NULL);
    fprintf(g_logFile, "tcLaunch test %s, %d\n", g_tcioDDName, g_myPid);
    fflush(g_logFile);
#endif

    int fd= initLinuxService();
    if(fd<0) {
        fprintf(g_logFile, "tcLaunch: can't open tcio device driver\n");
        return 1;
    }

    if(newan<1) {
        fprintf(g_logFile, "tcLaunch: too few arguments\n");
        return 1;
    }
    newav[0]= newav[1];
    newav[1]= programNamefromFileName(newav[0]);
    newan= 2;

    int   handle= 0;
    if(startAppfromDeviceDriver(fd, &handle, newan, newav))
        fprintf(g_logFile, "tcLaunch: measured program started, id: %d, exiting\n",
                        handle);
    else
        fprintf(g_logFile, "tcLaunch: program not started due to error\n");
    fflush(g_logFile);
    close(fd);
    closeLog();
    return 0;
}

// ------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include <boost/optional.hpp>

#include "../../../src/contents.hh"

namespace vick {
namespace move {

void mv(contents& contents, move_t y, move_t x) {
    contents.y = y;
    contents.x = x;
    if(static_cast<move_ts>(contents.y) < 0) contents.y = 0;
    if(contents.y >= contents.cont.size())
        contents.y = contents.cont.size() - 1;
    if(static_cast<move_ts>(contents.x) < 0) contents.x = 0;
    if(contents.x >= contents.cont[contents.y].size())
        contents.x = contents.cont[contents.y].size() - 1;
    return boost::none;
}

}
}
<commit_msg>In `mv()`, use parameters then set `contents.{y,x}` at end.<commit_after>#include <boost/optional.hpp>

#include "../../../src/contents.hh"

namespace vick {
namespace move {

void mv(contents& contents, move_t y, move_t x) {
    if(static_cast<move_ts>(y) < 0) y = 0;
    if(y >= contents.cont.size())
        y = contents.cont.size() - 1;
    if(static_cast<move_ts>(x) < 0) x = 0;
    if(x >= contents.cont[y].size())
        x = contents.cont[y].size() - 1;
    contents.y = y;
    contents.x = x;
}

}
}
<|endoftext|>


<commit_before>#include "TelegramNamespace.hpp"

namespace Telegram {

namespace Client {

class AccountStoragePrivate;

class AccountStorage : public QObject
{
    Q_OBJECT
public:
    explicit AccountStorage(QObject *parent = nullptr);

    bool hasMinimalDataSet() const;

    QString accountIdentifier() const;
    void setAccountIdentifier(const QString &account);

    QString phoneNumber() const;
    void setPhoneNumber(const QString &phoneNumber) const;

    quint64 authId() const;
    void setAuthId(quint64 id);

    QByteArray authKey() const;
    void setAuthKey(const QByteArray &newAuthKey);

    qint32 deltaTime() const;
    void setDeltaTime(const qint32 newDt);

    DcOption dcInfo() const;
    void setDcInfo(const DcOption &newDcInfo);

public slots:
    virtual bool saveData() const { return false; }
    virtual bool loadData() { return false; }

protected:
    AccountStorage(AccountStoragePrivate *dd, QObject *parent = nullptr);
    AccountStoragePrivate *d;
};

class FileAccountStorage : public AccountStorage
{
    Q_OBJECT
    Q_PROPERTY(QString fileName READ fileName WRITE setFileName NOTIFY fileNameChanged)
public:
    explicit FileAccountStorage(QObject *parent = nullptr);

    QString fileName() const;

public slots:
    bool saveData() const override;
    bool loadData() override;

    void setFileName(const QString &fileName);

signals:
    void fileNameChanged(const QString &fileName);

};

//class FileAccountStorage : public AccountStorage
//{
//    Q_OBJECT
//    Q_PROPERTY(QString directory READ directory WRITE setDirectory NOTIFY directoryChanged)
//    Q_PROPERTY(QStringList accounts READ accounts NOTIFY accountsChanged)
//public:

//};

} // Client namespace

} // Telegram namespace
<commit_msg>AccountStorage: Add missing include guards<commit_after>#ifndef TELEGRAM_ACCOUNT_STORAGE_HPP
#define TELEGRAM_ACCOUNT_STORAGE_HPP

#include "TelegramNamespace.hpp"

namespace Telegram {

namespace Client {

class AccountStoragePrivate;

class AccountStorage : public QObject
{
    Q_OBJECT
public:
    explicit AccountStorage(QObject *parent = nullptr);

    bool hasMinimalDataSet() const;

    QString accountIdentifier() const;
    void setAccountIdentifier(const QString &account);

    QString phoneNumber() const;
    void setPhoneNumber(const QString &phoneNumber) const;

    quint64 authId() const;
    void setAuthId(quint64 id);

    QByteArray authKey() const;
    void setAuthKey(const QByteArray &newAuthKey);

    qint32 deltaTime() const;
    void setDeltaTime(const qint32 newDt);

    DcOption dcInfo() const;
    void setDcInfo(const DcOption &newDcInfo);

public slots:
    virtual bool saveData() const { return false; }
    virtual bool loadData() { return false; }

protected:
    AccountStorage(AccountStoragePrivate *dd, QObject *parent = nullptr);
    AccountStoragePrivate *d;
};

class FileAccountStorage : public AccountStorage
{
    Q_OBJECT
    Q_PROPERTY(QString fileName READ fileName WRITE setFileName NOTIFY fileNameChanged)
public:
    explicit FileAccountStorage(QObject *parent = nullptr);

    QString fileName() const;

public slots:
    bool saveData() const override;
    bool loadData() override;

    void setFileName(const QString &fileName);

signals:
    void fileNameChanged(const QString &fileName);

};

//class FileAccountStorage : public AccountStorage
//{
//    Q_OBJECT
//    Q_PROPERTY(QString directory READ directory WRITE setDirectory NOTIFY directoryChanged)
//    Q_PROPERTY(QStringList accounts READ accounts NOTIFY accountsChanged)
//public:

//};

} // Client namespace

} // Telegram namespace

#endif // TELEGRAM_ACCOUNT_STORAGE_HPP
<|endoftext|>


<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>
#include <stdint.h>

#include "libxml/parser.h"

void ignore (void* ctx, const char* msg, ...) {
  // Error handler to avoid spam of error messages from libxml parser.
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  xmlSetGenericErrorFunc(NULL, &ignore);

  if (auto doc = xmlReadMemory(reinterpret_cast<const char*>(data),
                               static_cast<int>(size), "noname.xml", NULL, 0)) {
    xmlFreeDoc(doc);
  }

  return 0;
}
<commit_msg>extend libxml2_xml_read_memory_fuzzer to call xmlSaveDoc (#387)<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <cassert>
#include <stddef.h>
#include <stdint.h>

#include "libxml/parser.h"
#include "libxml/xmlsave.h"

void ignore (void* ctx, const char* msg, ...) {
  // Error handler to avoid spam of error messages from libxml parser.
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  xmlSetGenericErrorFunc(NULL, &ignore);

  if (auto doc = xmlReadMemory(reinterpret_cast<const char*>(data),
                               static_cast<int>(size), "noname.xml", NULL,
                               0 /*or:XML_PARSE_RECOVER*/)) {
    auto buf = xmlBufferCreate();
    assert(buf);
    auto ctxt = xmlSaveToBuffer(buf, NULL, 0);
    xmlSaveDoc(ctxt, doc);
    xmlSaveClose(ctxt);
    xmlFreeDoc(doc);
    xmlBufferFree(buf);
  }

  return 0;
}
<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER

#include "libs/catch/catch.hpp"

int main(int argc, char **argv) {
	int result = Catch::Session().run(argc, argv);
	return(result);
}
<commit_msg>cleaned up tests<commit_after>#define CATCH_CONFIG_RUNNER

#include <cstdlib>

#include "libs/catch/catch.hpp"

int main(int argc, char **argv) {
	int i = system("make prep");
	int result = Catch::Session().run(argc, argv);
	return(result);
}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <cstdio>
#include <vector>
#include "cuda_runtime_api.h"
#include "CudaUtil.h"
#include "CudaRtHandler.h"

using namespace std;

extern "C" {
    extern void** __cudaRegisterFatBinary(void *fatCubin);
    extern void __cudaUnregisterFatBinary(void **fatCubinHandle);
    extern void __cudaRegisterFunction(void **fatCubinHandle,
            const char *hostFun, char *deviceFun, const char *deviceName,
            int thread_limit, uint3 *tid, uint3 *bid, dim3 *bDim, dim3 *gDim,
            int *wSize);
    extern void __cudaRegisterVar(void **fatCubinHandle, char *hostVar,
            char *deviceAddress, const char *deviceName, int ext, int size,
            int constant, int global);
};

CUDA_ROUTINE_HANDLER(RegisterFatBinary) {
    char * handler = input_buffer->AssignString();
    __cudaFatCudaBinary * fatBin = CudaUtil::UnmarshalFatCudaBinary(input_buffer);
    void **fatCubinHandler = __cudaRegisterFatBinary((void *) fatBin);
    pThis->RegisterFatBinary(handler, fatCubinHandler);
    return new Result(cudaSuccess);
}

CUDA_ROUTINE_HANDLER(UnregisterFatBinary) {
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);

    __cudaUnregisterFatBinary(fatCubinHandle);

    pThis->UnregisterFatBinary(handler);

    return new Result(cudaSuccess);
}

CUDA_ROUTINE_HANDLER(RegisterFunction) {
    /* void __cudaRegisterFunction(void **fatCubinHandle,
     * const char *hostFun,
     * char *deviceFun,
     * const char *deviceName,
     * int thread_limit,
     * uint3 *tid,
     * uint3 *bid,
     * dim3 *bDim,
     * dim3 *gDim,
     * int *wSize) */
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);
    const char *hostFun = input_buffer->AssignString();
    char *deviceFun = input_buffer->AssignString();
    const char *deviceName = input_buffer->AssignString();
    int thread_limit = input_buffer->Get<int>();
    uint3 *tid = input_buffer->Assign<uint3 > ();
    uint3 *bid = input_buffer->Assign<uint3 > ();
    dim3 *bDim = input_buffer->Assign<dim3 > ();
    dim3 *gDim = input_buffer->Assign<dim3 > ();
    int *wSize = input_buffer->Assign<int>();

    __cudaRegisterFunction(fatCubinHandle, hostFun, deviceFun, deviceName,
            thread_limit, tid, bid, bDim, gDim, wSize);

    pThis->RegisterDeviceFunction(hostFun, deviceFun);

    Buffer * output_buffer = new Buffer();
    output_buffer->AddString(deviceFun);
    output_buffer->Add(tid);
    output_buffer->Add(bid);
    output_buffer->Add(bDim);
    output_buffer->Add(gDim);
    output_buffer->Add(wSize);

    return new Result(cudaSuccess, output_buffer);
}

CUDA_ROUTINE_HANDLER(RegisterVar) {
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);
    handler = input_buffer->AssignString();
    char *hostVar;
    char *deviceAddress = input_buffer->AssignString();
    char *deviceName = input_buffer->AssignString();
    int ext = input_buffer->Get<int>();
    int size = input_buffer->Get<int>();
    int constant = input_buffer->Get<int>();
    int global = input_buffer->Get<int>();
    hostVar = (char *) malloc(size);

    __cudaRegisterVar(fatCubinHandle, hostVar, deviceAddress, deviceName, ext,
            size, constant, global);

    return new Result(cudaSuccess);
}

#if 0
CUDA_ROUTINE_HANDLER(RegisterShared) {
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);
    char *dev_ptr_handler =
            input_buffer->Assign<char>(CudaUtil::MarshaledDevicePointerSize);
    void *devPtr = pThis->GetDevicePointer(dev_ptr_handler);
}
#endif<commit_msg>added a note<commit_after>#include <string>
#include <iostream>
#include <cstdio>
#include <vector>
#include "cuda_runtime_api.h"
#include "CudaUtil.h"
#include "CudaRtHandler.h"

using namespace std;

extern "C" {
    extern void** __cudaRegisterFatBinary(void *fatCubin);
    extern void __cudaUnregisterFatBinary(void **fatCubinHandle);
    extern void __cudaRegisterFunction(void **fatCubinHandle,
            const char *hostFun, char *deviceFun, const char *deviceName,
            int thread_limit, uint3 *tid, uint3 *bid, dim3 *bDim, dim3 *gDim,
            int *wSize);
    extern void __cudaRegisterVar(void **fatCubinHandle, char *hostVar,
            char *deviceAddress, const char *deviceName, int ext, int size,
            int constant, int global);
};

CUDA_ROUTINE_HANDLER(RegisterFatBinary) {
    char * handler = input_buffer->AssignString();
    __cudaFatCudaBinary * fatBin = CudaUtil::UnmarshalFatCudaBinary(input_buffer);
    void **fatCubinHandler = __cudaRegisterFatBinary((void *) fatBin);
    pThis->RegisterFatBinary(handler, fatCubinHandler);
    return new Result(cudaSuccess);
}

CUDA_ROUTINE_HANDLER(UnregisterFatBinary) {
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);

    __cudaUnregisterFatBinary(fatCubinHandle);

    pThis->UnregisterFatBinary(handler);

    return new Result(cudaSuccess);
}

CUDA_ROUTINE_HANDLER(RegisterFunction) {
    /* void __cudaRegisterFunction(void **fatCubinHandle,
     * const char *hostFun,
     * char *deviceFun,
     * const char *deviceName,
     * int thread_limit,
     * uint3 *tid,
     * uint3 *bid,
     * dim3 *bDim,
     * dim3 *gDim,
     * int *wSize) */
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);
    const char *hostFun = input_buffer->AssignString();
    char *deviceFun = input_buffer->AssignString();
    const char *deviceName = input_buffer->AssignString();
    int thread_limit = input_buffer->Get<int>();
    uint3 *tid = input_buffer->Assign<uint3 > ();
    uint3 *bid = input_buffer->Assign<uint3 > ();
    dim3 *bDim = input_buffer->Assign<dim3 > ();
    dim3 *gDim = input_buffer->Assign<dim3 > ();
    int *wSize = input_buffer->Assign<int>();

    __cudaRegisterFunction(fatCubinHandle, hostFun, deviceFun, deviceName,
            thread_limit, tid, bid, bDim, gDim, wSize);

    pThis->RegisterDeviceFunction(hostFun, deviceFun);

    Buffer * output_buffer = new Buffer();
    output_buffer->AddString(deviceFun);
    output_buffer->Add(tid);
    output_buffer->Add(bid);
    output_buffer->Add(bDim);
    output_buffer->Add(gDim);
    output_buffer->Add(wSize);

    return new Result(cudaSuccess, output_buffer);
}

CUDA_ROUTINE_HANDLER(RegisterVar) {
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);
    handler = input_buffer->AssignString();
    char *hostVar;
    char *deviceAddress = input_buffer->AssignString();
    char *deviceName = input_buffer->AssignString();
    int ext = input_buffer->Get<int>();
    int size = input_buffer->Get<int>();
    int constant = input_buffer->Get<int>();
    int global = input_buffer->Get<int>();

    // FIXME: this shouldn't be lost as it is
    hostVar = (char *) malloc(size);

    __cudaRegisterVar(fatCubinHandle, hostVar, deviceAddress, deviceName, ext,
            size, constant, global);

    return new Result(cudaSuccess);
}

#if 0
CUDA_ROUTINE_HANDLER(RegisterShared) {
    char * handler = input_buffer->AssignString();
    void **fatCubinHandle = pThis->GetFatBinary(handler);
    char *dev_ptr_handler =
            input_buffer->Assign<char>(CudaUtil::MarshaledDevicePointerSize);
    void *devPtr = pThis->GetDevicePointer(dev_ptr_handler);
}
#endif<|endoftext|>


<commit_before>/*
                          qpdf

    Copyright (C) 2015 Arthur Benilov,
    arthur.benilov@gmail.com
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    This software 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.
*/

#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QVBoxLayout>
#include "pdfjsbridge.h"
#include "qpdfwidget.h"

// NOTE:
// There is this bug in Qt https://bugreports.qt.io/browse/QTBUG-46973
// which causes the application to crash when loading from qrc:/ resources.
// Reported to be fixed as from Qt 5.6.0

const QString cPdfViewerUrl("qrc:/pdfview/viewer.html");

// class private members
struct QPdfWidgetPrivate
{
    PdfJsBridge *pPdfJsBridge;
    bool ready;
    QByteArray pdfData;
    QString pdfFile;
};

QPdfWidget::QPdfWidget(QWidget *pParent)
    : QWidget(pParent)
{
    m = new QPdfWidgetPrivate;
    m->pPdfJsBridge = new PdfJsBridge();
    connect(m->pPdfJsBridge, &PdfJsBridge::loadFinished, this, &QPdfWidget::onLoadFinished);
    connect(m->pPdfJsBridge, &PdfJsBridge::pdfDocumentloaded, this, &QPdfWidget::onRenderPdfFinished);
    m->ready = false;

    // Initialize pdf.js viewer
    QUrl url = QUrl::fromUserInput(cPdfViewerUrl);
    m->pPdfJsBridge->setUrl(url);

    // widget layout
    QVBoxLayout *pLayout = new QVBoxLayout();
    pLayout->setMargin(0);
    pLayout->addWidget(m->pPdfJsBridge);
    setLayout(pLayout);
}

QPdfWidget::~QPdfWidget()
{
    delete m;
}

bool QPdfWidget::loadFile(const QString &path)
{
    QFileInfo fi(path);
    if (fi.exists()) {
        m->pdfFile = path;
        renderPdfFile(path);
        return true;
    }

    return false;
}

void QPdfWidget::loadData(const QByteArray &data)
{
    m->pdfData = data;
    renderPdfData();
}

void QPdfWidget::close()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.close()");
}

void QPdfWidget::setPage(int page)
{
    QString script = QString("PDFViewerApplication.page = %1")
                        .arg(page);
    m->pPdfJsBridge->invokeJavaScript(script);
}

int QPdfWidget::page() const
{
    QVariant res = m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.page");
    if (res.isValid()) {
        return res.toInt();
    }
    return 0;
}

int QPdfWidget::pagesCount() const
{
    QVariant res = m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.pagesCount");
    if (res.isValid()) {
        return res.toInt();
    }
    return 0;
}

void QPdfWidget::rotatePages(int degrees)
{
    QString script = QString("PDFViewerApplication.rotatePages(%1)")
                        .arg(degrees);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::zoomIn(int ticks)
{
    QString script = QString("PDFViewerApplication.zoomIn(%1)").arg(ticks);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::zoomOut(int ticks)
{
    QString script = QString("PDFViewerApplication.zoomOut(%1)").arg(ticks);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::zoomReset(qreal scale)
{
    QString script = QString("PDFViewerApplication.pdfViewer.currentScaleValue=%1").arg(scale);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::showDocumentProperties()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.pdfDocumentProperties.open()");
}

void QPdfWidget::setToolbarVisible(bool v)
{
    m->pPdfJsBridge->setToolbarVisible(v);
}

void QPdfWidget::setFindBarVisible(bool v)
{
    QString script = QString("PDFViewerApplication.findBar.%1()")
            .arg(v ? "open" : "close");
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::findText(const QString &text)
{
    if (!text.isEmpty()) {
        setFindFieldText(text);
    }
    // Sending an empty event will actually send 'find' since it will be prepended to
    // the event name.
    // All options options are (viewer.js:1155):
    // 'find',
    // 'findagain',
    // 'findhighlightallchange',
    // 'findcasesensitivitychange'
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.findBar.dispatchEvent('', false);");
}

void QPdfWidget::findNext()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.findBar.dispatchEvent('again', false);");
}

void QPdfWidget::findPrevious()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.findBar.dispatchEvent('again', true);");
}

int QPdfWidget::findResultsCount() const
{
    QVariant res = m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.findController.matchCount");
    if (res.isValid()) {
        return res.toInt();
    }
    return 0;
}

void QPdfWidget::navigateTo(const QString &dest)
{
    QString escapedDest = dest;
    escapedDest.replace("\"", "\\\"");
    QString script = QString("PDFViewerApplication.pdfLinkService.navigateTo(\"%1\")")
            .arg(escapedDest);
    m->pPdfJsBridge->invokeJavaScript(script);
}

QStringList QPdfWidget::getDestinations() const
{
    return m->pPdfJsBridge->fetchPdfDocumentDestinations();
}

QWebEngineView* QPdfWidget::internalWebEngineView() const
{
    return dynamic_cast<QWebEngineView*>(m->pPdfJsBridge);
}

void QPdfWidget::onLoadFinished(bool status)
{
    if (!status) {
        qCritical() << "Unable to initialize the web view";
        return;
    }

    m->ready = true;
    if (!m->pdfData.isEmpty()) {
        renderPdfData();
    } else if (!m->pdfFile.isEmpty()) {
        renderPdfFile(m->pdfFile);
    }
}

void QPdfWidget::renderPdfData()
{
    if (!m->ready) {
        return;
    }

    m->pdfData = m->pdfData.toBase64();
    QString script = QString("qpdf_ShowPdfFileBase64('%1')")
                        .arg(QString::fromUtf8(m->pdfData));

    m->pPdfJsBridge->invokeJavaScript(script);

    // Clear pdf data
    m->pdfData.clear();
}

void QPdfWidget::renderPdfFile(const QString &file)
{
    if (!m->ready) {
        return;
    }

    m->pdfData = m->pdfData.toBase64();
    QString script = QString("qpdf_ShowPdfFile('%1')")
                        .arg(file);

    m->pPdfJsBridge->invokeJavaScript(script);

    // Clear pdf data
    m->pdfData.clear();
}

void QPdfWidget::onRenderPdfFinished()
{
    emit pdfDocumentLoaded();
}

void QPdfWidget::setFindFieldText(const QString &text)
{
    // Reset find controller.
    m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.findController.reset()");

    // Fill-in the find field.
    QString escapedText = text;
    escapedText.replace("\"", "\\\"");
    QString script = QString("PDFViewerApplication.findBar.findField.value=\"%1\"")
            .arg(escapedText);
    m->pPdfJsBridge->invokeJavaScript(script);
}
<commit_msg>Explisitly specify file:// when loading from file.<commit_after>/*
                          qpdf

    Copyright (C) 2015 Arthur Benilov,
    arthur.benilov@gmail.com
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    This software 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.
*/

#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QVBoxLayout>
#include "pdfjsbridge.h"
#include "qpdfwidget.h"

// NOTE:
// There is this bug in Qt https://bugreports.qt.io/browse/QTBUG-46973
// which causes the application to crash when loading from qrc:/ resources.
// Reported to be fixed as from Qt 5.6.0

const QString cPdfViewerUrl("qrc:/pdfview/viewer.html");

// class private members
struct QPdfWidgetPrivate
{
    PdfJsBridge *pPdfJsBridge;
    bool ready;
    QByteArray pdfData;
    QString pdfFile;
};

QPdfWidget::QPdfWidget(QWidget *pParent)
    : QWidget(pParent)
{
    m = new QPdfWidgetPrivate;
    m->pPdfJsBridge = new PdfJsBridge();
    connect(m->pPdfJsBridge, &PdfJsBridge::loadFinished, this, &QPdfWidget::onLoadFinished);
    connect(m->pPdfJsBridge, &PdfJsBridge::pdfDocumentloaded, this, &QPdfWidget::onRenderPdfFinished);
    m->ready = false;

    // Initialize pdf.js viewer
    QUrl url = QUrl::fromUserInput(cPdfViewerUrl);
    m->pPdfJsBridge->setUrl(url);

    // widget layout
    QVBoxLayout *pLayout = new QVBoxLayout();
    pLayout->setMargin(0);
    pLayout->addWidget(m->pPdfJsBridge);
    setLayout(pLayout);
}

QPdfWidget::~QPdfWidget()
{
    delete m;
}

bool QPdfWidget::loadFile(const QString &path)
{
    QFileInfo fi(path);
    if (fi.exists()) {
        m->pdfFile = path;
        renderPdfFile(path);
        return true;
    }

    return false;
}

void QPdfWidget::loadData(const QByteArray &data)
{
    m->pdfData = data;
    renderPdfData();
}

void QPdfWidget::close()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.close()");
}

void QPdfWidget::setPage(int page)
{
    QString script = QString("PDFViewerApplication.page = %1")
                        .arg(page);
    m->pPdfJsBridge->invokeJavaScript(script);
}

int QPdfWidget::page() const
{
    QVariant res = m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.page");
    if (res.isValid()) {
        return res.toInt();
    }
    return 0;
}

int QPdfWidget::pagesCount() const
{
    QVariant res = m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.pagesCount");
    if (res.isValid()) {
        return res.toInt();
    }
    return 0;
}

void QPdfWidget::rotatePages(int degrees)
{
    QString script = QString("PDFViewerApplication.rotatePages(%1)")
                        .arg(degrees);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::zoomIn(int ticks)
{
    QString script = QString("PDFViewerApplication.zoomIn(%1)").arg(ticks);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::zoomOut(int ticks)
{
    QString script = QString("PDFViewerApplication.zoomOut(%1)").arg(ticks);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::zoomReset(qreal scale)
{
    QString script = QString("PDFViewerApplication.pdfViewer.currentScaleValue=%1").arg(scale);
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::showDocumentProperties()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.pdfDocumentProperties.open()");
}

void QPdfWidget::setToolbarVisible(bool v)
{
    m->pPdfJsBridge->setToolbarVisible(v);
}

void QPdfWidget::setFindBarVisible(bool v)
{
    QString script = QString("PDFViewerApplication.findBar.%1()")
            .arg(v ? "open" : "close");
    m->pPdfJsBridge->invokeJavaScript(script);
}

void QPdfWidget::findText(const QString &text)
{
    if (!text.isEmpty()) {
        setFindFieldText(text);
    }
    // Sending an empty event will actually send 'find' since it will be prepended to
    // the event name.
    // All options options are (viewer.js:1155):
    // 'find',
    // 'findagain',
    // 'findhighlightallchange',
    // 'findcasesensitivitychange'
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.findBar.dispatchEvent('', false);");
}

void QPdfWidget::findNext()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.findBar.dispatchEvent('again', false);");
}

void QPdfWidget::findPrevious()
{
    m->pPdfJsBridge->invokeJavaScript("PDFViewerApplication.findBar.dispatchEvent('again', true);");
}

int QPdfWidget::findResultsCount() const
{
    QVariant res = m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.findController.matchCount");
    if (res.isValid()) {
        return res.toInt();
    }
    return 0;
}

void QPdfWidget::navigateTo(const QString &dest)
{
    QString escapedDest = dest;
    escapedDest.replace("\"", "\\\"");
    QString script = QString("PDFViewerApplication.pdfLinkService.navigateTo(\"%1\")")
            .arg(escapedDest);
    m->pPdfJsBridge->invokeJavaScript(script);
}

QStringList QPdfWidget::getDestinations() const
{
    return m->pPdfJsBridge->fetchPdfDocumentDestinations();
}

QWebEngineView* QPdfWidget::internalWebEngineView() const
{
    return dynamic_cast<QWebEngineView*>(m->pPdfJsBridge);
}

void QPdfWidget::onLoadFinished(bool status)
{
    if (!status) {
        qCritical() << "Unable to initialize the web view";
        return;
    }

    m->ready = true;
    if (!m->pdfData.isEmpty()) {
        renderPdfData();
    } else if (!m->pdfFile.isEmpty()) {
        renderPdfFile(m->pdfFile);
    }
}

void QPdfWidget::renderPdfData()
{
    if (!m->ready) {
        return;
    }

    m->pdfData = m->pdfData.toBase64();
    QString script = QString("qpdf_ShowPdfFileBase64('%1')")
                        .arg(QString::fromUtf8(m->pdfData));

    m->pPdfJsBridge->invokeJavaScript(script);

    // Clear pdf data
    m->pdfData.clear();
}

void QPdfWidget::renderPdfFile(const QString &file)
{
    if (!m->ready) {
        return;
    }

    m->pdfData = m->pdfData.toBase64();
    QString script = QString("qpdf_ShowPdfFile('file://%1')")
                        .arg(file);

    m->pPdfJsBridge->invokeJavaScript(script);

    // Clear pdf data
    m->pdfData.clear();
}

void QPdfWidget::onRenderPdfFinished()
{
    emit pdfDocumentLoaded();
}

void QPdfWidget::setFindFieldText(const QString &text)
{
    // Reset find controller.
    m->pPdfJsBridge->invokeJavaScriptAndWaitForResult("PDFViewerApplication.findController.reset()");

    // Fill-in the find field.
    QString escapedText = text;
    escapedText.replace("\"", "\\\"");
    QString script = QString("PDFViewerApplication.findBar.findField.value=\"%1\"")
            .arg(escapedText);
    m->pPdfJsBridge->invokeJavaScript(script);
}
<|endoftext|>


<commit_before>/* **********************************************

  File Name: gao.cpp

  Author: zhengdongjian@tju.edu.cn

  Created Time: Tue, Dec 27, 2016  2:14:23 PM

*********************************************** */
#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>

#include "libxl.h"
using namespace libxl;

const int MAX = 10086;  // line buffer size
char buffer[MAX];  // line buffer

const char HEADER[] = "Ethernet";  // paragraph header
const char HEADER_PATTERNS[2][256] = {
	"Input bandwidth utilization(%)",
	"Output bandwidth utilization(%)",
	// "Last 300 seconds input rate(bits/s)",
	// "Last 300 seconds output rate(bits/s)",
};
const char PATTERNS[2][256] = {
	/* all possible patterns */
	"Input bandwidth utilization",
	"Output bandwidth utilization",
	// "Last 300 seconds input rate",
	// "Last 300 seconds output rate",
};
const int PATTERN_NUM = sizeof(PATTERNS) / 256;

char* match_str(char* str, const char* pattern) {
	while (*pattern != '\0') {
		if (*str == '\0' || *pattern != *str) {
			return NULL;
		}
		++pattern;
		++str;
	}
	return str;
}

char* match_num(char* str) {
	bool flag = false;
	while (*str != '\0' && isdigit(*str)) {
		flag = true;
		++str;
	}
	return flag ? str : NULL;
}

//Eth-Trunk4.3 current state
//Eth-Trunk4 current state
//GigabitEthernet0/0/0 current state
//Ethernet0/0/0 current state
//~~Aux0/0/1 current state~~
bool match_ether(char* str) {
	char* tmp = match_str(str, "Ethernet");
	tmp || (tmp = match_str(str, "GigabitEthernet"));
	// tmp || (tmp = match_str(str, "Aux"));
	tmp && (tmp = match_num(tmp));
	tmp && (tmp = match_str(tmp, "/"));
	tmp && (tmp = match_num(tmp));
	tmp && (tmp = match_str(tmp, "/"));
	tmp && (tmp = match_num(tmp));
	tmp && (tmp = match_str(tmp, " current state"));
	return tmp != NULL;
}

bool match_trunk(char* str) {
	char* tmp = match_str(str, "Eth-Trunk");
	tmp && (tmp = match_num(tmp));
	if (tmp != NULL) {
		char* tmp2 = match_str(tmp, ".");
		if (tmp2 != NULL) {
			tmp = tmp2;
			tmp = match_num(tmp);
		}
	}
	tmp && (tmp = match_str(tmp, " current state"));
	return tmp != NULL;
}

bool match_header(char* line) {
	return match_ether(line) || match_trunk(line);
}

void gao(FILE* fd, Sheet* sheet) {
	sheet->writeStr(1, 0, "Device");
	for (int i = 0; i < PATTERN_NUM; ++i) {
		sheet->writeStr(1, i + 1, HEADER_PATTERNS[i]);
	}
	int device_id = 1;
	while (fgets(buffer, MAX, fd) != NULL) {
		if (match_header(buffer)) {
			/* we meet a new paragraph */
			char* end = buffer;
			while (*end != ' ' && *end != '\0') {
				++end;
			}
			*end = '\0';
			++device_id;
			sheet->writeStr(device_id, 0, buffer);
			printf("---- Device: %s ----\n", buffer);
			*end = ' ';
			continue;
		}

		for (int i = 0; i < PATTERN_NUM; ++i) {
			const char* pattern = PATTERNS[i];
			char* sub = strstr(buffer, pattern);
			//printf("try [%s] match pattern [%s]...\n", buffer, pattern);
			if (sub != NULL) {
				//printf("[%s] match pattern [%s]\n", buffer, pattern);
				while (!isdigit(*sub)) {
					++sub;
				}
				double rate = 0.0;
				while (isdigit(*sub)) {
					rate *= 10.0;
					rate += *sub - '0';
					++sub;
				}
				if (*sub == '.') {
					double tmp = 1.0;
					sub++;
					while (isdigit(*sub)) {
						tmp *= 0.1;
						rate += tmp * (*sub - '0');
						++sub;
					}
				}
				/* do anything needed with 'rate' here */
				sheet->writeNum(device_id, i + 1, rate);
				if (pattern[0] == 'L') {
					/* pattern(s) like: Last xxx */
					printf("%s: %.0f bits/s\n", pattern, rate);
				} else {
					/* pattern(s) like: Input/Output xxx */
					printf("%s: %.2f%%\n", pattern, rate);
				}
			}
		}
	}
	sheet->setAutoFitArea(0, 0, device_id + 1, PATTERN_NUM + 1);
}

char* parse_file_name(char* file_name) {
    char* s = file_name + strlen(file_name);
    while (s != file_name && *s != '/') {
        --s;
    }
    if (s != file_name) {
        ++s;
    }
    return s;
}

int main(int argc, char** argv) {
	Book* book = xlCreateBook();  // a new xlsx book :)
	if (book == NULL) {
		printf("o.o something is wrong\n");
		exit(1);
	}

    char file_name[1024];
	if (argc == 1) {
		/* no file name(s) specificed, read from stdin */
		int id = 1;
		while (true) {
			printf("Please input file name. one line each, press Enter directly to terminate...\n");
			fgets(file_name, 1024, stdin);
			int len = strlen(file_name);
			if (len <= 1) {
				break;
			}
			file_name[strlen(file_name) - 1] = '\0';
			Sheet* sheet = book->addSheet(parse_file_name(file_name));
			if (sheet == NULL) {
				printf("T.T something is wrong\n");
				exit(2);
			}
			printf("\tid = %d, file name: %s...\n", id++, file_name);
			FILE* fd = fopen(file_name, "r");
            if (fd == NULL) {
                strcpy(file_name + strlen(file_name), ".txt");
                fd = fopen(file_name, "r");
            }
			if (fd == NULL) {
				printf("open file %s failed...\n", file_name);
				continue;
			}
			gao(fd, sheet);
			fclose(fd);
			printf("--------------------------------------------\n");
		}
		if (id == 1) {
			exit(0);
		}
	} else {
		/* handle each of args */
		for (int i = 1; i < argc; ++i) {
			Sheet* sheet = book->addSheet(parse_file_name(argv[i]));
			if (sheet == NULL) {
				printf("T.T something is wrong\n");
				exit(2);
			}
			printf("\tid = %d, file name: %s...\n", i, argv[i]);
			FILE* fd = fopen(argv[i], "r");
            if (fd == NULL) {
                strcpy(file_name, argv[i]);
                strcpy(file_name + strlen(file_name), ".txt");
                fd = fopen(file_name, "r");
            }
			if (fd == NULL) {
				printf("open file %s failed...\n", file_name);
				continue;
			}
			gao(fd, sheet);
			fclose(fd);
			printf("--------------------------------------------\n");
		}
	}
	book->save("gao.xls");
	book->release();
	return 0;
}
<commit_msg>Only handle info from devices list<commit_after>/* **********************************************

  File Name: gao.cpp

  Author: zhengdongjian@tju.edu.cn

  Created Time: Tue, Dec 27, 2016  2:14:23 PM

*********************************************** */
#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>

#include "libxl.h"
using namespace libxl;

const int MAX = 10086;  // line buffer size
char buffer[MAX];  // line buffer

const char HEADER[] = "Ethernet";  // paragraph header
const char HEADER_PATTERNS[2][256] = {
	"Input bandwidth utilization(%)",
	"Output bandwidth utilization(%)",
	// "Last 300 seconds input rate(bits/s)",
	// "Last 300 seconds output rate(bits/s)",
};
const char PATTERNS[2][256] = {
	/* all possible patterns */
	"Input bandwidth utilization",
	"Output bandwidth utilization",
	// "Last 300 seconds input rate",
	// "Last 300 seconds output rate",
};
const int PATTERN_NUM = sizeof(PATTERNS) / 256;

char* match_str(char* str, const char* pattern) {
	while (*pattern != '\0') {
		if (*str == '\0' || *pattern != *str) {
			return NULL;
		}
		++pattern;
		++str;
	}
	return str;
}

char* match_num(char* str) {
	bool flag = false;
	while (*str != '\0' && isdigit(*str)) {
		flag = true;
		++str;
	}
	return flag ? str : NULL;
}

//Eth-Trunk4.3 current state
//Eth-Trunk4 current state
//GigabitEthernet0/0/0 current state
//Ethernet0/0/0 current state
//~~Aux0/0/1 current state~~
bool match_ether(char* str) {
	char* tmp = match_str(str, "Ethernet");
	tmp || (tmp = match_str(str, "GigabitEthernet"));
	// tmp || (tmp = match_str(str, "Aux"));
	tmp && (tmp = match_num(tmp));
	tmp && (tmp = match_str(tmp, "/"));
	tmp && (tmp = match_num(tmp));
	tmp && (tmp = match_str(tmp, "/"));
	tmp && (tmp = match_num(tmp));
	tmp && (tmp = match_str(tmp, " current state"));
	return tmp != NULL;
}

bool match_trunk(char* str) {
	char* tmp = match_str(str, "Eth-Trunk");
	tmp && (tmp = match_num(tmp));
	if (tmp != NULL) {
		char* tmp2 = match_str(tmp, ".");
		if (tmp2 != NULL) {
			tmp = tmp2;
			tmp = match_num(tmp);
		}
	}
	tmp && (tmp = match_str(tmp, " current state"));
	return tmp != NULL;
}

bool match_header(char* line) {
	return match_ether(line) || match_trunk(line);
}

void gao(FILE* fd, Sheet* sheet) {
	sheet->writeStr(1, 0, "Device");
	for (int i = 0; i < PATTERN_NUM; ++i) {
		sheet->writeStr(1, i + 1, HEADER_PATTERNS[i]);
	}
	int device_id = 1;
	int data_buffer_size = -1;
	while (fgets(buffer, MAX, fd) != NULL) {
		if (match_header(buffer)) {
			/* we meet a new paragraph */
			char* end = buffer;
			while (*end != ' ' && *end != '\0') {
				++end;
			}
			*end = '\0';
			++device_id;
			sheet->writeStr(device_id, 0, buffer);
			printf("---- Device: %s ----\n", buffer);
			*end = ' ';
			data_buffer_size = 0;
			continue;
		}

		for (int i = 0; i < PATTERN_NUM; ++i) {
			const char* pattern = PATTERNS[i];
			char* sub = strstr(buffer, pattern);
			//printf("try [%s] match pattern [%s]...\n", buffer, pattern);
			if (sub != NULL) {
				//printf("[%s] match pattern [%s]\n", buffer, pattern);
				if (data_buffer_size < 0 || data_buffer_size > 4) {
					// dropped
					continue;
				}
				++data_buffer_size;
				while (!isdigit(*sub)) {
					++sub;
				}
				double rate = 0.0;
				while (isdigit(*sub)) {
					rate *= 10.0;
					rate += *sub - '0';
					++sub;
				}
				if (*sub == '.') {
					double tmp = 1.0;
					sub++;
					while (isdigit(*sub)) {
						tmp *= 0.1;
						rate += tmp * (*sub - '0');
						++sub;
					}
				}
				/* do anything needed with 'rate' here */
				sheet->writeNum(device_id, i + 1, rate);
				if (pattern[0] == 'L') {
					/* pattern(s) like: Last xxx */
					printf("%s: %.0f bits/s\n", pattern, rate);
				} else {
					/* pattern(s) like: Input/Output xxx */
					printf("%s: %.2f%%\n", pattern, rate);
				}
			}
		}
	}
	sheet->setAutoFitArea(0, 0, device_id + 1, PATTERN_NUM + 1);
}

char* parse_file_name(char* file_name) {
    char* s = file_name + strlen(file_name);
    while (s != file_name && *s != '/') {
        --s;
    }
    if (s != file_name) {
        ++s;
    }
    return s;
}

int main(int argc, char** argv) {
	Book* book = xlCreateBook();  // a new xlsx book :)
	if (book == NULL) {
		printf("o.o something is wrong\n");
		exit(1);
	}

    char file_name[1024];
	if (argc == 1) {
		/* no file name(s) specificed, read from stdin */
		int id = 1;
		while (true) {
			printf("Please input file name. one line each, press Enter directly to terminate...\n");
			fgets(file_name, 1024, stdin);
			int len = strlen(file_name);
			if (len <= 1) {
				break;
			}
			file_name[strlen(file_name) - 1] = '\0';
			Sheet* sheet = book->addSheet(parse_file_name(file_name));
			if (sheet == NULL) {
				printf("T.T something is wrong\n");
				exit(2);
			}
			printf("\tid = %d, file name: %s...\n", id++, file_name);
			FILE* fd = fopen(file_name, "r");
            if (fd == NULL) {
                strcpy(file_name + strlen(file_name), ".txt");
                fd = fopen(file_name, "r");
            }
			if (fd == NULL) {
				printf("open file %s failed...\n", file_name);
				continue;
			}
			gao(fd, sheet);
			fclose(fd);
			printf("--------------------------------------------\n");
		}
		if (id == 1) {
			exit(0);
		}
	} else {
		/* handle each of args */
		for (int i = 1; i < argc; ++i) {
			Sheet* sheet = book->addSheet(parse_file_name(argv[i]));
			if (sheet == NULL) {
				printf("T.T something is wrong\n");
				exit(2);
			}
			printf("\tid = %d, file name: %s...\n", i, argv[i]);
			FILE* fd = fopen(argv[i], "r");
            if (fd == NULL) {
                strcpy(file_name, argv[i]);
                strcpy(file_name + strlen(file_name), ".txt");
                fd = fopen(file_name, "r");
            }
			if (fd == NULL) {
				printf("open file %s failed...\n", file_name);
				continue;
			}
			gao(fd, sheet);
			fclose(fd);
			printf("--------------------------------------------\n");
		}
	}
	book->save("gao.xls");
	book->release();
	return 0;
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <chrono>
#include <cstdio>
#include <set>
#include <string>
#include <vector>
#include <sdbusplus/vtable.hpp>
#include <systemd/sd-bus.h>
#include <systemd/sd-journal.h>
#include <phosphor-logging/elog-errors-HostEvent.hpp>
#include "config.h"
#include "elog_entry.hpp"
#include <phosphor-logging/log.hpp>
#include "log_manager.hpp"
#include "elog_meta.hpp"
#include "elog_serialize.hpp"

using namespace phosphor::logging;
extern const std::map<metadata::Metadata,
                      std::function<metadata::associations::Type>> meta;

namespace phosphor
{
namespace logging
{

void Manager::commit(uint64_t transactionId, std::string errMsg)
{
    constexpr const auto transactionIdVar = "TRANSACTION_ID";
    // Length of 'TRANSACTION_ID' string.
    constexpr const auto transactionIdVarSize = strlen(transactionIdVar);
    // Length of 'TRANSACTION_ID=' string.
    constexpr const auto transactionIdVarOffset = transactionIdVarSize + 1;

    sd_journal *j = nullptr;
    int rc = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY);
    if (rc < 0)
    {
        logging::log<logging::level::ERR>("Failed to open journal",
                           logging::entry("DESCRIPTION=%s", strerror(-rc)));
        return;
    }

    std::string transactionIdStr = std::to_string(transactionId);
    std::set<std::string> metalist;
    auto metamap = g_errMetaMap.find(errMsg);
    if (metamap != g_errMetaMap.end())
    {
        metalist.insert(metamap->second.begin(), metamap->second.end());
    }
    const auto& metalistHostEvent = g_errMetaMapHostEvent[errMsg];
    std::vector<std::string> additionalData;

    // TODO Remove once host event error header file is auto-generated.
    // Also make metalist a const variable.
    // Tracking with issue openbmc/phosphor-logging#4
    for (auto& metaVarStrHostEvent : metalistHostEvent)
    {
        metalist.insert(metaVarStrHostEvent);
    }

    // Read the journal from the end to get the most recent entry first.
    // The result from the sd_journal_get_data() is of the form VARIABLE=value.
    SD_JOURNAL_FOREACH_BACKWARDS(j)
    {
        const char *data = nullptr;
        size_t length = 0;

        // Look for the transaction id metadata variable
        rc = sd_journal_get_data(j, transactionIdVar, (const void **)&data,
                                &length);
        if (rc < 0)
        {
            // This journal entry does not have the TRANSACTION_ID
            // metadata variable.
            continue;
        }

        // journald does not guarantee that sd_journal_get_data() returns NULL
        // terminated strings, so need to specify the size to use to compare,
        // use the returned length instead of anything that relies on NULL
        // terminators like strlen().
        // The data variable is in the form of 'TRANSACTION_ID=1234'. Remove
        // the TRANSACTION_ID characters plus the (=) sign to do the comparison.
        // 'data + transactionIdVarOffset' will be in the form of '1234'.
        // 'length - transactionIdVarOffset' will be the length of '1234'.
        if ((length <= (transactionIdVarOffset)) ||
            (transactionIdStr.compare(0,
                                      transactionIdStr.size(),
                                      data + transactionIdVarOffset,
                                      length - transactionIdVarOffset) != 0))
        {
            // The value of the TRANSACTION_ID metadata is not the requested
            // transaction id number.
            continue;
        }

        // Search for all metadata variables in the current journal entry.
        for (auto i = metalist.cbegin(); i != metalist.cend();)
        {
            rc = sd_journal_get_data(j, (*i).c_str(),
                                    (const void **)&data, &length);
            if (rc < 0)
            {
                // Metadata variable not found, check next metadata variable.
                i++;
                continue;
            }

            // Metadata variable found, save it and remove it from the set.
            additionalData.emplace_back(data, length);
            i = metalist.erase(i);
        }
        if (metalist.empty())
        {
            // All metadata variables found, break out of journal loop.
            break;
        }
    }
    if (!metalist.empty())
    {
        // Not all the metadata variables were found in the journal.
        for (auto& metaVarStr : metalist)
        {
            logging::log<logging::level::INFO>("Failed to find metadata",
                    logging::entry("META_FIELD=%s", metaVarStr.c_str()));
        }
    }

    sd_journal_close(j);

    // Create error Entry dbus object
    entryId++;
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch()).count();
    auto objPath =  std::string(OBJ_ENTRY) + '/' +
            std::to_string(entryId);

    AssociationList objects {};
    processMetadata(errMsg, additionalData, objects);

    level reqLevel = level::INFO; // Default to INFO
    auto levelmap = g_errLevelMap.find(errMsg);
    if (levelmap != g_errLevelMap.end())
    {
        reqLevel = levelmap->second;
    }
    auto e = std::make_unique<Entry>(
                 busLog,
                 objPath,
                 entryId,
                 ms, // Milliseconds since 1970
                 static_cast<Entry::Level>(reqLevel),
                 std::move(errMsg),
                 std::move(additionalData),
                 std::move(objects),
                 *this);
    serialize(*e);
    entries.insert(std::make_pair(entryId, std::move(e)));
}

void Manager::processMetadata(const std::string& errorName,
                              const std::vector<std::string>& additionalData,
                              AssociationList& objects) const
{
    // additionalData is a list of "metadata=value"
    constexpr auto separator = '=';
    for(const auto& entry: additionalData)
    {
        auto found = entry.find(separator);
        if(std::string::npos != found)
        {
            auto metadata = entry.substr(0, found);
            auto iter = meta.find(metadata);
            if(meta.end() != iter)
            {
                (iter->second)(metadata, additionalData, objects);
            }
        }
    }
}

void Manager::erase(uint32_t entryId)
{
    auto entry = entries.find(entryId);
    auto id = entry->second->id();
    if(entries.end() != entry)
    {
        // Delete the persistent representation of this error.
        fs::path errorPath(ERRLOG_PERSIST_PATH);
        errorPath /= std::to_string(id);
        fs::remove(errorPath);

        entries.erase(entry);
    }
}

void Manager::restore()
{
    std::vector<uint32_t> errorIds;

    fs::path dir(ERRLOG_PERSIST_PATH);
    if (!fs::exists(dir) || fs::is_empty(dir))
    {
        return;
    }

    for(auto& file: fs::directory_iterator(dir))
    {
        auto id = file.path().filename().c_str();
        auto idNum = std::stol(id);
        auto e = std::make_unique<Entry>(
                     busLog,
                     std::string(OBJ_ENTRY) + '/' + id,
                     idNum,
                     *this);
        if (deserialize(file.path(), *e))
        {
            e->emit_object_added();
            entries.insert(std::make_pair(idNum, std::move(e)));
            errorIds.push_back(idNum);
        }
    }

    entryId = *(std::max_element(errorIds.begin(), errorIds.end()));
}

} // namespace logging
} // namepsace phosphor
<commit_msg>Fix host error logged as INFO<commit_after>#include <fstream>
#include <iostream>
#include <chrono>
#include <cstdio>
#include <set>
#include <string>
#include <vector>
#include <sdbusplus/vtable.hpp>
#include <systemd/sd-bus.h>
#include <systemd/sd-journal.h>
#include <phosphor-logging/elog-errors-HostEvent.hpp>
#include "config.h"
#include "elog_entry.hpp"
#include <phosphor-logging/log.hpp>
#include "log_manager.hpp"
#include "elog_meta.hpp"
#include "elog_serialize.hpp"

using namespace phosphor::logging;
extern const std::map<metadata::Metadata,
                      std::function<metadata::associations::Type>> meta;

namespace phosphor
{
namespace logging
{

void Manager::commit(uint64_t transactionId, std::string errMsg)
{
    constexpr const auto transactionIdVar = "TRANSACTION_ID";
    // Length of 'TRANSACTION_ID' string.
    constexpr const auto transactionIdVarSize = strlen(transactionIdVar);
    // Length of 'TRANSACTION_ID=' string.
    constexpr const auto transactionIdVarOffset = transactionIdVarSize + 1;

    sd_journal *j = nullptr;
    int rc = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY);
    if (rc < 0)
    {
        logging::log<logging::level::ERR>("Failed to open journal",
                           logging::entry("DESCRIPTION=%s", strerror(-rc)));
        return;
    }

    std::string transactionIdStr = std::to_string(transactionId);
    std::set<std::string> metalist;
    auto metamap = g_errMetaMap.find(errMsg);
    if (metamap != g_errMetaMap.end())
    {
        metalist.insert(metamap->second.begin(), metamap->second.end());
    }
    const auto& metalistHostEvent = g_errMetaMapHostEvent[errMsg];
    std::vector<std::string> additionalData;

    // TODO Remove once host event error header file is auto-generated.
    // Also make metalist a const variable.
    // Tracking with issue openbmc/phosphor-logging#4
    for (auto& metaVarStrHostEvent : metalistHostEvent)
    {
        metalist.insert(metaVarStrHostEvent);
    }

    // Read the journal from the end to get the most recent entry first.
    // The result from the sd_journal_get_data() is of the form VARIABLE=value.
    SD_JOURNAL_FOREACH_BACKWARDS(j)
    {
        const char *data = nullptr;
        size_t length = 0;

        // Look for the transaction id metadata variable
        rc = sd_journal_get_data(j, transactionIdVar, (const void **)&data,
                                &length);
        if (rc < 0)
        {
            // This journal entry does not have the TRANSACTION_ID
            // metadata variable.
            continue;
        }

        // journald does not guarantee that sd_journal_get_data() returns NULL
        // terminated strings, so need to specify the size to use to compare,
        // use the returned length instead of anything that relies on NULL
        // terminators like strlen().
        // The data variable is in the form of 'TRANSACTION_ID=1234'. Remove
        // the TRANSACTION_ID characters plus the (=) sign to do the comparison.
        // 'data + transactionIdVarOffset' will be in the form of '1234'.
        // 'length - transactionIdVarOffset' will be the length of '1234'.
        if ((length <= (transactionIdVarOffset)) ||
            (transactionIdStr.compare(0,
                                      transactionIdStr.size(),
                                      data + transactionIdVarOffset,
                                      length - transactionIdVarOffset) != 0))
        {
            // The value of the TRANSACTION_ID metadata is not the requested
            // transaction id number.
            continue;
        }

        // Search for all metadata variables in the current journal entry.
        for (auto i = metalist.cbegin(); i != metalist.cend();)
        {
            rc = sd_journal_get_data(j, (*i).c_str(),
                                    (const void **)&data, &length);
            if (rc < 0)
            {
                // Metadata variable not found, check next metadata variable.
                i++;
                continue;
            }

            // Metadata variable found, save it and remove it from the set.
            additionalData.emplace_back(data, length);
            i = metalist.erase(i);
        }
        if (metalist.empty())
        {
            // All metadata variables found, break out of journal loop.
            break;
        }
    }
    if (!metalist.empty())
    {
        // Not all the metadata variables were found in the journal.
        for (auto& metaVarStr : metalist)
        {
            logging::log<logging::level::INFO>("Failed to find metadata",
                    logging::entry("META_FIELD=%s", metaVarStr.c_str()));
        }
    }

    sd_journal_close(j);

    // Create error Entry dbus object
    entryId++;
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch()).count();
    auto objPath =  std::string(OBJ_ENTRY) + '/' +
            std::to_string(entryId);

    AssociationList objects {};
    processMetadata(errMsg, additionalData, objects);

    level reqLevel = level::ERR; // Default to ERR
    auto levelmap = g_errLevelMap.find(errMsg);
    if (levelmap != g_errLevelMap.end())
    {
        reqLevel = levelmap->second;
    }
    auto e = std::make_unique<Entry>(
                 busLog,
                 objPath,
                 entryId,
                 ms, // Milliseconds since 1970
                 static_cast<Entry::Level>(reqLevel),
                 std::move(errMsg),
                 std::move(additionalData),
                 std::move(objects),
                 *this);
    serialize(*e);
    entries.insert(std::make_pair(entryId, std::move(e)));
}

void Manager::processMetadata(const std::string& errorName,
                              const std::vector<std::string>& additionalData,
                              AssociationList& objects) const
{
    // additionalData is a list of "metadata=value"
    constexpr auto separator = '=';
    for(const auto& entry: additionalData)
    {
        auto found = entry.find(separator);
        if(std::string::npos != found)
        {
            auto metadata = entry.substr(0, found);
            auto iter = meta.find(metadata);
            if(meta.end() != iter)
            {
                (iter->second)(metadata, additionalData, objects);
            }
        }
    }
}

void Manager::erase(uint32_t entryId)
{
    auto entry = entries.find(entryId);
    auto id = entry->second->id();
    if(entries.end() != entry)
    {
        // Delete the persistent representation of this error.
        fs::path errorPath(ERRLOG_PERSIST_PATH);
        errorPath /= std::to_string(id);
        fs::remove(errorPath);

        entries.erase(entry);
    }
}

void Manager::restore()
{
    std::vector<uint32_t> errorIds;

    fs::path dir(ERRLOG_PERSIST_PATH);
    if (!fs::exists(dir) || fs::is_empty(dir))
    {
        return;
    }

    for(auto& file: fs::directory_iterator(dir))
    {
        auto id = file.path().filename().c_str();
        auto idNum = std::stol(id);
        auto e = std::make_unique<Entry>(
                     busLog,
                     std::string(OBJ_ENTRY) + '/' + id,
                     idNum,
                     *this);
        if (deserialize(file.path(), *e))
        {
            e->emit_object_added();
            entries.insert(std::make_pair(idNum, std::move(e)));
            errorIds.push_back(idNum);
        }
    }

    entryId = *(std::max_element(errorIds.begin(), errorIds.end()));
}

} // namespace logging
} // namepsace phosphor
<|endoftext|>