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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $
Version:   $Revision: 16719 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

=========================================================================*/

#include "QmitkMITKSurfaceMaterialEditorView.h"

#include "mitkBaseRenderer.h"
#include "mitkNodePredicateDataType.h"
#include "mitkProperties.h"

#include "mitkShaderEnumProperty.h"
#include "mitkShaderRepository.h"

#include "QmitkDataStorageComboBox.h"
#include "QmitkStdMultiWidget.h"

#include <vtkSphereSource.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkRenderer.h>
#include <vtkTextActor.h>
#include <vtkRenderer.h>
#include <vtkTextProperty.h>
#include <vtkCoordinate.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkXMLMaterial.h>
#include <vtkXMLShader.h>
#include <vtkXMLDataElement.h>

#include <mitkVtkPropRenderer.h>
#include <mitkVtkLayerController.h>

#include <qmessagebox.h>

#include "mitkStandaloneDataStorage.h"

const std::string QmitkMITKSurfaceMaterialEditorView::VIEW_ID = "org.mitk.views.mitksurfacematerialeditor";

QmitkMITKSurfaceMaterialEditorView::QmitkMITKSurfaceMaterialEditorView()
: QmitkFunctionality(),
  m_Controls(NULL),
  m_MultiWidget(NULL)
{
  fixedProperties.push_back( "shader" );
  fixedProperties.push_back( "representation" );
  fixedProperties.push_back( "color" );
  fixedProperties.push_back( "opacity" );
  fixedProperties.push_back( "wireframe line width" );

  fixedProperties.push_back( "color_coefficient" );
  fixedProperties.push_back( "specular_color" );
  fixedProperties.push_back( "specular_coefficient" );
  fixedProperties.push_back( "specular_power" );
  fixedProperties.push_back( "interpolation" );

  shaderProperties.push_back( "shader" );
  shaderProperties.push_back( "representation" );
  shaderProperties.push_back( "color" );
  shaderProperties.push_back( "opacity" );
  shaderProperties.push_back( "wireframe line width" );

  observerAllocated = false;

  mitk::ShaderRepository::GetGlobalShaderRepository();
}

QmitkMITKSurfaceMaterialEditorView::~QmitkMITKSurfaceMaterialEditorView()
{
}

void QmitkMITKSurfaceMaterialEditorView::InitPreviewWindow()
{

  usedTimer=0;

  m_MaterialProperty = mitk::MaterialProperty::New();

  vtkSphereSource* sphereSource = vtkSphereSource::New();
  sphereSource->SetThetaResolution(25);
  sphereSource->SetPhiResolution(25);
  sphereSource->Update();

  vtkPolyData* sphere = sphereSource->GetOutput();

  m_Surface = mitk::Surface::New();
  m_Surface->SetVtkPolyData( sphere );

  m_DataTreeNode = mitk::DataTreeNode::New();
  m_DataTreeNode->SetData( m_Surface );

  m_DataTree = mitk::StandaloneDataStorage::New();

  m_DataTree->Add( m_DataTreeNode , (mitk::DataTreeNode *)0 );

  m_Controls->m_PreviewRenderWindow->GetRenderer()->SetDataStorage( m_DataTree );
  m_Controls->m_PreviewRenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D );

  sphereSource->Delete();

  //m_DataTreeNode->GetPropertyList();

  //m_Controls->m_ShaderPropertyList->setNode( m_DataTreeNode );
}

void QmitkMITKSurfaceMaterialEditorView::RefreshPropertiesList()
{
  mitk::DataTreeNode* SrcND = m_Controls->m_ImageSelector->GetSelectedNode();
  mitk::DataTreeNode* DstND = m_DataTreeNode;

  mitk::PropertyList* DstPL = DstND->GetPropertyList();

  m_Controls->m_ShaderPropertyList->SetPropertyList( 0 );

  DstPL->Clear();

  if(observerAllocated)
  {
    observedProperty->RemoveObserver( observerIndex );
    observerAllocated=false;
  }

  if(SrcND)
  {
    mitk::PropertyList* SrcPL = SrcND->GetPropertyList();

    mitk::ShaderEnumProperty::Pointer shaderEnum = dynamic_cast<mitk::ShaderEnumProperty*>(SrcPL->GetProperty("shader"));

    std::string shaderState = "fixed";

    if(shaderEnum.IsNotNull())
    {
      shaderState = shaderEnum->GetValueAsString();

      itk::MemberCommand<QmitkMITKSurfaceMaterialEditorView>::Pointer propertyModifiedCommand = itk::MemberCommand<QmitkMITKSurfaceMaterialEditorView>::New();
      propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange);
      observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);
      observedProperty = shaderEnum;
      observerAllocated=true;
    }

    printf("PROPERTIES SCAN BEGIN\n");

    for(mitk::PropertyList::PropertyMap::const_iterator it=SrcPL->GetMap()->begin(); it!=SrcPL->GetMap()->end(); it++)
    {
      std::string name=it->first;
      mitk::BaseProperty *p=it->second.first;

      printf("property '%s' found\n",name.c_str());

      if(shaderState.compare("fixed")==0)
      {
        if(std::find(fixedProperties.begin(), fixedProperties.end(), name) != fixedProperties.end())
        {
          DstPL->SetProperty(name,p);
        }
      }
      else
      {
        //if(std::find(shaderProperties.begin(), shaderProperties.end(), name) != shaderProperties.end())
        {
          DstPL->SetProperty(name,p);
        }
      }
    }

    printf("PROPERTIES SCAN END\n");
  }

  m_Controls->m_ShaderPropertyList->SetPropertyList( DstPL );
}

    /*

      // subscribe for property change events

      itk::MemberCommand<QmitkPropertiesTableModel>::Pointer propertyModifiedCommand =
         itk::MemberCommand<QmitkPropertiesTableModel>::New();
      propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified);

       m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);

            itk::MemberCommand<QmitkDataStorageTableModel>::Pointer propertyModifiedCommand = itk::MemberCommand<QmitkDataStorageTableModel>::New();
        propertyModifiedCommand->SetCallbackFunction(this, &QmitkDataStorageTableModel::PropertyModified);

        mitk::BaseProperty* visibilityProperty = (*it)->GetProperty("visible");
        if(visibilityProperty)
          m_PropertyModifiedObserverTags[visibilityProperty]
        = visibilityProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);

        mitk::BaseProperty* nameProperty = (*it)->GetProperty("name");
        if(nameProperty)
          m_PropertyModifiedObserverTags[nameProperty]
        = nameProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);

    for(mitk::PropertyList::PropertyMap::const_iterator it=m_PropertyList->GetMap()->begin()
      ; it!=m_PropertyList->GetMap()->end()
      ; it++)
    {
      // add relevant property column values
      m_PropertyListElements.push_back((*it));

      // subscribe for property change events

      itk::MemberCommand<QmitkPropertiesTableModel>::Pointer propertyModifiedCommand =
         itk::MemberCommand<QmitkPropertiesTableModel>::New();
      propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified);

       m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);*/

void QmitkMITKSurfaceMaterialEditorView::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkMITKSurfaceMaterialEditorViewControls;
    m_Controls->setupUi(parent);
    this->CreateConnections();

    // define data type for combobox
    m_Controls->m_ImageSelector->SetDataStorage( this->GetDefaultDataStorage() );
    m_Controls->m_ImageSelector->SetPredicate( mitk::NodePredicateDataType::New("Surface") );

	  InitPreviewWindow();

	  connect( m_Controls->m_ImageSelector, SIGNAL( OnSelectionChanged(const mitk::DataTreeNode::Pointer) ), this, SLOT( SurfaceSelected() ) );

    RefreshPropertiesList();

  }
}

void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
  m_MultiWidget = &stdMultiWidget;
}

void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetNotAvailable()
{
  m_MultiWidget = NULL;
}

void QmitkMITKSurfaceMaterialEditorView::CreateConnections()
{
  if ( m_Controls )
  {
//    connect( (QObject*)(m_Controls->m_Button), SIGNAL(clicked()), this, SLOT(DoSomething()) );
  }
}

void QmitkMITKSurfaceMaterialEditorView::Activated()
{
  QmitkFunctionality::Activated();
}

void QmitkMITKSurfaceMaterialEditorView::Deactivated()
{
  QmitkFunctionality::Deactivated();
}

void QmitkMITKSurfaceMaterialEditorView::SurfaceSelected()
{
  postRefresh();
}

void QmitkMITKSurfaceMaterialEditorView::shaderEnumChange(const itk::Object *caller, const itk::EventObject &event)
{
  postRefresh();
}

/*
  mitk::DataTreeNode* node = m_Controls->m_ImageSelector->GetSelectedNode();
  if (!node)
  {
    // Nothing selected. Inform the user and return
    QMessageBox::information( NULL, "Template functionality", "Please load and select an image before starting some action.");
    return;
  }

  // here we have a valid mitk::DataTreeNode

  // a node itself is not very useful, we need its data item (the image)
  mitk::BaseData* data = node->GetData();
  if (data)
  {
    // test if this data item is really an image or not (could also be a surface or something totally different)
    mitk::Image* image = dynamic_cast<mitk::Image*>( data );
    if (image)
    {
      std::string name("(no name)");
      node->GetName(name);

      QMessageBox::information( NULL, "Image processing",
                                QString( "Doing something to '%1'" ).arg(name.c_str()) );

      // at this point anything can be done using the mitk::Image image.
    }
  }*/

