<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2010 Couchbase, Inc
 *
 *   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 <stdint.h>
#include <stdlib.h>
#include <string.h>

#if defined(__APPLE__)
#include <mach/mach_time.h>
#endif
#if defined(WIN32)
#include <Windows.h>
#else
#include <sys/time.h>
#endif
#if !defined(WIN32) && !defined(_WIN32)
#include <unistd.h>
#endif

#include "time_utils.h"

struct timeval _utime_gap(struct timeval a, struct timeval b)
{
    struct timeval ret;
    if (b.tv_usec >= a.tv_usec) {
        ret.tv_usec = b.tv_usec - a.tv_usec;
        ret.tv_sec = b.tv_sec - a.tv_sec;
    }else{
        ret.tv_usec = 1000000 + b.tv_usec - a.tv_usec;
        ret.tv_sec = b.tv_sec - a.tv_sec - 1;
    }
    return ret;
}

#if defined(WIN32) || defined(_WIN32)

void usleep(unsigned int usec)
{
    HANDLE timer;
    LARGE_INTEGER ft;

    // Convert to 100 nanosecond interval, negative value indicates relative time
    ft.QuadPart = -(10*usec);

    timer = CreateWaitableTimer(NULL, TRUE, NULL);
    SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
    WaitForSingleObject(timer, INFINITE);
    CloseHandle(timer);
}

#else

struct timespec convert_reltime_to_abstime(unsigned int ms) {
    struct timespec ts;
    struct timeval tp;
    uint64_t wakeup;

    memset(&ts, 0, sizeof(ts));

    /*
     * Unfortunately pthread_cond_timedwait doesn't support relative sleeps
     * so we need to convert back to an absolute time.
     */
    gettimeofday(&tp, NULL);
    wakeup = ((uint64_t)(tp.tv_sec) * 1000) + (tp.tv_usec / 1000) + ms;
    /* Round up for sub ms */
    if ((tp.tv_usec % 1000) > 499) {
        ++wakeup;
    }

    ts.tv_sec = wakeup / 1000;
    wakeup %= 1000;
    ts.tv_nsec = wakeup * 1000000;
    return ts;
}
#endif //!defined(WIN32) && !defined(_WIN32)

void decaying_usleep(unsigned int *sleep_time, unsigned int max_sleep_time) {
    usleep(*sleep_time);
    *sleep_time = *sleep_time << 1;
    if (max_sleep_time < *sleep_time) {
        *sleep_time = max_sleep_time;
    }
}

/*
    return a monotonically increasing value with a seconds frequency.
*/
ts_nsec get_monotonic_ts() {
    ts_nsec ts = 0;
#if defined(WIN32)
    LARGE_INTEGER _ts;
    QueryPerformanceCounter(&_ts);
    ts = _ts.QuadPart * 1000;
#elif defined(__APPLE__)
    long time = mach_absolute_time();

    static mach_timebase_info_data_t timebase;
    if (timebase.denom == 0) {
      mach_timebase_info(&timebase);
    }

    ts = (double)time * timebase.numer / timebase.denom;
#elif defined(__linux__) || defined(__sun) || defined(__FreeBSD__)
    /* Linux and Solaris can use clock_gettime */
    struct timespec tm;
    if (clock_gettime(CLOCK_MONOTONIC, &tm) == -1) {
        abort();
    }
    ts = tm.tv_nsec;
#else
#error "Don't know how to build get_monotonic_ts"
#endif

    return ts;
}

ts_nsec ts_diff(ts_nsec start, ts_nsec end)
{
    ts_nsec diff = 0;
    if ((end-start)<0) {
        diff  = 1000000000+end-start;
    } else {
        diff = end-start;
    }
    return diff/1000;
}
<commit_msg>MB-19390: Calculate time diff with PerfFreq on windows<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2010 Couchbase, Inc
 *
 *   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 <stdint.h>
#include <stdlib.h>
#include <string.h>

#if defined(__APPLE__)
#include <mach/mach_time.h>
#endif
#if defined(WIN32)
#include <Windows.h>
#else
#include <sys/time.h>
#endif
#if !defined(WIN32) && !defined(_WIN32)
#include <unistd.h>
#endif

#include "time_utils.h"

struct timeval _utime_gap(struct timeval a, struct timeval b)
{
    struct timeval ret;
    if (b.tv_usec >= a.tv_usec) {
        ret.tv_usec = b.tv_usec - a.tv_usec;
        ret.tv_sec = b.tv_sec - a.tv_sec;
    }else{
        ret.tv_usec = 1000000 + b.tv_usec - a.tv_usec;
        ret.tv_sec = b.tv_sec - a.tv_sec - 1;
    }
    return ret;
}

#if defined(WIN32) || defined(_WIN32)

void usleep(unsigned int usec)
{
    HANDLE timer;
    LARGE_INTEGER ft;

    // Convert to 100 nanosecond interval, negative value indicates relative time
    ft.QuadPart = -(10*usec);

    timer = CreateWaitableTimer(NULL, TRUE, NULL);
    SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
    WaitForSingleObject(timer, INFINITE);
    CloseHandle(timer);
}

#else

struct timespec convert_reltime_to_abstime(unsigned int ms) {
    struct timespec ts;
    struct timeval tp;
    uint64_t wakeup;

    memset(&ts, 0, sizeof(ts));

    /*
     * Unfortunately pthread_cond_timedwait doesn't support relative sleeps
     * so we need to convert back to an absolute time.
     */
    gettimeofday(&tp, NULL);
    wakeup = ((uint64_t)(tp.tv_sec) * 1000) + (tp.tv_usec / 1000) + ms;
    /* Round up for sub ms */
    if ((tp.tv_usec % 1000) > 499) {
        ++wakeup;
    }

    ts.tv_sec = wakeup / 1000;
    wakeup %= 1000;
    ts.tv_nsec = wakeup * 1000000;
    return ts;
}
#endif //!defined(WIN32) && !defined(_WIN32)

void decaying_usleep(unsigned int *sleep_time, unsigned int max_sleep_time) {
    usleep(*sleep_time);
    *sleep_time = *sleep_time << 1;
    if (max_sleep_time < *sleep_time) {
        *sleep_time = max_sleep_time;
    }
}

/*
    return a monotonically increasing value with a seconds frequency.
*/
ts_nsec get_monotonic_ts() {
    ts_nsec ts = 0;
#if defined(WIN32)
    LARGE_INTEGER _ts;
    QueryPerformanceCounter(&_ts);
    ts = _ts.QuadPart;
#elif defined(__APPLE__)
    long time = mach_absolute_time();

    static mach_timebase_info_data_t timebase;
    if (timebase.denom == 0) {
      mach_timebase_info(&timebase);
    }

    ts = (double)time * timebase.numer / timebase.denom;
#elif defined(__linux__) || defined(__sun) || defined(__FreeBSD__)
    /* Linux and Solaris can use clock_gettime */
    struct timespec tm;
    if (clock_gettime(CLOCK_MONOTONIC, &tm) == -1) {
        abort();
    }
    ts = tm.tv_nsec;
#else
#error "Don't know how to build get_monotonic_ts"
#endif

    return ts;
}

ts_nsec ts_diff(ts_nsec start, ts_nsec end)
{
    ts_nsec diff = 0;
    if ((end-start)<0) {
        diff  = 1000000000+end-start;
    } else {
        diff = end-start;
    }
#if defined(WIN32)
    LARGE_INTEGER Pf;
    QueryPerformanceFrequency(&Pf);
    return diff / (Pf.QuadPart/1000000);
#else
    return diff/1000;
#endif // defined(WIN32)
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief X11 utilities.
 *//*--------------------------------------------------------------------*/

#include "tcuLnxX11.hpp"
#include "gluRenderConfig.hpp"
#include "deMemory.h"

#include <X11/Xutil.h>

namespace tcu
{
namespace lnx
{
namespace x11
{

DisplayBase::DisplayBase (EventState& platform)
	: m_eventState	(platform)
{
}

DisplayBase::~DisplayBase (void)
{
}

WindowBase::WindowBase ()
	: m_visible	(false)
{
}

WindowBase::~WindowBase (void)
{
}

XlibDisplay::XlibDisplay (EventState& eventState, const char* name)
	: DisplayBase	(eventState)
{
	m_display = XOpenDisplay((char*)name); // Won't modify argument string.
	if (!m_display)
		throw ResourceError("Failed to open display", name, __FILE__, __LINE__);

	m_deleteAtom	= XInternAtom(m_display, "WM_DELETE_WINDOW", False);
}

XlibDisplay::~XlibDisplay (void)
{
	XCloseDisplay(m_display);
}

void XlibDisplay::processEvent (XEvent& event)
{
	switch (event.type)
	{
		case ClientMessage:
			if ((unsigned)event.xclient.data.l[0] == m_deleteAtom)
				m_eventState.setQuitFlag(true);
			break;
		// note: ConfigureNotify for window is handled in setDimensions()
		default:
			break;
	}
}

void XlibDisplay::processEvents (void)
{
	XEvent	event;

	while (XPending(m_display))
	{
		XNextEvent(m_display, &event);
		processEvent(event);
	}
}

bool XlibDisplay::getVisualInfo (VisualID visualID, XVisualInfo& dst)
{
	XVisualInfo		query;
	query.visualid = visualID;
	int				numVisuals	= 0;
	XVisualInfo*	response	= XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals);
	bool			succ		= false;

	if (response != DE_NULL)
	{
		if (numVisuals > 0) // should be 1, but you never know...
		{
			dst = response[0];
			succ = true;
		}
		XFree(response);
	}

	return succ;
}

::Visual* XlibDisplay::getVisual (VisualID visualID)
{
	XVisualInfo		info;

	if (getVisualInfo(visualID, info))
		return info.visual;

	return DE_NULL;
}

XlibWindow::XlibWindow (XlibDisplay& display, int width, int height, ::Visual* visual)
	: WindowBase	()
	, m_display		(display)
	, m_colormap	(None)
	, m_window		(None)
{
	XSetWindowAttributes	swa;
	::Display* const		dpy					= m_display.getXDisplay();
	::Window				root				= DefaultRootWindow(dpy);
	unsigned long			mask				= CWBorderPixel | CWEventMask;

	// If redirect is enabled, window size can't be guaranteed and it is up to
	// the window manager to decide whether to honor sizing requests. However,
	// overriding that causes window to appear as an overlay, which causes
	// other issues, so this is disabled by default.
	const bool				overrideRedirect	= false;

	if (overrideRedirect)
	{
		mask |= CWOverrideRedirect;
		swa.override_redirect = true;
	}

	if (visual == DE_NULL)
		visual = CopyFromParent;
	else
	{
		XVisualInfo	info	= XVisualInfo();
		bool		succ	= display.getVisualInfo(XVisualIDFromVisual(visual), info);

		TCU_CHECK_INTERNAL(succ);

		root				= RootWindow(dpy, info.screen);
		m_colormap			= XCreateColormap(dpy, root, visual, AllocNone);
		swa.colormap		= m_colormap;
		mask |= CWColormap;
	}

	swa.border_pixel	= 0;
	swa.event_mask		= ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask;

	if (width == glu::RenderConfig::DONT_CARE)
		width = DEFAULT_WINDOW_WIDTH;
	if (height == glu::RenderConfig::DONT_CARE)
		height = DEFAULT_WINDOW_HEIGHT;

	m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0,
							 CopyFromParent, InputOutput, visual, mask, &swa);
	TCU_CHECK(m_window);

	Atom deleteAtom = m_display.getDeleteAtom();
	XSetWMProtocols(dpy, m_window, &deleteAtom, 1);
	XSync(dpy,false);
}

void XlibWindow::setVisibility (bool visible)
{
	::Display*	dpy			= m_display.getXDisplay();
	int			eventType	= None;
	XEvent		event;

	if (visible == m_visible)
		return;

	if (visible)
	{
		XMapWindow(dpy, m_window);
		eventType = MapNotify;
	}
	else
	{
		XUnmapWindow(dpy, m_window);
		eventType = UnmapNotify;
	}

	// We are only interested about exposure/structure notify events, not user input
	XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask);

	do
	{
		XWindowEvent(dpy, m_window, ExposureMask | StructureNotifyMask, &event);
	} while (event.type != eventType);

	m_visible = visible;
}

void XlibWindow::getDimensions (int* width, int* height) const
{
	int x, y;
	::Window root;
	unsigned width_, height_, borderWidth, depth;

	XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth);
	if (width != DE_NULL)
		*width = static_cast<int>(width_);
	if (height != DE_NULL)
		*height = static_cast<int>(height_);
}

