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

  Program:   Visualization Toolkit
  Module:    vtkPointSet.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkPointSet.h"

#include "vtkCell.h"
#include "vtkGarbageCollector.h"
#include "vtkGenericCell.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkPointLocator.h"
#include "vtkSource.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

#include <vtkstd/set>

vtkCxxRevisionMacro(vtkPointSet, "1.11");

vtkCxxSetObjectMacro(vtkPointSet,Points,vtkPoints);

vtkPointSet::vtkPointSet ()
{
  this->Points = NULL;
  this->Locator = NULL;
}

//----------------------------------------------------------------------------
vtkPointSet::~vtkPointSet ()
{
  this->Initialize();
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
}

//----------------------------------------------------------------------------
// Copy the geometric structure of an input point set object.
void vtkPointSet::CopyStructure(vtkDataSet *ds)
{
  vtkPointSet *ps=static_cast<vtkPointSet *>(ds);

  if ( this->Points != ps->Points )
    {
    if ( this->Locator )
      {
      this->Locator->Initialize();
      }
    this->SetPoints(ps->Points);
    }
}

//----------------------------------------------------------------------------
void vtkPointSet::Initialize()
{
  vtkDataSet::Initialize();

  if ( this->Points )
    {
    this->Points->UnRegister(this);
    this->Points = NULL;
    }

  if ( this->Locator )
    {
    this->Locator->Initialize();
    }
}
//----------------------------------------------------------------------------
void vtkPointSet::ComputeBounds()
{
  double *bounds;

  if ( this->Points )
    {
    bounds = this->Points->GetBounds();
    for (int i=0; i<6; i++)
      {
      this->Bounds[i] = bounds[i];
      }
    this->ComputeTime.Modified();
    }
}

//----------------------------------------------------------------------------
unsigned long int vtkPointSet::GetMTime()
{
  unsigned long int dsTime = vtkDataSet::GetMTime();

  if ( this->Points )
    {
    if ( this->Points->GetMTime() > dsTime )
      {
      dsTime = this->Points->GetMTime();
      }
    }

  // don't get locator's mtime because its an internal object that cannot be
  // modified directly from outside. Causes problems due to FindCell()
  // SetPoints() method.

  return dsTime;
}

//----------------------------------------------------------------------------
vtkIdType vtkPointSet::FindPoint(double x[3])
{
  if ( !this->Points )
    {
    return -1;
    }

  if ( !this->Locator )
    {
    this->Locator = vtkPointLocator::New();
    this->Locator->Register(this);
    this->Locator->Delete();
    this->Locator->SetDataSet(this);
    }

  if ( this->Points->GetMTime() > this->Locator->GetMTime() )
    {
    this->Locator->SetDataSet(this);
    }

  return this->Locator->FindClosestPoint(x);
}

//the furthest the walk can be - prevents aimless wandering
#define VTK_MAX_WALK 12

//-----------------------------------------------------------------------------
// Used internally by FindCell to walk through neighbors from a starting cell.
// The arguments are the same as those for FindCell.  In addition, visitedCells
// keeps a list of cells already traversed.  If we run into such already
// visited, the walk terminates since we assume we already walked from that cell
// and found nothing.
static vtkIdType FindCellWalk(vtkPointSet *self, double x[3], vtkCell *cell,
                              vtkGenericCell *gencell, vtkIdType cellId,
                              double tol2, int &subId, double pcoords[3],
                              double *weights,
                              vtkstd::set<vtkIdType> &visitedCells)
{
  VTK_CREATE(vtkIdList, ptIds);
  ptIds->Allocate(8, 100);
  VTK_CREATE(vtkIdList, neighbors);
  neighbors->Allocate(8, 100);

  for (int walk = 0; walk < VTK_MAX_WALK; walk++)
    {
    // Check to see if we already visited this cell.
    if (visitedCells.find(cellId) != visitedCells.end()) break;
    visitedCells.insert(cellId);

    // Get information for the cell.
    if (!cell)
      {
      if (gencell)
        {
        self->GetCell(cellId, gencell);
        cell = gencell;
        }
      else
        {
        cell = self->GetCell(cellId);
        }
      }

    // Check to see if the cell contains the point.
    double closestPoint[3];
    double dist2;
    if (   (cell->EvaluatePosition(x, closestPoint, subId,
                                   pcoords, dist2, weights) == 1)
        && (dist2 <= tol2) )
      {
      return cellId;
      }

    // This is not the right cell.  Find the next one.
    cell->CellBoundary(subId, pcoords, ptIds);
    self->GetCellNeighbors(cellId, ptIds, neighbors);
    // If there is no next one, exit.
    if (neighbors->GetNumberOfIds() < 1) break;
    // Set the next cell as the current one and iterate.
    cellId = neighbors->GetId(0);
    cell = NULL;
    }

  // Could not find a cell.
  return -1;
}

//-----------------------------------------------------------------------------
static vtkIdType FindCellWalk(vtkPointSet *self, double x[3],
                              vtkGenericCell *gencell, vtkIdList *cellIds,
                              double tol2, int &subId, double pcoords[3],
                              double *weights,
                              vtkstd::set<vtkIdType> &visitedCells)
{
  for (vtkIdType i = 0; i < cellIds->GetNumberOfIds(); i++)
    {
    vtkIdType cellId = cellIds->GetId(i);
    vtkIdType foundCell = FindCellWalk(self, x, NULL, gencell, cellId,
                                       tol2, subId, pcoords, weights,
                                       visitedCells);
    if (foundCell >= 0) return foundCell;
    }
  return -1;
}

//----------------------------------------------------------------------------
vtkIdType vtkPointSet::FindCell(double x[3], vtkCell *cell,
                                vtkGenericCell *gencell, vtkIdType cellId,
                                double tol2, int& subId, double pcoords[3],
                                double *weights)
{
  vtkIdType foundCell;

  // make sure everything is up to snuff
  if ( !this->Points || this->Points->GetNumberOfPoints() < 1)
    {
    return -1;
    }

  // Check to see if the point is within the bounds of the data.  This is not
  // a strict check, but it is fast.
  double bounds[6];
  this->GetBounds(bounds);
  if (   (x[0] < bounds[0]) || (x[0] > bounds[1])
      || (x[1] < bounds[2]) || (x[1] > bounds[3])
      || (x[2] < bounds[4]) || (x[2] > bounds[5]) )
    {
    return -1;
    }

  if ( !this->Locator )
    {
    this->Locator = vtkPointLocator::New();
    this->Locator->Register(this);
    this->Locator->Delete();
    this->Locator->SetDataSet(this);
    this->Locator->BuildLocator();
    }

  if ( this->Points->GetMTime() > this->Locator->GetMTime() )
    {
    this->Locator->SetDataSet(this);
    this->Locator->BuildLocator();
    }

  vtkstd::set<vtkIdType> visitedCells;

  // If we are given a starting cell, try that.
  if (cell && (cellId >= 0))
    {
    foundCell = FindCellWalk(this, x, cell, gencell, cellId,
                             tol2, subId, pcoords, weights, visitedCells);
    if (foundCell >= 0) return foundCell;
    }

  VTK_CREATE(vtkIdList, cellIds);
  cellIds->Allocate(8,100);

  // Now find the point closest to the coordinates given and search from the
  // adjacent cells.
  vtkIdType ptId = this->Locator->FindClosestPoint(x);
  if (ptId < 0) return -1;
  this->GetPointCells(ptId, cellIds);
  foundCell = FindCellWalk(this, x, gencell, cellIds,
                           tol2, subId, pcoords, weights, visitedCells);
  if (foundCell >= 0) return foundCell;

  // It is possible that the toplogy is not fully connected.  That is, two
  // points in the point list could be coincident.  Handle that by looking
  // at every point within the tolerance and consider all cells connected.
  // It has been suggested that we should really do this coincident point
  // check at every point as we walk through neighbors, which would happen
  // in FindCellWalk.  If that were ever implemented, this step might become
  // unnecessary.
  double ptCoord[3];
  this->GetPoint(ptId, ptCoord);
  VTK_CREATE(vtkIdList, coincidentPtIds);
  this->Locator->FindPointsWithinRadius(tol2, ptCoord, coincidentPtIds);
  coincidentPtIds->DeleteId(ptId);      // Already searched this one.
  for (vtkIdType i = 0; i < coincidentPtIds->GetNumberOfIds(); i++)
    {
    this->GetPointCells(coincidentPtIds->GetId(i), cellIds);
    foundCell = FindCellWalk(this, x, gencell, cellIds,
                             tol2, subId, pcoords, weights, visitedCells);
    if (foundCell >= 0) return foundCell;
    }

  // Could not find the cell.
  return -1;
}

//----------------------------------------------------------------------------
vtkIdType vtkPointSet::FindCell(double x[3], vtkCell *cell, vtkIdType cellId,
                                double tol2, int& subId,double pcoords[3],
                                double *weights)
{
  return
    this->FindCell( x, cell, NULL, cellId, tol2, subId, pcoords, weights );
}

#undef VTK_MAX_WALK

//----------------------------------------------------------------------------
void vtkPointSet::Squeeze()
{
  if ( this->Points )
    {
    this->Points->Squeeze();
    }
  vtkDataSet::Squeeze();
}

//----------------------------------------------------------------------------
void vtkPointSet::ReportReferences(vtkGarbageCollector* collector)
{
  this->Superclass::ReportReferences(collector);
  vtkGarbageCollectorReport(collector, this->Locator, "Locator");
}

//----------------------------------------------------------------------------
unsigned long vtkPointSet::GetActualMemorySize()
{
  unsigned long size=this->vtkDataSet::GetActualMemorySize();
  if ( this->Points )
    {
    size += this->Points->GetActualMemorySize();
    }
  return size;
}

//----------------------------------------------------------------------------
void vtkPointSet::ShallowCopy(vtkDataObject *dataObject)
{
  vtkPointSet *pointSet = vtkPointSet::SafeDownCast(dataObject);

  if ( pointSet != NULL )
    {
    this->SetPoints(pointSet->GetPoints());
    }

  // Do superclass
  this->vtkDataSet::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkPointSet::DeepCopy(vtkDataObject *dataObject)
{
  vtkPointSet *pointSet = vtkPointSet::SafeDownCast(dataObject);

  if ( pointSet != NULL )
    {
    if (this->Points == NULL)
      {
      if ( pointSet->GetPoints() != NULL )
        {
        this->Points = pointSet->GetPoints()->NewInstance();
        this->Points->SetDataType(pointSet->GetPoints()->GetDataType());
        this->Points->Register(this);
        this->Points->Delete();
        }
      else
        {
        this->Points = vtkPoints::New();
        this->Points->Register(this);
        this->Points->Delete();
        }
      }
    this->Points->DeepCopy(pointSet->GetPoints());
    }

  // Do superclass
  this->vtkDataSet::DeepCopy(dataObject);
}

//----------------------------------------------------------------------------
vtkPointSet* vtkPointSet::GetData(vtkInformation* info)
{
  return info? vtkPointSet::SafeDownCast(info->Get(DATA_OBJECT())) : 0;
}

//----------------------------------------------------------------------------
vtkPointSet* vtkPointSet::GetData(vtkInformationVector* v, int i)
{
  return vtkPointSet::GetData(v->GetInformationObject(i));
}

//----------------------------------------------------------------------------
void vtkPointSet::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
  os << indent << "Point Coordinates: " << this->Points << "\n";
  os << indent << "Locator: " << this->Locator << "\n";
}

