<commit_before>/*******************************************************************************
 * This file is part of "Patrick's Programming Library", Version 7 (PPL7).
 * Web: http://www.pfp.de/ppl/
 *
 * $Author$
 * $Revision$
 * $Date$
 * $Id$
 *
 *******************************************************************************
 * Copyright (c) 2013, Patrick Fedick <patrick@pfp.de>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright notice, this
 *       list of conditions and the following disclaimer.
 *    2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER AND 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 "prolog_ppl7.h"

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif

#include "ppl7.h"
#include "ppl7-grafix.h"
#include "ppl7-tk.h"

namespace ppl7 {
namespace tk {

using namespace ppl7;
using namespace ppl7::grafix;

Frame::Frame()
{
	const WidgetStyle &style=GetWidgetStyle();
	myBorderStyle=Upset;
	myBackground=style.frameBackgroundColor;
	myBorderColorLight=style.frameBorderColorLight;
	myBorderColorShadow=style.frameBorderColorShadow;
	setTransparent(false);
	setClientOffset(3,3,3,3);
}

Frame::Frame(int x, int y, int width, int height, BorderStyle style)
{
	const WidgetStyle &wstyle=GetWidgetStyle();
	myBorderStyle=style;
	myBackground=wstyle.frameBackgroundColor;
	myBorderColorLight=wstyle.frameBorderColorLight;
	myBorderColorShadow=wstyle.frameBorderColorShadow;
	create(x,y,width,height);
	setTransparent(false);
	setClientOffset(3,3,3,3);
}

Frame::~Frame()
{

}

Frame::BorderStyle Frame::borderStyle() const
{
	return (BorderStyle)myBorderStyle;
}

void Frame::setBorderStyle(BorderStyle s)
{
	myBorderStyle=s;
	needsRedraw();
}

const Color &Frame::backgroundColor() const
{
	return myBackground;
}

void Frame::setBackgroundColor(const Color &c)
{
	myBackground=c;
	needsRedraw();
}

const Color &Frame::borderColorLight() const
{
	return myBorderColorLight;
}

void Frame::setBorderColorLight(const Color &c)
{
	myBorderColorLight=c;
	needsRedraw();
}

void Frame::setBorderColorShadow(const Color &c)
{
	myBorderColorShadow=c;
	needsRedraw();
}

void Frame::paint(Drawable &draw)
{
	Color white(255,255,255,255);
	Color bg;

	int w=width()-1;
	int h=height()-1;
	bool myTransparent=isTransparent();
	switch(myBorderStyle) {
		case NoBorder:
			if (!myTransparent) draw.cls(myBackground);
			break;
		case Normal:
			if (!myTransparent) draw.cls(myBackground);
			draw.drawRect(0,0,w,h,myBorderColorShadow);
			break;
		case Upset:
			if (!myTransparent) {
				bg=myBackground;
				draw.cls(bg);
			}
			draw.line(0,0,w,0,myBorderColorLight);
			draw.line(0,0,0,h,myBorderColorLight);
			draw.line(0,h,w,h,myBorderColorShadow);
			draw.line(w,0,w,h,myBorderColorShadow);
			break;
		case Inset:
			if (!myTransparent) {
				bg=myBackground;
				draw.cls(bg);
			}
			draw.line(0,0,w,0,myBorderColorShadow);
			draw.line(0,0,0,h,myBorderColorShadow);
			draw.line(0,h,w,h,myBorderColorLight);
			draw.line(w,0,w,h,myBorderColorLight);
			break;
	}
}

String Frame::widgetType() const
{
	return "Frame";
}

}	// EOF namespace tk
}	// EOF namespace ppl7

<commit_msg>removed unused code<commit_after>/*******************************************************************************
 * This file is part of "Patrick's Programming Library", Version 7 (PPL7).
 * Web: http://www.pfp.de/ppl/
 *
 * $Author$
 * $Revision$
 * $Date$
 * $Id$
 *
 *******************************************************************************
 * Copyright (c) 2013, Patrick Fedick <patrick@pfp.de>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright notice, this
 *       list of conditions and the following disclaimer.
 *    2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER AND 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 "prolog_ppl7.h"

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif

#include "ppl7.h"
#include "ppl7-grafix.h"
#include "ppl7-tk.h"

namespace ppl7 {
namespace tk {

using namespace ppl7;
using namespace ppl7::grafix;

Frame::Frame()
{
	const WidgetStyle &style=GetWidgetStyle();
	myBorderStyle=Upset;
	myBackground=style.frameBackgroundColor;
	myBorderColorLight=style.frameBorderColorLight;
	myBorderColorShadow=style.frameBorderColorShadow;
	setTransparent(false);
	setClientOffset(3,3,3,3);
}

Frame::Frame(int x, int y, int width, int height, BorderStyle style)
{
	const WidgetStyle &wstyle=GetWidgetStyle();
	myBorderStyle=style;
	myBackground=wstyle.frameBackgroundColor;
	myBorderColorLight=wstyle.frameBorderColorLight;
	myBorderColorShadow=wstyle.frameBorderColorShadow;
	create(x,y,width,height);
	setTransparent(false);
	setClientOffset(3,3,3,3);
}

Frame::~Frame()
{

}

Frame::BorderStyle Frame::borderStyle() const
{
	return (BorderStyle)myBorderStyle;
}

void Frame::setBorderStyle(BorderStyle s)
{
	myBorderStyle=s;
	needsRedraw();
}

const Color &Frame::backgroundColor() const
{
	return myBackground;
}

void Frame::setBackgroundColor(const Color &c)
{
	myBackground=c;
	needsRedraw();
}

const Color &Frame::borderColorLight() const
{
	return myBorderColorLight;
}

void Frame::setBorderColorLight(const Color &c)
{
	myBorderColorLight=c;
	needsRedraw();
}

void Frame::setBorderColorShadow(const Color &c)
{
	myBorderColorShadow=c;
	needsRedraw();
}

void Frame::paint(Drawable &draw)
{
	Color bg;
	int w=width()-1;
	int h=height()-1;
	bool myTransparent=isTransparent();
	switch(myBorderStyle) {
		case NoBorder:
			if (!myTransparent) draw.cls(myBackground);
			break;
		case Normal:
			if (!myTransparent) draw.cls(myBackground);
			draw.drawRect(0,0,w,h,myBorderColorShadow);
			break;
		case Upset:
			if (!myTransparent) {
				bg=myBackground;
				draw.cls(bg);
			}
			draw.line(0,0,w,0,myBorderColorLight);
			draw.line(0,0,0,h,myBorderColorLight);
			draw.line(0,h,w,h,myBorderColorShadow);
			draw.line(w,0,w,h,myBorderColorShadow);
			break;
		case Inset:
			if (!myTransparent) {
				bg=myBackground;
				draw.cls(bg);
			}
			draw.line(0,0,w,0,myBorderColorShadow);
			draw.line(0,0,0,h,myBorderColorShadow);
			draw.line(0,h,w,h,myBorderColorLight);
			draw.line(w,0,w,h,myBorderColorLight);
			break;
	}
	//draw.drawRect(0,0,w,h,Color(255,0,0,255));
}

String Frame::widgetType() const
{
	return "Frame";
}

}	// EOF namespace tk
}	// EOF namespace ppl7

<|endoftext|>


<commit_before>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <cgengine.h>
#include "version.h"
#include "imc.h"

using namespace std;
using namespace votca::csg;
using namespace votca::tools;

#include <stdlib.h>
#include <csgapplication.h>

//using namespace votca::tools;
using namespace std;
using namespace votca::csg;

class CsgStatApp
    : public CsgApplication
{
public:
    CsgStatApp() : _write_every(0) {}

    string ProgramName() { return "csg_stat"; }
    void HelpText(ostream &out);

    bool DoTrajectory() {return true;}
    bool DoMapping() {return true;}
    bool DoMappingDefault(void) { return false; }
    bool DoThreaded() {return true; }
    bool SynchronizeThreads() {return true;}
    void Initialize();
    bool EvaluateOptions();

    void BeginEvaluate(Topology *top, Topology *top_ref);
    void EndEvaluate();

    CsgApplication::Worker *ForkWorker() {
        return _imc.ForkWorker();
    }

    void MergeWorker(CsgApplication::Worker *worker) {
        _imc.MergeWorker(worker);
    }

public:
    Imc _imc;
    int _write_every;
};

void CsgStatApp::HelpText(ostream &out)
{
    out << "Calculate all distribuions (bonded + non-bonded) specified in options file.\n"
            "Optionally calculates update matrix for invere Monte Carlo. This program\n"
            "is called inside the inverse scripts. Unlike csg_boltzmann, big systems\n"
            "can be treated as well as non-bonded interactions evaluated.";
}

void CsgStatApp::Initialize()
{
    CsgApplication::Initialize();
    AddProgramOptions("Specific options")
            ("options", boost::program_options::value<string>(), "  options file for coarse graining")
            ("do-imc", "  write out inverse monte carlo data")
            ("write-every", boost::program_options::value<int>(&_write_every), "  write afer every block of this length, " \
                "if --blocking is set, the averages are cleared after every write")
            ("do-blocks", "  write output for blocking analysis");
}
bool CsgStatApp::EvaluateOptions()
{
    CsgApplication::EvaluateOptions();
    CheckRequired("options");
    CheckRequired("trj", "no trajectory file specified");

    _imc.LoadOptions(OptionsMap()["options"].as<string>());

    _imc.WriteEvery(_write_every);
    if(OptionsMap().count("do-blocks"))
        _imc.DoBlocks(true);
    if(OptionsMap().count("do-imc"))
    _imc.DoImc(true);

    _imc.Initialize();
    return true;
}

void CsgStatApp::BeginEvaluate(Topology *top, Topology *top_ref)
{
    _imc.BeginEvaluate(top, top_ref);
}

void CsgStatApp::EndEvaluate()
{
    _imc.EndEvaluate();
}

int main(int argc, char** argv)
{
    CsgStatApp app;
    app.Exec(argc, argv);
}

<commit_msg>typo in csg_stat<commit_after>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <boost/program_options.hpp>
#include <cgengine.h>
#include "version.h"
#include "imc.h"

using namespace std;
using namespace votca::csg;
using namespace votca::tools;

#include <stdlib.h>
#include <csgapplication.h>

//using namespace votca::tools;
using namespace std;
using namespace votca::csg;

class CsgStatApp
    : public CsgApplication
{
public:
    CsgStatApp() : _write_every(0) {}

    string ProgramName() { return "csg_stat"; }
    void HelpText(ostream &out);

    bool DoTrajectory() {return true;}
    bool DoMapping() {return true;}
    bool DoMappingDefault(void) { return false; }
    bool DoThreaded() {return true; }
    bool SynchronizeThreads() {return true;}
    void Initialize();
    bool EvaluateOptions();

    void BeginEvaluate(Topology *top, Topology *top_ref);
    void EndEvaluate();

    CsgApplication::Worker *ForkWorker() {
        return _imc.ForkWorker();
    }

    void MergeWorker(CsgApplication::Worker *worker) {
        _imc.MergeWorker(worker);
    }

public:
    Imc _imc;
    int _write_every;
};

void CsgStatApp::HelpText(ostream &out)
{
    out << "Calculate all distribuions (bonded + non-bonded) specified in options file.\n"
            "Optionally calculates update matrix for invere Monte Carlo. This program\n"
            "is called inside the inverse scripts. Unlike csg_boltzmann, big systems\n"
            "can be treated as well as non-bonded interactions evaluated.";
}

void CsgStatApp::Initialize()
{
    CsgApplication::Initialize();
    AddProgramOptions("Specific options")
            ("options", boost::program_options::value<string>(), "  options file for coarse graining")
            ("do-imc", "  write out inverse monte carlo data")
            ("write-every", boost::program_options::value<int>(&_write_every), "  write afer every block of this length, " \
                "if --blocking   is set, the averages are cleared after every write")
            ("do-blocks", "  write output for blocking analysis")
}

bool CsgStatApp::EvaluateOptions()
{
    CsgApplication::EvaluateOptions();
    CheckRequired("options");
    CheckRequired("trj", "no trajectory file specified");

    _imc.LoadOptions(OptionsMap()["options"].as<string>());

    _imc.WriteEvery(_write_every);
    if(OptionsMap().count("do-blocks"))
        _imc.DoBlocks(true);
    if(OptionsMap().count("do-imc"))
    _imc.DoImc(true);

    _imc.Initialize();
    return true;
}

void CsgStatApp::BeginEvaluate(Topology *top, Topology *top_ref)
{
    _imc.BeginEvaluate(top, top_ref);
}

void CsgStatApp::EndEvaluate()
{
    _imc.EndEvaluate();
}

int main(int argc, char** argv)
{
    CsgStatApp app;
    app.Exec(argc, argv);
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "bistro/bistro/scheduler/utils.h"

#include <string>

#include "bistro/bistro/config/Node.h"
#include "bistro/bistro/config/Job.h"

namespace facebook { namespace bistro {

using namespace std;

/**
 * Try to schedule the given node and job, satisfying resource constraints. If
 * it's possible to schedule it, call the callback with that task, and if it was
 * actually run, modify the passed in resource array.
 */