void XlibWindow::setDimensions (int width, int height)
{
	const unsigned int	mask		= CWWidth | CWHeight;
	XWindowChanges		changes;
	::Display*			dpy			= m_display.getXDisplay();
	XEvent				myevent;
	changes.width	= width;
	changes.height	= height;
	XConfigureWindow(dpy, m_window, mask, &changes);
	XFlush(dpy);

	for(;;)
	{
		XNextEvent(dpy, &myevent);
		if (myevent.type == ConfigureNotify) {
			XConfigureEvent e = myevent.xconfigure;
			if (e.width == width && e.height == height)
				break;
		}
		else
			m_display.processEvent(myevent);
	}
}

void XlibWindow::processEvents (void)
{
	// A bit of a hack, since we don't really handle all the events.
	m_display.processEvents();
}

XlibWindow::~XlibWindow (void)
{
	XDestroyWindow(m_display.getXDisplay(), m_window);
	if (m_colormap != None)
		XFreeColormap(m_display.getXDisplay(), m_colormap);
}

} // x11
} // lnx
} // tcu
<commit_msg>x11: Call XInitThreads() am: a8bd356e58 am: 4f03397c9d am: 84f10d0d99<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief X11 utilities.
 *//*--------------------------------------------------------------------*/

#include "tcuLnxX11.hpp"
#include "gluRenderConfig.hpp"
#include "deMemory.h"

#include <X11/Xutil.h>

namespace tcu
{
namespace lnx
{
namespace x11
{

DisplayBase::DisplayBase (EventState& platform)
	: m_eventState	(platform)
{
}

DisplayBase::~DisplayBase (void)
{
}

WindowBase::WindowBase ()
	: m_visible	(false)
{
}

WindowBase::~WindowBase (void)
{
}

XlibDisplay::XlibDisplay (EventState& eventState, const char* name)
	: DisplayBase	(eventState)
{
	// From man:XinitThreads(3):
	//
	//     The XInitThreads function initializes Xlib support for concurrent
	//     threads.  This function must be the first Xlib function
	//     a multi-threaded program calls, and it must complete before any other
	//     Xlib call is made.
	DE_CHECK_RUNTIME_ERR(XInitThreads() != 0);
	m_display = XOpenDisplay((char*)name); // Won't modify argument string.
	if (!m_display)
		throw ResourceError("Failed to open display", name, __FILE__, __LINE__);

	m_deleteAtom	= XInternAtom(m_display, "WM_DELETE_WINDOW", False);
}

XlibDisplay::~XlibDisplay (void)
{
	XCloseDisplay(m_display);
}

void XlibDisplay::processEvent (XEvent& event)
{
	switch (event.type)
	{
		case ClientMessage:
			if ((unsigned)event.xclient.data.l[0] == m_deleteAtom)
				m_eventState.setQuitFlag(true);
			break;
		// note: ConfigureNotify for window is handled in setDimensions()
		default:
			break;
	}
}

void XlibDisplay::processEvents (void)
{
	XEvent	event;

	while (XPending(m_display))
	{
		XNextEvent(m_display, &event);
		processEvent(event);
	}
}

bool XlibDisplay::getVisualInfo (VisualID visualID, XVisualInfo& dst)
{
	XVisualInfo		query;
	query.visualid = visualID;
	int				numVisuals	= 0;
	XVisualInfo*	response	= XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals);
	bool			succ		= false;

	if (response != DE_NULL)
	{
		if (numVisuals > 0) // should be 1, but you never know...
		{
			dst = response[0];
			succ = true;
		}
		XFree(response);
	}

	return succ;
}

::Visual* XlibDisplay::getVisual (VisualID visualID)
{
	XVisualInfo		info;

	if (getVisualInfo(visualID, info))
		return info.visual;

	return DE_NULL;
}

XlibWindow::XlibWindow (XlibDisplay& display, int width, int height, ::Visual* visual)
	: WindowBase	()
	, m_display		(display)
	, m_colormap	(None)
	, m_window		(None)
{
	XSetWindowAttributes	swa;
	::Display* const		dpy					= m_display.getXDisplay();
	::Window				root				= DefaultRootWindow(dpy);
	unsigned long			mask				= CWBorderPixel | CWEventMask;

	// If redirect is enabled, window size can't be guaranteed and it is up to
	// the window manager to decide whether to honor sizing requests. However,
	// overriding that causes window to appear as an overlay, which causes
	// other issues, so this is disabled by default.
	const bool				overrideRedirect	= false;

	if (overrideRedirect)
	{
		mask |= CWOverrideRedirect;
		swa.override_redirect = true;
	}

	if (visual == DE_NULL)
		visual = CopyFromParent;
	else
	{
		XVisualInfo	info	= XVisualInfo();
		bool		succ	= display.getVisualInfo(XVisualIDFromVisual(visual), info);

		TCU_CHECK_INTERNAL(succ);

		root				= RootWindow(dpy, info.screen);
		m_colormap			= XCreateColormap(dpy, root, visual, AllocNone);
		swa.colormap		= m_colormap;
		mask |= CWColormap;
	}

	swa.border_pixel	= 0;
	swa.event_mask		= ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask;

	if (width == glu::RenderConfig::DONT_CARE)
		width = DEFAULT_WINDOW_WIDTH;
	if (height == glu::RenderConfig::DONT_CARE)
		height = DEFAULT_WINDOW_HEIGHT;

	m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0,
							 CopyFromParent, InputOutput, visual, mask, &swa);
	TCU_CHECK(m_window);

	Atom deleteAtom = m_display.getDeleteAtom();
	XSetWMProtocols(dpy, m_window, &deleteAtom, 1);
	XSync(dpy,false);
}

void XlibWindow::setVisibility (bool visible)
{
	::Display*	dpy			= m_display.getXDisplay();
	int			eventType	= None;
	XEvent		event;

	if (visible == m_visible)
		return;

	if (visible)
	{
		XMapWindow(dpy, m_window);
		eventType = MapNotify;
	}
	else
	{
		XUnmapWindow(dpy, m_window);
		eventType = UnmapNotify;
	}

	// We are only interested about exposure/structure notify events, not user input
	XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask);

	do
	{
		XWindowEvent(dpy, m_window, ExposureMask | StructureNotifyMask, &event);
	} while (event.type != eventType);

	m_visible = visible;
}

void XlibWindow::getDimensions (int* width, int* height) const
{
	int x, y;
	::Window root;
	unsigned width_, height_, borderWidth, depth;

	XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth);
	if (width != DE_NULL)
		*width = static_cast<int>(width_);
	if (height != DE_NULL)
		*height = static_cast<int>(height_);
}

void XlibWindow::setDimensions (int width, int height)
{
	const unsigned int	mask		= CWWidth | CWHeight;
	XWindowChanges		changes;
	::Display*			dpy			= m_display.getXDisplay();
	XEvent				myevent;
	changes.width	= width;
	changes.height	= height;
	XConfigureWindow(dpy, m_window, mask, &changes);
	XFlush(dpy);

	for(;;)
	{
		XNextEvent(dpy, &myevent);
		if (myevent.type == ConfigureNotify) {
			XConfigureEvent e = myevent.xconfigure;
			if (e.width == width && e.height == height)
				break;
		}
		else
			m_display.processEvent(myevent);
	}
}

void XlibWindow::processEvents (void)
{
	// A bit of a hack, since we don't really handle all the events.
	m_display.processEvents();
}

XlibWindow::~XlibWindow (void)
{
	XDestroyWindow(m_display.getXDisplay(), m_window);
	if (m_colormap != None)
		XFreeColormap(m_display.getXDisplay(), m_colormap);
}

} // x11
} // lnx
} // tcu
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

// MOOSE includes
#include "OversampleOutput.h"
#include "FEProblem.h"
#include "DisplacedProblem.h"
#include "FileMesh.h"
#include "MooseApp.h"

// libMesh includes
#include "libmesh/equation_systems.h"
#include "libmesh/mesh_function.h"

template<>
InputParameters validParams<OversampleOutput>()
{

  // Get the parameters from the parent object
  InputParameters params = validParams<FileOutput>();
  params.addParam<unsigned int>("refinements", 0, "Number of uniform refinements for oversampling (refinement levels beyond any uniform refinements)");
  params.addParam<Point>("position", "Set a positional offset, this vector will get added to the nodal coordinates to move the domain.");
  params.addParam<MeshFileName>("file", "The name of the mesh file to read, for oversampling");

  // **** DEPRECATED AND REMOVED PARAMETERS ****
  params.addDeprecatedParam<bool>("oversample", false, "Set to true to enable oversampling",
                                  "This parameter is no longer active, simply set 'refinements' to a value greater than zero to evoke oversampling");
  params.addDeprecatedParam<bool>("append_oversample", false, "Append '_oversample' to the output file base",
                                  "This parameter is no longer operational, to append '_oversample' utilize the output block name or 'file_base'");

  // 'Oversampling' Group
  params.addParamNamesToGroup("refinements position file", "Oversampling");

  return params;
}

OversampleOutput::OversampleOutput(const InputParameters & parameters) :
    FileOutput(parameters),
    _mesh_ptr(getParam<bool>("use_displaced") ?
              &_problem_ptr->getDisplacedProblem()->mesh() : &_problem_ptr->mesh()),
    _refinements(getParam<unsigned int>("refinements")),
    _oversample(_refinements > 0 || isParamValid("file")),
    _change_position(isParamValid("position")),
    _position(_change_position ? getParam<Point>("position") : Point()),
    _oversample_mesh_changed(true)
{
  // ** DEPRECATED SUPPORT **
  if (getParam<bool>("append_oversample"))
    _file_base += "_oversample";

  // Creates and initializes the oversampled mesh
  initOversample();
}