<commit_msg>PERF: Create id arrays once per call to FindCell rather than every time we start a walk (which may or may not take a first step).<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPointSet.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkPointSet.h"

#include "vtkCell.h"
#include "vtkGarbageCollector.h"
#include "vtkGenericCell.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkPointLocator.h"
#include "vtkSource.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

#include <vtkstd/set>

vtkCxxRevisionMacro(vtkPointSet, "1.12");

vtkCxxSetObjectMacro(vtkPointSet,Points,vtkPoints);

vtkPointSet::vtkPointSet ()
{
  this->Points = NULL;
  this->Locator = NULL;
}

//----------------------------------------------------------------------------
vtkPointSet::~vtkPointSet ()
{
  this->Initialize();
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
}

//----------------------------------------------------------------------------
// Copy the geometric structure of an input point set object.
void vtkPointSet::CopyStructure(vtkDataSet *ds)
{
  vtkPointSet *ps=static_cast<vtkPointSet *>(ds);

  if ( this->Points != ps->Points )
    {
    if ( this->Locator )
      {
      this->Locator->Initialize();
      }
    this->SetPoints(ps->Points);
    }
}

//----------------------------------------------------------------------------
void vtkPointSet::Initialize()
{
  vtkDataSet::Initialize();

  if ( this->Points )
    {
    this->Points->UnRegister(this);
    this->Points = NULL;
    }

  if ( this->Locator )
    {
    this->Locator->Initialize();
    }
}
//----------------------------------------------------------------------------
void vtkPointSet::ComputeBounds()
{
  double *bounds;

  if ( this->Points )
    {
    bounds = this->Points->GetBounds();
    for (int i=0; i<6; i++)
      {
      this->Bounds[i] = bounds[i];
      }
    this->ComputeTime.Modified();
    }
}

//----------------------------------------------------------------------------
unsigned long int vtkPointSet::GetMTime()
{
  unsigned long int dsTime = vtkDataSet::GetMTime();

  if ( this->Points )
    {
    if ( this->Points->GetMTime() > dsTime )
      {
      dsTime = this->Points->GetMTime();
      }
    }

  // don't get locator's mtime because its an internal object that cannot be
  // modified directly from outside. Causes problems due to FindCell()
  // SetPoints() method.

  return dsTime;
}

//----------------------------------------------------------------------------
vtkIdType vtkPointSet::FindPoint(double x[3])
{
  if ( !this->Points )
    {
    return -1;
    }

  if ( !this->Locator )
    {
    this->Locator = vtkPointLocator::New();
    this->Locator->Register(this);
    this->Locator->Delete();
    this->Locator->SetDataSet(this);
    }

  if ( this->Points->GetMTime() > this->Locator->GetMTime() )
    {
    this->Locator->SetDataSet(this);
    }

  return this->Locator->FindClosestPoint(x);
}

//the furthest the walk can be - prevents aimless wandering
#define VTK_MAX_WALK 12

//-----------------------------------------------------------------------------
// Used internally by FindCell to walk through neighbors from a starting cell.
// The arguments are the same as those for FindCell.  In addition, visitedCells
// keeps a list of cells already traversed.  If we run into such already
// visited, the walk terminates since we assume we already walked from that cell
// and found nothing.  The ptIds and neighbors lists are buffers used
// internally.  They are passed in so that they do not have to be continuously
// reallocated.
static vtkIdType FindCellWalk(vtkPointSet *self, double x[3], vtkCell *cell,
                              vtkGenericCell *gencell, vtkIdType cellId,
                              double tol2, int &subId, double pcoords[3],
                              double *weights,
                              vtkstd::set<vtkIdType> &visitedCells,
                              vtkIdList *ptIds, vtkIdList *neighbors)
{
  for (int walk = 0; walk < VTK_MAX_WALK; walk++)
    {
    // Check to see if we already visited this cell.
    if (visitedCells.find(cellId) != visitedCells.end()) break;
    visitedCells.insert(cellId);

    // Get information for the cell.
    if (!cell)
      {
      if (gencell)
        {
        self->GetCell(cellId, gencell);
        cell = gencell;
        }
      else
        {
        cell = self->GetCell(cellId);
        }
      }

    // Check to see if the cell contains the point.
    double closestPoint[3];
    double dist2;
    if (   (cell->EvaluatePosition(x, closestPoint, subId,
                                   pcoords, dist2, weights) == 1)
        && (dist2 <= tol2) )
      {
      return cellId;
      }

    // This is not the right cell.  Find the next one.
    cell->CellBoundary(subId, pcoords, ptIds);
    self->GetCellNeighbors(cellId, ptIds, neighbors);
    // If there is no next one, exit.
    if (neighbors->GetNumberOfIds() < 1) break;
    // Set the next cell as the current one and iterate.
    cellId = neighbors->GetId(0);
    cell = NULL;
    }

  // Could not find a cell.
  return -1;
}

//-----------------------------------------------------------------------------
static vtkIdType FindCellWalk(vtkPointSet *self, double x[3],
                              vtkGenericCell *gencell, vtkIdList *cellIds,
                              double tol2, int &subId, double pcoords[3],
                              double *weights,
                              vtkstd::set<vtkIdType> &visitedCells,
                              vtkIdList *ptIds, vtkIdList *neighbors)
{
  for (vtkIdType i = 0; i < cellIds->GetNumberOfIds(); i++)
    {
    vtkIdType cellId = cellIds->GetId(i);
    vtkIdType foundCell = FindCellWalk(self, x, NULL, gencell, cellId,
                                       tol2, subId, pcoords, weights,
                                       visitedCells, ptIds, neighbors);
    if (foundCell >= 0) return foundCell;
    }
  return -1;
}

//----------------------------------------------------------------------------
vtkIdType vtkPointSet::FindCell(double x[3], vtkCell *cell,
                                vtkGenericCell *gencell, vtkIdType cellId,
                                double tol2, int& subId, double pcoords[3],
                                double *weights)
{
  vtkIdType foundCell;

  // make sure everything is up to snuff
  if ( !this->Points || this->Points->GetNumberOfPoints() < 1)
    {
    return -1;
    }

  // Check to see if the point is within the bounds of the data.  This is not
  // a strict check, but it is fast.
  double bounds[6];
  this->GetBounds(bounds);
  if (   (x[0] < bounds[0]) || (x[0] > bounds[1])
      || (x[1] < bounds[2]) || (x[1] > bounds[3])
      || (x[2] < bounds[4]) || (x[2] > bounds[5]) )
    {
    return -1;
    }

  if ( !this->Locator )
    {
    this->Locator = vtkPointLocator::New();
    this->Locator->Register(this);
    this->Locator->Delete();
    this->Locator->SetDataSet(this);
    this->Locator->BuildLocator();
    }

  if ( this->Points->GetMTime() > this->Locator->GetMTime() )
    {
    this->Locator->SetDataSet(this);
    this->Locator->BuildLocator();
    }

  vtkstd::set<vtkIdType> visitedCells;
  VTK_CREATE(vtkIdList, ptIds);
  ptIds->Allocate(8, 100);
  VTK_CREATE(vtkIdList, neighbors);
  neighbors->Allocate(8, 100);

  // If we are given a starting cell, try that.
  if (cell && (cellId >= 0))
    {
    foundCell = FindCellWalk(this, x, cell, gencell, cellId,
                             tol2, subId, pcoords, weights,
                             visitedCells, ptIds, neighbors);
    if (foundCell >= 0) return foundCell;
    }

  VTK_CREATE(vtkIdList, cellIds);
  cellIds->Allocate(8,100);

  // Now find the point closest to the coordinates given and search from the
  // adjacent cells.
  vtkIdType ptId = this->Locator->FindClosestPoint(x);
  if (ptId < 0) return -1;
  this->GetPointCells(ptId, cellIds);
  foundCell = FindCellWalk(this, x, gencell, cellIds,
                           tol2, subId, pcoords, weights,
                           visitedCells, ptIds, neighbors);
  if (foundCell >= 0) return foundCell;

  // It is possible that the toplogy is not fully connected.  That is, two
  // points in the point list could be coincident.  Handle that by looking
  // at every point within the tolerance and consider all cells connected.
  // It has been suggested that we should really do this coincident point
  // check at every point as we walk through neighbors, which would happen
  // in FindCellWalk.  If that were ever implemented, this step might become
  // unnecessary.
  double ptCoord[3];
  this->GetPoint(ptId, ptCoord);
  VTK_CREATE(vtkIdList, coincidentPtIds);
  coincidentPtIds->Allocate(8, 100);
  this->Locator->FindPointsWithinRadius(tol2, ptCoord, coincidentPtIds);
  coincidentPtIds->DeleteId(ptId);      // Already searched this one.
  for (vtkIdType i = 0; i < coincidentPtIds->GetNumberOfIds(); i++)
    {
    this->GetPointCells(coincidentPtIds->GetId(i), cellIds);
    foundCell = FindCellWalk(this, x, gencell, cellIds,
                             tol2, subId, pcoords, weights,
                             visitedCells, ptIds, neighbors);
    if (foundCell >= 0) return foundCell;
    }

  // Could not find the cell.
  return -1;
}

//----------------------------------------------------------------------------
vtkIdType vtkPointSet::FindCell(double x[3], vtkCell *cell, vtkIdType cellId,
                                double tol2, int& subId,double pcoords[3],
                                double *weights)
{
  return
    this->FindCell( x, cell, NULL, cellId, tol2, subId, pcoords, weights );
}

#undef VTK_MAX_WALK

//----------------------------------------------------------------------------
void vtkPointSet::Squeeze()
{
  if ( this->Points )
    {
    this->Points->Squeeze();
    }
  vtkDataSet::Squeeze();
}

//----------------------------------------------------------------------------
void vtkPointSet::ReportReferences(vtkGarbageCollector* collector)
{
  this->Superclass::ReportReferences(collector);
  vtkGarbageCollectorReport(collector, this->Locator, "Locator");
}