TaskRunnerResponse try_to_schedule(
    ResourcesByNodeType& resources_by_node,
    const NodePtr& node_ptr,
    const JobPtr& job_ptr,
    TaskRunnerCallback cb) {

  // Store the potential new resources for each node. We'll only actually modify
  // them at the end if we are able to satisfy all the resource constraints.
  ResourcesByNodeType new_resources_by_node;

  auto& job_resources = job_ptr->resources();
  for (const auto& node : node_ptr->traverseUp()) {
    new_resources_by_node[node.id()] = resources_by_node[node.id()];
    auto& cur_resources = new_resources_by_node[node.id()];
    for (int i = 0; i < cur_resources.size() && i < job_resources.size(); ++i) {
      int& amount = cur_resources[i];
      amount -= job_resources[i];
      if (amount < 0) {
        return TaskRunnerResponse::DidNotRunTask;
      }
    }
  }

  const auto ret = cb(job_ptr, node_ptr);
  if (ret == TaskRunnerResponse::RanTask) {
    for (const auto& pair : new_resources_by_node) {
      resources_by_node[pair.first] = pair.second;
    }
  }
  return ret;
}

}}
<commit_msg>use std::move() in try_to_schedule()<commit_after>/*
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "bistro/bistro/scheduler/utils.h"

#include <string>

#include "bistro/bistro/config/Node.h"
#include "bistro/bistro/config/Job.h"

namespace facebook { namespace bistro {

using namespace std;

/**
 * Try to schedule the given node and job, satisfying resource constraints. If
 * it's possible to schedule it, call the callback with that task, and if it was
 * actually run, modify the passed in resource array.
 */
TaskRunnerResponse try_to_schedule(
    ResourcesByNodeType& resources_by_node,
    const NodePtr& node_ptr,
    const JobPtr& job_ptr,
    TaskRunnerCallback cb) {

  // Store the potential new resources for each node. We'll only actually modify
  // them at the end if we are able to satisfy all the resource constraints.
  ResourcesByNodeType new_resources_by_node;

  auto& job_resources = job_ptr->resources();
  for (const auto& node : node_ptr->traverseUp()) {
    new_resources_by_node[node.id()] = resources_by_node[node.id()];
    auto& cur_resources = new_resources_by_node[node.id()];
    for (int i = 0; i < cur_resources.size() && i < job_resources.size(); ++i) {
      int& amount = cur_resources[i];
      amount -= job_resources[i];
      if (amount < 0) {
        return TaskRunnerResponse::DidNotRunTask;
      }
    }
  }

  const auto ret = cb(job_ptr, node_ptr);
  if (ret == TaskRunnerResponse::RanTask) {
    for (auto&& pair : new_resources_by_node) {
      resources_by_node[pair.first] = std::move(pair.second);
    }
  }
  return ret;
}

}}
<|endoftext|>


<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "libmesh_logging.h"
#include "metis_partitioner.h"
#include "serial_mesh.h"

namespace libMesh
{

// ------------------------------------------------------------
// SerialMesh class member functions
SerialMesh::SerialMesh (unsigned int d) :
  UnstructuredMesh (d)
{
  _partitioner = AutoPtr<Partitioner>(new MetisPartitioner());
}

SerialMesh::~SerialMesh ()
{
  this->clear();  // Free nodes and elements
}

// This might be specialized later, but right now it's just here to
// make sure the compiler doesn't give us a default (non-deep) copy
// constructor instead.
SerialMesh::SerialMesh (const SerialMesh &other_mesh) :
  UnstructuredMesh (other_mesh)
{
  this->copy_nodes_and_elements(other_mesh);
  *this->boundary_info = *other_mesh.boundary_info;
}

SerialMesh::SerialMesh (const UnstructuredMesh &other_mesh) :
  UnstructuredMesh (other_mesh)
{
  this->copy_nodes_and_elements(other_mesh);
  *this->boundary_info = *other_mesh.boundary_info;
}

const Point& SerialMesh::point (const unsigned int i) const
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return (*_nodes[i]);
}

const Node& SerialMesh::node (const unsigned int i) const
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return (*_nodes[i]);
}

Node& SerialMesh::node (const unsigned int i)
{
  if (i >= this->n_nodes())
    {
      libMesh::out << " i=" << i
		    << ", n_nodes()=" << this->n_nodes()
		    << std::endl;
      libmesh_error();
    }

  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return (*_nodes[i]);
}

const Node* SerialMesh::node_ptr (const unsigned int i) const
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return _nodes[i];
}

Node* & SerialMesh::node_ptr (const unsigned int i)
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return _nodes[i];
}

Elem* SerialMesh::elem (const unsigned int i) const
{
  libmesh_assert (i < this->n_elem());
  libmesh_assert (_elements[i] != NULL);
  libmesh_assert (_elements[i]->id() == i); // This will change soon

  return _elements[i];
}

Elem* SerialMesh::add_elem (Elem* e)
{
  libmesh_assert(e);

  // We only append elements with SerialMesh
  libmesh_assert (!e->valid_id() ||
          e->id() == _elements.size());

  e->set_id (_elements.size());

  _elements.push_back(e);

  return e;
}