OversampleOutput::~OversampleOutput()
{
  // TODO: Remove once libmesh Issue #1184 is fixed
  _oversample_es.reset();
  _cloned_mesh_ptr.reset();
}

void
OversampleOutput::meshChanged()
{
  _oversample_mesh_changed = true;
}

void
OversampleOutput::initOversample()
{
  // Perform the mesh cloning, if needed
  if (_change_position || _oversample)
    cloneMesh();
  else
    return;

  // Re-position the oversampled mesh
  if (_change_position)
    for (MeshBase::node_iterator nd = _mesh_ptr->getMesh().nodes_begin(); nd != _mesh_ptr->getMesh().nodes_end(); ++nd)
      *(*nd) += _position;

  // Perform the mesh refinement
  if (_oversample)
  {
    MeshRefinement mesh_refinement(_mesh_ptr->getMesh());
    mesh_refinement.uniformly_refine(_refinements);
  }

  // We can't allow renumbering if we want to output multiple time
  // steps to the same Exodus file
  _mesh_ptr->getMesh().allow_renumbering(false);

  // Create the new EquationSystems
  _oversample_es = libmesh_make_unique<EquationSystems>(_mesh_ptr->getMesh());
  _es_ptr = _oversample_es.get();

  // Reference the system from which we are copying
  EquationSystems & source_es = _problem_ptr->es();

  // Initialize the _mesh_functions vector
  unsigned int num_systems = source_es.n_systems();
  _mesh_functions.resize(num_systems);

  // Loop over the number of systems
  for (unsigned int sys_num = 0; sys_num < num_systems; sys_num++)
  {
    // Reference to the current system
    System & source_sys = source_es.get_system(sys_num);

    // Add the system to the new EquationsSystems
    ExplicitSystem & dest_sys = _oversample_es->add_system<ExplicitSystem>(source_sys.name());

    // Loop through the variables in the System
    unsigned int num_vars = source_sys.n_vars();
    if (num_vars > 0)
    {
      _mesh_functions[sys_num].resize(num_vars);
      _serialized_solution = NumericVector<Number>::build(_communicator);
      _serialized_solution->init(source_sys.n_dofs(), false, SERIAL);

      // Need to pull down a full copy of this vector on every processor so we can get values in parallel
      source_sys.solution->localize(*_serialized_solution);

      // Add the variables to the system... simultaneously creating MeshFunctions for them.
      for (unsigned int var_num = 0; var_num < num_vars; var_num++)
      {
        // Add the variable, allow for first and second lagrange
        const FEType & fe_type = source_sys.variable_type(var_num);
        FEType second(SECOND, LAGRANGE);
        if (fe_type == second)
          dest_sys.add_variable(source_sys.variable_name(var_num), second);
        else
          dest_sys.add_variable(source_sys.variable_name(var_num), FEType());
      }
    }
  }

  // Initialize the newly created EquationSystem
  _oversample_es->init();
}

void
OversampleOutput::updateOversample()
{
  // Do nothing if oversampling and changing position are not enabled
  if (!_oversample && !_change_position)
    return;

  // Get a reference to actual equation system
  EquationSystems & source_es = _problem_ptr->es();

  // Loop throuch each system
  for (unsigned int sys_num = 0; sys_num < source_es.n_systems(); ++sys_num)
  {
    if (!_mesh_functions[sys_num].empty())
    {
      // Get references to the source and destination systems
      System & source_sys = source_es.get_system(sys_num);
      System & dest_sys = _oversample_es->get_system(sys_num);

      // Update the solution for the oversampled mesh
      _serialized_solution->clear();
      _serialized_solution->init(source_sys.n_dofs(), false, SERIAL);
      source_sys.solution->localize(*_serialized_solution);

      // Update the mesh functions
      for (unsigned int var_num = 0; var_num < _mesh_functions[sys_num].size(); ++var_num)
      {

        // If the mesh has change the MeshFunctions need to be re-built, otherwise simply clear it for re-initialization
        if (!_mesh_functions[sys_num][var_num] || _oversample_mesh_changed)
          _mesh_functions[sys_num][var_num] = libmesh_make_unique<MeshFunction>(source_es, *_serialized_solution, source_sys.get_dof_map(), var_num);
        else
          _mesh_functions[sys_num][var_num]->clear();

        // Initialize the MeshFunctions for application to the oversampled solution
        _mesh_functions[sys_num][var_num]->init();
      }

      // Now loop over the nodes of the oversampled mesh setting values for each variable.
      for (MeshBase::const_node_iterator nd = _mesh_ptr->localNodesBegin(); nd != _mesh_ptr->localNodesEnd(); ++nd)
        for (unsigned int var_num = 0; var_num < _mesh_functions[sys_num].size(); ++var_num)
          if ((*nd)->n_dofs(sys_num, var_num))
            dest_sys.solution->set((*nd)->dof_number(sys_num, var_num, 0), (*_mesh_functions[sys_num][var_num])(**nd - _position)); // 0 value is for component
    }
  }

  // Set this to false so that new output files are not created, since the oversampled mesh doesn't actually change
  _oversample_mesh_changed = false;
}

void
OversampleOutput::cloneMesh()
{
  // Create the new mesh from a file
  if (isParamValid("file"))
  {
    InputParameters mesh_params = emptyInputParameters();
    mesh_params += _problem_ptr->mesh().parameters();
    mesh_params.set<MeshFileName>("file") = getParam<MeshFileName>("file");
    mesh_params.set<bool>("nemesis") = false;
    mesh_params.set<bool>("skip_partitioning") = false;
    mesh_params.set<std::string>("_object_name") = "output_problem_mesh";
    _cloned_mesh_ptr = libmesh_make_unique<FileMesh>(mesh_params);
    _cloned_mesh_ptr->allowRecovery(false); // We actually want to reread the initial mesh
    _cloned_mesh_ptr->init();
    _cloned_mesh_ptr->prepare();
    _cloned_mesh_ptr->meshChanged();
  }

  // Clone the existing mesh
  else
  {
    if (_app.isRecovering())
      mooseWarning("Recovering or Restarting with Oversampling may not work (especially with adapted meshes)!!  Refs #2295");

    _cloned_mesh_ptr.reset(&(_problem_ptr->mesh().clone()));
  }

  // Make sure that the mesh pointer points to the newly cloned mesh
  _mesh_ptr = _cloned_mesh_ptr.get();
}
<commit_msg>Skip repartitioning on oversampling meshes<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

// MOOSE includes
#include "OversampleOutput.h"
#include "FEProblem.h"
#include "DisplacedProblem.h"
#include "FileMesh.h"
#include "MooseApp.h"

// libMesh includes
#include "libmesh/equation_systems.h"
#include "libmesh/mesh_function.h"

template<>
InputParameters validParams<OversampleOutput>()
{

  // Get the parameters from the parent object
  InputParameters params = validParams<FileOutput>();
  params.addParam<unsigned int>("refinements", 0, "Number of uniform refinements for oversampling (refinement levels beyond any uniform refinements)");
  params.addParam<Point>("position", "Set a positional offset, this vector will get added to the nodal coordinates to move the domain.");
  params.addParam<MeshFileName>("file", "The name of the mesh file to read, for oversampling");

  // **** DEPRECATED AND REMOVED PARAMETERS ****
  params.addDeprecatedParam<bool>("oversample", false, "Set to true to enable oversampling",
                                  "This parameter is no longer active, simply set 'refinements' to a value greater than zero to evoke oversampling");
  params.addDeprecatedParam<bool>("append_oversample", false, "Append '_oversample' to the output file base",
                                  "This parameter is no longer operational, to append '_oversample' utilize the output block name or 'file_base'");

  // 'Oversampling' Group
  params.addParamNamesToGroup("refinements position file", "Oversampling");

  return params;
}

OversampleOutput::OversampleOutput(const InputParameters & parameters) :
    FileOutput(parameters),
    _mesh_ptr(getParam<bool>("use_displaced") ?
              &_problem_ptr->getDisplacedProblem()->mesh() : &_problem_ptr->mesh()),
    _refinements(getParam<unsigned int>("refinements")),
    _oversample(_refinements > 0 || isParamValid("file")),
    _change_position(isParamValid("position")),
    _position(_change_position ? getParam<Point>("position") : Point()),
    _oversample_mesh_changed(true)
{
  // ** DEPRECATED SUPPORT **
  if (getParam<bool>("append_oversample"))
    _file_base += "_oversample";

  // Creates and initializes the oversampled mesh
  initOversample();
}

OversampleOutput::~OversampleOutput()
{
  // TODO: Remove once libmesh Issue #1184 is fixed
  _oversample_es.reset();
  _cloned_mesh_ptr.reset();
}

void
OversampleOutput::meshChanged()
{
  _oversample_mesh_changed = true;
}

void
OversampleOutput::initOversample()
{
  // Perform the mesh cloning, if needed
  if (_change_position || _oversample)
    cloneMesh();
  else
    return;

  // Re-position the oversampled mesh
  if (_change_position)
    for (MeshBase::node_iterator nd = _mesh_ptr->getMesh().nodes_begin(); nd != _mesh_ptr->getMesh().nodes_end(); ++nd)
      *(*nd) += _position;

  // Perform the mesh refinement
  if (_oversample)
  {
    MeshRefinement mesh_refinement(_mesh_ptr->getMesh());

    // We want original and refined partitioning to match so we can
    // query from one to the other safely on distributed meshes.
    _mesh_ptr->getMesh().skip_partitioning(true);
    mesh_refinement.uniformly_refine(_refinements);
  }

  // We can't allow renumbering if we want to output multiple time
  // steps to the same Exodus file
  _mesh_ptr->getMesh().allow_renumbering(false);

  // Create the new EquationSystems
  _oversample_es = libmesh_make_unique<EquationSystems>(_mesh_ptr->getMesh());
  _es_ptr = _oversample_es.get();

  // Reference the system from which we are copying
  EquationSystems & source_es = _problem_ptr->es();

  // Initialize the _mesh_functions vector
  unsigned int num_systems = source_es.n_systems();
  _mesh_functions.resize(num_systems);

  // Loop over the number of systems
  for (unsigned int sys_num = 0; sys_num < num_systems; sys_num++)
  {
    // Reference to the current system
    System & source_sys = source_es.get_system(sys_num);

    // Add the system to the new EquationsSystems
    ExplicitSystem & dest_sys = _oversample_es->add_system<ExplicitSystem>(source_sys.name());

    // Loop through the variables in the System
    unsigned int num_vars = source_sys.n_vars();
    if (num_vars > 0)
    {
      _mesh_functions[sys_num].resize(num_vars);
      _serialized_solution = NumericVector<Number>::build(_communicator);
      _serialized_solution->init(source_sys.n_dofs(), false, SERIAL);

      // Need to pull down a full copy of this vector on every processor so we can get values in parallel
      source_sys.solution->localize(*_serialized_solution);

      // Add the variables to the system... simultaneously creating MeshFunctions for them.
      for (unsigned int var_num = 0; var_num < num_vars; var_num++)
      {
        // Add the variable, allow for first and second lagrange
        const FEType & fe_type = source_sys.variable_type(var_num);
        FEType second(SECOND, LAGRANGE);
        if (fe_type == second)
          dest_sys.add_variable(source_sys.variable_name(var_num), second);
        else
          dest_sys.add_variable(source_sys.variable_name(var_num), FEType());
      }
    }
  }

  // Initialize the newly created EquationSystem
  _oversample_es->init();
}