//----------------------------------------------------------------------------
unsigned long vtkPointSet::GetActualMemorySize()
{
  unsigned long size=this->vtkDataSet::GetActualMemorySize();
  if ( this->Points )
    {
    size += this->Points->GetActualMemorySize();
    }
  return size;
}

//----------------------------------------------------------------------------
void vtkPointSet::ShallowCopy(vtkDataObject *dataObject)
{
  vtkPointSet *pointSet = vtkPointSet::SafeDownCast(dataObject);

  if ( pointSet != NULL )
    {
    this->SetPoints(pointSet->GetPoints());
    }

  // Do superclass
  this->vtkDataSet::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkPointSet::DeepCopy(vtkDataObject *dataObject)
{
  vtkPointSet *pointSet = vtkPointSet::SafeDownCast(dataObject);

  if ( pointSet != NULL )
    {
    if (this->Points == NULL)
      {
      if ( pointSet->GetPoints() != NULL )
        {
        this->Points = pointSet->GetPoints()->NewInstance();
        this->Points->SetDataType(pointSet->GetPoints()->GetDataType());
        this->Points->Register(this);
        this->Points->Delete();
        }
      else
        {
        this->Points = vtkPoints::New();
        this->Points->Register(this);
        this->Points->Delete();
        }
      }
    this->Points->DeepCopy(pointSet->GetPoints());
    }

  // Do superclass
  this->vtkDataSet::DeepCopy(dataObject);
}

//----------------------------------------------------------------------------
vtkPointSet* vtkPointSet::GetData(vtkInformation* info)
{
  return info? vtkPointSet::SafeDownCast(info->Get(DATA_OBJECT())) : 0;
}

//----------------------------------------------------------------------------
vtkPointSet* vtkPointSet::GetData(vtkInformationVector* v, int i)
{
  return vtkPointSet::GetData(v->GetInformationObject(i));
}

//----------------------------------------------------------------------------
void vtkPointSet::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
  os << indent << "Point Coordinates: " << this->Points << "\n";
  os << indent << "Locator: " << this->Locator << "\n";
}

<|endoftext|>


<commit_before>// ClockTool.cc
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//                and Simon Bowden    (rathnor at users.sourceforge.net)
//
// 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.

// $Id: ClockTool.cc,v 1.6 2003/12/04 23:02:23 fluxgen Exp $

#include "ClockTool.hh"

#include "ToolTheme.hh"
#include "Screen.hh"

#include "FbTk/SimpleCommand.hh"
#include "FbTk/ImageControl.hh"
#include "FbTk/Menu.hh"
#include "FbTk/MenuItem.hh"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include <ctime>

class ClockMenuItem: public FbTk::MenuItem {
public:
    ClockMenuItem::ClockMenuItem(ClockTool &tool):
        FbTk::MenuItem(""), m_tool(tool) {
        // determine 12/24 hour format
        if (m_tool.timeFormat().find("%k") != std::string::npos ||
            m_tool.timeFormat().find("%H") != std::string::npos ||
            m_tool.timeFormat().find("%T") != std::string::npos)
            setLabel("Clock: 24h");
        else
            setLabel("Clock: 12h");
    }

    void click(int button, int time) {
        std::string newformat = m_tool.timeFormat();
        size_t pos = newformat.find("%k");
        std::string newstr;
        bool clock24hour = true;
        if (pos != std::string::npos)
            newstr = "%l";
        else if ((pos = newformat.find("%H")) != std::string::npos)
            newstr = "%I";
        else if ((pos = newformat.find("%T")) != std::string::npos)
            newstr = "%r";

        // 12 hour
        if (newstr.empty()) {
            clock24hour = false;
            if ((pos = newformat.find("%l")) != std::string::npos)
                newstr = "%k";
            else if ((pos = newformat.find("%I")) != std::string::npos)
                newstr = "%H";
            else if ((pos = newformat.find("%r")) != std::string::npos)
                newstr = "%T";

        }

        if (!newstr.empty()) {

            newformat.replace(pos, 2, newstr);
            if (!clock24hour) { // erase %P/%p (AM|PM / am|pm)
                pos = newformat.find("%p");
                if (pos != std::string::npos)
                    newformat.erase(pos, 2);
                else if ((pos = newformat.find("%P")) != std::string::npos)
                    newformat.erase(pos, 2);
            }
            if (clock24hour)
                setLabel("Clock: 24h");
            else
                setLabel("Clock: 12h");

            m_tool.setTimeFormat(newformat);
        } // else some other strange format...so we don't do anything
        FbTk::MenuItem::click(button, time);
    }
private:
    ClockTool &m_tool;
};

ClockTool::ClockTool(const FbTk::FbWindow &parent,
                     ToolTheme &theme, BScreen &screen, FbTk::Menu &menu):
    ToolbarItem(ToolbarItem::FIXED),
    m_button(parent, theme.font(), ""),
    m_theme(theme),
    m_screen(screen),
    m_pixmap(0),
    m_timeformat(screen.resourceManager(), std::string("%k:%M"),
                 screen.name() + ".strftimeFormat", screen.altName() + ".StrftimeFormat") {
    // attach signals
    theme.reconfigSig().attach(this);

    // setup timer to update the graphics each second
    timeval delay;
    delay.tv_sec = 1;
    delay.tv_usec = 0;
    m_timer.setTimeout(delay);
    FbTk::RefCount<FbTk::Command> update_graphic(new FbTk::SimpleCommand<ClockTool>(*this,
                                                                                &ClockTool::updateTime));
    m_timer.setCommand(update_graphic);
    m_timer.start();

    m_button.setGC(m_theme.textGC());
    menu.insert(new ClockMenuItem(*this));
    update(0);
}

ClockTool::~ClockTool() {
    // remove cached pixmap
    if (m_pixmap)
        m_screen.imageControl().removeImage(m_pixmap);
}

void ClockTool::move(int x, int y) {
    m_button.move(x, y);
}

void ClockTool::resize(unsigned int width, unsigned int height) {
    m_button.resize(width, height);
    renderTheme();
}

void ClockTool::moveResize(int x, int y,
                      unsigned int width, unsigned int height) {
    m_button.moveResize(x, y, width, height);
    renderTheme();
}

void ClockTool::show() {
    m_button.show();
}

void ClockTool::hide() {
    m_button.hide();
}

void ClockTool::setTimeFormat(const std::string &format) {
    *m_timeformat = format;
    update(0);
}

void ClockTool::update(FbTk::Subject *subj) {
    updateTime();

    // + 2 to make the entire text fit inside
    std::string text;
    for (size_t i=0; i<m_button.text().size() + 2; ++i)
        text += '0';

    resize(m_theme.font().textWidth(text.c_str(), text.size()), m_button.height());
}

unsigned int ClockTool::borderWidth() const {
    return m_button.borderWidth();
}

unsigned int ClockTool::width() const {
    return m_button.width();
}

unsigned int ClockTool::height() const {
    return m_button.height();
}

void ClockTool::updateTime() {

    // update clock
    time_t the_time = time(0);

    if (the_time != -1) {
        char time_string[255];
        struct tm *time_type = localtime(&the_time);
        if (time_type == 0)
            return;

#ifdef HAVE_STRFTIME
        if (!strftime(time_string, 255, m_timeformat->c_str(), time_type))
            return;
        m_button.setText(time_string);
#else // dont have strftime so we have to set it to hour:minut
        //        sprintf(time_string, "%d:%d", );
#endif // HAVE_STRFTIME
    }

    m_button.clear();
}

void ClockTool::renderTheme() {
    Pixmap old_pm = m_pixmap;
    if (m_theme.texture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_pixmap = 0;
        m_button.setBackgroundColor(m_theme.texture().color());
    } else {
        m_pixmap = m_screen.imageControl().renderImage(m_button.width(), m_button.height(), m_theme.texture());
        m_button.setBackgroundPixmap(m_pixmap);
    }

    if (old_pm)
        m_screen.imageControl().removeImage(old_pm);

    m_button.setJustify(m_theme.justify());
    m_button.setBorderWidth(m_theme.border().width());
    m_button.setBorderColor(m_theme.border().color());
    m_button.clear();
}
<commit_msg>fixed minor bug in menu item and saving resources when changing value<commit_after>// ClockTool.cc
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//                and Simon Bowden    (rathnor at users.sourceforge.net)
//
// 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.

// $Id: ClockTool.cc,v 1.7 2003/12/06 16:49:06 fluxgen Exp $

#include "ClockTool.hh"

#include "ToolTheme.hh"
#include "Screen.hh"
#include "CommandParser.hh"

#include "FbTk/SimpleCommand.hh"
#include "FbTk/ImageControl.hh"
#include "FbTk/Menu.hh"
#include "FbTk/MenuItem.hh"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include <ctime>

class ClockMenuItem: public FbTk::MenuItem {
public:
    explicit ClockMenuItem::ClockMenuItem(ClockTool &tool):
        FbTk::MenuItem(""), m_tool(tool) {
        // determine 12/24 hour format
        if (m_tool.timeFormat().find("%k") != std::string::npos ||
            m_tool.timeFormat().find("%H") != std::string::npos ||
            m_tool.timeFormat().find("%T") != std::string::npos)
            setLabel("Clock: 24h");
        else
            setLabel("Clock: 12h");
    }

    void click(int button, int time) {
        std::string newformat = m_tool.timeFormat();
        size_t pos = newformat.find("%k");
        std::string newstr;
        bool clock24hour = true;
        if (pos != std::string::npos)
            newstr = "%l";
        else if ((pos = newformat.find("%H")) != std::string::npos)
            newstr = "%I";
        else if ((pos = newformat.find("%T")) != std::string::npos)
            newstr = "%r";

        // 12 hour
        if (newstr.empty()) {
            clock24hour = false;
            if ((pos = newformat.find("%l")) != std::string::npos)
                newstr = "%k";
            else if ((pos = newformat.find("%I")) != std::string::npos)
                newstr = "%H";
            else if ((pos = newformat.find("%r")) != std::string::npos)
                newstr = "%T";

        }

        if (!newstr.empty()) {

            newformat.replace(pos, 2, newstr);
            if (!clock24hour) { // erase %P/%p (AM|PM / am|pm)
                pos = newformat.find("%p");
                if (pos != std::string::npos)
                    newformat.erase(pos, 2);
                else if ((pos = newformat.find("%P")) != std::string::npos)
                    newformat.erase(pos, 2);
            }

            m_tool.setTimeFormat(newformat);

            if (m_tool.timeFormat().find("%k") != std::string::npos ||
                m_tool.timeFormat().find("%H") != std::string::npos ||
                m_tool.timeFormat().find("%T") != std::string::npos)
                setLabel("Clock: 24h");
            else
                setLabel("Clock: 12h");

        } // else some other strange format...so we don't do anything
        FbTk::MenuItem::click(button, time);
    }
private:
    ClockTool &m_tool;
};