void QmitkMITKSurfaceMaterialEditorView::postRefresh()
{
  if(usedTimer)
    return;

  usedTimer=startTimer(0);

  printf("SHADERENUM POSTREFRESH\n");
}

void QmitkMITKSurfaceMaterialEditorView::timerEvent( QTimerEvent *e )
{
  if(usedTimer!=e->timerId())
  {
    printf("INTERNAL ERROR: usedTimer[%d] != timerId[%d]\n",usedTimer,e->timerId());
  }

  if(usedTimer)
  {
    killTimer(usedTimer);
    usedTimer=0;
  }

  printf("GOT TIMER EVENT\n");

  RefreshPropertiesList();
}<commit_msg>FIX (#2292): replaced printf by LOG_INFO<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $
Version:   $Revision: 16719 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information.

=========================================================================*/

#include "QmitkMITKSurfaceMaterialEditorView.h"

#include "mitkBaseRenderer.h"
#include "mitkNodePredicateDataType.h"
#include "mitkProperties.h"

#include "mitkShaderEnumProperty.h"
#include "mitkShaderRepository.h"

#include "QmitkDataStorageComboBox.h"
#include "QmitkStdMultiWidget.h"

#include <vtkSphereSource.h>
#include <vtkPolyData.h>
#include <vtkCamera.h>
#include <vtkRenderer.h>
#include <vtkTextActor.h>
#include <vtkRenderer.h>
#include <vtkTextProperty.h>
#include <vtkCoordinate.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkXMLMaterial.h>
#include <vtkXMLShader.h>
#include <vtkXMLDataElement.h>

#include <mitkVtkPropRenderer.h>
#include <mitkVtkLayerController.h>

#include <qmessagebox.h>

#include "mitkStandaloneDataStorage.h"

const std::string QmitkMITKSurfaceMaterialEditorView::VIEW_ID = "org.mitk.views.mitksurfacematerialeditor";

QmitkMITKSurfaceMaterialEditorView::QmitkMITKSurfaceMaterialEditorView()
: QmitkFunctionality(),
  m_Controls(NULL),
  m_MultiWidget(NULL)
{
  fixedProperties.push_back( "shader" );
  fixedProperties.push_back( "representation" );
  fixedProperties.push_back( "color" );
  fixedProperties.push_back( "opacity" );
  fixedProperties.push_back( "wireframe line width" );

  fixedProperties.push_back( "color_coefficient" );
  fixedProperties.push_back( "specular_color" );
  fixedProperties.push_back( "specular_coefficient" );
  fixedProperties.push_back( "specular_power" );
  fixedProperties.push_back( "interpolation" );

  shaderProperties.push_back( "shader" );
  shaderProperties.push_back( "representation" );
  shaderProperties.push_back( "color" );
  shaderProperties.push_back( "opacity" );
  shaderProperties.push_back( "wireframe line width" );

  observerAllocated = false;

  mitk::ShaderRepository::GetGlobalShaderRepository();
}

QmitkMITKSurfaceMaterialEditorView::~QmitkMITKSurfaceMaterialEditorView()
{
}

void QmitkMITKSurfaceMaterialEditorView::InitPreviewWindow()
{

  usedTimer=0;

  m_MaterialProperty = mitk::MaterialProperty::New();

  vtkSphereSource* sphereSource = vtkSphereSource::New();
  sphereSource->SetThetaResolution(25);
  sphereSource->SetPhiResolution(25);
  sphereSource->Update();

  vtkPolyData* sphere = sphereSource->GetOutput();

  m_Surface = mitk::Surface::New();
  m_Surface->SetVtkPolyData( sphere );

  m_DataTreeNode = mitk::DataTreeNode::New();
  m_DataTreeNode->SetData( m_Surface );

  m_DataTree = mitk::StandaloneDataStorage::New();

  m_DataTree->Add( m_DataTreeNode , (mitk::DataTreeNode *)0 );

  m_Controls->m_PreviewRenderWindow->GetRenderer()->SetDataStorage( m_DataTree );
  m_Controls->m_PreviewRenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D );

  sphereSource->Delete();

  //m_DataTreeNode->GetPropertyList();

  //m_Controls->m_ShaderPropertyList->setNode( m_DataTreeNode );
}

void QmitkMITKSurfaceMaterialEditorView::RefreshPropertiesList()
{
  mitk::DataTreeNode* SrcND = m_Controls->m_ImageSelector->GetSelectedNode();
  mitk::DataTreeNode* DstND = m_DataTreeNode;

  mitk::PropertyList* DstPL = DstND->GetPropertyList();

  m_Controls->m_ShaderPropertyList->SetPropertyList( 0 );

  DstPL->Clear();

  if(observerAllocated)
  {
    observedProperty->RemoveObserver( observerIndex );
    observerAllocated=false;
  }

  if(SrcND)
  {
    mitk::PropertyList* SrcPL = SrcND->GetPropertyList();

    mitk::ShaderEnumProperty::Pointer shaderEnum = dynamic_cast<mitk::ShaderEnumProperty*>(SrcPL->GetProperty("shader"));

    std::string shaderState = "fixed";

    if(shaderEnum.IsNotNull())
    {
      shaderState = shaderEnum->GetValueAsString();

      itk::MemberCommand<QmitkMITKSurfaceMaterialEditorView>::Pointer propertyModifiedCommand = itk::MemberCommand<QmitkMITKSurfaceMaterialEditorView>::New();
      propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange);
      observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);
      observedProperty = shaderEnum;
      observerAllocated=true;
    }

    LOG_INFO << "PROPERTIES SCAN BEGIN";

    for(mitk::PropertyList::PropertyMap::const_iterator it=SrcPL->GetMap()->begin(); it!=SrcPL->GetMap()->end(); it++)
    {
      std::string name=it->first;
      mitk::BaseProperty *p=it->second.first;

      // LOG_INFO << "property '" << name << "' found";

      if(shaderState.compare("fixed")==0)
      {
        if(std::find(fixedProperties.begin(), fixedProperties.end(), name) != fixedProperties.end())
        {
          DstPL->SetProperty(name,p);
        }
      }
      else
      {
        //if(std::find(shaderProperties.begin(), shaderProperties.end(), name) != shaderProperties.end())
        {
          DstPL->SetProperty(name,p);
        }
      }
    }

    LOG_INFO << "PROPERTIES SCAN END";
  }

  m_Controls->m_ShaderPropertyList->SetPropertyList( DstPL );
}

    /*

      // subscribe for property change events

      itk::MemberCommand<QmitkPropertiesTableModel>::Pointer propertyModifiedCommand =
         itk::MemberCommand<QmitkPropertiesTableModel>::New();
      propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified);

       m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);

            itk::MemberCommand<QmitkDataStorageTableModel>::Pointer propertyModifiedCommand = itk::MemberCommand<QmitkDataStorageTableModel>::New();
        propertyModifiedCommand->SetCallbackFunction(this, &QmitkDataStorageTableModel::PropertyModified);

        mitk::BaseProperty* visibilityProperty = (*it)->GetProperty("visible");
        if(visibilityProperty)
          m_PropertyModifiedObserverTags[visibilityProperty]
        = visibilityProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);

        mitk::BaseProperty* nameProperty = (*it)->GetProperty("name");
        if(nameProperty)
          m_PropertyModifiedObserverTags[nameProperty]
        = nameProperty->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);

    for(mitk::PropertyList::PropertyMap::const_iterator it=m_PropertyList->GetMap()->begin()
      ; it!=m_PropertyList->GetMap()->end()
      ; it++)
    {
      // add relevant property column values
      m_PropertyListElements.push_back((*it));

      // subscribe for property change events

      itk::MemberCommand<QmitkPropertiesTableModel>::Pointer propertyModifiedCommand =
         itk::MemberCommand<QmitkPropertiesTableModel>::New();
      propertyModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified);

       m_PropertyModifiedObserverTags[it->first] = it->second.first->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);*/

void QmitkMITKSurfaceMaterialEditorView::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkMITKSurfaceMaterialEditorViewControls;
    m_Controls->setupUi(parent);
    this->CreateConnections();

    // define data type for combobox
    m_Controls->m_ImageSelector->SetDataStorage( this->GetDefaultDataStorage() );
    m_Controls->m_ImageSelector->SetPredicate( mitk::NodePredicateDataType::New("Surface") );

	  InitPreviewWindow();

	  connect( m_Controls->m_ImageSelector, SIGNAL( OnSelectionChanged(const mitk::DataTreeNode::Pointer) ), this, SLOT( SurfaceSelected() ) );

    RefreshPropertiesList();

  }
}

void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
  m_MultiWidget = &stdMultiWidget;
}