void
OversampleOutput::updateOversample()
{
  // Do nothing if oversampling and changing position are not enabled
  if (!_oversample && !_change_position)
    return;

  // Get a reference to actual equation system
  EquationSystems & source_es = _problem_ptr->es();

  // Loop throuch each system
  for (unsigned int sys_num = 0; sys_num < source_es.n_systems(); ++sys_num)
  {
    if (!_mesh_functions[sys_num].empty())
    {
      // Get references to the source and destination systems
      System & source_sys = source_es.get_system(sys_num);
      System & dest_sys = _oversample_es->get_system(sys_num);

      // Update the solution for the oversampled mesh
      _serialized_solution->clear();
      _serialized_solution->init(source_sys.n_dofs(), false, SERIAL);
      source_sys.solution->localize(*_serialized_solution);

      // Update the mesh functions
      for (unsigned int var_num = 0; var_num < _mesh_functions[sys_num].size(); ++var_num)
      {

        // If the mesh has change the MeshFunctions need to be re-built, otherwise simply clear it for re-initialization
        if (!_mesh_functions[sys_num][var_num] || _oversample_mesh_changed)
          _mesh_functions[sys_num][var_num] = libmesh_make_unique<MeshFunction>(source_es, *_serialized_solution, source_sys.get_dof_map(), var_num);
        else
          _mesh_functions[sys_num][var_num]->clear();

        // Initialize the MeshFunctions for application to the oversampled solution
        _mesh_functions[sys_num][var_num]->init();
      }

      // Now loop over the nodes of the oversampled mesh setting values for each variable.
      for (MeshBase::const_node_iterator nd = _mesh_ptr->localNodesBegin(); nd != _mesh_ptr->localNodesEnd(); ++nd)
        for (unsigned int var_num = 0; var_num < _mesh_functions[sys_num].size(); ++var_num)
          if ((*nd)->n_dofs(sys_num, var_num))
            dest_sys.solution->set((*nd)->dof_number(sys_num, var_num, 0), (*_mesh_functions[sys_num][var_num])(**nd - _position)); // 0 value is for component
    }
  }

  // Set this to false so that new output files are not created, since the oversampled mesh doesn't actually change
  _oversample_mesh_changed = false;
}

void
OversampleOutput::cloneMesh()
{
  // Create the new mesh from a file
  if (isParamValid("file"))
  {
    InputParameters mesh_params = emptyInputParameters();
    mesh_params += _problem_ptr->mesh().parameters();
    mesh_params.set<MeshFileName>("file") = getParam<MeshFileName>("file");
    mesh_params.set<bool>("nemesis") = false;
    mesh_params.set<bool>("skip_partitioning") = false;
    mesh_params.set<std::string>("_object_name") = "output_problem_mesh";
    _cloned_mesh_ptr = libmesh_make_unique<FileMesh>(mesh_params);
    _cloned_mesh_ptr->allowRecovery(false); // We actually want to reread the initial mesh
    _cloned_mesh_ptr->init();
    _cloned_mesh_ptr->prepare();
    _cloned_mesh_ptr->meshChanged();
  }

  // Clone the existing mesh
  else
  {
    if (_app.isRecovering())
      mooseWarning("Recovering or Restarting with Oversampling may not work (especially with adapted meshes)!!  Refs #2295");

    _cloned_mesh_ptr.reset(&(_problem_ptr->mesh().clone()));
  }

  // Make sure that the mesh pointer points to the newly cloned mesh
  _mesh_ptr = _cloned_mesh_ptr.get();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/validation/Type.h"

using namespace db::rt;
using namespace db::validation;

Type::Type(db::rt::DynamicObjectType type, const char* errorMessage) :
   Validator(errorMessage),
   mType(type)
{
}

Type::~Type()
{
}

bool Type::isValid(DynamicObject& obj, ValidatorContext* context)
{
   bool rval = (!obj.isNull() && obj->getType() == mType);

   if(!rval)
   {
      const char* strType = DynamicObject::descriptionForType(obj->getType());
      int length = 40 + strlen(strType);
      char temp[length];
      snprintf(temp, length, "Invalid type, received '%s'", strType);

      DynamicObject detail = context->addError("db.validation.TypeError", &obj);
      detail["validator"] = "db.validator.Type";
      // FIXME: localize
      detail["message"] = mErrorMessage ? mErrorMessage : temp;
      detail["expectedType"] = DynamicObject::descriptionForType(mType);
   }
   return rval;
}
<commit_msg>Handle null DynamicObject.<commit_after>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/validation/Type.h"

using namespace db::rt;
using namespace db::validation;

Type::Type(db::rt::DynamicObjectType type, const char* errorMessage) :
   Validator(errorMessage),
   mType(type)
{
}

Type::~Type()
{
}

bool Type::isValid(DynamicObject& obj, ValidatorContext* context)
{
   bool rval = (!obj.isNull() && obj->getType() == mType);

   if(!rval)
   {
      const char* strType =
         obj.isNull() ?
            "null" :
            DynamicObject::descriptionForType(obj->getType());
      int length = 40 + strlen(strType);
      char temp[length];
      snprintf(temp, length, "Invalid type, received '%s'", strType);

      DynamicObject detail = context->addError("db.validation.TypeError", &obj);
      detail["validator"] = "db.validator.Type";
      // FIXME: localize
      detail["message"] = mErrorMessage ? mErrorMessage : temp;
      detail["expectedType"] = DynamicObject::descriptionForType(mType);
   }
   return rval;
}
<|endoftext|>


<commit_before>/**
 *  \file RMF/paths.cpp
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2012 IMP Inventors. All rights reserved.
 *
 */

#include <RMF/internal/paths.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <stdexcept>

namespace RMF {
  namespace internal {
    std::string get_relative_path(std::string base,
                                  std::string file) {
      // assume it already is
      return file;
    }
    std::string get_absolute_path(std::string base,
                                  std::string file) {
      return boost::filesystem::canonical(boost::filesystem::path(base)
                                          /boost::filesystem::path(file))
        .string();
    }
  } // namespace internal
} /* namespace RMF */
<commit_msg>force filesystem version 3<commit_after>/**
 *  \file RMF/paths.cpp
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2012 IMP Inventors. All rights reserved.
 *
 */

#include <RMF/internal/paths.h>
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <stdexcept>

namespace RMF {
  namespace internal {
    std::string get_relative_path(std::string base,
                                  std::string file) {
      // assume it already is
      return file;
    }
    std::string get_absolute_path(std::string base,
                                  std::string file) {
      return boost::filesystem::canonical(boost::filesystem::path(base)
                                          /boost::filesystem::path(file))
        .string();
    }
  } // namespace internal
} /* namespace RMF */
<|endoftext|>


<commit_before>// $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTTPCDigitDumpComponent.cxx
    @author Matthias Richter
    @date
    @brief  Special file writer converting TPC digit input to ASCII. */

// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

#include <cassert>
#include "AliHLTTPCDigitDumpComponent.h"
#include "AliHLTTPCTransform.h"
#include "AliHLTTPCDigitReaderRaw.h"
#include "AliHLTTPCDefinitions.h"

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCDigitDumpComponent)

AliHLTTPCDigitDumpComponent::AliHLTTPCDigitDumpComponent()
  :
  AliHLTFileWriter(),
  fRawreaderMode(0)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTTPCDigitDumpComponent::~AliHLTTPCDigitDumpComponent()
{
  // see header file for class documentation
}

const char* AliHLTTPCDigitDumpComponent::GetComponentID()
{
  // see header file for class documentation
  return "TPCDigitDump";
}

void AliHLTTPCDigitDumpComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
  // see header file for class documentation
  list.clear();
  list.push_back(kAliHLTAnyDataType);
}

AliHLTComponent* AliHLTTPCDigitDumpComponent::Spawn()
{
  // see header file for class documentation
  return new AliHLTTPCDigitDumpComponent;
}

int AliHLTTPCDigitDumpComponent::InitWriter()
{
  // see header file for class documentation
  return 0;
}

int AliHLTTPCDigitDumpComponent::ScanArgument(int argc, const char** argv)
{
  // see header file for class documentation
  int iResult=0;
  TString argument="";
  bool bMissingParam=0;
  int i=0;
  for (; i<argc && iResult>=0; i++) {
    argument=argv[i];
    if (argument.IsNull()) continue;

    // -rawreadermode
    if (argument.CompareTo("-rawreadermode")==0) {
      if ((bMissingParam=(++i>=argc))) break;
      int mode=AliHLTTPCDigitReaderRaw::DecodeMode(argv[i]);
      if (mode<0) {
	HLTError("invalid rawreadermode specifier '%s'", argv[i]);
	iResult=-EINVAL;
      } else {
	fRawreaderMode=static_cast<unsigned>(mode);
      }
      break;
    }
  }

  if (bMissingParam) {
    iResult=-EPROTO;
  }
  if (iResult>=0) iResult=i+1;

  return iResult;
}

int AliHLTTPCDigitDumpComponent::CloseWriter()
{
  // see header file for class documentation
  return 0;
}