Elem* SerialMesh::insert_elem (Elem* e)
{
  unsigned int eid = e->id();
  libmesh_assert(eid < _elements.size());
  Elem *oldelem = _elements[eid];

  if (oldelem)
    {
      libmesh_assert(oldelem->id() == eid);
      this->delete_elem(oldelem);
    }

  _elements[e->id()] = e;

  return e;
}

void SerialMesh::delete_elem(Elem* e)
{
  libmesh_assert (e != NULL);

  // Initialize an iterator to eventually point to the element we want to delete
  std::vector<Elem*>::iterator pos = _elements.end();

  // In many cases, e->id() gives us a clue as to where e
  // is located in the _elements vector.  Try that first
  // before trying the O(n_elem) search.
  libmesh_assert (e->id() < _elements.size());

  if (_elements[e->id()] == e)
    {
      // We found it!
      pos = _elements.begin();
      std::advance(pos, e->id());
    }

  else
    {
      // This search is O(n_elem)
      pos = std::find (_elements.begin(),
		       _elements.end(),
		       e);
    }

  // Huh? Element not in the vector?
  libmesh_assert (pos != _elements.end());

  // Remove the element from the BoundaryInfo object
  this->boundary_info->remove(e);

  // delete the element
  delete e;

  // explicitly NULL the pointer
  *pos = NULL;
}

void SerialMesh::renumber_elem(const unsigned int old_id,
                               const unsigned int new_id)
{
  // This doesn't get used in serial yet
  Elem *elem = _elements[old_id];
  libmesh_assert (elem);

  elem->set_id(new_id);
  libmesh_assert (!_elements[new_id]);
  _elements[new_id] = elem;
  _elements[old_id] = NULL;
}

Node* SerialMesh::add_point (const Point& p,
			     const unsigned int id,
			     const unsigned int proc_id)
{
//   // We only append points with SerialMesh
//   libmesh_assert(id == DofObject::invalid_id || id == _nodes.size());
//   Node *n = Node::build(p, _nodes.size()).release();
//   n->processor_id() = proc_id;
//   _nodes.push_back (n);

  Node *n = NULL;

  // If the user requests a valid id, either
  // provide the existing node or resize the container
  // to fit the new node.
  if (id != DofObject::invalid_id)
    if (id < _nodes.size())
      n = _nodes[id];
    else
      _nodes.resize(id+1);
  else
    _nodes.push_back (static_cast<Node*>(NULL));

  // if the node already exists, then assign new (x,y,z) values
  if (n)
    *n = p;
  // otherwise build a new node, put it in the right spot, and return
  // a valid pointer.
  else
    {
      n = Node::build(p, (id == DofObject::invalid_id) ? _nodes.size()-1 : id).release();
      n->processor_id() = proc_id;

      if (id == DofObject::invalid_id)
	_nodes.back() = n;
      else
	_nodes[id] = n;
    }

  // better not pass back a NULL pointer.
  libmesh_assert (n);

  return n;
}

Node* SerialMesh::add_node (Node* n)
{
  libmesh_assert(n);
  // We only append points with SerialMesh
  libmesh_assert(!n->valid_id() || n->id() == _nodes.size());

  n->set_id (_nodes.size());

  _nodes.push_back(n);

  return n;
}

void SerialMesh::delete_node(Node* n)
{
  libmesh_assert (n != NULL);
  libmesh_assert (n->id() < _nodes.size());

  // Initialize an iterator to eventually point to the element we want
  // to delete
  std::vector<Node*>::iterator pos;

  // In many cases, e->id() gives us a clue as to where e
  // is located in the _elements vector.  Try that first
  // before trying the O(n_elem) search.
  if (_nodes[n->id()] == n)
    {
      pos = _nodes.begin();
      std::advance(pos, n->id());
    }
  else
    {
      pos = std::find (_nodes.begin(),
		       _nodes.end(),
		       n);
    }

  // Huh? Node not in the vector?
  libmesh_assert (pos != _nodes.end());

  // Delete the node from the BoundaryInfo object
  this->boundary_info->remove(n);

  // delete the node
  delete n;

  // explicitly NULL the pointer
  *pos = NULL;
}

void SerialMesh::renumber_node(const unsigned int old_id,
                               const unsigned int new_id)
{
  // This doesn't get used in serial yet
  Node *node = _nodes[old_id];
  libmesh_assert (node);

  node->set_id(new_id);
  libmesh_assert (!_nodes[new_id]);
  _nodes[new_id] = node;
  _nodes[old_id] = NULL;
}

void SerialMesh::clear ()
{
  // Call parent clear function
  MeshBase::clear();

  // Clear our elements and nodes
  {
    std::vector<Elem*>::iterator       it  = _elements.begin();
    const std::vector<Elem*>::iterator end = _elements.end();

    // There is no need to remove the elements from
    // the BoundaryInfo data structure since we
    // already cleared it.
    for (; it != end; ++it)
      delete *it;

    _elements.clear();
  }

  // clear the nodes data structure
  {
    std::vector<Node*>::iterator       it  = _nodes.begin();
    const std::vector<Node*>::iterator end = _nodes.end();

    // There is no need to remove the nodes from
    // the BoundaryInfo data structure since we
    // already cleared it.
    for (; it != end; ++it)
      delete *it;

    _nodes.clear();
  }
}

void SerialMesh::renumber_nodes_and_elements ()
{

  START_LOG("renumber_nodes_and_elem()", "Mesh");

  // node and element id counters
  unsigned int next_free_elem = 0;
  unsigned int next_free_node = 0;

  // Loop over the elements.  Note that there may
  // be NULLs in the _elements vector from the coarsening
  // process.  Pack the elements in to a contiguous array
  // and then trim any excess.
  {
    std::vector<Elem*>::iterator in        = _elements.begin();
    std::vector<Elem*>::iterator out       = _elements.begin();
    const std::vector<Elem*>::iterator end = _elements.end();

    for (; in != end; ++in)
      if (*in != NULL)
	{
	  Elem* elem = *in;

	  *out = *in;
	  ++out;

	  // Increment the element counter
	  elem->set_id (next_free_elem++);

	  // Loop over this element's nodes.  Number them,
	  // if they have not been numbered already.  Also,
	  // position them in the _nodes vector so that they
	  // are packed contiguously from the beginning.
	  for (unsigned int n=0; n<elem->n_nodes(); n++)
	    if (elem->node(n) == next_free_node)     // don't need to process
	      next_free_node++;                      // [(src == dst) below]

	    else if (elem->node(n) > next_free_node) // need to process
	      {
		// The source and destination indices
		// for this node
		const unsigned int src_idx = elem->node(n);
		const unsigned int dst_idx = next_free_node++;

		// ensure we want to swap a valid nodes
		libmesh_assert (_nodes[src_idx] != NULL);

		// Swap the source and destination nodes
                std::swap(_nodes[src_idx],
                          _nodes[dst_idx] );

		// Set proper indices where that makes sense
		if (_nodes[src_idx] != NULL)
		  _nodes[src_idx]->set_id (src_idx);
		_nodes[dst_idx]->set_id (dst_idx);
	      }
	}

    // Erase any additional storage. These elements have been
    // copied into NULL voids by the procedure above, and are
    // thus repeated and unnecessary.
    _elements.erase (out, end);
  }

  // Any nodes in the vector >= _nodes[next_free_node]
  // are not connected to any elements and may be deleted
  // if desired.

  // (This code block will erase the unused nodes)
  // Now, delete the unused nodes
  {
    std::vector<Node*>::iterator nd        = _nodes.begin();
    const std::vector<Node*>::iterator end = _nodes.end();

    std::advance (nd, next_free_node);

    for (std::vector<Node*>::iterator it=nd;
	 it != end; ++it)
      {
        // Mesh modification code might have already deleted some
        // nodes
	if (*it == NULL)
          continue;

	// remove any boundary information associated with
	// this node
	this->boundary_info->remove (*it);

	// delete the node
	delete *it;
	*it = NULL;
      }

    _nodes.erase (nd, end);
  }

  libmesh_assert (next_free_elem == _elements.size());
  libmesh_assert (next_free_node == _nodes.size());

  STOP_LOG("renumber_nodes_and_elem()", "Mesh");
}

void SerialMesh::fix_broken_node_and_element_numbering ()
{
   // Nodes first
  for (unsigned int n=0; n<this->_nodes.size(); n++)
    if (this->_nodes[n] != NULL)
      this->_nodes[n]->set_id() = n;

  // Elements next
  for (unsigned int e=0; e<this->_elements.size(); e++)
    if (this->_elements[e] != NULL)
      this->_elements[e]->set_id() = e;
}

unsigned int SerialMesh::n_active_elem () const
{
  return static_cast<unsigned int>(std::distance (this->active_elements_begin(),
						  this->active_elements_end()));
}

} // namespace libMesh
<commit_msg>Support out-of-order and sparse add_elem on SerialMesh; this doesn't break anything and it's the easiest way to make some higher level code ParallelMesh/SerialMesh agnostic.<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "libmesh_logging.h"
#include "metis_partitioner.h"
#include "serial_mesh.h"