void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetNotAvailable()
{
  m_MultiWidget = NULL;
}

void QmitkMITKSurfaceMaterialEditorView::CreateConnections()
{
  if ( m_Controls )
  {
//    connect( (QObject*)(m_Controls->m_Button), SIGNAL(clicked()), this, SLOT(DoSomething()) );
  }
}

void QmitkMITKSurfaceMaterialEditorView::Activated()
{
  QmitkFunctionality::Activated();
}

void QmitkMITKSurfaceMaterialEditorView::Deactivated()
{
  QmitkFunctionality::Deactivated();
}

void QmitkMITKSurfaceMaterialEditorView::SurfaceSelected()
{
  postRefresh();
}

void QmitkMITKSurfaceMaterialEditorView::shaderEnumChange(const itk::Object *caller, const itk::EventObject &event)
{
  postRefresh();
}

/*
  mitk::DataTreeNode* node = m_Controls->m_ImageSelector->GetSelectedNode();
  if (!node)
  {
    // Nothing selected. Inform the user and return
    QMessageBox::information( NULL, "Template functionality", "Please load and select an image before starting some action.");
    return;
  }

  // here we have a valid mitk::DataTreeNode

  // a node itself is not very useful, we need its data item (the image)
  mitk::BaseData* data = node->GetData();
  if (data)
  {
    // test if this data item is really an image or not (could also be a surface or something totally different)
    mitk::Image* image = dynamic_cast<mitk::Image*>( data );
    if (image)
    {
      std::string name("(no name)");
      node->GetName(name);

      QMessageBox::information( NULL, "Image processing",
                                QString( "Doing something to '%1'" ).arg(name.c_str()) );

      // at this point anything can be done using the mitk::Image image.
    }
  }*/

void QmitkMITKSurfaceMaterialEditorView::postRefresh()
{
  if(usedTimer)
    return;

  usedTimer=startTimer(0);
}

void QmitkMITKSurfaceMaterialEditorView::timerEvent( QTimerEvent *e )
{
  if(usedTimer!=e->timerId())
  {
    LOG_ERROR << "INTERNAL ERROR: usedTimer[" << usedTimer << "] != timerId[" << e->timerId() << "]";
  }

  if(usedTimer)
  {
    killTimer(usedTimer);
    usedTimer=0;
  }

  RefreshPropertiesList();
}<|endoftext|>


<commit_before>// webadmin.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include "plugin_utils.h"
#include "plugin_HTTP.h"
#include <fstream>
#include <cstring>
#include <algorithm>

class WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass
{
public:
  WebAdmin();
  virtual const char * getVDir ( void ){return "webadmin";}
  virtual const char * getDescription ( void ){return "Server Administration (Login Required)";}

  void init (const char *tDir);

  virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );

  // from TemplateCallbackClass
  virtual void keyCallback (std::string &data, const std::string &key);
  virtual bool loopCallback (const std::string &key);
  virtual bool ifCallback (const std::string &key);

private:
  size_t loopPos;
  std::map<std::string,std::string> templateVars;

  typedef void (WebAdmin::*page_callback)(const HTTPRequest &);
  std::map<std::string,page_callback> controllers;
  std::vector<std::string> pagenames;

  void mainPageCallback (const HTTPRequest &request);
  void WebAdmin::banlistPageCallback (const HTTPRequest &request);

  bz_APIIntList players;
};

WebAdmin *webAdmin = NULL;

BZ_GET_PLUGIN_VERSION

BZF_PLUGIN_CALL int bz_Load(const char* commandLine)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = new WebAdmin;
  webAdmin->init(commandLine);

  bz_debugMessage(4,"webadmin plugin loaded");
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload(void)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = NULL;

  bz_debugMessage(4,"webadmin plugin unloaded");
  return 0;
}

WebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)
{
	registerVDir();

	// add new pages here
	controllers["main"] = &WebAdmin::mainPageCallback;
	controllers["banlist"] = &WebAdmin::banlistPageCallback;
	controllers["helpmsg"] = NULL;
	controllers["group"] = NULL;

  std::map<std::string,page_callback>::iterator pair;
  for(pair = controllers.begin(); pair != controllers.end(); pair++)
    pagenames.push_back(pair->first);
}

void WebAdmin::init(const char* cmdln)
{
  templateSystem.addSearchPath(cmdln ? cmdln : "./");

  // level one has admin perms
  addPermToLevel(1,"ADMIN");

  templateSystem.addIF("IsCurrentPage",this);
  templateSystem.addIF("Error",this);

  templateSystem.addKey("Error",this);
  templateSystem.addKey("Callsign",this);
  templateSystem.addKey("BannedUser",this);
  templateSystem.addKey("PageName",this);

  templateSystem.addLoop("Navigation",this);
  templateSystem.addLoop("Players",this);
  templateSystem.addLoop("IPBanList",this);
  templateSystem.addLoop("IDBanList",this);

  templateSystem.setPluginName("webadmin", getBaseURL().c_str());

  setupAuth();
}

// event hook for [$Something] in templates
void WebAdmin::keyCallback (std::string &data, const std::string &key)
{
  const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);
  if (pair != templateVars.end())
		data = pair->second;
}

// condition check for [*START] in templates
bool WebAdmin::loopCallback (const std::string &key)
{
  if (key == "players") {
    if (!loopPos) bz_getPlayerIndexList(&players);
    else if (loopPos < players.size()) {
      templateVars["playerid"] = players[loopPos];
      templateVars["callsign"] = bz_getPlayerCallsign(players[loopPos++]);
      return true;
    } else {
      players.clear();
      return loopPos = 0;
    }
  } else if (key == "navigation") {
    if (loopPos < pagenames.size()) {
      templateVars["pagename"] = pagenames[loopPos++];
      return true;
    } else return loopPos = 0;
  } else if (key == "permissions") {
    if (loopPos < bzu_standardPerms().size()) {
      templateVars["permission"] = bzu_standardPerms()[loopPos++];
      return true;
    } else return loopPos = 0;
  } else return false;
}

// condition check for [?IF] in templates
bool WebAdmin::ifCallback (const std::string &key)
{
  if (key == "iscurrentpage")
    return templateVars["pagename"] == templateVars["currentpage"];
  return false;
}

bool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )
{
  std::map<std::string,page_callback>::iterator pair;
  size_t last;
  std::string pagename = request.resource;

  switch(level) {
  case 1:
  case VERIFIED:
    last = pagename.size()-1;
    if (pagename[last] == '/') pagename.erase(last);
    if (pagename.empty()) pagename = "main";
    pair = controllers.find(pagename);
    if (pair != controllers.end()) {
      (this->*pair->second)(request);
      if (!templateSystem.processTemplateFile(reply.body, (pagename + ".tmpl").c_str())) {
        reply.returnCode = HTTPReply::e500ServerError;
          if (!templateSystem.processTemplateFile(reply.body, "500.tmpl"))
            reply.body = format("Missing template: %s.tmpl", pagename.c_str());
        }
    } else {
      reply.returnCode = HTTPReply::e404NotFound;
      if (!templateSystem.processTemplateFile(reply.body, "404.tmpl"))
        reply.body = format("No such resource: %s", pagename.c_str());
    }
    break;
  //reply.body = format("Not authenticated(Verified) sessionID %d",request.sessionID);
  default:
    reply.body = format("Not authenticated sessionID %d",request.sessionID);
  }

  reply.docType = HTTPReply::eHTML;

  templateVars.clear();
  return true;
}

void WebAdmin::mainPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> players;
  if (!request.getParam("players", players)) return;
  std::string dummy, reason;
  bool notify = request.getParam("notify", dummy);
  request.getParam("reason", reason);
  std::vector<std::string>::iterator i;
  if (request.getParam("kick", dummy))
    for (i = players.begin(); i != players.end(); i++)
      bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);
  else if (request.getParam("ipban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());
    }
  }
  else if (request.getParam("idban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());
    }
  }
}

void WebAdmin::banlistPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> banRemovals;
  std::vector<std::string>::iterator i;
  if (request.getParam("delip", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IPUnbanUser(i->c_str());
  if (request.getParam("delid", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IDUnbanUser(i->c_str());

}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=2 expandtab
<commit_msg>compile error fix on linux<commit_after>// webadmin.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include "plugin_utils.h"
#include "plugin_HTTP.h"
#include <fstream>
#include <cstring>
#include <algorithm>

class WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass
{
public:
  WebAdmin();
  virtual const char * getVDir ( void ){return "webadmin";}
  virtual const char * getDescription ( void ){return "Server Administration (Login Required)";}

  void init (const char *tDir);

  virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );

  // from TemplateCallbackClass
  virtual void keyCallback (std::string &data, const std::string &key);
  virtual bool loopCallback (const std::string &key);
  virtual bool ifCallback (const std::string &key);

private:
  size_t loopPos;
  std::map<std::string,std::string> templateVars;

  typedef void (WebAdmin::*page_callback)(const HTTPRequest &);
  std::map<std::string,page_callback> controllers;
  std::vector<std::string> pagenames;

  void mainPageCallback (const HTTPRequest &request);
  void banlistPageCallback (const HTTPRequest &request);

  bz_APIIntList players;
};

WebAdmin *webAdmin = NULL;

BZ_GET_PLUGIN_VERSION

BZF_PLUGIN_CALL int bz_Load(const char* commandLine)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = new WebAdmin;
  webAdmin->init(commandLine);

  bz_debugMessage(4,"webadmin plugin loaded");
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload(void)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = NULL;

  bz_debugMessage(4,"webadmin plugin unloaded");
  return 0;
}

WebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)
{
	registerVDir();

	// add new pages here
	controllers["main"] = &WebAdmin::mainPageCallback;
	controllers["banlist"] = &WebAdmin::banlistPageCallback;
	controllers["helpmsg"] = NULL;
	controllers["group"] = NULL;

  std::map<std::string,page_callback>::iterator pair;
  for(pair = controllers.begin(); pair != controllers.end(); pair++)
    pagenames.push_back(pair->first);
}