int AliHLTTPCDigitDumpComponent::DumpEvent( const AliHLTComponentEventData& evtData,
					    const AliHLTComponentBlockData* blocks,
					    AliHLTComponentTriggerData& /*trigData*/ )
{
  // see header file for class documentation
  int iResult=0;
  int iPrintedSlice=-1;
  int iPrintedPart=-1;
  int blockno=0;
  const AliHLTComponentBlockData* pDesc=NULL;

  for (pDesc=GetFirstInputBlock(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginTPC); pDesc!=NULL; pDesc=GetNextInputBlock(), blockno++) {
    HLTDebug("event %Lu block %d: %s 0x%08x size %d", evtData.fEventID, blockno, DataType2Text(pDesc->fDataType).c_str(), pDesc->fSpecification, pDesc->fSize);
    TString filename;
    iResult=BuildFileName(evtData.fEventID, blockno, pDesc->fDataType, pDesc->fSpecification, filename);
    ios::openmode filemode=(ios::openmode)0;
    if (fCurrentFileName.CompareTo(filename)==0) {
      // append to the file
      filemode=ios::app;
    } else {
      // store the file for the next block
      fCurrentFileName=filename;
    }
    if (iResult>=0) {
      ofstream dump(filename.Data(), filemode);
      if (dump.good()) {
	int part=AliHLTTPCDefinitions::GetMinPatchNr(*pDesc);
	assert(part==AliHLTTPCDefinitions::GetMaxPatchNr(*pDesc));
	int slice=AliHLTTPCDefinitions::GetMinSliceNr(*pDesc);
	assert(slice==AliHLTTPCDefinitions::GetMaxSliceNr(*pDesc));
	int firstRow=AliHLTTPCTransform::GetFirstRow(part);
	int lastRow=AliHLTTPCTransform::GetLastRow(part);
	AliHLTTPCDigitReaderRaw reader(fRawreaderMode);
	reader.InitBlock(pDesc->fPtr,pDesc->fSize,firstRow,lastRow,part,slice);

	int iPrintedRow=-1;
	int iPrintedPad=-1;
	int iLastTime=-1;
	while (reader.Next()) {
	  if ((iPrintedSlice!=-1 && iLastTime!=reader.GetTime()+1 && iLastTime!=reader.GetTime()-1) ||
	      (iPrintedPad!=-1 && iPrintedPad!=reader.GetPad()) ||
	      (iPrintedRow!=-1 && iPrintedRow!=reader.GetRow())) {
	    dump << endl;
	  }
	  if (iPrintedSlice!=slice || iPrintedPart!=part) {
	    iPrintedSlice=slice;
	    iPrintedPart=part;
	    dump << "====================================================================" << endl;
	    dump << "    Slice: " << iPrintedSlice << "   Partition: " << iPrintedPart << endl;
	    iPrintedRow=-1;
	  }
	  if (iPrintedRow!=reader.GetRow()) {
	    iPrintedRow=reader.GetRow();
	    dump << "--------------------------------------------------------------------" << endl;
	    dump << "Row: " << iPrintedRow << endl;
	    iPrintedPad=-1;
	  }
	  if (iPrintedPad!=reader.GetPad()) {
	    iPrintedPad=reader.GetPad();
	    dump << "Row: " << iPrintedRow << "  Pad: " << iPrintedPad << endl;
	    iLastTime=-1;
	  }
	  if (iLastTime!=reader.GetTime()+1 && iLastTime!=reader.GetTime()-1 ) {
	    dump << "                     Time " << reader.GetTime() << ":  ";
	  }
	  iLastTime=reader.GetTime();
	  dump << "  " << reader.GetSignal();
	}
	dump << endl << endl;
      } else {
	HLTError("can not open file %s for writing", filename.Data());
	iResult=-EBADF;
      }
      dump.close();
    }
  }
  return iResult;
}
<commit_msg>minor bugfix in argument scanning<commit_after>// $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTTPCDigitDumpComponent.cxx
    @author Matthias Richter
    @date
    @brief  Special file writer converting TPC digit input to ASCII. */

// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

#include <cassert>
#include "AliHLTTPCDigitDumpComponent.h"
#include "AliHLTTPCTransform.h"
#include "AliHLTTPCDigitReaderRaw.h"
#include "AliHLTTPCDefinitions.h"

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCDigitDumpComponent)

AliHLTTPCDigitDumpComponent::AliHLTTPCDigitDumpComponent()
  :
  AliHLTFileWriter(),
  fRawreaderMode(0)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTTPCDigitDumpComponent::~AliHLTTPCDigitDumpComponent()
{
  // see header file for class documentation
}

const char* AliHLTTPCDigitDumpComponent::GetComponentID()
{
  // see header file for class documentation
  return "TPCDigitDump";
}

void AliHLTTPCDigitDumpComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
  // see header file for class documentation
  list.clear();
  list.push_back(kAliHLTAnyDataType);
}

AliHLTComponent* AliHLTTPCDigitDumpComponent::Spawn()
{
  // see header file for class documentation
  return new AliHLTTPCDigitDumpComponent;
}

int AliHLTTPCDigitDumpComponent::InitWriter()
{
  // see header file for class documentation
  return 0;
}

int AliHLTTPCDigitDumpComponent::ScanArgument(int argc, const char** argv)
{
  // see header file for class documentation
  int iResult=0;
  TString argument="";
  bool bMissingParam=0;
  int i=0;
  do {
    if (i>=argc || (argument=argv[i]).IsNull()) continue;

    // -rawreadermode
    if (argument.CompareTo("-rawreadermode")==0) {
      if ((bMissingParam=(++i>=argc))) break;
      int mode=AliHLTTPCDigitReaderRaw::DecodeMode(argv[i]);
      if (mode<0) {
	HLTError("invalid rawreadermode specifier '%s'", argv[i]);
	iResult=-EINVAL;
      } else {
	fRawreaderMode=static_cast<unsigned>(mode);
      }
    }
  } while (0); // just use the do/while here to have the option of breaking

  if (bMissingParam) iResult=-EPROTO;
  else if (iResult>=0) iResult=i;

  return iResult;
}

int AliHLTTPCDigitDumpComponent::CloseWriter()
{
  // see header file for class documentation
  return 0;
}