ClockTool::ClockTool(const FbTk::FbWindow &parent,
                     ToolTheme &theme, BScreen &screen, FbTk::Menu &menu):
    ToolbarItem(ToolbarItem::FIXED),
    m_button(parent, theme.font(), ""),
    m_theme(theme),
    m_screen(screen),
    m_pixmap(0),
    m_timeformat(screen.resourceManager(), std::string("%k:%M"),
                 screen.name() + ".strftimeFormat", screen.altName() + ".StrftimeFormat") {
    // attach signals
    theme.reconfigSig().attach(this);

    // setup timer to update the graphics each second
    timeval delay;
    delay.tv_sec = 1;
    delay.tv_usec = 0;
    m_timer.setTimeout(delay);
    FbTk::RefCount<FbTk::Command> update_graphic(new FbTk::SimpleCommand<ClockTool>(*this,
                                                                                &ClockTool::updateTime));
    m_timer.setCommand(update_graphic);
    m_timer.start();

    m_button.setGC(m_theme.textGC());
    FbTk::RefCount<FbTk::Command> saverc(CommandParser::instance().parseLine("saverc"));
    FbTk::MenuItem *item = new ClockMenuItem(*this);
    item->setCommand(saverc);
    menu.insert(item);
    update(0);
}

ClockTool::~ClockTool() {
    // remove cached pixmap
    if (m_pixmap)
        m_screen.imageControl().removeImage(m_pixmap);
}

void ClockTool::move(int x, int y) {
    m_button.move(x, y);
}

void ClockTool::resize(unsigned int width, unsigned int height) {
    m_button.resize(width, height);
    renderTheme();
}

void ClockTool::moveResize(int x, int y,
                      unsigned int width, unsigned int height) {
    m_button.moveResize(x, y, width, height);
    renderTheme();
}

void ClockTool::show() {
    m_button.show();
}

void ClockTool::hide() {
    m_button.hide();
}

void ClockTool::setTimeFormat(const std::string &format) {
    *m_timeformat = format;
    update(0);
}

void ClockTool::update(FbTk::Subject *subj) {
    updateTime();

    // + 2 to make the entire text fit inside
    std::string text;
    for (size_t i=0; i<m_button.text().size() + 2; ++i)
        text += '0';

    resize(m_theme.font().textWidth(text.c_str(), text.size()), m_button.height());
}

unsigned int ClockTool::borderWidth() const {
    return m_button.borderWidth();
}

unsigned int ClockTool::width() const {
    return m_button.width();
}

unsigned int ClockTool::height() const {
    return m_button.height();
}

void ClockTool::updateTime() {

    // update clock
    time_t the_time = time(0);

    if (the_time != -1) {
        char time_string[255];
        struct tm *time_type = localtime(&the_time);
        if (time_type == 0)
            return;

#ifdef HAVE_STRFTIME
        if (!strftime(time_string, 255, m_timeformat->c_str(), time_type))
            return;
        m_button.setText(time_string);
#else // dont have strftime so we have to set it to hour:minut
        //        sprintf(time_string, "%d:%d", );
#endif // HAVE_STRFTIME
    }

    m_button.clear();
}

void ClockTool::renderTheme() {
    Pixmap old_pm = m_pixmap;
    if (m_theme.texture().type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
        m_pixmap = 0;
        m_button.setBackgroundColor(m_theme.texture().color());
    } else {
        m_pixmap = m_screen.imageControl().renderImage(m_button.width(), m_button.height(), m_theme.texture());
        m_button.setBackgroundPixmap(m_pixmap);
    }

    if (old_pm)
        m_screen.imageControl().removeImage(old_pm);

    m_button.setJustify(m_theme.justify());
    m_button.setBorderWidth(m_theme.border().width());
    m_button.setBorderColor(m_theme.border().color());
    m_button.clear();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#define TIMER_START(name) Timer name_timer;
#define TIMER_END(name) std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;

#include <iostream>
#include <cstdio>

#include "Compiler.hpp"

#include "Timer.hpp"
#include "Options.hpp"

#include "StringPool.hpp"
#include "FunctionTable.hpp"
/*
#include "MainDeclaration.hpp"
#include "Methods.hpp"
#include "il/IntermediateProgram.hpp"
*/

#include "ast/Program.hpp"

#include "ContextAnnotator.hpp"
#include "VariableChecker.hpp"
#include "StringChecker.hpp"
#include "FunctionChecker.hpp"

#include "parser/SpiritParser.hpp"

using std::string;
using std::cout;
using std::endl;

using namespace eddic;

void defineContexts(ASTProgram& program);

void checkVariables(ASTProgram& program);
void checkStrings(ASTProgram& program, std::shared_ptr<StringPool> pool);
void checkFunctions(ASTProgram& program, FunctionTable& functionTable);

void execCommand(const string& command);

int Compiler::compile(const string& file) {
    cout << "Compile " << file << endl;

    Timer timer;

    string output = Options::get(ValueOption::OUTPUT);

    int code = 0;
    try {
        TIMER_START(parsing)

        SpiritParser parser;

        //The program to build
        ASTProgram program;

        //Parse the file into the program
        bool parsing = parser.parse(file, program);

        TIMER_END(parsing)

        if(parsing){
            defineContexts(program);

            auto pool = std::make_shared<StringPool>();
            FunctionTable functionTable;

            //Semantical analysis
            checkVariables(program);
            checkStrings(program, pool);
            checkFunctions(program, functionTable);

            //TODO program->checkFunctions(*program);

            //TODO Add things to the program (pool, main, methods)

            /*

              program->addFirst(std::shared_ptr<ParseNode>(new MainDeclaration(program->context(), parser.getLexer().getDefaultToken())));
              program->addLast(std::shared_ptr<ParseNode>(new Methods(program->context(), parser.getLexer().getDefaultToken())));
              program->addLast(pool);

            //Optimize the parse tree
            program->optimize();

            //Write Intermediate representation of the parse tree
            IntermediateProgram il;
            program->writeIL(il);

            //Write assembly code
            writer.open("output.asm");
            il.writeAsm(writer);

            if(!Options::isSet(BooleanOption::ASSEMBLY_ONLY)){
            execCommand("as --32 -o output.o output.asm");

            string ldCommand = "gcc -m32 -static -o ";
            ldCommand += output;
            ldCommand += " output.o -lc";

            execCommand(ldCommand);

            //Remove temporary files
            remove("output.asm");
            remove("output.o");
            }*/

        }
    } catch (const CompilerException& e) {
        cout << e.what() << endl;
        code = 1;
    }

    //Close input and output
    //writer.close();

    cout << "Compilation took " << timer.elapsed() << "s" << endl;

    return code;
}

void defineContexts(ASTProgram& program){
    TIMER_START(contexts)
    ContextAnnotator annotator;
    annotator.annotate(program);
    TIMER_END(contexts);
}

void checkVariables(ASTProgram& program){
    TIMER_START(check_variables)
    VariableChecker checker;
    checker.check(program);
    TIMER_END(check_variables)
}

void checkStrings(ASTProgram& program, std::shared_ptr<StringPool> pool){
    TIMER_START(check_strings)
    StringChecker checker;
    checker.check(program, pool);
    TIMER_END(check_strings)
}

void checkFunctions(ASTProgram& program, FunctionTable& functionTable){
    TIMER_START(check_functions)
    FunctionChecker checker;
    checker.check(program, functionTable);
    TIMER_END(check_functions)
}

void execCommand(const string& command) {
    cout << "eddic : exec command : " << command << endl;

    char buffer[1024];

    FILE* stream = popen(command.c_str(), "r");

    while (fgets(buffer, 1024, stream) != NULL) {
        cout << buffer;
    }

    pclose(stream);
}
<commit_msg>Prepare implementation of optimization<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#define TIMER_START(name) Timer name_timer;
#define TIMER_END(name) std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;

#include <iostream>
#include <cstdio>

#include "Compiler.hpp"

#include "Timer.hpp"
#include "Options.hpp"

#include "StringPool.hpp"
#include "FunctionTable.hpp"
/*
#include "MainDeclaration.hpp"
#include "Methods.hpp"
#include "il/IntermediateProgram.hpp"
*/

#include "ast/Program.hpp"

#include "ContextAnnotator.hpp"
#include "VariableChecker.hpp"
#include "StringChecker.hpp"
#include "FunctionChecker.hpp"

#include "parser/SpiritParser.hpp"

using std::string;
using std::cout;
using std::endl;

using namespace eddic;

void defineContexts(ASTProgram& program);

void checkVariables(ASTProgram& program);
void checkStrings(ASTProgram& program, std::shared_ptr<StringPool> pool);
void checkFunctions(ASTProgram& program, FunctionTable& functionTable);
void optimize(ASTProgram& program);

void execCommand(const string& command);

int Compiler::compile(const string& file) {
    cout << "Compile " << file << endl;

    Timer timer;

    string output = Options::get(ValueOption::OUTPUT);

    int code = 0;
    try {
        TIMER_START(parsing)

        SpiritParser parser;

        //The program to build
        ASTProgram program;

        //Parse the file into the program
        bool parsing = parser.parse(file, program);

        TIMER_END(parsing)

        if(parsing){
            defineContexts(program);

            auto pool = std::make_shared<StringPool>();
            FunctionTable functionTable;

            //Semantical analysis
            checkVariables(program);
            checkStrings(program, pool);
            checkFunctions(program, functionTable);

            //Optimize the AST
            optimize(program);

            //TODO Add things to the program (pool, main, methods)

            /*

              program->addFirst(std::shared_ptr<ParseNode>(new MainDeclaration(program->context(), parser.getLexer().getDefaultToken())));
              program->addLast(std::shared_ptr<ParseNode>(new Methods(program->context(), parser.getLexer().getDefaultToken())));
              program->addLast(pool);

            //Write Intermediate representation of the parse tree
            IntermediateProgram il;
            program->writeIL(il);

            //Write assembly code
            writer.open("output.asm");
            il.writeAsm(writer);

            if(!Options::isSet(BooleanOption::ASSEMBLY_ONLY)){
            execCommand("as --32 -o output.o output.asm");

            string ldCommand = "gcc -m32 -static -o ";
            ldCommand += output;
            ldCommand += " output.o -lc";

            execCommand(ldCommand);

            //Remove temporary files
            remove("output.asm");
            remove("output.o");
            }*/

        }
    } catch (const CompilerException& e) {
        cout << e.what() << endl;
        code = 1;
    }

    //Close input and output
    //writer.close();

    cout << "Compilation took " << timer.elapsed() << "s" << endl;

    return code;
}

void defineContexts(ASTProgram& program){
    TIMER_START(contexts)
    ContextAnnotator annotator;
    annotator.annotate(program);
    TIMER_END(contexts);
}

void checkVariables(ASTProgram& program){
    TIMER_START(check_variables)
    VariableChecker checker;
    checker.check(program);
    TIMER_END(check_variables)
}

void checkStrings(ASTProgram& program, std::shared_ptr<StringPool> pool){
    TIMER_START(check_strings)
    StringChecker checker;
    checker.check(program, pool);
    TIMER_END(check_strings)
}

void checkFunctions(ASTProgram& program, FunctionTable& functionTable){
    TIMER_START(check_functions)
    FunctionChecker checker;
    checker.check(program, functionTable);
    TIMER_END(check_functions)
}

void optimize(ASTProgram& program){
    TIMER_START(optimization)
    //TODO
    TIMER_END(optimization)
}

void execCommand(const string& command) {
    cout << "eddic : exec command : " << command << endl;

    char buffer[1024];

    FILE* stream = popen(command.c_str(), "r");

    while (fgets(buffer, 1024, stream) != NULL) {
        cout << buffer;
    }

    pclose(stream);
}
<|endoftext|>


<commit_before>#include "inspectable_web_contents_view_linux.h"

#include "browser/browser_client.h"
#include "browser/inspectable_web_contents_impl.h"

#include "content/public/browser/web_contents_view.h"

namespace brightray {

InspectableWebContentsView* CreateInspectableContentsView(InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewLinux(inspectable_web_contents);
}

InspectableWebContentsViewLinux::InspectableWebContentsViewLinux(InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents) {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::InspectableWebContentsViewLinux\n");
}

InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux() {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux\n");
}

gfx::NativeView InspectableWebContentsViewLinux::GetNativeView() const {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::~GetNativeView\n");
	return NULL;
}

void InspectableWebContentsViewLinux::ShowDevTools() {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::ShowDevTools\n");
}

void InspectableWebContentsViewLinux::CloseDevTools() {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::CloseDevTools\n");
}

bool InspectableWebContentsViewLinux::SetDockSide(const std::string& side) {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::SetDockSide\n");
  return false;
}

}
<commit_msg>fix typo<commit_after>#include "inspectable_web_contents_view_linux.h"

#include "browser/browser_client.h"
#include "browser/inspectable_web_contents_impl.h"

#include "content/public/browser/web_contents_view.h"

namespace brightray {

InspectableWebContentsView* CreateInspectableContentsView(InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewLinux(inspectable_web_contents);
}

InspectableWebContentsViewLinux::InspectableWebContentsViewLinux(InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents) {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::InspectableWebContentsViewLinux\n");
}

InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux() {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux\n");
}

gfx::NativeView InspectableWebContentsViewLinux::GetNativeView() const {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::GetNativeView\n");
	return NULL;
}

void InspectableWebContentsViewLinux::ShowDevTools() {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::ShowDevTools\n");
}

void InspectableWebContentsViewLinux::CloseDevTools() {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::CloseDevTools\n");
}

bool InspectableWebContentsViewLinux::SetDockSide(const std::string& side) {
	// TODO
	fprintf(stderr, "InspectableWebContentsViewLinux::SetDockSide\n");
  return false;
}

}
<|endoftext|>


<commit_before>/** \addtogroup examples
  * @{
  * \defgroup neural neural
  * @{
  * \brief Neural Network
  */

#include <ctf.hpp>
using namespace CTF;

/**
 * \brief computes a neural network iteration for tensor n*n*m tensor X
 *        whose sparsity fraction is sp. Filter W is d*d*m and dense.
 *  Y_ij = sum_{k=1}^m sum_{a=1}^d sum_{b=1}^d X_{i+a,j+b,k} * W_{abk}
 *        this algorithm assumes n = 0 (mod d)
 */
int neural(int     n,
           int     m,
           int     d,
           double  sp,
           World & dw){
  int lens_X[3] = {n, n, m};
  int lens_W[3] = {d, d, m};

  Tensor<> X(3, lens_X);
  Tensor<> W(3, lens_W);
  Matrix<> Y(n, n);

  X.fill_sp_random(0.0, 1.0, sp);
  W.fill_random(0.0, 1.0);

  //fold first two modes of X into a pair of modes that are n/d-by-d
  int lens_X5[] = {n/d, d, n/d, d, m};
  Tensor<> X5(5, lens_X5);

  int64_t * inds_X;
  double * vals_X;
  int64_t n_X;
  //global index ordering is preserved between the two tensors, so we can fold simply
  X.read_local(&n_X, &inds_X, &vals_X);
  X5.write(n_X, inds_X, vals_X);

  int lens_Y4[] = {n/d, d, n/d, d, m};
  Tensor<> Y4(4, lens_Y4);

  //define a matrix that rotates the elements of a vector
  Matrix<> R(d, d);
  if (dw.rank == 0){
    int64_t inds_R[d];
    double vals_R[d];
    std::fill(vals_R, vals_R+d, 1.0);
    for (int i=0; i<d; i++){
      inds_R[i] = ((i+1) % d) + i*d;
    }
    R.write(d,inds_R,vals_R);
  } else R.write(0,NULL,NULL);

  for (int a=0; a<d; a++){
    for (int b=0; b<d; b++){
      Y4["iajb"] += X5["iajbk"]*W["abk"];
      W["abk"] = R["ac"]*W["ack"];
      Y4["iajb"] = R["ac"]*Y4["iajc"];
    }
    W["abk"] = R["ac"]*W["cbk"];
    Y4["iajb"] = R["ac"]*Y4["icjb"];
  }

  //unfold output into matrix
  int64_t * inds_Y;
  double * vals_Y;
  int64_t n_Y;
  //global index ordering is preserved between the two tensors, so we can unfold simply
  Y4.read_local(&n_Y, &inds_Y, &vals_Y);
  Y.write(n_Y, inds_Y, vals_Y);

  bool pass = Y.norm2() >= 1.E-6;

  if (dw.rank == 0){
    if (pass)
      printf("{ Neural network with sparse X } passed \n");
    else
      printf("{ Neural network with sparse X } failed \n");
  }
  return pass;
}

#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
                   char ** end,
                   const   std::string & option){
  char ** itr = std::find(begin, end, option);
  if (itr != end && ++itr != end){
    return *itr;
  }
  return 0;
}