void WebAdmin::init(const char* cmdln)
{
  templateSystem.addSearchPath(cmdln ? cmdln : "./");

  // level one has admin perms
  addPermToLevel(1,"ADMIN");

  templateSystem.addIF("IsCurrentPage",this);
  templateSystem.addIF("Error",this);

  templateSystem.addKey("Error",this);
  templateSystem.addKey("Callsign",this);
  templateSystem.addKey("BannedUser",this);
  templateSystem.addKey("PageName",this);

  templateSystem.addLoop("Navigation",this);
  templateSystem.addLoop("Players",this);
  templateSystem.addLoop("IPBanList",this);
  templateSystem.addLoop("IDBanList",this);

  templateSystem.setPluginName("webadmin", getBaseURL().c_str());

  setupAuth();
}

// event hook for [$Something] in templates
void WebAdmin::keyCallback (std::string &data, const std::string &key)
{
  const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);
  if (pair != templateVars.end())
		data = pair->second;
}

// condition check for [*START] in templates
bool WebAdmin::loopCallback (const std::string &key)
{
  if (key == "players") {
    if (!loopPos) bz_getPlayerIndexList(&players);
    else if (loopPos < players.size()) {
      templateVars["playerid"] = players[loopPos];
      templateVars["callsign"] = bz_getPlayerCallsign(players[loopPos++]);
      return true;
    } else {
      players.clear();
      return loopPos = 0;
    }
  } else if (key == "navigation") {
    if (loopPos < pagenames.size()) {
      templateVars["pagename"] = pagenames[loopPos++];
      return true;
    } else return loopPos = 0;
  } else if (key == "permissions") {
    if (loopPos < bzu_standardPerms().size()) {
      templateVars["permission"] = bzu_standardPerms()[loopPos++];
      return true;
    } else return loopPos = 0;
  } else return false;
}

// condition check for [?IF] in templates
bool WebAdmin::ifCallback (const std::string &key)
{
  if (key == "iscurrentpage")
    return templateVars["pagename"] == templateVars["currentpage"];
  return false;
}

bool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )
{
  std::map<std::string,page_callback>::iterator pair;
  size_t last;
  std::string pagename = request.resource;

  switch(level) {
  case 1:
  case VERIFIED:
    last = pagename.size()-1;
    if (pagename[last] == '/') pagename.erase(last);
    if (pagename.empty()) pagename = "main";
    pair = controllers.find(pagename);
    if (pair != controllers.end()) {
      (this->*pair->second)(request);
      if (!templateSystem.processTemplateFile(reply.body, (pagename + ".tmpl").c_str())) {
        reply.returnCode = HTTPReply::e500ServerError;
          if (!templateSystem.processTemplateFile(reply.body, "500.tmpl"))
            reply.body = format("Missing template: %s.tmpl", pagename.c_str());
        }
    } else {
      reply.returnCode = HTTPReply::e404NotFound;
      if (!templateSystem.processTemplateFile(reply.body, "404.tmpl"))
        reply.body = format("No such resource: %s", pagename.c_str());
    }
    break;
  //reply.body = format("Not authenticated(Verified) sessionID %d",request.sessionID);
  default:
    reply.body = format("Not authenticated sessionID %d",request.sessionID);
  }

  reply.docType = HTTPReply::eHTML;

  templateVars.clear();
  return true;
}

void WebAdmin::mainPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> players;
  if (!request.getParam("players", players)) return;
  std::string dummy, reason;
  bool notify = request.getParam("notify", dummy);
  request.getParam("reason", reason);
  std::vector<std::string>::iterator i;
  if (request.getParam("kick", dummy))
    for (i = players.begin(); i != players.end(); i++)
      bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);
  else if (request.getParam("ipban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());
    }
  }
  else if (request.getParam("idban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());
    }
  }
}