namespace libMesh
{

// ------------------------------------------------------------
// SerialMesh class member functions
SerialMesh::SerialMesh (unsigned int d) :
  UnstructuredMesh (d)
{
  _partitioner = AutoPtr<Partitioner>(new MetisPartitioner());
}

SerialMesh::~SerialMesh ()
{
  this->clear();  // Free nodes and elements
}

// This might be specialized later, but right now it's just here to
// make sure the compiler doesn't give us a default (non-deep) copy
// constructor instead.
SerialMesh::SerialMesh (const SerialMesh &other_mesh) :
  UnstructuredMesh (other_mesh)
{
  this->copy_nodes_and_elements(other_mesh);
  *this->boundary_info = *other_mesh.boundary_info;
}

SerialMesh::SerialMesh (const UnstructuredMesh &other_mesh) :
  UnstructuredMesh (other_mesh)
{
  this->copy_nodes_and_elements(other_mesh);
  *this->boundary_info = *other_mesh.boundary_info;
}

const Point& SerialMesh::point (const unsigned int i) const
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return (*_nodes[i]);
}

const Node& SerialMesh::node (const unsigned int i) const
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return (*_nodes[i]);
}

Node& SerialMesh::node (const unsigned int i)
{
  if (i >= this->n_nodes())
    {
      libMesh::out << " i=" << i
		    << ", n_nodes()=" << this->n_nodes()
		    << std::endl;
      libmesh_error();
    }

  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return (*_nodes[i]);
}

const Node* SerialMesh::node_ptr (const unsigned int i) const
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return _nodes[i];
}

Node* & SerialMesh::node_ptr (const unsigned int i)
{
  libmesh_assert (i < this->n_nodes());
  libmesh_assert (_nodes[i] != NULL);
  libmesh_assert (_nodes[i]->id() == i); // This will change soon

  return _nodes[i];
}

Elem* SerialMesh::elem (const unsigned int i) const
{
  libmesh_assert (i < this->n_elem());
  libmesh_assert (_elements[i] != NULL);
  libmesh_assert (_elements[i]->id() == i); // This will change soon

  return _elements[i];
}

Elem* SerialMesh::add_elem (Elem* e)
{
  libmesh_assert(e);

  // We no longer merely append elements with SerialMesh

  // If the user requests a valid id that doesn't correspond to an
  // existing element, let's give them that id, resizing the elements
  // container if necessary.
  if (!e->valid_id())
    e->set_id (_elements.size());

  const unsigned int id = e->id();

  if (id < _elements.size())
    {
      // Overwriting existing elements is still probably a mistake.
      libmesh_assert(!_elements[id]);
    }
  else
    {
      _elements.resize(id+1, NULL);
    }

  _elements[id] = e;

  return e;
}

Elem* SerialMesh::insert_elem (Elem* e)
{
  unsigned int eid = e->id();
  libmesh_assert(eid < _elements.size());
  Elem *oldelem = _elements[eid];

  if (oldelem)
    {
      libmesh_assert(oldelem->id() == eid);
      this->delete_elem(oldelem);
    }

  _elements[e->id()] = e;

  return e;
}

void SerialMesh::delete_elem(Elem* e)
{
  libmesh_assert (e != NULL);

  // Initialize an iterator to eventually point to the element we want to delete
  std::vector<Elem*>::iterator pos = _elements.end();

  // In many cases, e->id() gives us a clue as to where e
  // is located in the _elements vector.  Try that first
  // before trying the O(n_elem) search.
  libmesh_assert (e->id() < _elements.size());

  if (_elements[e->id()] == e)
    {
      // We found it!
      pos = _elements.begin();
      std::advance(pos, e->id());
    }

  else
    {
      // This search is O(n_elem)
      pos = std::find (_elements.begin(),
		       _elements.end(),
		       e);
    }

  // Huh? Element not in the vector?
  libmesh_assert (pos != _elements.end());

  // Remove the element from the BoundaryInfo object
  this->boundary_info->remove(e);

  // delete the element
  delete e;

  // explicitly NULL the pointer
  *pos = NULL;
}

void SerialMesh::renumber_elem(const unsigned int old_id,
                               const unsigned int new_id)
{
  // This doesn't get used in serial yet
  Elem *elem = _elements[old_id];
  libmesh_assert (elem);

  elem->set_id(new_id);
  libmesh_assert (!_elements[new_id]);
  _elements[new_id] = elem;
  _elements[old_id] = NULL;
}

Node* SerialMesh::add_point (const Point& p,
			     const unsigned int id,
			     const unsigned int proc_id)
{
//   // We only append points with SerialMesh
//   libmesh_assert(id == DofObject::invalid_id || id == _nodes.size());
//   Node *n = Node::build(p, _nodes.size()).release();
//   n->processor_id() = proc_id;
//   _nodes.push_back (n);

  Node *n = NULL;

  // If the user requests a valid id, either
  // provide the existing node or resize the container
  // to fit the new node.
  if (id != DofObject::invalid_id)
    if (id < _nodes.size())
      n = _nodes[id];
    else
      _nodes.resize(id+1);
  else
    _nodes.push_back (static_cast<Node*>(NULL));

  // if the node already exists, then assign new (x,y,z) values
  if (n)
    *n = p;
  // otherwise build a new node, put it in the right spot, and return
  // a valid pointer.
  else
    {
      n = Node::build(p, (id == DofObject::invalid_id) ? _nodes.size()-1 : id).release();
      n->processor_id() = proc_id;

      if (id == DofObject::invalid_id)
	_nodes.back() = n;
      else
	_nodes[id] = n;
    }

  // better not pass back a NULL pointer.
  libmesh_assert (n);

  return n;
}

Node* SerialMesh::add_node (Node* n)
{
  libmesh_assert(n);
  // We only append points with SerialMesh
  libmesh_assert(!n->valid_id() || n->id() == _nodes.size());

  n->set_id (_nodes.size());

  _nodes.push_back(n);

  return n;
}

void SerialMesh::delete_node(Node* n)
{
  libmesh_assert (n != NULL);
  libmesh_assert (n->id() < _nodes.size());

  // Initialize an iterator to eventually point to the element we want
  // to delete
  std::vector<Node*>::iterator pos;

  // In many cases, e->id() gives us a clue as to where e
  // is located in the _elements vector.  Try that first
  // before trying the O(n_elem) search.
  if (_nodes[n->id()] == n)
    {
      pos = _nodes.begin();
      std::advance(pos, n->id());
    }
  else
    {
      pos = std::find (_nodes.begin(),
		       _nodes.end(),
		       n);
    }

  // Huh? Node not in the vector?
  libmesh_assert (pos != _nodes.end());

  // Delete the node from the BoundaryInfo object
  this->boundary_info->remove(n);

  // delete the node
  delete n;

  // explicitly NULL the pointer
  *pos = NULL;
}

void SerialMesh::renumber_node(const unsigned int old_id,
                               const unsigned int new_id)
{
  // This doesn't get used in serial yet
  Node *node = _nodes[old_id];
  libmesh_assert (node);

  node->set_id(new_id);
  libmesh_assert (!_nodes[new_id]);
  _nodes[new_id] = node;
  _nodes[old_id] = NULL;
}

void SerialMesh::clear ()
{
  // Call parent clear function
  MeshBase::clear();

  // Clear our elements and nodes
  {
    std::vector<Elem*>::iterator       it  = _elements.begin();
    const std::vector<Elem*>::iterator end = _elements.end();

    // There is no need to remove the elements from
    // the BoundaryInfo data structure since we
    // already cleared it.
    for (; it != end; ++it)
      delete *it;

    _elements.clear();
  }

  // clear the nodes data structure
  {
    std::vector<Node*>::iterator       it  = _nodes.begin();
    const std::vector<Node*>::iterator end = _nodes.end();

    // There is no need to remove the nodes from
    // the BoundaryInfo data structure since we
    // already cleared it.
    for (; it != end; ++it)
      delete *it;

    _nodes.clear();
  }
}