int AliHLTTPCDigitDumpComponent::DumpEvent( const AliHLTComponentEventData& evtData,
					    const AliHLTComponentBlockData* blocks,
					    AliHLTComponentTriggerData& /*trigData*/ )
{
  // see header file for class documentation
  int iResult=0;
  int iPrintedSlice=-1;
  int iPrintedPart=-1;
  int blockno=0;
  const AliHLTComponentBlockData* pDesc=NULL;

  for (pDesc=GetFirstInputBlock(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginTPC); pDesc!=NULL; pDesc=GetNextInputBlock(), blockno++) {
    HLTDebug("event %Lu block %d: %s 0x%08x size %d", evtData.fEventID, blockno, DataType2Text(pDesc->fDataType).c_str(), pDesc->fSpecification, pDesc->fSize);
    TString filename;
    iResult=BuildFileName(evtData.fEventID, blockno, pDesc->fDataType, pDesc->fSpecification, filename);
    ios::openmode filemode=(ios::openmode)0;
    if (fCurrentFileName.CompareTo(filename)==0) {
      // append to the file
      filemode=ios::app;
    } else {
      // store the file for the next block
      fCurrentFileName=filename;
    }
    if (iResult>=0) {
      ofstream dump(filename.Data(), filemode);
      if (dump.good()) {
	int part=AliHLTTPCDefinitions::GetMinPatchNr(*pDesc);
	assert(part==AliHLTTPCDefinitions::GetMaxPatchNr(*pDesc));
	int slice=AliHLTTPCDefinitions::GetMinSliceNr(*pDesc);
	assert(slice==AliHLTTPCDefinitions::GetMaxSliceNr(*pDesc));
	int firstRow=AliHLTTPCTransform::GetFirstRow(part);
	int lastRow=AliHLTTPCTransform::GetLastRow(part);
	AliHLTTPCDigitReaderRaw reader(fRawreaderMode);
	reader.InitBlock(pDesc->fPtr,pDesc->fSize,firstRow,lastRow,part,slice);

	int iPrintedRow=-1;
	int iPrintedPad=-1;
	int iLastTime=-1;
	while (reader.Next()) {
	  if ((iPrintedSlice!=-1 && iLastTime!=reader.GetTime()+1 && iLastTime!=reader.GetTime()-1) ||
	      (iPrintedPad!=-1 && iPrintedPad!=reader.GetPad()) ||
	      (iPrintedRow!=-1 && iPrintedRow!=reader.GetRow())) {
	    dump << endl;
	  }
	  if (iPrintedSlice!=slice || iPrintedPart!=part) {
	    iPrintedSlice=slice;
	    iPrintedPart=part;
	    dump << "====================================================================" << endl;
	    dump << "    Slice: " << iPrintedSlice << "   Partition: " << iPrintedPart << endl;
	    iPrintedRow=-1;
	  }
	  if (iPrintedRow!=reader.GetRow()) {
	    iPrintedRow=reader.GetRow();
	    dump << "--------------------------------------------------------------------" << endl;
	    dump << "Row: " << iPrintedRow << endl;
	    iPrintedPad=-1;
	  }
	  if (iPrintedPad!=reader.GetPad()) {
	    iPrintedPad=reader.GetPad();
	    dump << "Row: " << iPrintedRow << "  Pad: " << iPrintedPad << endl;
	    iLastTime=-1;
	  }
	  if (iLastTime!=reader.GetTime()+1 && iLastTime!=reader.GetTime()-1 ) {
	    dump << "                     Time " << reader.GetTime() << ":  ";
	  }
	  iLastTime=reader.GetTime();
	  dump << "  " << reader.GetSignal();
	}
	dump << endl << endl;
      } else {
	HLTError("can not open file %s for writing", filename.Data());
	iResult=-EBADF;
      }
      dump.close();
    }
  }
  return iResult;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * Copyright (c) 2010, 2011 Kohei Yoshida
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 ************************************************************************/

#ifndef __MDDS_QUAD_TYPE_MATRIX_HPP__
#define __MDDS_QUAD_TYPE_MATRIX_HPP__

#include "mdds/global.hpp"
#include "mdds/mixed_type_matrix_element.hpp"
#include "mdds/mixed_type_matrix_storage.hpp"
#include "mdds/mixed_type_matrix_flag_storage.hpp"

#include <iostream>
#include <cstdlib>

namespace mdds {

enum matrix_density_t
{
    matrix_density_filled_zero,
    matrix_density_filled_empty,
    matrix_density_sparse_zero,
    matrix_density_sparse_empty
};

class matrix_error : public ::mdds::general_error
{
public:
    matrix_error(const ::std::string& msg) : general_error(msg) {}
};

/**
 * This data structure represents a matrix where each individual element may
 * be of one of four types: value, boolean, string, or empty.
 */
template<typename _String, typename _Flag>
class mixed_type_matrix
{
public:
    typedef _String     string_type;
    typedef _Flag       flag_type;
    typedef size_t      size_type;
    typedef ::std::pair<size_type, size_type> size_pair_type;
    typedef ::mdds::element<string_type> element;

private:
    struct size_pair_type_hash
    {
        size_t operator() (const size_pair_type& val) const
        {
            size_t n = val.first + (val.second << 8);
            return n;
        }
    };
    typedef ::mdds::storage_base<mixed_type_matrix> storage_base;

    static storage_base* create_storage(size_t rows, size_t cols, matrix_density_t density);

public:
    typedef ::mdds::__mtm::flag_storage<flag_type, size_pair_type, size_pair_type_hash> flag_storage;
    typedef ::mdds::__mtm::storage_filled_linear<mixed_type_matrix> filled_storage_type;
    typedef ::mdds::__mtm::storage_filled_linear_zero<mixed_type_matrix> filled_storage_zero_type;
    typedef ::mdds::__mtm::storage_sparse<mixed_type_matrix> sparse_storage_type;

    typedef typename storage_base::const_iterator const_iterator;

    /**
     * Default constructor.
     */
    mixed_type_matrix();

    /**
     * Construct an empty matrix with specified density type.
     */
    mixed_type_matrix(matrix_density_t density);

    /**
     * Construct a matrix of specified size with specified density type.
     */
    mixed_type_matrix(size_t rows, size_t cols, matrix_density_t density);

    mixed_type_matrix(const mixed_type_matrix& r);
    ~mixed_type_matrix();

    const_iterator begin() const;
    const_iterator end() const;

    mixed_type_matrix& operator= (const mixed_type_matrix& r);

    /**
     * Get the type of element specified by its position.  The type can be one
     * of empty, string, numeric, or boolean.
     *
     * @return element type.
     */
    matrix_element_t get_type(size_t row, size_t col) const;

    double get_numeric(size_t row, size_t col) const;
    bool get_boolean(size_t row, size_t col) const;
    const string_type* get_string(size_t row, size_t col) const;

    void set_numeric(size_t row, size_t col, double val);
    void set_boolean(size_t row, size_t col, bool val);
    void set_string(size_t row, size_t col, string_type* str);
    void set_empty(size_t row, size_t col);

    void set(size_t row, size_t col, double val);
    void set(size_t row, size_t col, bool val);
    void set(size_t row, size_t col, string_type* str);

    /**
     * Set flag value at specified position.
     *
     * @param row row position
     * @param col column position
     * @param flag_type flag value
     */
    void set_flag(size_t row, size_t col, flag_type flag);

    /**
     * Get flag value at specified position.
     *
     * @param row row position
     * @param col column position
     *
     * @return flag value stored at specified position
     */
    flag_type get_flag(size_t row, size_t col) const;

    void clear_flag(size_t row, size_t cols);

    /**
     * Return the size of matrix as a pair.  The first value is the row size,
     * while the second value is the column size.
     *
     * @return matrix size as a value pair.
     */
    size_pair_type size() const;

    /**
     * Transpose the stored matrix data.
     *
     * @return reference to this matrix instance.
     */
    mixed_type_matrix& transpose();

    /**
     * Assign values from the passed matrix instance.  If the size of the
     * passed matrix is smaller, then the element values are assigned by their
     * positions, while the rest of the elements that fall outside the size of
     * the passed matrix instance will remain unmodified.  If the size of the
     * pass matrix instance is larger, then only the elements within the size
     * of this matrix instance will get assigned.
     *
     * @param r passed matrix object to assign element values from.
     */
    void assign(const mixed_type_matrix& r);

    /**
     * Resize the matrix to specified size.  This method supports resizing to
     * zero-sized matrix; however, either specifying the row or column size to
     * zero will resize the matrix to 0 x 0.
     *
     * @param row new row size
     * @param col new column size
     */
    void resize(size_t row, size_t col);

    /**
     * Empty the matrix.
     */
    void clear();

    /**
     * Check whether or not this matrix is numeric.  A numeric matrix contains
     * only numeric or boolean elements.
     *
     * @return true if the matrix contains only numeric or boolean elements,
     *         or false otherwise.
     */
    bool numeric() const;

    /**
     * Check whether or not this matrix is empty.
     *
     * @return true if this matrix is empty, or false otherwise.
     */
    bool empty() const;

    /**
     * Swap the content of the matrix with another instance.
     */
    void swap(mixed_type_matrix& r);

#ifdef UNIT_TEST
    void dump() const;
    void dump_flags() const;
    size_pair_type get_storage_size() const;
#endif

private:
    /**
     * Storage classes have no vtable; the concrete class type must be
     * specified when deleting the instance.
     */
    void delete_storage();

private:
    storage_base* mp_storage;
    size_pair_type m_cached_size;
};

}

#include "mixed_type_matrix_def.inl"

#endif
<commit_msg>Fixed header guard name.<commit_after>/*************************************************************************
 *
 * Copyright (c) 2010, 2011 Kohei Yoshida
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 ************************************************************************/

#ifndef __MDDS_MIXED_TYPE_MATRIX_HPP__
#define __MDDS_MIXED_TYPE_MATRIX_HPP__

#include "mdds/global.hpp"
#include "mdds/mixed_type_matrix_element.hpp"
#include "mdds/mixed_type_matrix_storage.hpp"
#include "mdds/mixed_type_matrix_flag_storage.hpp"

#include <iostream>
#include <cstdlib>

namespace mdds {

enum matrix_density_t
{
    matrix_density_filled_zero,
    matrix_density_filled_empty,
    matrix_density_sparse_zero,
    matrix_density_sparse_empty
};

class matrix_error : public ::mdds::general_error
{
public:
    matrix_error(const ::std::string& msg) : general_error(msg) {}
};

/**
 * This data structure represents a matrix where each individual element may
 * be of one of four types: value, boolean, string, or empty.
 */
template<typename _String, typename _Flag>
class mixed_type_matrix
{
public:
    typedef _String     string_type;
    typedef _Flag       flag_type;
    typedef size_t      size_type;
    typedef ::std::pair<size_type, size_type> size_pair_type;
    typedef ::mdds::element<string_type> element;

private:
    struct size_pair_type_hash
    {
        size_t operator() (const size_pair_type& val) const
        {
            size_t n = val.first + (val.second << 8);
            return n;
        }
    };
    typedef ::mdds::storage_base<mixed_type_matrix> storage_base;

    static storage_base* create_storage(size_t rows, size_t cols, matrix_density_t density);

public:
    typedef ::mdds::__mtm::flag_storage<flag_type, size_pair_type, size_pair_type_hash> flag_storage;
    typedef ::mdds::__mtm::storage_filled_linear<mixed_type_matrix> filled_storage_type;
    typedef ::mdds::__mtm::storage_filled_linear_zero<mixed_type_matrix> filled_storage_zero_type;
    typedef ::mdds::__mtm::storage_sparse<mixed_type_matrix> sparse_storage_type;

    typedef typename storage_base::const_iterator const_iterator;

    /**
     * Default constructor.
     */
    mixed_type_matrix();

    /**
     * Construct an empty matrix with specified density type.
     */
    mixed_type_matrix(matrix_density_t density);

    /**
     * Construct a matrix of specified size with specified density type.
     */
    mixed_type_matrix(size_t rows, size_t cols, matrix_density_t density);

    mixed_type_matrix(const mixed_type_matrix& r);
    ~mixed_type_matrix();

    const_iterator begin() const;
    const_iterator end() const;

    mixed_type_matrix& operator= (const mixed_type_matrix& r);

    /**
     * Get the type of element specified by its position.  The type can be one
     * of empty, string, numeric, or boolean.
     *
     * @return element type.
     */
    matrix_element_t get_type(size_t row, size_t col) const;

    double get_numeric(size_t row, size_t col) const;
    bool get_boolean(size_t row, size_t col) const;
    const string_type* get_string(size_t row, size_t col) const;

    void set_numeric(size_t row, size_t col, double val);
    void set_boolean(size_t row, size_t col, bool val);
    void set_string(size_t row, size_t col, string_type* str);
    void set_empty(size_t row, size_t col);

    void set(size_t row, size_t col, double val);
    void set(size_t row, size_t col, bool val);
    void set(size_t row, size_t col, string_type* str);

    /**
     * Set flag value at specified position.
     *
     * @param row row position
     * @param col column position
     * @param flag_type flag value
     */
    void set_flag(size_t row, size_t col, flag_type flag);

    /**
     * Get flag value at specified position.
     *
     * @param row row position
     * @param col column position
     *
     * @return flag value stored at specified position
     */
    flag_type get_flag(size_t row, size_t col) const;

    void clear_flag(size_t row, size_t cols);

    /**
     * Return the size of matrix as a pair.  The first value is the row size,
     * while the second value is the column size.
     *
     * @return matrix size as a value pair.
     */
    size_pair_type size() const;

    /**
     * Transpose the stored matrix data.
     *
     * @return reference to this matrix instance.
     */
    mixed_type_matrix& transpose();

    /**
     * Assign values from the passed matrix instance.  If the size of the
     * passed matrix is smaller, then the element values are assigned by their
     * positions, while the rest of the elements that fall outside the size of
     * the passed matrix instance will remain unmodified.  If the size of the
     * pass matrix instance is larger, then only the elements within the size
     * of this matrix instance will get assigned.
     *
     * @param r passed matrix object to assign element values from.
     */
    void assign(const mixed_type_matrix& r);

    /**
     * Resize the matrix to specified size.  This method supports resizing to
     * zero-sized matrix; however, either specifying the row or column size to
     * zero will resize the matrix to 0 x 0.
     *
     * @param row new row size
     * @param col new column size
     */
    void resize(size_t row, size_t col);

    /**
     * Empty the matrix.
     */
    void clear();

    /**
     * Check whether or not this matrix is numeric.  A numeric matrix contains
     * only numeric or boolean elements.
     *
     * @return true if the matrix contains only numeric or boolean elements,
     *         or false otherwise.
     */
    bool numeric() const;

    /**
     * Check whether or not this matrix is empty.
     *
     * @return true if this matrix is empty, or false otherwise.
     */
    bool empty() const;

    /**
     * Swap the content of the matrix with another instance.
     */
    void swap(mixed_type_matrix& r);

#ifdef UNIT_TEST
    void dump() const;
    void dump_flags() const;
    size_pair_type get_storage_size() const;
#endif

private:
    /**
     * Storage classes have no vtable; the concrete class type must be
     * specified when deleting the instance.
     */
    void delete_storage();

private:
    storage_base* mp_storage;
    size_pair_type m_cached_size;
};

}

#include "mixed_type_matrix_def.inl"

#endif
<|endoftext|>


<commit_before>/***************************************************************************
 *  @file       The code is for the exercises in C++ Primmer 5th Edition
 *  @author     Alan.W
 *  @date       23  DEC 2013
 *  @remark
 ***************************************************************************/
//
// Exercise 12.11:
// What would happen if we called process as follows?
//  An error was generated at run time : double free or corruption.
//  See the comments below.

#include <iostream>
#include <vector>
#include <string>
#include <memory>

void process(std::shared_ptr<int> ptr)
{
    std::cout << "inside the process function:" << ptr.use_count() << "\n";
}

int main()
{
    std::shared_ptr<int> p(new int(42));

    /**
     * @brief   std::shared_ptr<int>(p.get()) construct a temporary shared_ptr and copy it
     *          to the parameter.However it is not a copy of p. As a result, at end of this
     *          main function p will free the memory that has been freed inside process ().
     *          That's why "double freed or corruption" was generated.
     */
    process(std::shared_ptr<int>(p.get()));

    return 0;
}
<commit_msg>Update ex12_11.cpp<commit_after>/***************************************************************************
 *  @file       The code is for the exercises in C++ Primmer 5th Edition
 *  @author     Alan.W
 *  @date       23  DEC 2013
 *  @remark
 ***************************************************************************/
//
// Exercise 12.11:
// What would happen if we called process as follows?
//  An error was generated at run time : double free or corruption.
//  See the comments below.

#include <iostream>
#include <vector>
#include <string>
#include <memory>

void process(std::shared_ptr<int> ptr)
{
    std::cout << "inside the process function:" << ptr.use_count() << "\n";
}

int main()
{
    std::shared_ptr<int> p(new int(42));
    /**
     * @brief   std::shared_ptr<int>(p.get()) construct a temporary shared_ptr and copy it
     *          to the parameter.However it is not a copy of p. As a result, at end of this
     *          main function p will free the memory that has been freed inside process ().
     *          That's why "double freed or corruption" was generated.
     */
    process(std::shared_ptr<int>(p.get()));
    return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#if defined(__clang__)
#define HADESMEM_CLANG
#elif defined(__INTEL_COMPILER)
#define HADESMEM_INTEL
#elif defined(__GNUC__)
#define HADESMEM_GCC
#elif defined(_MSC_VER)
#define HADESMEM_MSVC
#else
#error "[HadesMem] Unsupported compiler."
#endif

#define HADESMEM_VERSION_MAJOR 2
#define HADESMEM_VERSION_MINOR 0
#define HADESMEM_VERSION_PATCH 0

#define HADESMEM_VERSION_STRING_GEN_EXP(x, y, z) "v" #x "." #y "." #z

#define HADESMEM_VERSION_STRING_GEN(x, y, z) \
HADESMEM_VERSION_STRING_GEN_EXP(x, y, z)

#define HADESMEM_VERSION_STRING HADESMEM_VERSION_STRING_GEN(\
HADESMEM_VERSION_MAJOR, HADESMEM_VERSION_MINOR, HADESMEM_VERSION_PATCH)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_DELETED_FUNCTIONS
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_NOEXCEPT
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_VARIADIC_TEMPLATES
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_NO_DELETED_FUNCTIONS)
#define HADESMEM_DELETED_FUNCTION
#else // #if defined(HADESMEM_NO_DELETED_FUNCTIONS)
#define HADESMEM_DELETED_FUNCTION = delete
#endif // #if defined(HADESMEM_NO_DELETED_FUNCTIONS)