int main(int argc, char ** argv){
  int rank, np, n, m, d, pass;
  double sp;
  int const in_num = argc;
  char ** input_str = argv;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &np);

  if (getCmdOption(input_str, input_str+in_num, "-n")){
    n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
    if (n < 0) n = 16;
  } else n = 16;

  if (getCmdOption(input_str, input_str+in_num, "-m")){
    m = atoi(getCmdOption(input_str, input_str+in_num, "-m"));
    if (m < 0) m = 9;
  } else m = 9;

  if (getCmdOption(input_str, input_str+in_num, "-d")){
    d = atoi(getCmdOption(input_str, input_str+in_num, "-d"));
    if (d < 0) d = 4;
  } else d = 4;

  if (getCmdOption(input_str, input_str+in_num, "-sp")){
    sp = atof(getCmdOption(input_str, input_str+in_num, "-sp"));
    if (sp < 0) sp = .2;
  } else sp = .2;

  {
    World dw(argc, argv);

    if (rank == 0){
      printf("Running neural network with dimensions %d*%d*%d and sparsity fraction %lf with dense filter of dimensions %d*%d*%d\n",n,n,m,sp,d,d,m);
    }
    pass = neural(n, m, d, sp, dw);
    assert(pass);
  }

  MPI_Finalize();
  return 0;
}
/**
 * @}
 * @}
 */

#endif
<commit_msg>Made Rotation of Y go across boundary of d-by-d squares<commit_after>/** \addtogroup examples
  * @{
  * \defgroup neural neural
  * @{
  * \brief Neural Network
  */

#include <ctf.hpp>
using namespace CTF;

/** \brief folds a tensor X into tensor Y assuming the lexicographical ordering of elements in both tensors is the same but the order is different */
void fold_unfold(Tensor<>& X, Tensor<>& Y){
  int64_t * inds_X;
  double * vals_X;
  int64_t n_X;
  //if global index ordering is preserved between the two tensors, we can fold simply
  X.read_local(&n_X, &inds_X, &vals_X);
  Y.write(n_X, inds_X, vals_X);
}

/**
 * \brief computes a neural network iteration for tensor n*n*m tensor X
 *        whose sparsity fraction is sp. Filter W is d*d*m and dense.
 *  Y_ij = sum_{k=1}^m sum_{a=1}^d sum_{b=1}^d X_{i+a % n, j+b % n, k} * W_{abk}
 *        this algorithm assumes n = 0 (mod d)
 */
int neural(int     n,
           int     m,
           int     d,
           double  sp,
           World & dw){
  int lens_X[3] = {n, n, m};
  int lens_W[3] = {d, d, m};

  Tensor<> X(3, lens_X);
  Tensor<> W(3, lens_W);
  Matrix<> Y(n, n);

  X.fill_sp_random(0.0, 1.0, sp);
  W.fill_random(0.0, 1.0);

  //fold first two modes of X into a pair of modes that are n/d-by-d
  int lens_X5[] = {n/d, d, n/d, d, m};
  Tensor<> X5(5, lens_X5);

  fold_unfold(X, X5);

  int lens_Y4[] = {n/d, d, n/d, d};
  Tensor<> Y4(4, lens_Y4);

  //define a matrix that rotates the elements of a vector with wrap around
  Matrix<> Rd(d, d);
  if (dw.rank == 0){
    int64_t inds_Rd[d];
    double vals_Rd[d];
    std::fill(vals_Rd, vals_Rd+d, 1.0);
    for (int i=0; i<d; i++){
      inds_Rd[i] = ((i+1) % d) + i*d;
    }
    Rd.write(d,inds_Rd,vals_Rd);
  } else Rd.write(0,NULL,NULL);

  //define a matrix that rotates the elements of a vector of length n with wrap around
  Matrix<> Rn(n, n);
  if (dw.rank == 0){
    int64_t inds_Rn[n];
    double vals_Rn[n];
    std::fill(vals_Rn, vals_Rn+n, 1.0);
    for (int i=0; i<n; i++){
      inds_Rn[i] = ((i+1) % n) + i*n;
    }
    Rn.write(n,inds_Rn,vals_Rn);
  } else Rn.write(0,NULL,NULL);

  //fold that vector rotation into a tensor of order 4, to make it act on a vector folded into a n/d-by-d matrix
  Tensor<> Rn4(4, lens_Y4);
  fold_unfold(Rn, Rn4);

  //define a matrix that rotates the elements of a vector of length n by d with wrap around
  Matrix<> Rnd(n, n);
  if (dw.rank == 0){
    int64_t inds_Rnd[n];
    double vals_Rnd[n];
    std::fill(vals_Rnd, vals_Rnd+n, 1.0);
    for (int i=0; i<n; i++){
      inds_Rnd[i] = ((i+d) % n) + i*n;
    }
    Rnd.write(n,inds_Rnd,vals_Rnd);
  } else Rnd.write(0,NULL,NULL);

  //fold that vector d-depth rotation into a tensor of order 4, to make it act on a vector folded into a n/d-by-d matrix
  Tensor<> Rnd4(4, lens_Y4);
  fold_unfold(Rnd, Rnd4);

  for (int a=0; a<d; a++){
    for (int b=0; b<d; b++){
      //compute k of the kd^2 contributions to the output Y
      Y4["iajb"] += X5["iajbk"]*W["abk"];
      //rotate the filter cyclically in the first mode
      W["abk"] = Rd["bc"]*W["ack"];
      //rotate Y cyclically in the first mode
      Y4["iajb"] = Rn4["jbkc"]*Y4["iakc"];
    }
    //now rotate Y back by d in the first mode
    Y4["iajb"] = Rnd4["kcjb"]*Y4["iakc"];
    //rotate W cyclically in the second mode
    W["abk"] = Rd["ac"]*W["cbk"];
    //rotate Y cyclically in the second mode
    Y4["iajb"] = Rn4["iakc"]*Y4["kcjb"];
  }
  //now rotate Y back by d in the second mode
  Y4["iajb"] = Rnd4["kcia"]*Y4["kcjb"];

  //unfold output into matrix
  fold_unfold(Y4, Y);

  bool pass = Y.norm2() >= 1.E-6;

  if (dw.rank == 0){
    if (pass)
      printf("{ Neural network with sparse X } passed \n");
    else
      printf("{ Neural network with sparse X } failed \n");
  }
  return pass;
}