void WebAdmin::banlistPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> banRemovals;
  std::vector<std::string>::iterator i;
  if (request.getParam("delip", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IPUnbanUser(i->c_str());
  if (request.getParam("delid", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IDUnbanUser(i->c_str());

}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=2 expandtab
<|endoftext|>


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

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include "image_tools/options.hpp"

bool find_command_option(const std::vector<std::string> & args, const std::string & option)
{
  return std::find(args.begin(), args.end(), option) != args.end();
}

std::string get_command_option(const std::vector<std::string> & args, const std::string & option)
{
  auto it = std::find(args.begin(), args.end(), option);
  if (it != args.end() && ++it != args.end()) {
    return *it;
  }
  return std::string();
}

bool get_flag_option(const std::vector<std::string> & args, const std::string & option)
{
  auto it = std::find(args.begin(), args.end(), option);
  if (it != args.end()) {
    return true;
  }
  return false;
}

bool parse_command_options(
  int argc, char ** argv, size_t * depth,
  rmw_qos_reliability_policy_t * reliability_policy,
  rmw_qos_history_policy_t * history_policy, bool * show_camera,
  double * freq, size_t * width, size_t * height, bool * burger_mode,
  std::string * topic)
{
  std::vector<std::string> args(argv, argv + argc);

  if (find_command_option(args, "-h")) {
    std::stringstream ss;
    ss << "Usage:" << std::endl;
    ss << " -h: This message." << std::endl;
    ss << " -r: Reliability QoS setting:" << std::endl;
    ss << "    0 - best effort" << std::endl;
    ss << "    1 - reliable (default)" << std::endl;
    ss << " -d: Depth of the queue: only honored if used together with 'keep last'. " <<
      "10 (default)" << std::endl;
    ss << " -f: Publish frequency in Hz. 30 (default)" << std::endl;
    ss << " -k: History QoS setting:" << std::endl;
    ss << "    0 - only store up to N samples, configurable via the queue depth (default)" <<
      std::endl;
    ss << "    1 - keep all the samples" << std::endl;
    if (show_camera != nullptr) {
      ss << " -s: Camera stream:" << std::endl;
      ss << "    0 - Do not show the camera stream" << std::endl;
      ss << "    1 - Show the camera stream" << std::endl;
    }
    if (width != nullptr && height != nullptr) {
      ss << " -x WIDTH and -y HEIGHT. Resolution. " << std::endl;
      ss << "    Please type v4l2-ctl --list-formats-ext " << std::endl;
      ss << "    to obtain a list of valid values." << std::endl;
    }
    if (burger_mode != nullptr) {
      ss << " -b: produce images of burgers rather than connecting to a camera" << std::endl;
    }
    if (topic != nullptr) {
      ss << " -t TOPIC: use topic TOPIC instead of the default" << std::endl;
    }
    std::cout << ss.str();
    return false;
  }

  auto show_camera_str = get_command_option(args, "-s");
  if (!show_camera_str.empty()) {
    *show_camera = std::stoul(show_camera_str.c_str()) != 0 ? true : false;
  }

  auto depth_str = get_command_option(args, "-d");
  if (!depth_str.empty()) {
    *depth = std::stoul(depth_str.c_str());
  }

  if (freq != nullptr) {
    auto freq_str = get_command_option(args, "-f");
    if (!freq_str.empty()) {
      *freq = std::stod(freq_str.c_str());
    }
  }

  auto reliability_str = get_command_option(args, "-r");
  if (!reliability_str.empty()) {
    unsigned int r = std::stoul(reliability_str.c_str());
    *reliability_policy =
      r ? RMW_QOS_POLICY_RELIABILITY_RELIABLE : RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
  }

  auto history_str = get_command_option(args, "-k");
  if (!history_str.empty()) {
    unsigned int r = std::stoul(history_str.c_str());
    *history_policy = r ? RMW_QOS_POLICY_HISTORY_KEEP_ALL : RMW_QOS_POLICY_HISTORY_KEEP_LAST;
  }

  if (width != nullptr && height != nullptr) {
    auto width_str = get_command_option(args, "-x");
    auto height_str = get_command_option(args, "-y");
    if (!width_str.empty() && !height_str.empty()) {
      *width = std::stoul(width_str.c_str());
      *height = std::stoul(height_str.c_str());
    }
  }

  if (burger_mode) {
    *burger_mode = get_flag_option(args, "-b");
  }

  if (topic != nullptr) {
    std::string tmptopic = get_command_option(args, "-t");
    if (!tmptopic.empty()) {
      *topic = tmptopic;
    }
  }

  return true;
}
<commit_msg>Do not show freq parameter on help when not necessary (#296)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include "image_tools/options.hpp"

bool find_command_option(const std::vector<std::string> & args, const std::string & option)
{
  return std::find(args.begin(), args.end(), option) != args.end();
}

std::string get_command_option(const std::vector<std::string> & args, const std::string & option)
{
  auto it = std::find(args.begin(), args.end(), option);
  if (it != args.end() && ++it != args.end()) {
    return *it;
  }
  return std::string();
}

bool get_flag_option(const std::vector<std::string> & args, const std::string & option)
{
  auto it = std::find(args.begin(), args.end(), option);
  if (it != args.end()) {
    return true;
  }
  return false;
}

bool parse_command_options(
  int argc, char ** argv, size_t * depth,
  rmw_qos_reliability_policy_t * reliability_policy,
  rmw_qos_history_policy_t * history_policy, bool * show_camera,
  double * freq, size_t * width, size_t * height, bool * burger_mode,
  std::string * topic)
{
  std::vector<std::string> args(argv, argv + argc);

  if (find_command_option(args, "-h")) {
    std::stringstream ss;
    ss << "Usage:" << std::endl;
    ss << " -h: This message." << std::endl;
    ss << " -r: Reliability QoS setting:" << std::endl;
    ss << "    0 - best effort" << std::endl;
    ss << "    1 - reliable (default)" << std::endl;
    ss << " -d: Depth of the queue: only honored if used together with 'keep last'. " <<
      "10 (default)" << std::endl;
    if (freq != nullptr) {
      ss << " -f: Publish frequency in Hz. 30 (default)" << std::endl;
    }
    ss << " -k: History QoS setting:" << std::endl;
    ss << "    0 - only store up to N samples, configurable via the queue depth (default)" <<
      std::endl;
    ss << "    1 - keep all the samples" << std::endl;
    if (show_camera != nullptr) {
      ss << " -s: Camera stream:" << std::endl;
      ss << "    0 - Do not show the camera stream" << std::endl;
      ss << "    1 - Show the camera stream" << std::endl;
    }
    if (width != nullptr && height != nullptr) {
      ss << " -x WIDTH and -y HEIGHT. Resolution. " << std::endl;
      ss << "    Please type v4l2-ctl --list-formats-ext " << std::endl;
      ss << "    to obtain a list of valid values." << std::endl;
    }
    if (burger_mode != nullptr) {
      ss << " -b: produce images of burgers rather than connecting to a camera" << std::endl;
    }
    if (topic != nullptr) {
      ss << " -t TOPIC: use topic TOPIC instead of the default" << std::endl;
    }
    std::cout << ss.str();
    return false;
  }

  auto show_camera_str = get_command_option(args, "-s");
  if (!show_camera_str.empty()) {
    *show_camera = std::stoul(show_camera_str.c_str()) != 0 ? true : false;
  }

  auto depth_str = get_command_option(args, "-d");
  if (!depth_str.empty()) {
    *depth = std::stoul(depth_str.c_str());
  }

  if (freq != nullptr) {
    auto freq_str = get_command_option(args, "-f");
    if (!freq_str.empty()) {
      *freq = std::stod(freq_str.c_str());
    }
  }

  auto reliability_str = get_command_option(args, "-r");
  if (!reliability_str.empty()) {
    unsigned int r = std::stoul(reliability_str.c_str());
    *reliability_policy =
      r ? RMW_QOS_POLICY_RELIABILITY_RELIABLE : RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
  }

  auto history_str = get_command_option(args, "-k");
  if (!history_str.empty()) {
    unsigned int r = std::stoul(history_str.c_str());
    *history_policy = r ? RMW_QOS_POLICY_HISTORY_KEEP_ALL : RMW_QOS_POLICY_HISTORY_KEEP_LAST;
  }

  if (width != nullptr && height != nullptr) {
    auto width_str = get_command_option(args, "-x");
    auto height_str = get_command_option(args, "-y");
    if (!width_str.empty() && !height_str.empty()) {
      *width = std::stoul(width_str.c_str());
      *height = std::stoul(height_str.c_str());
    }
  }

  if (burger_mode) {
    *burger_mode = get_flag_option(args, "-b");
  }

  if (topic != nullptr) {
    std::string tmptopic = get_command_option(args, "-t");
    if (!tmptopic.empty()) {
      *topic = tmptopic;
    }
  }

  return true;
}
<|endoftext|>


<commit_before>// Implementations for SPQR/KLU/CHOLMOD, i.e. "SuiteSparse" implementation

#include <iostream>
#include <cassert>

#include "suitesparse_shim.hpp"

namespace SuiteSparse {

// definition of specializations

template<>
common_wrapper<cholmod_common>::common_wrapper() {
    cholmod_l_start(&common_);
}

template<>
common_wrapper<cholmod_common>::~common_wrapper() {
    cholmod_l_finish(&common_);
}

template<>
common_wrapper<klu_l_common>::common_wrapper() {
    klu_l_defaults(&common_);
}

// sparse matrix constructors
Shim::sparsemat_t::sparsemat_t( ss_shared_ptr<cholmod_sparse> mat )
    : mat_(mat) {}

Shim::sparsemat_t::sparsemat_t( ss_unique_ptr<cholmod_sparse, cholmod_common> && mat )
    : mat_(std::move(mat)) {}

std::ostream&
operator<< ( std::ostream& os, Shim::sparsemat_t const& mat ) {
    // only works for cout/stdout
    assert( &os == &std::cout );
    cholmod_l_write_sparse( stdout, mat.wrapped().get(), nullptr, nullptr,
                            spqr_common.get() );
    fflush(stdout);
    return os;
}

// definitions for calculation methods

// LU
Shim::lu_t::lu_t(Shim::sparsemat_t const& mat)
    : KS_(make_ss_unique_ptr(
              klu_l_analyze(  mat.wrapped()->nrow,
                              reinterpret_cast<long*>(mat.wrapped()->p),
                              reinterpret_cast<long*>(mat.wrapped()->i),
                              klu_common.get() ),
              klu_common)),
      KN_(make_ss_unique_ptr(
              klu_l_factor(   reinterpret_cast<long*>(mat.wrapped()->p),
                              reinterpret_cast<long*>(mat.wrapped()->i),
                              reinterpret_cast<double*>(mat.wrapped()->x),
                              KS_.get(),
                              klu_common.get()),
              klu_common))
{}

Shim::sparsemat_t
Shim::lu_t::solve(sparsemat_t const& B) const {
    // convert B (right hand side) to a dense matrix
    auto Bdense = make_ss_unique_ptr(
        cholmod_l_sparse_to_dense( B.wrapped().get(), spqr_common.get() ),
        spqr_common);

    klu_l_solve ( KS_.get(),          // Symbolic factorization
                  KN_.get(),          // Numeric
                  B.wrapped()->nrow,
                  B.wrapped()->ncol,
                  reinterpret_cast<double*>(Bdense->x),
                  klu_common.get() );

    // convert to cholmod_sparse
    return make_ss_unique_ptr( cholmod_l_dense_to_sparse( Bdense.get(), 1, spqr_common.get() ),
                               spqr_common);
}

// QR
Shim::qr_t::qr_t( sparsemat_t const & mat ) {
    cholmod_sparse * Q;   // results
    cholmod_sparse * R;
    // This is kind of ugly :( SuiteSparseQR returns two pointers by reference
    // Not clear what happens if it can allocate one but not the other
    assert( SuiteSparseQR<double> ( SPQR_ORDERING_DEFAULT, SPQR_DEFAULT_TOL, 3,
                                    mat.wrapped().get(),
                                    &Q, &R, nullptr, spqr_common.get() ) >= 0);

    // Now we can finally take ownership
    Q_ =           make_ss_shared_ptr( Q, spqr_common );
    R_ = std::move(make_ss_unique_ptr( R, spqr_common ));
}

Shim::sparsemat_t
Shim::qr_t::Q() const {
    return Q_;
}

}
<commit_msg>Eliminate "pessimizing move" detected by Clang<commit_after>// Implementations for SPQR/KLU/CHOLMOD, i.e. "SuiteSparse" implementation

#include <iostream>
#include <cassert>

#include "suitesparse_shim.hpp"

namespace SuiteSparse {

// definition of specializations

template<>
common_wrapper<cholmod_common>::common_wrapper() {
    cholmod_l_start(&common_);
}

template<>
common_wrapper<cholmod_common>::~common_wrapper() {
    cholmod_l_finish(&common_);
}

template<>
common_wrapper<klu_l_common>::common_wrapper() {
    klu_l_defaults(&common_);
}

// sparse matrix constructors
Shim::sparsemat_t::sparsemat_t( ss_shared_ptr<cholmod_sparse> mat )
    : mat_(mat) {}

Shim::sparsemat_t::sparsemat_t( ss_unique_ptr<cholmod_sparse, cholmod_common> && mat )
    : mat_(std::move(mat)) {}

std::ostream&
operator<< ( std::ostream& os, Shim::sparsemat_t const& mat ) {
    // only works for cout/stdout
    assert( &os == &std::cout );
    cholmod_l_write_sparse( stdout, mat.wrapped().get(), nullptr, nullptr,
                            spqr_common.get() );
    fflush(stdout);
    return os;
}

// definitions for calculation methods

// LU
Shim::lu_t::lu_t(Shim::sparsemat_t const& mat)
    : KS_(make_ss_unique_ptr(
              klu_l_analyze(  mat.wrapped()->nrow,
                              reinterpret_cast<long*>(mat.wrapped()->p),
                              reinterpret_cast<long*>(mat.wrapped()->i),
                              klu_common.get() ),
              klu_common)),
      KN_(make_ss_unique_ptr(
              klu_l_factor(   reinterpret_cast<long*>(mat.wrapped()->p),
                              reinterpret_cast<long*>(mat.wrapped()->i),
                              reinterpret_cast<double*>(mat.wrapped()->x),
                              KS_.get(),
                              klu_common.get()),
              klu_common))
{}

Shim::sparsemat_t
Shim::lu_t::solve(sparsemat_t const& B) const {
    // convert B (right hand side) to a dense matrix
    auto Bdense = make_ss_unique_ptr(
        cholmod_l_sparse_to_dense( B.wrapped().get(), spqr_common.get() ),
        spqr_common);

    klu_l_solve ( KS_.get(),          // Symbolic factorization
                  KN_.get(),          // Numeric
                  B.wrapped()->nrow,
                  B.wrapped()->ncol,
                  reinterpret_cast<double*>(Bdense->x),
                  klu_common.get() );

    // convert to cholmod_sparse
    return make_ss_unique_ptr( cholmod_l_dense_to_sparse( Bdense.get(), 1, spqr_common.get() ),
                               spqr_common);
}

// QR
Shim::qr_t::qr_t( sparsemat_t const & mat ) {
    cholmod_sparse * Q;   // results
    cholmod_sparse * R;
    // This is kind of ugly :( SuiteSparseQR returns two pointers by reference
    // Not clear what happens if it can allocate one but not the other
    assert( SuiteSparseQR<double> ( SPQR_ORDERING_DEFAULT, SPQR_DEFAULT_TOL, 3,
                                    mat.wrapped().get(),
                                    &Q, &R, nullptr, spqr_common.get() ) >= 0);

    // Now we can finally take ownership
    Q_ = make_ss_shared_ptr( Q, spqr_common );
    R_ = make_ss_unique_ptr( R, spqr_common );
}

Shim::sparsemat_t
Shim::qr_t::Q() const {
    return Q_;
}

}
<|endoftext|>


<commit_before>#include "display_controller.h"
#include "Armboard.h"
#include "pRTOS.h"
#include "common.h"

void DisplayController::display(DisplayInfo & content)
{
	LCDChannel.write(content);
}

void DisplayController::write()
{
	armboard::LCD::clear();
	int y;

	for (y = 0; y < display::height; y++)
	{
		writeString(buffer[y],display::width);
		armboard::LCD::goto_xy(0,y+1);// char_write('/n') werkt niet.
		for (int i = 0; i < display::width; i++)
		{
			std::cout << buffer[y][i];
		}
		std::cout << std::endl;
	}
}

void DisplayController::main(void)
{
	forever
	{
		RTOS::event e = wait();
		if (e == standbyFlag)
		{
			armboard::LCD::command(0x08); //turn off LCD entirely.
			running = false;
		}
		else if (e == testFlag)
		{
			if (!running)
			{
				armboard::LCD::command(0x0C);
				running = true;
			}
			LCDTest();
		}
		else if (e == LCDChannel)
		{
			if (!running)
			{
				armboard::LCD::command(0x0C); //LCD on, no blinking cursor.
				running = true;
			}
			DisplayInfo toPrint = LCDChannel.read();
			int x,y;
			int index = 0;

			// Since writing to the display involves several waits,
			// the data to be written is copied to a buffer first
			// so the source of the data can't accidentally overwrite
			// it during writing to the display.
			/*
			for (y = 0; y < display::height; y++)
			{
				for (x = 0; x < display::width; x++)
				{
					buffer[index] = toPrint.nextChar();
					index++;
				}
				buffer[index] = '\n';
				index++;
			}
			*/
			for (y = 0; y < display::height; y++)
			{
				toPrint.copyBuffer(y,buffer[y]);
			}

			write();
		}
	}
}

void DisplayController::test(void)
{
	this -> testFlag.set();
}

void DisplayController::writeString(const char * string, int length)
{
	int i;
	for (i = 0; i < length; i++)
	{
		armboard::LCD::char_write_raw(*(string+i));
	}
}

void DisplayController::LCDTest()
{
	if (!tested)
	{
		tested = true;
		armboard::LCD::command(0x40);
		writeString("5*5*5*5*",8);
		writeString("*5*5*5*5",8);
		armboard::LCD::command(0x80);
	}
	armboard::LCD::clear();
	int x,y;
	for (y = 0; y < display::height; y++)
	{
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(0);
		}
		armboard::LCD::char_write('\n');
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(0);
		}
	}
	sleep (1 S);
	armboard::LCD::clear();
	for (y = 0; y < display::height; y++)
	{
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(1);
		}
		armboard::LCD::char_write('\n');
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(1);
		}

	}
}<commit_msg>cleaned up debug statements<commit_after>#include "display_controller.h"
#include "Armboard.h"
#include "pRTOS.h"
#include "common.h"