#if defined(HADESMEM_NO_NOEXCEPT)
#define HADESMEM_NOEXCEPT
#define HADESMEM_NOEXCEPT_IF(Pred)
#define HADESMEM_NOEXCEPT_EXPR(Expr) false
#else // #if defined(HADESMEM_NO_NOEXCEPT)
#define HADESMEM_NOEXCEPT noexcept
#define HADESMEM_NOEXCEPT_IF(Pred) noexcept((Pred))
#define HADESMEM_NOEXCEPT_EXPR(Expr) noexcept((Expr))
#endif // #if defined(HADESMEM_NO_NOEXCEPT)

#if defined(_M_IX86)
#define HADESMEM_ARCH_X86
#endif // #if defined(_M_IX86)

#if defined(_M_AMD64)
#define HADESMEM_ARCH_X64
#endif // #if defined(_M_AMD64)

#if !defined(HADESMEM_ARCH_X86) && !defined(HADESMEM_ARCH_X64)
#error "[HadesMem] Unsupported architecture."
#endif // #if !defined(HADESMEM_ARCH_X86) && !defined(HADESMEM_ARCH_X64)

#if !defined(HADESMEM_CALL_MAX_ARGS)
#define HADESMEM_CALL_MAX_ARGS 10
#endif // #ifndef HADESMEM_CALL_MAX_ARGS

// This is required because of a bug in Clang's dllexport support on Windows,
// this is worked around by using a linker flag to export all symbols
// unconditionally.
// TODO: Remove this hack once Clang has been fixed.
#ifdef HADESMEM_CLANG
#define HADESMEM_DLLEXPORT
#else
#define HADESMEM_DLLEXPORT __declspec(dllexport)
#endif

// Approximate equivalent of MAX_PATH for Unicode APIs.
// See: http://goo.gl/1VVA3
#define HADESMEM_MAX_PATH_UNICODE (1 << 15)
<commit_msg>* Add constexpr support to config.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#if defined(__clang__)
#define HADESMEM_CLANG
#elif defined(__INTEL_COMPILER)
#define HADESMEM_INTEL
#elif defined(__GNUC__)
#define HADESMEM_GCC
#elif defined(_MSC_VER)
#define HADESMEM_MSVC
#else
#error "[HadesMem] Unsupported compiler."
#endif

#define HADESMEM_VERSION_MAJOR 2
#define HADESMEM_VERSION_MINOR 0
#define HADESMEM_VERSION_PATCH 0

#define HADESMEM_VERSION_STRING_GEN_EXP(x, y, z) "v" #x "." #y "." #z

#define HADESMEM_VERSION_STRING_GEN(x, y, z) \
HADESMEM_VERSION_STRING_GEN_EXP(x, y, z)

#define HADESMEM_VERSION_STRING HADESMEM_VERSION_STRING_GEN(\
HADESMEM_VERSION_MAJOR, HADESMEM_VERSION_MINOR, HADESMEM_VERSION_PATCH)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_DELETED_FUNCTIONS
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_NOEXCEPT
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_CONSTEXPR
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_MSVC)
#define HADESMEM_NO_VARIADIC_TEMPLATES
#endif // #if defined(HADESMEM_MSVC)

#if defined(HADESMEM_NO_DELETED_FUNCTIONS)
#define HADESMEM_DELETED_FUNCTION
#else // #if defined(HADESMEM_NO_DELETED_FUNCTIONS)
#define HADESMEM_DELETED_FUNCTION = delete
#endif // #if defined(HADESMEM_NO_DELETED_FUNCTIONS)

#if defined(HADESMEM_NO_NOEXCEPT)
#define HADESMEM_NOEXCEPT
#define HADESMEM_NOEXCEPT_IF(Pred)
#define HADESMEM_NOEXCEPT_EXPR(Expr) false
#else // #if defined(HADESMEM_NO_NOEXCEPT)
#define HADESMEM_NOEXCEPT noexcept
#define HADESMEM_NOEXCEPT_IF(Pred) noexcept((Pred))
#define HADESMEM_NOEXCEPT_EXPR(Expr) noexcept((Expr))
#endif // #if defined(HADESMEM_NO_NOEXCEPT)

#if defined(HADESMEM_NO_CONSTEXPR)
#define HADESMEM_CONSTEXPR
#else // #if defined(HADESMEM_NO_CONSTEXPR)
#define HADESMEM_CONSTEXPR constexpr
#endif // #if defined(HADESMEM_NO_CONSTEXPR)

#if defined(_M_IX86)
#define HADESMEM_ARCH_X86
#endif // #if defined(_M_IX86)

#if defined(_M_AMD64)
#define HADESMEM_ARCH_X64
#endif // #if defined(_M_AMD64)

#if !defined(HADESMEM_ARCH_X86) && !defined(HADESMEM_ARCH_X64)
#error "[HadesMem] Unsupported architecture."
#endif // #if !defined(HADESMEM_ARCH_X86) && !defined(HADESMEM_ARCH_X64)

#if !defined(HADESMEM_CALL_MAX_ARGS)
#define HADESMEM_CALL_MAX_ARGS 10
#endif // #ifndef HADESMEM_CALL_MAX_ARGS

// This is required because of a bug in Clang's dllexport support on Windows,
// this is worked around by using a linker flag to export all symbols
// unconditionally.
// TODO: Remove this hack once Clang has been fixed.
#ifdef HADESMEM_CLANG
#define HADESMEM_DLLEXPORT
#else
#define HADESMEM_DLLEXPORT __declspec(dllexport)
#endif

// Approximate equivalent of MAX_PATH for Unicode APIs.
// See: http://goo.gl/1VVA3
#define HADESMEM_MAX_PATH_UNICODE (1 << 15)
<|endoftext|>


<commit_before>#include "ex14_07.h"
#include <algorithm>
#include <iostream>

std::pair<char*, char*>
String::alloc_n_copy(const char *b, const char *e)
{
	auto str = alloc.allocate(e-b);
	return{ str, std::uninitialized_copy(b, e, str)};
}

void String::range_initializer(const char *first, const char *last)
{
	auto newstr = alloc_n_copy(first, last);
	elements = newstr.first;
	end = newstr.second;
}

String::String(const char *s)
{
	char *sl = const_cast<char*>(s);
	while (*sl)
		++sl;
	range_initializer(s, ++sl);
}

String::String(const String& rhs)
{
	range_initializer(rhs.elements, rhs.end);
    std::cout << "copy constructor" << std::endl;
}

void String::free()
{
	if (elements) {
		std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); });
		alloc.deallocate(elements, end - elements);
	}
}

String::~String()
{
	free();
}

String& String::operator = (const String &rhs)
{
	auto newstr = alloc_n_copy(rhs.elements, rhs.end);
	free();
	elements = newstr.first;
	end = newstr.second;
    std::cout << "copy-assignment" << std::endl;
	return *this;
}

std::ostream& operator<<(std::ostream &os, const String &s)
{
    char *c = const_cast<char*>(s.c_str());
    while (*c)
        os << *c++;
    return os;
}
<commit_msg>Update ex14_07.cpp<commit_after>#include "ex14_07.h"
#include <algorithm>
#include <iostream>

std::pair<char*, char*>
String::alloc_n_copy(const char *b, const char *e)
{
    auto str = alloc.allocate(e - b);
    return{ str, std::uninitialized_copy(b, e, str) };
}

void String::range_initializer(const char *first, const char *last)
{
    auto newstr = alloc_n_copy(first, last);
    elements = newstr.first;
    end = newstr.second;
}

String::String(const char *s)
{
    char *sl = const_cast<char*>(s);
    while (*sl)
        ++sl;
    range_initializer(s, ++sl);
}

String::String(const String& rhs)
{
    range_initializer(rhs.elements, rhs.end);
    std::cout << "copy constructor" << std::endl;
}

void String::free()
{
    if (elements) {
        std::for_each(elements, end, [this](char &c){ alloc.destroy(&c); });
        alloc.deallocate(elements, end - elements);
    }
}

String::~String()
{
    free();
}

String& String::operator = (const String &rhs)
{
    auto newstr = alloc_n_copy(rhs.elements, rhs.end);
    free();
    elements = newstr.first;
    end = newstr.second;
    std::cout << "copy-assignment" << std::endl;
    return *this;
}