void SerialMesh::renumber_nodes_and_elements ()
{

  START_LOG("renumber_nodes_and_elem()", "Mesh");

  // node and element id counters
  unsigned int next_free_elem = 0;
  unsigned int next_free_node = 0;

  // Loop over the elements.  Note that there may
  // be NULLs in the _elements vector from the coarsening
  // process.  Pack the elements in to a contiguous array
  // and then trim any excess.
  {
    std::vector<Elem*>::iterator in        = _elements.begin();
    std::vector<Elem*>::iterator out       = _elements.begin();
    const std::vector<Elem*>::iterator end = _elements.end();

    for (; in != end; ++in)
      if (*in != NULL)
	{
	  Elem* elem = *in;

	  *out = *in;
	  ++out;

	  // Increment the element counter
	  elem->set_id (next_free_elem++);

	  // Loop over this element's nodes.  Number them,
	  // if they have not been numbered already.  Also,
	  // position them in the _nodes vector so that they
	  // are packed contiguously from the beginning.
	  for (unsigned int n=0; n<elem->n_nodes(); n++)
	    if (elem->node(n) == next_free_node)     // don't need to process
	      next_free_node++;                      // [(src == dst) below]

	    else if (elem->node(n) > next_free_node) // need to process
	      {
		// The source and destination indices
		// for this node
		const unsigned int src_idx = elem->node(n);
		const unsigned int dst_idx = next_free_node++;

		// ensure we want to swap a valid nodes
		libmesh_assert (_nodes[src_idx] != NULL);

		// Swap the source and destination nodes
                std::swap(_nodes[src_idx],
                          _nodes[dst_idx] );

		// Set proper indices where that makes sense
		if (_nodes[src_idx] != NULL)
		  _nodes[src_idx]->set_id (src_idx);
		_nodes[dst_idx]->set_id (dst_idx);
	      }
	}

    // Erase any additional storage. These elements have been
    // copied into NULL voids by the procedure above, and are
    // thus repeated and unnecessary.
    _elements.erase (out, end);
  }

  // Any nodes in the vector >= _nodes[next_free_node]
  // are not connected to any elements and may be deleted
  // if desired.

  // (This code block will erase the unused nodes)
  // Now, delete the unused nodes
  {
    std::vector<Node*>::iterator nd        = _nodes.begin();
    const std::vector<Node*>::iterator end = _nodes.end();

    std::advance (nd, next_free_node);

    for (std::vector<Node*>::iterator it=nd;
	 it != end; ++it)
      {
        // Mesh modification code might have already deleted some
        // nodes
	if (*it == NULL)
          continue;

	// remove any boundary information associated with
	// this node
	this->boundary_info->remove (*it);

	// delete the node
	delete *it;
	*it = NULL;
      }

    _nodes.erase (nd, end);
  }

  libmesh_assert (next_free_elem == _elements.size());
  libmesh_assert (next_free_node == _nodes.size());

  STOP_LOG("renumber_nodes_and_elem()", "Mesh");
}

void SerialMesh::fix_broken_node_and_element_numbering ()
{
   // Nodes first
  for (unsigned int n=0; n<this->_nodes.size(); n++)
    if (this->_nodes[n] != NULL)
      this->_nodes[n]->set_id() = n;

  // Elements next
  for (unsigned int e=0; e<this->_elements.size(); e++)
    if (this->_elements[e] != NULL)
      this->_elements[e]->set_id() = e;
}

unsigned int SerialMesh::n_active_elem () const
{
  return static_cast<unsigned int>(std::distance (this->active_elements_begin(),
						  this->active_elements_end()));
}

} // namespace libMesh
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <assert.h>
#include <memory>
#include <fnordmetric/thread/threadpool.h>
#include <fnordmetric/util/runtimeexception.h>
#include <sys/select.h>
#include <thread>

using fnord::util::ExceptionHandler;

namespace fnord {
namespace thread {

ThreadPool::ThreadPool(
    std::unique_ptr<ExceptionHandler> error_handler) :
    error_handler_(std::move(error_handler)),
    free_threads_(0) {}

void ThreadPool::run(std::shared_ptr<Task> task) {
  runInternal([this, task] () {
    task->run();
  });
}

void ThreadPool::runOnReadable(std::shared_ptr<Task> task, int fd) {
  runInternal([this, task, fd] () {
    fd_set op_read, op_write;
    FD_ZERO(&op_read);
    FD_ZERO(&op_write);
    FD_SET(fd, &op_read);

    auto res = select(fd + 1, &op_read, &op_write, NULL, NULL);

    if (res == 0) {
      RAISE(kIOError, "unexpected timeout while select()ing");
    }

    if (res == -1) {
      RAISE_ERRNO(kIOError, "select() failed");
    }

    task->run();
  });
}

void ThreadPool::runOnWritable(std::shared_ptr<Task> task, int fd) {
  runInternal([task, fd] () {
    fd_set op_read, op_write;
    FD_ZERO(&op_read);
    FD_ZERO(&op_write);
    FD_SET(fd, &op_write);

    auto res = select(fd + 1, &op_read, &op_write, NULL, NULL);

    if (res == 0) {
      RAISE(kIOError, "unexpected timeout while select()ing");
    }

    if (res == -1) {
      RAISE_ERRNO(kIOError, "select() failed");
    }

    task->run();
  });
}

void ThreadPool::runInternal(std::function<void()> fn) {
  bool start_thread = true;

  {
    std::lock_guard<std::mutex> lock_holder(runq_mutex_);
    runq_.push_back(fn);

    if (runq_.size() < free_threads_) {
      start_thread = false;
    }
  }

  if (start_thread) {
    startThread();
  }

  wakeup_.notify_one();
}

void ThreadPool::startThread() {
  std::thread thread([this] () {
    for (;;) {
      std::function<void()> task;

      {
        std::unique_lock<std::mutex> lk(runq_mutex_);
        free_threads_++;

        while (runq_.size() == 0) {
          wakeup_.wait(lk);
        }

        assert(runq_.size() > 0);
        task = runq_.front();
        runq_.pop_front();
        free_threads_--;
      }

      try {
        task();
      } catch (const std::exception& e) {
        this->error_handler_->onException(e);
      }
    }
  });

  thread.detach();
}

}
}
<commit_msg>better error handling in ThreadPool<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <assert.h>
#include <memory>
#include <fnordmetric/thread/threadpool.h>
#include <fnordmetric/util/runtimeexception.h>
#include <sys/select.h>
#include <thread>

using fnord::util::ExceptionHandler;

namespace fnord {
namespace thread {

ThreadPool::ThreadPool(
    std::unique_ptr<ExceptionHandler> error_handler) :
    error_handler_(std::move(error_handler)),
    free_threads_(0) {}

void ThreadPool::run(std::shared_ptr<Task> task) {
  runInternal([this, task] () {
    task->run();
  });
}

void ThreadPool::runOnReadable(std::shared_ptr<Task> task, int fd) {
  runInternal([this, task, fd] () {
    fd_set op_read, op_write;
    FD_ZERO(&op_read);
    FD_ZERO(&op_write);
    FD_SET(fd, &op_read);

    auto res = select(fd + 1, &op_read, &op_write, NULL, NULL);

    if (res == 0) {
      RAISE(kIOError, "unexpected timeout while select()ing");
    }

    if (res == -1) {
      RAISE_ERRNO(kIOError, "select() failed");
    }

    task->run();
  });
}

void ThreadPool::runOnWritable(std::shared_ptr<Task> task, int fd) {
  runInternal([task, fd] () {
    fd_set op_read, op_write;
    FD_ZERO(&op_read);
    FD_ZERO(&op_write);
    FD_SET(fd, &op_write);

    auto res = select(fd + 1, &op_read, &op_write, NULL, NULL);

    if (res == 0) {
      RAISE(kIOError, "unexpected timeout while select()ing");
    }

    if (res == -1) {
      RAISE_ERRNO(kIOError, "select() failed");
    }

    task->run();
  });
}

void ThreadPool::runInternal(std::function<void()> fn) {
  bool start_thread = true;

  {
    std::lock_guard<std::mutex> lock_holder(runq_mutex_);
    runq_.push_back(fn);

    if (runq_.size() < free_threads_) {
      start_thread = false;
    }
  }

  if (start_thread) {
    startThread();
  }

  wakeup_.notify_one();
}

void ThreadPool::startThread() {
  try {
    std::thread thread([this] () {
      for (;;) {
        try {
          std::function<void()> task;

          {
            std::unique_lock<std::mutex> lk(runq_mutex_);
            free_threads_++;

            while (runq_.size() == 0) {
              wakeup_.wait(lk);
            }

            assert(runq_.size() > 0);
            task = runq_.front();
            runq_.pop_front();
            free_threads_--;
          }

          task();
        } catch (const std::exception& e) {
          this->error_handler_->onException(e);
        }
      }
    });

    thread.detach();
  } catch (const std::exception& e) {
    this->error_handler_->onException(e);
  }
}

}
}
<|endoftext|>


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

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

#include <helper/imageproducer.hxx>

namespace framework
{

static pfunc_getImage   _pGetImageFunc = NULL;

pfunc_getImage SAL_CALL SetImageProducer( pfunc_getImage pNewGetImageFunc )
{
    pfunc_getImage  pOldFunc = _pGetImageFunc;
    _pGetImageFunc = pNewGetImageFunc;

    return pOldFunc;
}

Image SAL_CALL GetImageFromURL( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig, BOOL bHiContrast )
{
    if ( _pGetImageFunc )
        return _pGetImageFunc( rFrame, aURL, bBig, bHiContrast );
    else
        return Image();
}

}

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

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

#include <helper/imageproducer.hxx>

namespace framework
{

static pfunc_getImage   _pGetImageFunc = NULL;

pfunc_getImage SAL_CALL SetImageProducer( pfunc_getImage pNewGetImageFunc )
{
    pfunc_getImage  pOldFunc = _pGetImageFunc;
    _pGetImageFunc = pNewGetImageFunc;

    return pOldFunc;
}

Image SAL_CALL GetImageFromURL( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig, BOOL bHiContrast )
{
    if ( _pGetImageFunc )
        return _pGetImageFunc( rFrame, aURL, bBig, bHiContrast );
    else
        return Image();
}

}

<|endoftext|>


<commit_before>/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mimapplication.h"

#include <MWindow>
#include <MDebug>

#include "x11wrapper.h"

X11Wrapper::X11Wrapper()
    : remoteWindowId(0),
      remoteWindowXPixmap(0)
{
}