void DisplayController::display(DisplayInfo & content)
{
	LCDChannel.write(content);
}

void DisplayController::write()
{
	armboard::LCD::clear();
	int y;

	for (y = 0; y < display::height; y++)
	{
		writeString(buffer[y],display::width);
		armboard::LCD::goto_xy(0,y+1);// char_write('/n') werkt niet.
	}
}

void DisplayController::main(void)
{
	forever
	{
		RTOS::event e = wait();
		if (e == standbyFlag)
		{
			armboard::LCD::command(0x08); //turn off LCD entirely.
			running = false;
		}
		else if (e == testFlag)
		{
			if (!running)
			{
				armboard::LCD::command(0x0C);
				running = true;
			}
			LCDTest();
		}
		else if (e == LCDChannel)
		{
			if (!running)
			{
				armboard::LCD::command(0x0C); //LCD on, no blinking cursor.
				running = true;
			}
			DisplayInfo toPrint = LCDChannel.read();
			int x,y;
			int index = 0;

			// Since writing to the display involves several waits,
			// the data to be written is copied to a buffer first
			// so the source of the data can't accidentally overwrite
			// it during writing to the display.
			/*
			for (y = 0; y < display::height; y++)
			{
				for (x = 0; x < display::width; x++)
				{
					buffer[index] = toPrint.nextChar();
					index++;
				}
				buffer[index] = '\n';
				index++;
			}
			*/
			for (y = 0; y < display::height; y++)
			{
				toPrint.copyBuffer(y,buffer[y]);
			}

			write();
		}
	}
}

void DisplayController::test(void)
{
	this -> testFlag.set();
}

void DisplayController::writeString(const char * string, int length)
{
	int i;
	for (i = 0; i < length; i++)
	{
		armboard::LCD::char_write_raw(*(string+i));
	}
}

void DisplayController::LCDTest()
{
	if (!tested)
	{
		tested = true;
		armboard::LCD::command(0x40);
		writeString("5*5*5*5*",8);
		writeString("*5*5*5*5",8);
		armboard::LCD::command(0x80);
	}
	armboard::LCD::clear();
	int x,y;
	for (y = 0; y < display::height; y++)
	{
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(0);
		}
		armboard::LCD::char_write('\n');
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(0);
		}
	}
	sleep (1 S);
	armboard::LCD::clear();
	for (y = 0; y < display::height; y++)
	{
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(1);
		}
		armboard::LCD::char_write('\n');
		for (x = 0; x < display::width; x++)
		{
			armboard::LCD::char_write_raw(1);
		}

	}
}<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2009 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
// boost
#include <boost/format.hpp>
// stl
#include <sstream>

namespace mapnik {

color::color( std::string const& css_string)
{
    color_factory::init_from_string(*this,css_string.c_str());
}

std::string color::to_string() const
{
    std::stringstream ss;
    if (alpha() == 255) {
        ss << "rgb("
           << red()   << ","
           << green() << ","
           << blue()  << ")";
    } else {
        ss << "rgba("
           << red()   << ","
           << green() << ","
           << blue()  << ","
           << alpha()/255.0 << ")";
    }
    return ss.str();
}

std::string color::to_hex_string() const
{
    return (boost::format("#%1$02x%2$02x%3$02x")
            % red()
            % green()
            % blue() ).str();
}
}

<commit_msg>+ catch config_error in  color::color(str) ctor<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2009 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
// boost
#include <boost/format.hpp>
// stl
#include <sstream>