std::ostream& operator<<(std::ostream &os, const String &s)
{
    char *c = const_cast<char*>(s.c_str());
    while (*c)
        os << *c++;
    return os;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, Sean Ogden
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of WTF nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "client/rereplicate.h"
#include "client/constants.h"
#include "client/pending_read.h"
#include "client/file.h"

#ifdef TRACECALLS
#define TRACE std::cerr << __FILE__ << ":" << __func__ << std::endl
#else
#define TRACE
#endif

using namespace std;
using wtf::rereplicate;

rereplicate :: rereplicate(const char* host, in_port_t port,
                         const char* hyper_host, in_port_t hyper_port)
{
    wc = new client(host, port, hyper_host, hyper_port);
    TRACE;
}

rereplicate :: ~rereplicate() throw ()
{
    delete wc;
    TRACE;
}

int64_t
rereplicate :: replicate(const char* filename, uint64_t sid)
{
    cout << "filename " << filename << " sid " << sid << endl;
    int64_t ret;
    int64_t client_id = 0;

    e::intrusive_ptr<wtf::file> f = new wtf::file(filename, 0, CHUNKSIZE);
    ret = wc->get_file_metadata(f->path().get(), f, false);

    if (ret < 0)
    {
        return -1;
    }

    std::auto_ptr<e::buffer> old_blockmap = f->serialize_blockmap();
    std::map<uint64_t, e::intrusive_ptr<wtf::block> >::const_iterator it;
    for (it = f->blocks_begin(); it != f->blocks_end(); ++it)
    {
        bool match = false;
        std::vector<server_id> servers;
        uint64_t si; // TODO DELETE
        uint64_t bi; // TODO DELETE
        std::vector<wtf::block_location>::iterator it2;
        for (it2 = it->second->blocks_begin(); it2 != it->second->blocks_end(); ++it2)
        {

            if (it2->si == sid)
            {
                cout << "match " << *it2 << endl;
                match = true;
            }
            else
            {
                cout << "no match " << *it2 << endl;
                if (servers.size() < 1)
                {
                    servers.push_back(server_id(it2->si));
                    si = it2->si;
                    bi = it2->bi;
                }
            }

        }
        if (match)
        {
            wtf_client_returncode status;
            e::intrusive_ptr<pending_read> op;
            size_t buf_sz = it->second->length() - it->second->offset();
            char buf[buf_sz];
            cout << "buf_sz " << buf_sz << endl;

            //int64_t fd = wc->open(filename, O_RDONLY, 0, 0, 0);
            //int64_t reqid;
            //do {
            //    buf_sz = 4096;
            //    reqid = wc->read(fd, buf, &buf_sz, &status);
            //    reqid = wc->loop(reqid, -1, &status);
            //    e::slice data = e::slice(buf, buf_sz);
            //    cout << "reqid " << reqid << " read " << buf_sz << endl;
            //    cout << data.hex() << endl;
            //    //reqid = wc.write(fd, buf, &buf_sz, 0, &status);
            //    //reqid = wc.loop(reqid, -1, &status);
            //} while (false);
            //wc->close(fd, &status);

            client_id++;
            op = new pending_read(client_id, &status, buf, &buf_sz);
            f->add_pending_op(client_id);
            op->set_offset(si, bi, 0, it->second->offset(), it->second->length());
            cout << "si " << si << " bi " << bi << " buf_offset 0 block_offset " << it->second->offset() << " advance " << it->second->length() << endl;

            size_t sz = WTF_CLIENT_HEADER_SIZE_REQ
                + sizeof(uint64_t) // bl.bi (local block number)
                + sizeof(uint32_t); //block_length
            std::auto_ptr<e::buffer> msg(e::buffer::create(sz));
            msg->pack_at(WTF_CLIENT_HEADER_SIZE_REQ) << bi << (uint32_t)it->second->length();

            if (!wc->maintain_coord_connection(&status))
            {
                return -1;
            }

            buf_sz = 0;
            wc->perform_aggregation(servers, op.get(), REQ_GET, msg, &status);

            wc->loop(client_id, -1, &status);
            e::slice data = e::slice(buf, buf_sz);
            cout << "buf_sz " << buf_sz << endl << data.hex() << endl;
        }
    }

    //wtf::Client wc("127.0.0.1", 1981, "127.0.0.1", 1982);
    //wtf_client_returncode s;
    //if (!wc.maintain_coord_connection(&s)) { cout << "NOOOOOOOOOOOOOOOOO" << endl; } else { cout << "YESSSSSSSSSSSSSSSS" << endl; }
    /*
    uint64_t mode = f->mode;
    uint64_t directory = f->is_directory;
    std::auto_ptr<e::buffer> new_blockmap = f->serialize_blockmap();
    struct hyperdex_client_attribute update_attr[3];

    update_attr[0].attr = "mode";
    update_attr[0].value = (const char*)&mode;
    update_attr[0].value_sz = sizeof(mode);
    update_attr[0].datatype = HYPERDATATYPE_INT64;

    update_attr[1].attr = "directory";
    update_attr[1].value = (const char*)&directory;
    update_attr[1].value_sz = sizeof(directory);
    update_attr[1].datatype = HYPERDATATYPE_INT64;

    update_attr[2].attr = "blockmap";
    update_attr[2].value = reinterpret_cast<const char*>(new_blockmap->data());
    update_attr[2].value_sz = new_blockmap->size();
    update_attr[2].datatype = HYPERDATATYPE_STRING;

    struct hyperdex_client_attribute_check cond_attr;

    cond_attr.attr = "blockmap";
    cond_attr.value = reinterpret_cast<const char*>(old_blockmap->data());
    cond_attr.value_sz = old_blockmap->size();
    cond_attr.datatype = HYPERDATATYPE_STRING;
    cond_attr.predicate = HYPERPREDICATE_EQUALS;

    ret = wc.m_hyperdex_client.cond_put("wtf", f->path().get(), strlen(f->path().get()), &cond_attr, 1,
                                     update_attr, 3, &status);

    print_return();

    wtf::Client wc("127.0.0.1", 1981, "127.0.0.1", 1982);
    wtf_client_returncode s;
    int64_t fd = wc.open(filename, O_RDONLY, 0, 0, 0, &s);
    char buf[4096];

    size_t size;
    int64_t reqid;
    do {
        size = 4096;
        reqid = wc.read(fd, buf, &size, &s);
        reqid = wc.loop(reqid, -1, &s);
        e::slice data = e::slice(buf, size);
        cout << "reqid " << reqid << " read " << size << " status " << s << endl;
        cout << data.hex() << endl;
        reqid = wc.write(fd, buf, &size, 0, &s);
        reqid = wc.loop(reqid, -1, &s);
    } while (false);

    wc.close(fd, &s);
    */

    return 0;
}

<commit_msg>read single block should work by now<commit_after>// Copyright (c) 2013, Sean Ogden
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of WTF nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "client/rereplicate.h"
#include "client/constants.h"
#include "client/pending_read.h"
#include "client/file.h"

#ifdef TRACECALLS
#define TRACE std::cerr << __FILE__ << ":" << __func__ << std::endl
#else
#define TRACE
#endif

using namespace std;
using wtf::rereplicate;

rereplicate :: rereplicate(const char* host, in_port_t port,
                         const char* hyper_host, in_port_t hyper_port)
{
    wc = new client(host, port, hyper_host, hyper_port);
    TRACE;
}

rereplicate :: ~rereplicate() throw ()
{
    delete wc;
    TRACE;
}

int64_t
rereplicate :: replicate(const char* filename, uint64_t sid)
{
    cout << "filename " << filename << " sid " << sid << endl;
    int64_t ret;
    int64_t client_id = 0;

    e::intrusive_ptr<wtf::file> f = new wtf::file(filename, 0, CHUNKSIZE);
    ret = wc->get_file_metadata(f->path().get(), f, false);

    if (ret < 0)
    {
        return -1;
    }

    std::auto_ptr<e::buffer> old_blockmap = f->serialize_blockmap();
    std::map<uint64_t, e::intrusive_ptr<wtf::block> >::const_iterator it;
    for (it = f->blocks_begin(); it != f->blocks_end(); ++it)
    {
        bool match = false;
        std::vector<server_id> servers;
        uint64_t si; // TODO DELETE
        uint64_t bi; // TODO DELETE
        std::vector<wtf::block_location>::iterator it2;
        for (it2 = it->second->blocks_begin(); it2 != it->second->blocks_end(); ++it2)
        {

            if (it2->si == sid)
            {
                cout << "match " << *it2 << endl;
                match = true;
            }
            else
            {
                cout << "no match " << *it2 << endl;
                if (servers.size() < 1)
                {
                    servers.push_back(server_id(it2->si));
                    si = it2->si;
                    bi = it2->bi;
                }
            }

        }
        if (match)
        {
            wtf_client_returncode status;
            e::intrusive_ptr<pending_read> op;
            size_t buf_sz = it->second->length();
            char buf[buf_sz];
            cout << "buf_sz created " << buf_sz << endl;

            //int64_t fd = wc->open(filename, O_RDONLY, 0, 0, 0);
            //int64_t reqid;
            //do {
            //    buf_sz = 4096;
            //    reqid = wc->read(fd, buf, &buf_sz, &status);
            //    reqid = wc->loop(reqid, -1, &status);
            //    e::slice data = e::slice(buf, buf_sz);
            //    cout << "reqid " << reqid << " read " << buf_sz << endl;
            //    cout << data.hex() << endl;
            //    //reqid = wc.write(fd, buf, &buf_sz, 0, &status);
            //    //reqid = wc.loop(reqid, -1, &status);
            //} while (false);
            //wc->close(fd, &status);

            client_id++;
            op = new pending_read(client_id, &status, buf, &buf_sz);
            op->set_offset(si, bi, 0, 0, it->second->length());
            cout << "si " << si << " bi " << bi << " buf_offset 0 block_offset 0 advance " << it->second->length() << endl;

            size_t sz = WTF_CLIENT_HEADER_SIZE_REQ
                + sizeof(uint64_t) // bl.bi (local block number)
                + sizeof(uint32_t); //block_length
            std::auto_ptr<e::buffer> msg(e::buffer::create(sz));
            msg->pack_at(WTF_CLIENT_HEADER_SIZE_REQ) << bi << (uint32_t)it->second->length();

            if (!wc->maintain_coord_connection(&status))
            {
                return -1;
            }

            buf_sz = 0;
            wc->perform_aggregation(servers, op.get(), REQ_GET, msg, &status);

            wc->loop(client_id, -1, &status);
            e::slice data = e::slice(buf, buf_sz);
            cout << "buf_sz read " << buf_sz << endl << data.hex() << endl;
        }
    }

    //wtf::Client wc("127.0.0.1", 1981, "127.0.0.1", 1982);
    //wtf_client_returncode s;
    //if (!wc.maintain_coord_connection(&s)) { cout << "NOOOOOOOOOOOOOOOOO" << endl; } else { cout << "YESSSSSSSSSSSSSSSS" << endl; }
    /*
    uint64_t mode = f->mode;
    uint64_t directory = f->is_directory;
    std::auto_ptr<e::buffer> new_blockmap = f->serialize_blockmap();
    struct hyperdex_client_attribute update_attr[3];

    update_attr[0].attr = "mode";
    update_attr[0].value = (const char*)&mode;
    update_attr[0].value_sz = sizeof(mode);
    update_attr[0].datatype = HYPERDATATYPE_INT64;

    update_attr[1].attr = "directory";
    update_attr[1].value = (const char*)&directory;
    update_attr[1].value_sz = sizeof(directory);
    update_attr[1].datatype = HYPERDATATYPE_INT64;

    update_attr[2].attr = "blockmap";
    update_attr[2].value = reinterpret_cast<const char*>(new_blockmap->data());
    update_attr[2].value_sz = new_blockmap->size();
    update_attr[2].datatype = HYPERDATATYPE_STRING;

    struct hyperdex_client_attribute_check cond_attr;

    cond_attr.attr = "blockmap";
    cond_attr.value = reinterpret_cast<const char*>(old_blockmap->data());
    cond_attr.value_sz = old_blockmap->size();
    cond_attr.datatype = HYPERDATATYPE_STRING;
    cond_attr.predicate = HYPERPREDICATE_EQUALS;

    ret = wc.m_hyperdex_client.cond_put("wtf", f->path().get(), strlen(f->path().get()), &cond_attr, 1,
                                     update_attr, 3, &status);

    print_return();

    wtf::Client wc("127.0.0.1", 1981, "127.0.0.1", 1982);
    wtf_client_returncode s;
    int64_t fd = wc.open(filename, O_RDONLY, 0, 0, 0, &s);
    char buf[4096];

    size_t size;
    int64_t reqid;
    do {
        size = 4096;
        reqid = wc.read(fd, buf, &size, &s);
        reqid = wc.loop(reqid, -1, &s);
        e::slice data = e::slice(buf, size);
        cout << "reqid " << reqid << " read " << size << " status " << s << endl;
        cout << data.hex() << endl;
        reqid = wc.write(fd, buf, &size, 0, &s);
        reqid = wc.loop(reqid, -1, &s);
    } while (false);

    wc.close(fd, &s);
    */

    return 0;
}

<|endoftext|>