MIMApplication::MIMApplication(int &argc, char **argv)
    : MApplication(argc, argv),
      passThruWindow(0),
      x11Wrapper(new X11Wrapper)
{
    int damageError;

    XDamageQueryExtension(QX11Info::display(), &damageBase, &damageError);

}

MIMApplication::~MIMApplication()
{
    delete x11Wrapper;
}

bool MIMApplication::x11EventFilter(XEvent *ev)
{
    handleMapNotifyEvents(ev);
    handleTransientEvents(ev);
    handleDamageEvents(ev);
    return MApplication::x11EventFilter(ev);
}

void MIMApplication::handleMapNotifyEvents(XEvent *ev)
{
    if (wasPassThruWindowMapped(ev)) {
        mDebug("MIMApplication") << "PassThru window was mapped.";
        emit passThruWindowMapped();
    } else if (wasPassThruWindowUnmapped(ev)) {
        mDebug("MIMApplication") << "PassThru window was unmapped.";
        emit passThruWindowUnmapped();
    }
}

void MIMApplication::handleTransientEvents(XEvent *ev)
{
    if (0 == x11Wrapper->remoteWindowId || not passThruWindow) {
        return;
    }

    if (wasRemoteWindowIconified(ev) || wasRemoteWindowUnmapped(ev)) {
        mDebug("MIMApplication") << "Remote window was destroyed or iconified - hiding.";
        destroyDamage();
        x11Wrapper->remoteWindowId = 0;
        emit remoteWindowGone();
    }
}

void MIMApplication::setTransientHint(int newRemoteWinId)
{
    if (0 == newRemoteWinId || not activeWindow()) {
        return;
    }

    x11Wrapper->remoteWindowId = newRemoteWinId;

    XSetTransientForHint(QX11Info::display(),
                         passThruWindow->effectiveWinId(),
                         x11Wrapper->remoteWindowId);

    // Using PropertyChangeMask is a work-around for NB#172722 (a WONTFIX):
    XSelectInput(QX11Info::display(),
                 x11Wrapper->remoteWindowId,
                 StructureNotifyMask | PropertyChangeMask);
}

void MIMApplication::setPassThruWindow(QWidget *newPassThruWindow)
{
    if (newPassThruWindow != passThruWindow) {
        passThruWindow = newPassThruWindow;
    }
}

MIMApplication *MIMApplication::instance()
{
    return static_cast<MIMApplication *>(QCoreApplication::instance());
}

bool MIMApplication::wasRemoteWindowIconified(XEvent *ev) const
{
    if (PropertyNotify != ev->type) {
        return false;
    }

    static const Atom wmState = XInternAtom(QX11Info::display(), "WM_STATE", false);

    if (ev->xproperty.atom == wmState) {
        Atom type;
        int format;
        unsigned long length;
        unsigned long after;
        unsigned long *state;
        uchar *data = 0;

        int queryResult = XGetWindowProperty(QX11Info::display(), x11Wrapper->remoteWindowId, wmState, 0, 2,
                                             false, AnyPropertyType, &type, &format, &length,
                                             &after, &data);
        state = (unsigned long *) data;

        bool result = (queryResult == Success && data && format == 32 && *state == IconicState);

        if (data) {
            XFree(data);
        }

        return result;
    }

    return false;
}

bool MIMApplication::wasRemoteWindowUnmapped(XEvent *ev) const
{
    return (UnmapNotify == ev->type &&
            ev->xunmap.event == x11Wrapper->remoteWindowId);
}

bool MIMApplication::wasPassThruWindowMapped(XEvent *ev) const
{
    return (passThruWindow &&
            MapNotify == ev->type &&
            static_cast<WId>(ev->xmap.event) == passThruWindow->effectiveWinId());
}

bool MIMApplication::wasPassThruWindowUnmapped(XEvent *ev) const
{
    return (passThruWindow &&
            UnmapNotify == ev->type &&
            static_cast<WId>(ev->xunmap.event) == passThruWindow->effectiveWinId());
}

void MIMApplication::setupDamage()
{
    if (x11Wrapper->remoteWindowId == 0)
        return;

    if (x11Wrapper->pixmapDamage != 0)
        destroyDamage();

    x11Wrapper->pixmapDamage = XDamageCreate(QX11Info::display(), x11Wrapper->remoteWindowId, XDamageReportNonEmpty);
}

void MIMApplication::destroyDamage()
{
    if (x11Wrapper->pixmapDamage != 0) {
        XDamageDestroy(QX11Info::display(), x11Wrapper->pixmapDamage);
        x11Wrapper->pixmapDamage = 0;
    }
}

void MIMApplication::handleDamageEvents(XEvent *event)
{
    if (x11Wrapper->remoteWindowId == 0 ||
        x11Wrapper->pixmapDamage == 0)
        return;

    if (event->type == damageBase + XDamageNotify) {
        XDamageNotifyEvent *e = reinterpret_cast<XDamageNotifyEvent*>(event);

        if (x11Wrapper->pixmapDamage == e->damage) {
            XserverRegion parts = XFixesCreateRegion(QX11Info::display(), 0, 0);
            XDamageSubtract(QX11Info::display(), e->damage, None, parts);

            QRegion region;

            int nrects;
            XRectangle *rects = XFixesFetchRegion (QX11Info::display(), parts, &nrects);
            if (rects) {
                for (int i = 0; i < nrects; ++i) {
                    region += QRect(rects[i].x, rects[i].y, rects[i].width, rects[i].height);
                }
            }
            free(rects);

            XFixesDestroyRegion(QX11Info::display(), parts);
            // TODO: Replace QRect() with actual damage parts
            emit remoteWindowUpdated(region);
        }
    }
}

void MIMApplication::redirectRemoteWindow()
{
    if (x11Wrapper->remoteWindowId != 0) {
        // TODO: Handle error here
        XCompositeRedirectWindow(QX11Info::display(),
            x11Wrapper->remoteWindowId,
            CompositeRedirectManual);

        if (x11Wrapper->remoteWindowXPixmap != 0) {
            XFreePixmap(QX11Info::display(), x11Wrapper->remoteWindowXPixmap);
            x11Wrapper->remoteWindowXPixmap = 0;
        }

        x11Wrapper->remoteWindowXPixmap = XCompositeNameWindowPixmap(QX11Info::display(), x11Wrapper->remoteWindowId);
        XSync(QX11Info::display(), FALSE);
        if (x11Wrapper->remoteWindowXPixmap != 0) {
            x11Wrapper->remoteWindowPixmap = QPixmap::fromX11Pixmap(x11Wrapper->remoteWindowXPixmap, QPixmap::ExplicitlyShared);
        }
        setupDamage();
        emit remoteWindowUpdated(QRegion());
    }
}

void MIMApplication::unredirectRemoteWindow()
{
    if (x11Wrapper->remoteWindowId != 0) {
        XCompositeUnredirectWindow(QX11Info::display(),
            x11Wrapper->remoteWindowId,
            CompositeRedirectManual);
        destroyDamage();
    }
}

QPixmap MIMApplication::remoteWindowPixmap() const
{
    return x11Wrapper->remoteWindowPixmap;
}
<commit_msg>Changes: Remove unnecesary TODO comment.<commit_after>/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mimapplication.h"

#include <MWindow>
#include <MDebug>

#include "x11wrapper.h"

X11Wrapper::X11Wrapper()
    : remoteWindowId(0),
      remoteWindowXPixmap(0)
{
}

MIMApplication::MIMApplication(int &argc, char **argv)
    : MApplication(argc, argv),
      passThruWindow(0),
      x11Wrapper(new X11Wrapper)
{
    int damageError;

    XDamageQueryExtension(QX11Info::display(), &damageBase, &damageError);

}

MIMApplication::~MIMApplication()
{
    delete x11Wrapper;
}

bool MIMApplication::x11EventFilter(XEvent *ev)
{
    handleMapNotifyEvents(ev);
    handleTransientEvents(ev);
    handleDamageEvents(ev);
    return MApplication::x11EventFilter(ev);
}

void MIMApplication::handleMapNotifyEvents(XEvent *ev)
{
    if (wasPassThruWindowMapped(ev)) {
        mDebug("MIMApplication") << "PassThru window was mapped.";
        emit passThruWindowMapped();
    } else if (wasPassThruWindowUnmapped(ev)) {
        mDebug("MIMApplication") << "PassThru window was unmapped.";
        emit passThruWindowUnmapped();
    }
}

void MIMApplication::handleTransientEvents(XEvent *ev)
{
    if (0 == x11Wrapper->remoteWindowId || not passThruWindow) {
        return;
    }

    if (wasRemoteWindowIconified(ev) || wasRemoteWindowUnmapped(ev)) {
        mDebug("MIMApplication") << "Remote window was destroyed or iconified - hiding.";
        destroyDamage();
        x11Wrapper->remoteWindowId = 0;
        emit remoteWindowGone();
    }
}