namespace mapnik {

color::color( std::string const& css_string)
{
    try
    {
        color_factory::init_from_string(*this,css_string.c_str());
    }
    catch (config_error const& err)
    {
        std::cerr << err.what() << std::endl;
        red_ = 0;
        green_ = 0;
        blue_ = 0;
        alpha_ = 255;
    }
}

std::string color::to_string() const
{
    std::stringstream ss;
    if (alpha() == 255) {
        ss << "rgb("
           << red()   << ","
           << green() << ","
           << blue()  << ")";
    } else {
        ss << "rgba("
           << red()   << ","
           << green() << ","
           << blue()  << ","
           << alpha()/255.0 << ")";
    }
    return ss.str();
}

std::string color::to_hex_string() const
{
    return (boost::format("#%1$02x%2$02x%3$02x")
            % red()
            % green()
            % blue() ).str();
}
}

<|endoftext|>


<commit_before>#ifndef COLOR_HPP_INCLUDED
#define COLOR_HPP_INCLUDED

#include "glm.hpp"

namespace gst
{
    class Color {
    public:
        Color();
        Color(float red, float green, float blue, float alpha = 1.0f);

        bool operator==(Color const & other);
        bool operator!=(Color const & other);

        float get_red() const;
        float get_green() const;
        float get_blue() const;
        float get_alpha() const;
    private:
        glm::vec4 color;
    };
}

#endif
<commit_msg>add documentation to color<commit_after>#ifndef COLOR_HPP_INCLUDED
#define COLOR_HPP_INCLUDED

#include "glm.hpp"

namespace gst
{
    // The responsibility of this class is to describe a color in RGBA format.
    class Color {
    public:
        // Construct color with red, green and blue set to 0 and alpha to 1.
        Color();
        // Construct color from specified components.
        Color(float red, float green, float blue, float alpha = 1.0f);

        // Return true if specified color is equal to this color, false
        // otherwise.
        bool operator==(Color const & other);
        // Return true if specified color is not equal to this color, false
        // otherwise.
        bool operator!=(Color const & other);

        // Return red-component.
        float get_red() const;
        // Return green-component.
        float get_green() const;
        // Return blue-component.
        float get_blue() const;
        // Return alpha-component.
        float get_alpha() const;
    private:
        glm::vec4 color;
    };
}

#endif
<|endoftext|>


<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "trace.h"
#include "utils.h"
#include "pal.h"
#include "fx_ver.h"
#include "error_codes.h"

#define LIBFXR_NAME MAKE_LIBNAME("hostfxr")

typedef int(*hostfxr_main_fn) (const int argc, const pal::char_t* argv[]);

pal::string_t resolve_fxr_path(const pal::string_t& own_dir)
{
    pal::string_t fxr_dir = own_dir;
    append_path(&fxr_dir, _X("host"));
    append_path(&fxr_dir, _X("fxr"));
    if (pal::directory_exists(fxr_dir))
    {
        trace::info(_X("Reading fx resolver directory=[%s]"), fxr_dir.c_str());

        std::vector<pal::string_t> list;
        pal::readdir(fxr_dir, &list);

        fx_ver_t max_ver(-1, -1, -1);
        for (const auto& dir : list)
        {
            trace::info(_X("Considering fxr version=[%s]..."), dir.c_str());

            pal::string_t ver = get_filename(dir);

            fx_ver_t fx_ver(-1, -1, -1);
            if (fx_ver_t::parse(ver, &fx_ver, false))
            {
                max_ver = std::max(max_ver, fx_ver);
            }
        }

        pal::string_t max_ver_str = max_ver.as_str();
        append_path(&fxr_dir, max_ver_str.c_str());
        trace::info(_X("Detected latest fxr version=[%s]..."), fxr_dir.c_str());

        pal::string_t ret_path;
        if (library_exists_in_dir(fxr_dir, LIBFXR_NAME, &ret_path))
        {
            trace::info(_X("Resolved fxr [%s]..."), ret_path.c_str());
            return ret_path;
        }
    }

    pal::string_t fxr_path;
    if (library_exists_in_dir(own_dir, LIBFXR_NAME, &fxr_path))
    {
        trace::info(_X("Resolved fxr [%s]..."), fxr_path.c_str());
        return fxr_path;
    }
    return pal::string_t();
}

int run(const int argc, const pal::char_t* argv[])
{
    pal::string_t own_path;
    if (!pal::get_own_executable_path(&own_path) || !pal::realpath(&own_path))
    {
        trace::error(_X("Failed to resolve full path of the current executable [%s]"), own_path.c_str());
        return StatusCode::CoreHostCurExeFindFailure;
    }

    pal::dll_t fxr;

    pal::string_t own_dir = get_directory(own_path);

    // Load library
    pal::string_t fxr_path = resolve_fxr_path(own_dir);
    if (!pal::load_library(fxr_path.c_str(), &fxr))
    {
        trace::info(_X("Load library of %s failed"), fxr_path.c_str());
        return StatusCode::CoreHostLibLoadFailure;
    }

    // Obtain entrypoint symbols
    hostfxr_main_fn main_fn = (hostfxr_main_fn) pal::get_symbol(fxr, "hostfxr_main");
    int code = main_fn(argc, argv);
    pal::unload_library(fxr);
    return code;
}

static char sccsid[] = "@(#)"            \
                       "version: "       \
                       HOST_PKG_VER      \
                       "; commit: "      \
                       REPO_COMMIT_HASH  \
                       "; built: "       \
                       __DATE__          \
                       " "               \
                       __TIME__          \
                       ;

#if defined(_WIN32)
int __cdecl wmain(const int argc, const pal::char_t* argv[])
#else
int main(const int argc, const pal::char_t* argv[])
#endif
{
    trace::setup();

printf("%s\n", sccsid);
    if (trace::is_enabled())
    {
        trace::info(_X("--- Invoked dotnet [version: %s, commit hash: %s] main = {"), _STRINGIFY(HOST_PKG_VER), _STRINGIFY(REPO_COMMIT_HASH));
        for (int i = 0; i < argc; ++i)
        {
            trace::info(_X("%s"), argv[i]);
        }
        trace::info(_X("}"));
    }

    return run(argc, argv);
}

<commit_msg>Remove printf debugging<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "trace.h"
#include "utils.h"
#include "pal.h"
#include "fx_ver.h"
#include "error_codes.h"

#define LIBFXR_NAME MAKE_LIBNAME("hostfxr")

typedef int(*hostfxr_main_fn) (const int argc, const pal::char_t* argv[]);

pal::string_t resolve_fxr_path(const pal::string_t& own_dir)
{
    pal::string_t fxr_dir = own_dir;
    append_path(&fxr_dir, _X("host"));
    append_path(&fxr_dir, _X("fxr"));
    if (pal::directory_exists(fxr_dir))
    {
        trace::info(_X("Reading fx resolver directory=[%s]"), fxr_dir.c_str());

        std::vector<pal::string_t> list;
        pal::readdir(fxr_dir, &list);

        fx_ver_t max_ver(-1, -1, -1);
        for (const auto& dir : list)
        {
            trace::info(_X("Considering fxr version=[%s]..."), dir.c_str());

            pal::string_t ver = get_filename(dir);

            fx_ver_t fx_ver(-1, -1, -1);
            if (fx_ver_t::parse(ver, &fx_ver, false))
            {
                max_ver = std::max(max_ver, fx_ver);
            }
        }

        pal::string_t max_ver_str = max_ver.as_str();
        append_path(&fxr_dir, max_ver_str.c_str());
        trace::info(_X("Detected latest fxr version=[%s]..."), fxr_dir.c_str());

        pal::string_t ret_path;
        if (library_exists_in_dir(fxr_dir, LIBFXR_NAME, &ret_path))
        {
            trace::info(_X("Resolved fxr [%s]..."), ret_path.c_str());
            return ret_path;
        }
    }

    pal::string_t fxr_path;
    if (library_exists_in_dir(own_dir, LIBFXR_NAME, &fxr_path))
    {
        trace::info(_X("Resolved fxr [%s]..."), fxr_path.c_str());
        return fxr_path;
    }
    return pal::string_t();
}

int run(const int argc, const pal::char_t* argv[])
{
    pal::string_t own_path;
    if (!pal::get_own_executable_path(&own_path) || !pal::realpath(&own_path))
    {
        trace::error(_X("Failed to resolve full path of the current executable [%s]"), own_path.c_str());
        return StatusCode::CoreHostCurExeFindFailure;
    }

    pal::dll_t fxr;

    pal::string_t own_dir = get_directory(own_path);

    // Load library
    pal::string_t fxr_path = resolve_fxr_path(own_dir);
    if (!pal::load_library(fxr_path.c_str(), &fxr))
    {
        trace::info(_X("Load library of %s failed"), fxr_path.c_str());
        return StatusCode::CoreHostLibLoadFailure;
    }

    // Obtain entrypoint symbols
    hostfxr_main_fn main_fn = (hostfxr_main_fn) pal::get_symbol(fxr, "hostfxr_main");
    int code = main_fn(argc, argv);
    pal::unload_library(fxr);
    return code;
}

static char sccsid[] = "@(#)"            \
                       "version: "       \
                       HOST_PKG_VER      \
                       "; commit: "      \
                       REPO_COMMIT_HASH  \
                       "; built: "       \
                       __DATE__          \
                       " "               \
                       __TIME__          \
                       ;