#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
                   char ** end,
                   const   std::string & option){
  char ** itr = std::find(begin, end, option);
  if (itr != end && ++itr != end){
    return *itr;
  }
  return 0;
}

int main(int argc, char ** argv){
  int rank, np, n, m, d, pass;
  double sp;
  int const in_num = argc;
  char ** input_str = argv;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &np);

  if (getCmdOption(input_str, input_str+in_num, "-n")){
    n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
    if (n < 0) n = 16;
  } else n = 16;

  if (getCmdOption(input_str, input_str+in_num, "-m")){
    m = atoi(getCmdOption(input_str, input_str+in_num, "-m"));
    if (m < 0) m = 9;
  } else m = 9;

  if (getCmdOption(input_str, input_str+in_num, "-d")){
    d = atoi(getCmdOption(input_str, input_str+in_num, "-d"));
    if (d < 0) d = 4;
  } else d = 4;

  if (getCmdOption(input_str, input_str+in_num, "-sp")){
    sp = atof(getCmdOption(input_str, input_str+in_num, "-sp"));
    if (sp < 0) sp = .2;
  } else sp = .2;

  {
    World dw(argc, argv);

    if (rank == 0){
      printf("Running neural network with dimensions %d*%d*%d and sparsity fraction %lf with dense filter of dimensions %d*%d*%d\n",n,n,m,sp,d,d,m);
    }
    pass = neural(n, m, d, sp, dw);
    assert(pass);
  }

  MPI_Finalize();
  return 0;
}
/**
 * @}
 * @}
 */

#endif
<|endoftext|>


<commit_before>#include "Debugger.h"
#include <iostream>
#include <cctype>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <utility>
#include <map>
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#include <unistd.h>
#include <csignal>
#elif _WIN32 || _WIN64
#include <windows.h>
#endif

using namespace Debug;

static Debugger* _debugger = nullptr;

// While the debugger is running, trap the SIGINT to pause the emulation.
static void interrupt_handler(int s) {
	if (_debugger == nullptr) return;
	if (_debugger->getEmulator()->cpu.running) {
		std::clog << "Emulation paused. Type 'run' to resume." << std::endl;
		_debugger->getEmulator()->cpu.running = false;
		return;
	}
	exit(s);
}

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
static void setup_signal_trap() {
	struct sigaction sigintHandler;
	sigintHandler.sa_handler = interrupt_handler;
	sigemptyset(&sigintHandler.sa_mask);
	sigintHandler.sa_flags = 0;
	sigaction(SIGINT, &sigintHandler, NULL);
}
#elif _WIN32 || _WIN64
static BOOL InterruptHandlerProxy(DWORD ctrlType) {
	switch (ctrlType) {
	case CTRL_C_EVENT:
		interrupt_handler(0);
		return TRUE;
	}
	return FALSE;
}
#endif

// { cmd_string => { command, n.args } }
static const std::map<std::string, std::pair<DebugInstr, int>> debugInstructions = {
	{ "run",      std::make_pair(CMD_RUN,       0) },
	{ "print",    std::make_pair(CMD_PRINT,     1) },
	{ "reg",      std::make_pair(CMD_REGISTERS, 0) },
	{ "stack",    std::make_pair(CMD_STACK,     0) },
	{ "flags",    std::make_pair(CMD_FLAGS,     0) },
	{ "mem",      std::make_pair(CMD_MEMORY,    1) },
	{ "track",    std::make_pair(CMD_TRACK,     0) },
	{ "break",    std::make_pair(CMD_BREAK,     1) },
	{ "quit",     std::make_pair(CMD_QUIT,      0) },
	{ "exit",     std::make_pair(CMD_QUIT,      0) },
	{ "step",     std::make_pair(CMD_STEP,      0) },
	{ "cont",     std::make_pair(CMD_CONTINUE,  0) },
	{ "continue", std::make_pair(CMD_CONTINUE,  0) },
	{ "help",     std::make_pair(CMD_HELP,      0) },
	{ "?",        std::make_pair(CMD_HELP,      0) }
};

Debugger::Debugger(Emulator* _emulator, uint8_t _opts) {
	emulator = _emulator;
	opts = _opts;
	track = false;
}

Debugger::~Debugger() {}

void Debugger::Run() {
	emulator->cpu.running = (opts & DBG_NOSTART) == DBG_NOSTART;

	// Trap SIGINT to pause the execution
	_debugger = this;
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	setup_signal_trap();
#elif _WIN32 || _WIN64
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)InterruptHandlerProxy, TRUE);
#endif

	while (emulator->running) {
		emulator->Update();

		if (!emulator->cpu.running || opts & DBG_INTERACTIVE) {
			DebugCmd cmd = getCommand("(mfemu)");
			switch (cmd.instr) {
			case CMD_RUN:
				std::clog << "Starting emulation..." << std::endl;
				emulator->cpu.running = true;
				break;
			case CMD_PRINT: {
				uint16_t arg = emulator->cpu.PC;
				if (cmd.args.front().length() > 0) {
					std::stringstream ss(cmd.args.front());
					ss >> std::hex >> arg;
				}
				printInstruction(arg);
				break;
			}
			case CMD_REGISTERS:
				printRegisters();
				break;
			case CMD_STACK:
				printStack();
				break;
			case CMD_MEMORY: {
				std::stringstream ss(cmd.args.front());
				uint16_t arg;
				ss >> std::hex >> arg;
				std::cout << std::hex << std::setfill('0') << std::setw(2) << (int) emulator->mmu.Read(arg) << std::endl;
				break;
			}
			case CMD_FLAGS:
				printFlags();
				break;
			case CMD_TRACK:
				track = !track;
				std::cout << "Tracking has been " << (track ? "ENABLED" : "DISABLED") << std::endl;
				break;
			case CMD_BREAK: {
				std::stringstream ss(cmd.args.front());
				uint16_t arg;
				ss >> std::hex >> arg;
				setBreakpoint(arg);
				break;
			}
			case CMD_STEP:
				if (emulator->cpu.running) {
					if (!(opts & DBG_NOGRAPHICS)) {
						SDL_RenderClear(emulator->renderer);
					}
					emulator->cpu.Step();
					printInstruction(emulator->cpu.PC);
				} else {
					std::cerr << "CPU is not running: type `run` to start emulation." << std::endl;
				}
				break;
			case CMD_CONTINUE:
				if (emulator->cpu.running) {
					opts &= ~DBG_INTERACTIVE;
				} else {
					std::cerr << "CPU is not running: type `run` to start emulation." << std::endl;
				}
				break;
			case CMD_HELP:
				std::cout
					<< "run           Start emulation\r\n"
					<< "print         Print current instruction\r\n"
					<< "reg           Print registers\r\n"
					<< "stack         Print stack\r\n"
					<< "break <addr>  Set breakpoint at <addr>\r\n"
					<< "step          Fetch and execute a single instruction\r\n"
					<< "continue      Resume execution\r\n"
					<< "track         Toggle instruction printing\r\n"
					<< "help          Print a help message\r\n"
					<< "quit          Quit the debugger" << std::endl;
				break;
			case CMD_QUIT:
				std::clog << "...quitting." << std::endl;
				return;
			default:
				std::cerr << "Invalid command" << std::endl;
			}
		} else {
			// Execute instructions until a breakpoint is found
			uint16_t PC = emulator->cpu.PC;
			if (breakPoints.find(PC) != breakPoints.end()) {
				opts |= DBG_INTERACTIVE;
				std::cout << "Breakpoint reached: " << std::hex << (int)PC << std::endl;
				continue;
			}

			if (track) {
				printInstruction(emulator->cpu.PC);
			}
			emulator->Step();
		}
	}
}

// Reads a command from stdin and returns a struct { cmd, args }.
// Currently only takes 1 argument.
DebugCmd Debugger::getCommand(const char* prompt) {
	static DebugCmd latest = { CMD_INVALID };

	std::cout << prompt << " " << std::flush;

	std::string line;
	std::string instr;
	DebugCmd cmd;

	std::getline(std::cin, line);

	if ((std::cin.rdstate() & std::cin.eofbit) != 0) {
		cmd.instr = CMD_QUIT;
		return cmd;
	}

	// rtrim spaces
	line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end());
	std::stringstream ss(line);

	if (line.length() < 1) {
		if (latest.instr != CMD_INVALID) {
			// repeat latest command
			return latest;
		} else {
			return getCommand(prompt);
		}
	} else {
		ss >> instr;
	}

	auto inst_pair = debugInstructions.find(instr);
	if (inst_pair != debugInstructions.end()) {
		cmd.instr = inst_pair->second.first;
		for (int i = 0; i < inst_pair->second.second; ++i) {
			std::string arg;
			ss >> arg;
			cmd.args.push_back(arg);
		}
	} else {
		cmd.instr = CMD_INVALID;
	}

	latest = cmd;
	return cmd;
}