void MIMApplication::setTransientHint(int newRemoteWinId)
{
    if (0 == newRemoteWinId || not activeWindow()) {
        return;
    }

    x11Wrapper->remoteWindowId = newRemoteWinId;

    XSetTransientForHint(QX11Info::display(),
                         passThruWindow->effectiveWinId(),
                         x11Wrapper->remoteWindowId);

    // Using PropertyChangeMask is a work-around for NB#172722 (a WONTFIX):
    XSelectInput(QX11Info::display(),
                 x11Wrapper->remoteWindowId,
                 StructureNotifyMask | PropertyChangeMask);
}

void MIMApplication::setPassThruWindow(QWidget *newPassThruWindow)
{
    if (newPassThruWindow != passThruWindow) {
        passThruWindow = newPassThruWindow;
    }
}

MIMApplication *MIMApplication::instance()
{
    return static_cast<MIMApplication *>(QCoreApplication::instance());
}

bool MIMApplication::wasRemoteWindowIconified(XEvent *ev) const
{
    if (PropertyNotify != ev->type) {
        return false;
    }

    static const Atom wmState = XInternAtom(QX11Info::display(), "WM_STATE", false);

    if (ev->xproperty.atom == wmState) {
        Atom type;
        int format;
        unsigned long length;
        unsigned long after;
        unsigned long *state;
        uchar *data = 0;

        int queryResult = XGetWindowProperty(QX11Info::display(), x11Wrapper->remoteWindowId, wmState, 0, 2,
                                             false, AnyPropertyType, &type, &format, &length,
                                             &after, &data);
        state = (unsigned long *) data;

        bool result = (queryResult == Success && data && format == 32 && *state == IconicState);

        if (data) {
            XFree(data);
        }

        return result;
    }

    return false;
}

bool MIMApplication::wasRemoteWindowUnmapped(XEvent *ev) const
{
    return (UnmapNotify == ev->type &&
            ev->xunmap.event == x11Wrapper->remoteWindowId);
}

bool MIMApplication::wasPassThruWindowMapped(XEvent *ev) const
{
    return (passThruWindow &&
            MapNotify == ev->type &&
            static_cast<WId>(ev->xmap.event) == passThruWindow->effectiveWinId());
}

bool MIMApplication::wasPassThruWindowUnmapped(XEvent *ev) const
{
    return (passThruWindow &&
            UnmapNotify == ev->type &&
            static_cast<WId>(ev->xunmap.event) == passThruWindow->effectiveWinId());
}

void MIMApplication::setupDamage()
{
    if (x11Wrapper->remoteWindowId == 0)
        return;

    if (x11Wrapper->pixmapDamage != 0)
        destroyDamage();

    x11Wrapper->pixmapDamage = XDamageCreate(QX11Info::display(), x11Wrapper->remoteWindowId, XDamageReportNonEmpty);
}

void MIMApplication::destroyDamage()
{
    if (x11Wrapper->pixmapDamage != 0) {
        XDamageDestroy(QX11Info::display(), x11Wrapper->pixmapDamage);
        x11Wrapper->pixmapDamage = 0;
    }
}

void MIMApplication::handleDamageEvents(XEvent *event)
{
    if (x11Wrapper->remoteWindowId == 0 ||
        x11Wrapper->pixmapDamage == 0)
        return;

    if (event->type == damageBase + XDamageNotify) {
        XDamageNotifyEvent *e = reinterpret_cast<XDamageNotifyEvent*>(event);

        if (x11Wrapper->pixmapDamage == e->damage) {
            XserverRegion parts = XFixesCreateRegion(QX11Info::display(), 0, 0);
            XDamageSubtract(QX11Info::display(), e->damage, None, parts);

            QRegion region;

            int nrects;
            XRectangle *rects = XFixesFetchRegion (QX11Info::display(), parts, &nrects);
            if (rects) {
                for (int i = 0; i < nrects; ++i) {
                    region += QRect(rects[i].x, rects[i].y, rects[i].width, rects[i].height);
                }
            }
            free(rects);

            XFixesDestroyRegion(QX11Info::display(), parts);
            emit remoteWindowUpdated(region);
        }
    }
}

void MIMApplication::redirectRemoteWindow()
{
    if (x11Wrapper->remoteWindowId != 0) {
        // TODO: Handle error here
        XCompositeRedirectWindow(QX11Info::display(),
            x11Wrapper->remoteWindowId,
            CompositeRedirectManual);

        if (x11Wrapper->remoteWindowXPixmap != 0) {
            XFreePixmap(QX11Info::display(), x11Wrapper->remoteWindowXPixmap);
            x11Wrapper->remoteWindowXPixmap = 0;
        }

        x11Wrapper->remoteWindowXPixmap = XCompositeNameWindowPixmap(QX11Info::display(), x11Wrapper->remoteWindowId);
        XSync(QX11Info::display(), FALSE);
        if (x11Wrapper->remoteWindowXPixmap != 0) {
            x11Wrapper->remoteWindowPixmap = QPixmap::fromX11Pixmap(x11Wrapper->remoteWindowXPixmap, QPixmap::ExplicitlyShared);
        }
        setupDamage();
        emit remoteWindowUpdated(QRegion());
    }
}

void MIMApplication::unredirectRemoteWindow()
{
    if (x11Wrapper->remoteWindowId != 0) {
        XCompositeUnredirectWindow(QX11Info::display(),
            x11Wrapper->remoteWindowId,
            CompositeRedirectManual);
        destroyDamage();
    }
}

QPixmap MIMApplication::remoteWindowPixmap() const
{
    return x11Wrapper->remoteWindowPixmap;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *  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 Willow Garage, Inc. 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.
 *
 * $Id$
 *
 */

#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/pcl_tests.h>

using namespace pcl;
using namespace pcl::test;

PointCloud<PointXYZ> cloud;
const size_t size = 10 * 480;

TEST (PointCloud, size)
{
  EXPECT_EQ(cloud.points.size (), cloud.size ());
}

TEST (PointCloud, sq_brackets_wrapper)
{
  for (uint32_t i = 0; i < size; ++i)
  {
    Eigen::Vector3f direct = cloud.points[i].getVector3fMap ();
    Eigen::Vector3f wrapped = cloud[i].getVector3fMap ();
    EXPECT_EQ_VECTORS (direct,wrapped);
  }
}

TEST (PointCloud, at)
{
  for (uint32_t i = 0; i < size; ++i)
  {
    Eigen::Vector3f direct = cloud.points.at (i).getVector3fMap ();
    Eigen::Vector3f wrapped = cloud.at (i).getVector3fMap ();
    EXPECT_EQ_VECTORS (direct,wrapped);
  }
}

TEST (PointCloud, front)
{
  Eigen::Vector3f direct = cloud.points.front ().getVector3fMap ();
  Eigen::Vector3f wrapped = cloud.front ().getVector3fMap ();
  EXPECT_EQ_VECTORS (direct,wrapped);
}

TEST (PointCloud, back)
{
  Eigen::Vector3f direct = cloud.points.back ().getVector3fMap ();
  Eigen::Vector3f wrapped = cloud.back ().getVector3fMap ();
  EXPECT_EQ_VECTORS (direct,wrapped);
}

int
main (int argc, char** argv)
{
  cloud.width = 10;
  cloud.height = 480;
  for (uint32_t i = 0; i < size; ++i)
    cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
<commit_msg>Add: test for constructor with memory allocation and range inserter<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *  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 Willow Garage, Inc. 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.
 *
 * $Id$
 *
 */

#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/pcl_tests.h>

using namespace pcl;
using namespace pcl::test;

PointCloud<PointXYZ> cloud;
const size_t size = 10 * 480;

TEST (PointCloud, size)
{
  EXPECT_EQ(cloud.points.size (), cloud.size ());
}

TEST (PointCloud, sq_brackets_wrapper)
{
  for (uint32_t i = 0; i < size; ++i)
  {
    Eigen::Vector3f direct = cloud.points[i].getVector3fMap ();
    Eigen::Vector3f wrapped = cloud[i].getVector3fMap ();
    EXPECT_EQ_VECTORS (direct,wrapped);
  }
}

TEST (PointCloud, at)
{
  for (uint32_t i = 0; i < size; ++i)
  {
    Eigen::Vector3f direct = cloud.points.at (i).getVector3fMap ();
    Eigen::Vector3f wrapped = cloud.at (i).getVector3fMap ();
    EXPECT_EQ_VECTORS (direct,wrapped);
  }
}

TEST (PointCloud, front)
{
  Eigen::Vector3f direct = cloud.points.front ().getVector3fMap ();
  Eigen::Vector3f wrapped = cloud.front ().getVector3fMap ();
  EXPECT_EQ_VECTORS (direct,wrapped);
}

TEST (PointCloud, back)
{
  Eigen::Vector3f direct = cloud.points.back ().getVector3fMap ();
  Eigen::Vector3f wrapped = cloud.back ().getVector3fMap ();
  EXPECT_EQ_VECTORS (direct,wrapped);
}

TEST (PointCloud, constructor_with_allocation)
{
  PointCloud<PointXYZ> cloud2 (5, 80);
  EXPECT_EQ (cloud2.width, 5);
  EXPECT_EQ (cloud2.height, 80);
  EXPECT_EQ (cloud2.size (), 5*80);
}

TEST (PointCloud, insert_range)
{
  PointCloud<PointXYZ> cloud2 (10, 1);
  for (uint32_t i = 0; i < 10; ++i)
    cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2);

  uint32_t old_size = cloud.size ();
  cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ());
  EXPECT_EQ (cloud.width, cloud.size ());
  EXPECT_EQ (cloud.height, 1);
  EXPECT_EQ (cloud.width, old_size + cloud2.size ());
  PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
  PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin ();
  for (; pit2 < cloud2.end (); ++pit2, ++pit)
    EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}