#if defined(_WIN32)
int __cdecl wmain(const int argc, const pal::char_t* argv[])
#else
int main(const int argc, const pal::char_t* argv[])
#endif
{
    trace::setup();

    if (trace::is_enabled())
    {
        trace::info(_X("--- Invoked dotnet [version: %s, commit hash: %s] main = {"), _STRINGIFY(HOST_PKG_VER), _STRINGIFY(REPO_COMMIT_HASH));
        for (int i = 0; i < argc; ++i)
        {
            trace::info(_X("%s"), argv[i]);
        }
        trace::info(_X("}"));
    }

    return run(argc, argv);
}

<|endoftext|>


<commit_before>// Copyright 2015 The libcount Authors.
//
// 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. See the AUTHORS file for names of
// contributors.

#include "count/hll.h"
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "count/utility.h"

namespace {

// The minimum and maximum allowed precision values.
const int HLL_MIN_PRECISION = 4;
const int HLL_MAX_PRECISION = 16;

using libcount::CountLeadingZeroes;

// Helper to return the appropriate alpha value used to scale the raw estimate
double GetAlphaForPrecision(int precision) {
  assert(precision >= HLL_MIN_PRECISION);
  assert(precision <= HLL_MAX_PRECISION);

  // TODO(tdial): These magic constants were derived from empirical research
  // by the authors of the HyperLogLog++ paper. Cite reference.
  switch (precision) {
    case 4:
      return 0.673f;
    case 5:
      return 0.697f;
    case 6:
      return 0.709f;
    default:
      return (0.7213f / (1.0f + (1.079f / static_cast<double>(precision))));
  }
}

// Helper to calculate the index into the table of registers from the hash
inline int RegisterIndexOf(uint64_t hash, int precision) {
  return (hash >> (64 - precision));
}

// Helper to count the leading zeros (less the bits used for the reg. index)
inline uint8_t ZeroCountOf(uint64_t hash, int precision) {
  // Make a mask for isolating the leading bits used for the register index.
  const uint64_t ONE = 1;
  const uint64_t mask = ~(((ONE << precision) - ONE) << (64 - precision));

  // Count zeroes, less the index bits we're masking off.
  return (CountLeadingZeroes(hash & mask) - static_cast<uint8_t>(precision));
}

}  // namespace

namespace libcount {

HLL::HLL(int precision)
    : precision_(precision), updates_(0), register_count_(0), registers_(NULL) {
  // The precision is vetted by the Create() function.  Assertions nonetheless.
  assert(precision >= HLL_MIN_PRECISION);
  assert(precision <= HLL_MAX_PRECISION);

  // We employ (2 ^ precision) "registers" to store max leading zeroes.
  register_count_ = (1 << precision);

  // Allocate space for the registers. We can safely economize by using bytes
  // for the counters because we know the value can't ever exceed ~60.
  registers_ = new uint8_t[register_count_];
  memset(registers_, 0, register_count_ * sizeof(registers_[0]));
}

HLL::~HLL() { delete[] registers_; }

HLL* HLL::Create(int precision, int* error) {
  if ((precision < HLL_MIN_PRECISION) || (precision > HLL_MAX_PRECISION)) {
    MaybeAssign(error, EINVAL);
    return NULL;
  }
  return new HLL(precision);
}

void HLL::Update(uint64_t hash) {
  // Which register will potentially receive the zero count of this hash?
  const int index = RegisterIndexOf(hash, precision_);
  assert(index < register_count_);

  // Count the zeroes for the hash, and add one, per the algorithm spec.
  const uint8_t count = ZeroCountOf(hash, precision_) + 1;
  assert(count <= 64);

  // Update the appropriate register if the new count is greater than current.
  if (count > registers_[index]) {
    registers_[index] = count;
  }
}

uint64_t HLL::EstimateCardinality() const {
  // Let 'm' be the number of registers.
  const double m = static_cast<double>(register_count_);

  // For each register, let 'max' be the contents of the register
  // Let 'term' be the reciprocal of 2 ^ max
  // And let 'sum' be the sum of all terms
  double sum = 0.0;
  for (int i = 0; i < register_count_; ++i) {
    const double max = static_cast<double>(registers_[i]);
    const double term = pow(2.0, -max);
    sum += term;
  }

  // Next, calculate the harmonic mean
  const double harmonic_mean = m * (1.0 / sum);
  assert(harmonic_mean >= 0.0);

  // The estimate is bias-corrected using a constant that depends on precision
  const double scale_factor = m * GetAlphaForPrecision(precision_);
  assert(scale_factor >= 0.0);

  // Calculate the bias-corrected estimate
  const double estimate = harmonic_mean * scale_factor;
  assert(estimate >= 0.0);

  return static_cast<uint64_t>(estimate);
}

}  // namespace libcount
<commit_msg>remember to record update count<commit_after>// Copyright 2015 The libcount Authors.
//
// 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. See the AUTHORS file for names of
// contributors.

#include "count/hll.h"
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "count/utility.h"

namespace {

// The minimum and maximum allowed precision values.
const int HLL_MIN_PRECISION = 4;
const int HLL_MAX_PRECISION = 16;

using libcount::CountLeadingZeroes;

// Helper to return the appropriate alpha value used to scale the raw estimate
double GetAlphaForPrecision(int precision) {
  assert(precision >= HLL_MIN_PRECISION);
  assert(precision <= HLL_MAX_PRECISION);

  // TODO(tdial): These magic constants were derived from empirical research
  // by the authors of the HyperLogLog++ paper. Cite reference.
  switch (precision) {
    case 4:
      return 0.673f;
    case 5:
      return 0.697f;
    case 6:
      return 0.709f;
    default:
      return (0.7213f / (1.0f + (1.079f / static_cast<double>(precision))));
  }
}

// Helper to calculate the index into the table of registers from the hash
inline int RegisterIndexOf(uint64_t hash, int precision) {
  return (hash >> (64 - precision));
}

// Helper to count the leading zeros (less the bits used for the reg. index)
inline uint8_t ZeroCountOf(uint64_t hash, int precision) {
  // Make a mask for isolating the leading bits used for the register index.
  const uint64_t ONE = 1;
  const uint64_t mask = ~(((ONE << precision) - ONE) << (64 - precision));

  // Count zeroes, less the index bits we're masking off.
  return (CountLeadingZeroes(hash & mask) - static_cast<uint8_t>(precision));
}

}  // namespace

namespace libcount {

HLL::HLL(int precision)
    : precision_(precision), updates_(0), register_count_(0), registers_(NULL) {
  // The precision is vetted by the Create() function.  Assertions nonetheless.
  assert(precision >= HLL_MIN_PRECISION);
  assert(precision <= HLL_MAX_PRECISION);

  // We employ (2 ^ precision) "registers" to store max leading zeroes.
  register_count_ = (1 << precision);

  // Allocate space for the registers. We can safely economize by using bytes
  // for the counters because we know the value can't ever exceed ~60.
  registers_ = new uint8_t[register_count_];
  memset(registers_, 0, register_count_ * sizeof(registers_[0]));
}

HLL::~HLL() { delete[] registers_; }

HLL* HLL::Create(int precision, int* error) {
  if ((precision < HLL_MIN_PRECISION) || (precision > HLL_MAX_PRECISION)) {
    MaybeAssign(error, EINVAL);
    return NULL;
  }
  return new HLL(precision);
}

void HLL::Update(uint64_t hash) {
  // Which register will potentially receive the zero count of this hash?
  const int index = RegisterIndexOf(hash, precision_);
  assert(index < register_count_);

  // Count the zeroes for the hash, and add one, per the algorithm spec.
  const uint8_t count = ZeroCountOf(hash, precision_) + 1;
  assert(count <= 64);

  // Update the appropriate register if the new count is greater than current.
  if (count > registers_[index]) {
    registers_[index] = count;
  }

  // Record update count.
  // TODO(tdial): Provide an API to return this value.
  ++updates_;
}

uint64_t HLL::EstimateCardinality() const {
  // Let 'm' be the number of registers.
  const double m = static_cast<double>(register_count_);

  // For each register, let 'max' be the contents of the register
  // Let 'term' be the reciprocal of 2 ^ max
  // And let 'sum' be the sum of all terms
  double sum = 0.0;
  for (int i = 0; i < register_count_; ++i) {
    const double max = static_cast<double>(registers_[i]);
    const double term = pow(2.0, -max);
    sum += term;
  }

  // Next, calculate the harmonic mean
  const double harmonic_mean = m * (1.0 / sum);
  assert(harmonic_mean >= 0.0);

  // The estimate is bias-corrected using a constant that depends on precision
  const double scale_factor = m * GetAlphaForPrecision(precision_);
  assert(scale_factor >= 0.0);

  // Calculate the bias-corrected estimate
  const double estimate = harmonic_mean * scale_factor;
  assert(estimate >= 0.0);

  return static_cast<uint64_t>(estimate);
}

}  // namespace libcount
<|endoftext|>