void Debugger::setBreakpoint(uint16_t addr) {
	breakPoints.insert(addr);
	std::clog << "Set breakpoint to " << std::setfill('0') << std::setw(4) << std::hex << (int)addr << std::endl;
}
<commit_msg>Update help text<commit_after>#include "Debugger.h"
#include <iostream>
#include <cctype>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <utility>
#include <map>
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#include <unistd.h>
#include <csignal>
#elif _WIN32 || _WIN64
#include <windows.h>
#endif

using namespace Debug;

static Debugger* _debugger = nullptr;

// While the debugger is running, trap the SIGINT to pause the emulation.
static void interrupt_handler(int s) {
	if (_debugger == nullptr) return;
	if (_debugger->getEmulator()->cpu.running) {
		std::clog << "Emulation paused. Type 'run' to resume." << std::endl;
		_debugger->getEmulator()->cpu.running = false;
		return;
	}
	exit(s);
}

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
static void setup_signal_trap() {
	struct sigaction sigintHandler;
	sigintHandler.sa_handler = interrupt_handler;
	sigemptyset(&sigintHandler.sa_mask);
	sigintHandler.sa_flags = 0;
	sigaction(SIGINT, &sigintHandler, NULL);
}
#elif _WIN32 || _WIN64
static BOOL InterruptHandlerProxy(DWORD ctrlType) {
	switch (ctrlType) {
	case CTRL_C_EVENT:
		interrupt_handler(0);
		return TRUE;
	}
	return FALSE;
}
#endif

// { cmd_string => { command, n.args } }
static const std::map<std::string, std::pair<DebugInstr, int>> debugInstructions = {
	{ "run",      std::make_pair(CMD_RUN,       0) },
	{ "print",    std::make_pair(CMD_PRINT,     1) },
	{ "reg",      std::make_pair(CMD_REGISTERS, 0) },
	{ "stack",    std::make_pair(CMD_STACK,     0) },
	{ "flags",    std::make_pair(CMD_FLAGS,     0) },
	{ "mem",      std::make_pair(CMD_MEMORY,    1) },
	{ "track",    std::make_pair(CMD_TRACK,     0) },
	{ "break",    std::make_pair(CMD_BREAK,     1) },
	{ "quit",     std::make_pair(CMD_QUIT,      0) },
	{ "exit",     std::make_pair(CMD_QUIT,      0) },
	{ "step",     std::make_pair(CMD_STEP,      0) },
	{ "cont",     std::make_pair(CMD_CONTINUE,  0) },
	{ "continue", std::make_pair(CMD_CONTINUE,  0) },
	{ "help",     std::make_pair(CMD_HELP,      0) },
	{ "?",        std::make_pair(CMD_HELP,      0) }
};

Debugger::Debugger(Emulator* _emulator, uint8_t _opts) {
	emulator = _emulator;
	opts = _opts;
	track = false;
}

Debugger::~Debugger() {}

void Debugger::Run() {
	emulator->cpu.running = (opts & DBG_NOSTART) == DBG_NOSTART;

	// Trap SIGINT to pause the execution
	_debugger = this;
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	setup_signal_trap();
#elif _WIN32 || _WIN64
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)InterruptHandlerProxy, TRUE);
#endif

	while (emulator->running) {
		emulator->Update();

		if (!emulator->cpu.running || opts & DBG_INTERACTIVE) {
			DebugCmd cmd = getCommand("(mfemu)");
			switch (cmd.instr) {
			case CMD_RUN:
				std::clog << "Starting emulation..." << std::endl;
				emulator->cpu.running = true;
				break;
			case CMD_PRINT: {
				uint16_t arg = emulator->cpu.PC;
				if (cmd.args.front().length() > 0) {
					std::stringstream ss(cmd.args.front());
					ss >> std::hex >> arg;
				}
				printInstruction(arg);
				break;
			}
			case CMD_REGISTERS:
				printRegisters();
				break;
			case CMD_STACK:
				printStack();
				break;
			case CMD_MEMORY: {
				std::stringstream ss(cmd.args.front());
				uint16_t arg;
				ss >> std::hex >> arg;
				std::cout << std::hex << std::setfill('0') << std::setw(2) << (int) emulator->mmu.Read(arg) << std::endl;
				break;
			}
			case CMD_FLAGS:
				printFlags();
				break;
			case CMD_TRACK:
				track = !track;
				std::cout << "Tracking has been " << (track ? "ENABLED" : "DISABLED") << std::endl;
				break;
			case CMD_BREAK: {
				std::stringstream ss(cmd.args.front());
				uint16_t arg;
				ss >> std::hex >> arg;
				setBreakpoint(arg);
				break;
			}
			case CMD_STEP:
				if (emulator->cpu.running) {
					if (!(opts & DBG_NOGRAPHICS)) {
						SDL_RenderClear(emulator->renderer);
					}
					emulator->cpu.Step();
					printInstruction(emulator->cpu.PC);
				} else {
					std::cerr << "CPU is not running: type `run` to start emulation." << std::endl;
				}
				break;
			case CMD_CONTINUE:
				if (emulator->cpu.running) {
					opts &= ~DBG_INTERACTIVE;
				} else {
					std::cerr << "CPU is not running: type `run` to start emulation." << std::endl;
				}
				break;
			case CMD_HELP:
				std::cout
					<< "run           Start emulation\r\n"
					<< "print         Print current instruction (or any given one via argument)\r\n"
					<< "mem           Print value at a specified memory location\r\n"
					<< "reg           Print registers\r\n"
					<< "stack         Print stack\r\n"
					<< "break <addr>  Set breakpoint at <addr>\r\n"
					<< "step          Fetch and execute a single instruction\r\n"
					<< "continue      Resume execution\r\n"
					<< "track         Toggle instruction printing\r\n"
					<< "help          Print a help message\r\n"
					<< "quit          Quit the debugger" << std::endl;
				break;
			case CMD_QUIT:
				std::clog << "...quitting." << std::endl;
				return;
			default:
				std::cerr << "Invalid command" << std::endl;
			}
		} else {
			// Execute instructions until a breakpoint is found
			uint16_t PC = emulator->cpu.PC;
			if (breakPoints.find(PC) != breakPoints.end()) {
				opts |= DBG_INTERACTIVE;
				std::cout << "Breakpoint reached: " << std::hex << (int)PC << std::endl;
				continue;
			}

			if (track) {
				printInstruction(emulator->cpu.PC);
			}
			emulator->Step();
		}
	}
}

// Reads a command from stdin and returns a struct { cmd, args }.
// Currently only takes 1 argument.
DebugCmd Debugger::getCommand(const char* prompt) {
	static DebugCmd latest = { CMD_INVALID };

	std::cout << prompt << " " << std::flush;

	std::string line;
	std::string instr;
	DebugCmd cmd;

	std::getline(std::cin, line);

	if ((std::cin.rdstate() & std::cin.eofbit) != 0) {
		cmd.instr = CMD_QUIT;
		return cmd;
	}

	// rtrim spaces
	line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end());
	std::stringstream ss(line);

	if (line.length() < 1) {
		if (latest.instr != CMD_INVALID) {
			// repeat latest command
			return latest;
		} else {
			return getCommand(prompt);
		}
	} else {
		ss >> instr;
	}

	auto inst_pair = debugInstructions.find(instr);
	if (inst_pair != debugInstructions.end()) {
		cmd.instr = inst_pair->second.first;
		for (int i = 0; i < inst_pair->second.second; ++i) {
			std::string arg;
			ss >> arg;
			cmd.args.push_back(arg);
		}
	} else {
		cmd.instr = CMD_INVALID;
	}

	latest = cmd;
	return cmd;
}

void Debugger::setBreakpoint(uint16_t addr) {
	breakPoints.insert(addr);
	std::clog << "Set breakpoint to " << std::setfill('0') << std::setw(4) << std::hex << (int)addr << std::endl;
}
<|endoftext|>


<commit_before>#include <httpserver.h>

using namespace std;
using namespace qttp;
using namespace native::http;

int main(int argc, char** argv)
{
  auto result = 0;

  try
  {
    LOG_TRACE;

    QCoreApplication app(argc, argv);

    HttpServer* svr = HttpServer::getInstance();

    // Always initialize in the main thread.
    svr->initialize();

    svr->registerRoute("get", "helloworld", "/helloworld");
    svr->addAction("helloworld", [](HttpData& data) {
      QJsonObject& json = data.getJson();
      json["response"] = "Hello World!";
    });

    svr->registerRoute("post", "echobody", "/echobody");
    svr->addAction("echobody", [](HttpData& data) {
        QJsonObject& json = data.getJson();
        json["response"] = data.getRequestParams();
    });

    svr->startServer();

    result = app.exec();
  }
  catch(std::exception& e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }
  catch(...)
  {
    std::cerr << "ERROR: Caught an unknown exception" << std::endl;
  }

  return result;
}
<commit_msg>Trivial<commit_after>#include <httpserver.h>

using namespace std;
using namespace qttp;
using namespace native::http;