int
main (int argc, char** argv)
{
  cloud.width = 10;
  cloud.height = 480;
  for (uint32_t i = 0; i < size; ++i)
    cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_PRISM
#define MFEM_PRISM

#include "../config/config.hpp"
#include "element.hpp"

namespace mfem
{

/// Data type Prism element
class Prism : public Element
{
protected:
   int indices[6];

   // Rrefinement not yet supported
   // int refinement_flag;

   // Not sure what this might be
   // unsigned transform;

public:
   typedef Geometry::Constants<Geometry::PRISM> geom_t;

   Prism() : Element(Geometry::PRISM) { }

   /// Constructs prism by specifying the indices and the attribute.
   Prism(const int *ind, int attr = 1);

   /// Constructs prism by specifying the indices and the attribute.
   Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,
         int attr = 1);

   /// Return element's type.
   virtual Type GetType() const { return Element::PRISM; }

   // void  ParseRefinementFlag(int refinement_edges[2], int &type, int &flag);
   // void CreateRefinementFlag(int refinement_edges[2], int  type, int  flag = 0);

   // void GetMarkedFace(const int face, int *fv);

   // virtual int GetRefinementFlag() { return refinement_flag; }

   // void SetRefinementFlag(int rf) { refinement_flag = rf; }

   /// Return 1 if the element needs refinement in order to get conforming mesh.
   // virtual int NeedRefinement(DSTable &v_to_v, int *middle) const;

   /// Set the vertices according to the given input.
   virtual void SetVertices(const int *ind);

   /// Mark the longest edge by assuming/changing the order of the vertices.
   virtual void MarkEdge(DenseMatrix &pmat) { }

   /** Reorder the vertices so that the longest edge is from vertex 0
       to vertex 1. If called it should be once from the mesh constructor,
       because the order may be used later for setting the edges. **/
   // virtual void MarkEdge(const DSTable &v_to_v, const int *length);

   // virtual void ResetTransform(int tr) { transform = tr; }
   // virtual unsigned GetTransform() const { return transform; }

   /// Add 'tr' to the current chain of coarse-fine transformations.
   // virtual void PushTransform(int tr)
   // { transform = (transform << 3) | (tr + 1); }

   /// Calculate point matrix corresponding to a chain of transformations.
   // static void GetPointMatrix(unsigned transform, DenseMatrix &pm);

   /// Returns the indices of the element's  vertices.
   virtual void GetVertices(Array<int> &v) const;

   virtual int *GetVertices() { return indices; }

   virtual int GetNVertices() const { return 6; }

   virtual int GetNEdges() const { return 9; }

   virtual const int *GetEdgeVertices(int ei) const
   { return geom_t::Edges[ei]; }

   virtual int GetNFaces(int &nFaceVertices) const
   { nFaceVertices = 4; return 5; }

   virtual int GetNFaceVerticess(int fi) const
   { return ( ( fi < 2 ) ? 3 : 4); }

   virtual const int *GetFaceVertices(int fi) const
   { return geom_t::FaceVert[fi]; }

   virtual Element *Duplicate(Mesh *m) const
   { return new Prism(indices, attribute); }

   virtual ~Prism() { }
};

extern BiLinear3DFiniteElement PrismFE;

}

#endif
<commit_msg>make style<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#ifndef MFEM_PRISM
#define MFEM_PRISM

#include "../config/config.hpp"
#include "element.hpp"

namespace mfem
{

/// Data type Prism element
class Prism : public Element
{
protected:
   int indices[6];

   // Rrefinement not yet supported
   // int refinement_flag;

   // Not sure what this might be
   // unsigned transform;

public:
   typedef Geometry::Constants<Geometry::PRISM> geom_t;

   Prism() : Element(Geometry::PRISM) { }

   /// Constructs prism by specifying the indices and the attribute.
   Prism(const int *ind, int attr = 1);

   /// Constructs prism by specifying the indices and the attribute.
   Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,
         int attr = 1);

   /// Return element's type.
   virtual Type GetType() const { return Element::PRISM; }

   // void  ParseRefinementFlag(int refinement_edges[2], int &type, int &flag);
   // void CreateRefinementFlag(int refinement_edges[2], int  type, int  flag = 0);

   // void GetMarkedFace(const int face, int *fv);

   // virtual int GetRefinementFlag() { return refinement_flag; }

   // void SetRefinementFlag(int rf) { refinement_flag = rf; }

   /// Return 1 if the element needs refinement in order to get conforming mesh.
   // virtual int NeedRefinement(DSTable &v_to_v, int *middle) const;

   /// Set the vertices according to the given input.
   virtual void SetVertices(const int *ind);

   /// Mark the longest edge by assuming/changing the order of the vertices.
   virtual void MarkEdge(DenseMatrix &pmat) { }

   /** Reorder the vertices so that the longest edge is from vertex 0
       to vertex 1. If called it should be once from the mesh constructor,
       because the order may be used later for setting the edges. **/
   // virtual void MarkEdge(const DSTable &v_to_v, const int *length);

   // virtual void ResetTransform(int tr) { transform = tr; }
   // virtual unsigned GetTransform() const { return transform; }

   /// Add 'tr' to the current chain of coarse-fine transformations.
   // virtual void PushTransform(int tr)
   // { transform = (transform << 3) | (tr + 1); }

   /// Calculate point matrix corresponding to a chain of transformations.
   // static void GetPointMatrix(unsigned transform, DenseMatrix &pm);

   /// Returns the indices of the element's  vertices.
   virtual void GetVertices(Array<int> &v) const;

   virtual int *GetVertices() { return indices; }

   virtual int GetNVertices() const { return 6; }

   virtual int GetNEdges() const { return 9; }

   virtual const int *GetEdgeVertices(int ei) const
   { return geom_t::Edges[ei]; }

   virtual int GetNFaces(int &nFaceVertices) const
   { nFaceVertices = 4; return 5; }

   virtual int GetNFaceVerticess(int fi) const
   { return ( ( fi < 2 ) ? 3 : 4); }

   virtual const int *GetFaceVertices(int fi) const
   { return geom_t::FaceVert[fi]; }

   virtual Element *Duplicate(Mesh *m) const
   { return new Prism(indices, attribute); }

   virtual ~Prism() { }
};

extern BiLinear3DFiniteElement PrismFE;

}

#endif
<|endoftext|>


<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s
#include "Inputs/system-header-simulator-cxx.h"

#if !(LEAKS && !ALLOCATOR_INLINING)
// expected-no-diagnostics
#endif

void *allocator(std::size_t size);

void *operator new[](std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); }
void *operator new(std::size_t, double d);

class C {
public:
  void *operator new(std::size_t);
};

void testNewMethod() {
  void *p1 = C::operator new(0); // no warn

  C *p2 = new C; // no warn

  C *c3 = ::new C;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'c3'}}
#endif

void testOpNewArray() {
  void *p = operator new[](0); // call is inlined, no warn
}

void testNewExprArray() {
  int *p = new int[0];
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom non-placement operators
void testOpNew() {
  void *p = operator new(0); // call is inlined, no warn
}

void testNewExpr() {
  int *p = new int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom NoThrow placement operators
void testOpNewNoThrow() {
  void *p = operator new(0, std::nothrow); // call is inlined, no warn
}

void testNewExprNoThrow() {
  int *p = new(std::nothrow) int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom placement operators
void testOpNewPlacement() {
  void *p = operator new(0, 0.1); // no warn
}

void testNewExprPlacement() {
  int *p = new(0.1) int; // no warn
}
<commit_msg>[analyzer] Enable c++-allocator-inlining by default.<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=false -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=false -DLEAKS=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -DALLOCATOR_INLINING=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s
#include "Inputs/system-header-simulator-cxx.h"

#if !(LEAKS && !ALLOCATOR_INLINING)
// expected-no-diagnostics
#endif

void *allocator(std::size_t size);

void *operator new[](std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); }
void *operator new(std::size_t, double d);

class C {
public:
  void *operator new(std::size_t);
};

void testNewMethod() {
  void *p1 = C::operator new(0); // no warn

  C *p2 = new C; // no warn

  C *c3 = ::new C;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'c3'}}
#endif

void testOpNewArray() {
  void *p = operator new[](0); // call is inlined, no warn
}

void testNewExprArray() {
  int *p = new int[0];
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom non-placement operators
void testOpNew() {
  void *p = operator new(0); // call is inlined, no warn
}

void testNewExpr() {
  int *p = new int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom NoThrow placement operators
void testOpNewNoThrow() {
  void *p = operator new(0, std::nothrow); // call is inlined, no warn
}

void testNewExprNoThrow() {
  int *p = new(std::nothrow) int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom placement operators
void testOpNewPlacement() {
  void *p = operator new(0, 0.1); // no warn
}

void testNewExprPlacement() {
  int *p = new(0.1) int; // no warn
}
<|endoftext|>