int main(int argc, char** argv)
{
  auto result = 0;

  try
  {
    LOG_TRACE;

    QCoreApplication app(argc, argv);

    HttpServer* svr = HttpServer::getInstance();

    // Always initialize in the main thread.
    svr->initialize();

    svr->registerRoute("get", "helloworld", "/helloworld");
    svr->addAction("helloworld", [](HttpData& data) {
      QJsonObject& json = data.getJson();
      json["response"] = "Hello World!";

      //json["response"] = data.getHttpRequest().getBody() +
      //                   data.getHttpRequest().getUrl().getPath();
    });

    svr->registerRoute("post", "echobody", "/echobody");
    svr->addAction("echobody", [](HttpData& data) {
        QJsonObject& json = data.getJson();
        json["response"] = data.getRequestParams();
    });

    svr->startServer();

    result = app.exec();
  }
  catch(std::exception& e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }
  catch(...)
  {
    std::cerr << "ERROR: Caught an unknown exception" << std::endl;
  }

  return result;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/range/iterator_range.hpp>

#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/complex.hpp>

#include <amgcl/solver/runtime.hpp>
#include <amgcl/coarsening/runtime.hpp>
#include <amgcl/relaxation/runtime.hpp>
#include <amgcl/preconditioner/runtime.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/amg.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/io/mm.hpp>

#include <amgcl/profiler.hpp>

#include "sample_problem.hpp"

namespace amgcl { profiler<> prof; }
using amgcl::prof;
using amgcl::precondition;

//---------------------------------------------------------------------------
template <template <class> class Precond>
std::tuple<size_t, double> solve(
        const boost::property_tree::ptree &prm,
        size_t rows,
        std::vector<ptrdiff_t> const &ptr,
        std::vector<ptrdiff_t> const &col,
        std::vector< std::complex<double> > const &val,
        std::vector< std::complex<double> > const &rhs,
        std::vector< std::complex<double> >       &x
        )
{
    typedef amgcl::backend::builtin< std::complex<double> > Backend;
    Backend::params bprm;

    typedef amgcl::make_solver<
        Precond<Backend>,
        amgcl::runtime::solver::wrapper<Backend>
        > Solver;

    prof.tic("setup");
    Solver solve(std::tie(rows, ptr, col, val), prm, bprm);
    prof.toc("setup");

    std::cout << solve.precond() << std::endl;

    {
        auto t = prof.scoped_tic("solve");
        return solve(rhs, x);
    }
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    namespace po = boost::program_options;
    namespace io = amgcl::io;

    using amgcl::prof;
    using std::vector;
    using std::string;

    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "Show this help.")
        ("prm-file,P",
         po::value<string>(),
         "Parameter file in json format. "
        )
        (
         "prm,p",
         po::value< vector<string> >()->multitoken(),
         "Parameters specified as name=value pairs. "
         "May be provided multiple times. Examples:\n"
         "  -p solver.tol=1e-3\n"
         "  -p precond.coarse_enough=300"
        )
        ("matrix,A",
         po::value<string>(),
         "System matrix in the MatrixMarket format. "
         "When not specified, solves a Poisson problem in 3D unit cube. "
        )
        (
         "rhs,f",
         po::value<string>(),
         "The RHS vector in the MatrixMarket format. "
         "When omitted, a vector of ones is used by default. "
         "Should only be provided together with a system matrix. "
        )
        (
         "null,N",
         po::value<string>(),
         "The near null-space vectors in the MatrixMarket format. "
         "Should be a dense matrix of size N*M, where N is the number of "
         "unknowns, and M is the number of null-space vectors. "
         "Should only be provided together with a system matrix. "
        )
        (
         "size,n",
         po::value<int>()->default_value(32),
         "The size of the Poisson problem to solve when no system matrix is given. "
         "Specified as number of grid nodes along each dimension of a unit cube. "
         "The resulting system will have n*n*n unknowns. "
        )
        (
         "single-level,1",
         po::bool_switch()->default_value(false),
         "When specified, the AMG hierarchy is not constructed. "
         "Instead, the problem is solved using a single-level smoother as preconditioner. "
        )
        (
         "initial,x",
         po::value<double>()->default_value(0),
         "Value to use as initial approximation. "
        )
        (
         "output,o",
         po::value<string>(),
         "Output file. Will be saved in the MatrixMarket format. "
         "When omitted, the solution is not saved. "
        )
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    boost::property_tree::ptree prm;
    if (vm.count("prm-file")) {
        read_json(vm["prm-file"].as<string>(), prm);
    }

    if (vm.count("prm")) {
        for(const string &v : vm["prm"].as<vector<string> >()) {
            amgcl::put(prm, v);
        }
    }

    size_t rows;
    vector<ptrdiff_t> ptr, col;
    vector< std::complex<double> > val, rhs, null, x;

    if (vm.count("matrix")) {
        auto t = prof.scoped_tic("reading");

        string Afile = vm["matrix"].as<string>();

        size_t cols;
        std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);
        precondition(rows == cols, "Non-square system matrix");

        if (vm.count("rhs")) {
            string bfile = vm["rhs"].as<string>();

            size_t n, m;
            std::tie(n, m) = io::mm_reader(bfile)(rhs);

            precondition(n == rows && m == 1, "The RHS vector has wrong size");
        } else {
            rhs.resize(rows, 1.0);
        }

        if (vm.count("null")) {
            string nfile = vm["null"].as<string>();

            size_t m, nv;
            std::tie(m, nv) = io::mm_reader(nfile)(null);

            precondition(m == rows, "Near null-space vectors have wrong size");

            prm.put("precond.coarsening.nullspace.cols", nv);
            prm.put("precond.coarsening.nullspace.rows", rows);
            prm.put("precond.coarsening.nullspace.B",    &null[0]);
        }
    } else {
        auto t = prof.scoped_tic("assembling");
        rows = sample_problem(vm["size"].as<int>(), val, col, ptr, rhs);
    }

    x.resize(rows, vm["initial"].as<double>());

    size_t iters;
    double error;

    if (vm["single-level"].as<bool>())
        prm.put("precond.class", "relaxation");

    std::tie(iters, error) = solve<amgcl::runtime::preconditioner>(
            prm, rows, ptr, col, val, rhs, x);

    if (vm.count("output")) {
        auto t = prof.scoped_tic("write");
        amgcl::io::mm_write(vm["output"].as<string>(), &x[0], x.size());
    }

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << error << std::endl
              << prof << std::endl;
}
<commit_msg>Support binary input format in solver_complex<commit_after>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/range/iterator_range.hpp>

#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/complex.hpp>

#include <amgcl/solver/runtime.hpp>
#include <amgcl/coarsening/runtime.hpp>
#include <amgcl/relaxation/runtime.hpp>
#include <amgcl/preconditioner/runtime.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/amg.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/io/mm.hpp>
#include <amgcl/io/binary.hpp>

#include <amgcl/profiler.hpp>

#include "sample_problem.hpp"

namespace amgcl { profiler<> prof; }
using amgcl::prof;
using amgcl::precondition;

//---------------------------------------------------------------------------
template <template <class> class Precond>
std::tuple<size_t, double> solve(
        const boost::property_tree::ptree &prm,
        size_t rows,
        std::vector<ptrdiff_t> const &ptr,
        std::vector<ptrdiff_t> const &col,
        std::vector< std::complex<double> > const &val,
        std::vector< std::complex<double> > const &rhs,
        std::vector< std::complex<double> >       &x
        )
{
    typedef amgcl::backend::builtin< std::complex<double> > Backend;
    Backend::params bprm;

    typedef amgcl::make_solver<
        Precond<Backend>,
        amgcl::runtime::solver::wrapper<Backend>
        > Solver;

    prof.tic("setup");
    Solver solve(std::tie(rows, ptr, col, val), prm, bprm);
    prof.toc("setup");

    std::cout << solve.precond() << std::endl;

    {
        auto t = prof.scoped_tic("solve");
        return solve(rhs, x);
    }
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    namespace po = boost::program_options;
    namespace io = amgcl::io;

    using amgcl::prof;
    using std::vector;
    using std::string;

    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "Show this help.")
        ("prm-file,P",
         po::value<string>(),
         "Parameter file in json format. "
        )
        (
         "prm,p",
         po::value< vector<string> >()->multitoken(),
         "Parameters specified as name=value pairs. "
         "May be provided multiple times. Examples:\n"
         "  -p solver.tol=1e-3\n"
         "  -p precond.coarse_enough=300"
        )
        ("matrix,A",
         po::value<string>(),
         "System matrix in the MatrixMarket format. "
         "When not specified, solves a Poisson problem in 3D unit cube. "
        )
        (
         "rhs,f",
         po::value<string>(),
         "The RHS vector in the MatrixMarket format. "
         "When omitted, a vector of ones is used by default. "
         "Should only be provided together with a system matrix. "
        )
        (
         "null,N",
         po::value<string>(),
         "The near null-space vectors in the MatrixMarket format. "
         "Should be a dense matrix of size N*M, where N is the number of "
         "unknowns, and M is the number of null-space vectors. "
         "Should only be provided together with a system matrix. "
        )
        (
         "binary,B",
         po::bool_switch()->default_value(false),
         "When specified, treat input files as binary instead of as MatrixMarket. "
         "It is assumed the files were converted to binary format with mm2bin utility. "
        )
        (
         "size,n",
         po::value<int>()->default_value(32),
         "The size of the Poisson problem to solve when no system matrix is given. "
         "Specified as number of grid nodes along each dimension of a unit cube. "
         "The resulting system will have n*n*n unknowns. "
        )
        (
         "single-level,1",
         po::bool_switch()->default_value(false),
         "When specified, the AMG hierarchy is not constructed. "
         "Instead, the problem is solved using a single-level smoother as preconditioner. "
        )
        (
         "initial,x",
         po::value<double>()->default_value(0),
         "Value to use as initial approximation. "
        )
        (
         "output,o",
         po::value<string>(),
         "Output file. Will be saved in the MatrixMarket format. "
         "When omitted, the solution is not saved. "
        )
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    boost::property_tree::ptree prm;
    if (vm.count("prm-file")) {
        read_json(vm["prm-file"].as<string>(), prm);
    }

    if (vm.count("prm")) {
        for(const string &v : vm["prm"].as<vector<string> >()) {
            amgcl::put(prm, v);
        }
    }

    size_t rows;
    vector<ptrdiff_t> ptr, col;
    vector< std::complex<double> > val, rhs, null, x;

    if (vm.count("matrix")) {
        auto t = prof.scoped_tic("reading");

        string Afile = vm["matrix"].as<string>();
        bool   binary = vm["binary"].as<bool>();

        if (binary) {
            io::read_crs(Afile, rows, ptr, col, val);
        } else {
            size_t cols;
            std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);
            precondition(rows == cols, "Non-square system matrix");
        }

        if (vm.count("rhs")) {
            string bfile = vm["rhs"].as<string>();

            size_t n, m;
            if (binary) {
                io::read_dense(bfile, n, m, rhs);
            } else {
                std::tie(n, m) = io::mm_reader(bfile)(rhs);
            }

            precondition(n == rows && m == 1, "The RHS vector has wrong size");
        } else {
            rhs.resize(rows, 1.0);
        }

        if (vm.count("null")) {
            string nfile = vm["null"].as<string>();

            size_t m, nv;

            if (binary) {
                io::read_dense(nfile, m, nv, null);
            } else {
                std::tie(m, nv) = io::mm_reader(nfile)(null);
            }

            precondition(m == rows, "Near null-space vectors have wrong size");

            prm.put("precond.coarsening.nullspace.cols", nv);
            prm.put("precond.coarsening.nullspace.rows", rows);
            prm.put("precond.coarsening.nullspace.B",    &null[0]);
        }
    } else {
        auto t = prof.scoped_tic("assembling");
        rows = sample_problem(vm["size"].as<int>(), val, col, ptr, rhs);
    }

    x.resize(rows, vm["initial"].as<double>());

    size_t iters;
    double error;

    if (vm["single-level"].as<bool>())
        prm.put("precond.class", "relaxation");

    std::tie(iters, error) = solve<amgcl::runtime::preconditioner>(
            prm, rows, ptr, col, val, rhs, x);

    if (vm.count("output")) {
        auto t = prof.scoped_tic("write");
        amgcl::io::mm_write(vm["output"].as<string>(), &x[0], x.size());
    }

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << error << std::endl
              << prof << std::endl;
}
<|endoftext|>