<commit_before>#include "DataTreeNode.h"
#include "MapperFactory.h"
#include <vtkTransform.h>

#include "mitkProperties.h"
#include "mitkFloatProperty.h"
#include "mitkStringProperty.h"
#include "mitkBoolProperty.h"
#include "mitkColorProperty.h"
#include "mitkLevelWindowProperty.h"

//##ModelId=3D6A0E8C02CC
mitk::Mapper* mitk::DataTreeNode::GetMapper(MapperSlotId id) const
{
    // TODO

    if (mappers[id].IsNull()) {

        mappers[id] = MapperFactory::CreateMapper(const_cast<DataTreeNode*>(this),id);

    }

    // mappers[id]->AddInput(GetData());

    return mappers[id];

    //  return NULL;

}

//##ModelId=3E32C49D00A8
mitk::BaseData* mitk::DataTreeNode::GetData() const
{
    return m_Data;
}

//##ModelId=3ED91D050121
vtkTransform* mitk::DataTreeNode::GetVtkTransform() const
{
  return m_VtkTransform;
}

mitk::StateMachine::Pointer mitk::DataTreeNode::GetInteractor() const
{
  return m_Interactor;
}

//##ModelId=3E33F4E4025B
void mitk::DataTreeNode::SetData(mitk::BaseData* baseData)
{
    if(m_Data!=baseData)
    {
        m_Data=baseData;
        Modified();
    }
}

void mitk::DataTreeNode::SetInteractor(mitk::StateMachine* interactor)
{
	m_Interactor = interactor;
}

//##ModelId=3E33F5D702AA
mitk::DataTreeNode::DataTreeNode() : m_Data(NULL)
{
    memset(mappers, 0, sizeof(mappers));

    m_PropertyList = PropertyList::New();

    m_VtkTransform = vtkTransform::New();
}

//##ModelId=3E33F5D702D3
mitk::DataTreeNode::~DataTreeNode()
{
    m_VtkTransform->Delete();
}

//##ModelId=3E33F5D7032D
mitk::DataTreeNode& mitk::DataTreeNode::operator=(const DataTreeNode& right)
{
    mitk::DataTreeNode* node=mitk::DataTreeNode::New();
    node->SetData(right.GetData());
    return *node;
}

mitk::DataTreeNode& mitk::DataTreeNode::operator=(mitk::BaseData* right)
{
    mitk::DataTreeNode* node=mitk::DataTreeNode::New();
    node->SetData(right);
    return *node;
}

#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::istream& mitk::operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::istream& operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
{
    dtn = mitk::DataTreeNode::New();
    //i >> av.get();
    return i;
}

#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::ostream& mitk::operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::ostream& operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
{
    if(dtn->GetData()!=NULL)
        o<<dtn->GetData()->GetNameOfClass();
    else
        o<<"empty data";
    return o;
}

//##ModelId=3E69331903C9
void mitk::DataTreeNode::SetMapper(MapperSlotId id, mitk::Mapper* mapper)
{
    mappers[id] = mapper;

    if (mapper!=NULL)
        mapper->SetInput(this);
}

//##ModelId=3E860A5C0032
void mitk::DataTreeNode::UpdateOutputInformation()
{
    if (this->GetSource())
    {
        this->GetSource()->UpdateOutputInformation();
    }
}

//##ModelId=3E860A5E011B
void mitk::DataTreeNode::SetRequestedRegionToLargestPossibleRegion()
{
}

//##ModelId=3E860A5F03D9
bool mitk::DataTreeNode::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

//##ModelId=3E860A620080
bool mitk::DataTreeNode::VerifyRequestedRegion()
{
    return GetData()!=NULL;
}

//##ModelId=3E860A640156
void mitk::DataTreeNode::SetRequestedRegion(itk::DataObject *data)
{
}

//##ModelId=3E860A6601DB
void mitk::DataTreeNode::CopyInformation(const itk::DataObject *data)
{
}
//##ModelId=3E3FE0420273
mitk::PropertyList::Pointer mitk::DataTreeNode::GetPropertyList(const mitk::BaseRenderer* renderer) const
{
    if(renderer==NULL)
        return m_PropertyList;

    mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer];

    if(propertyList.IsNull())
        propertyList = mitk::PropertyList::New();

    assert(m_MapOfPropertyLists[renderer].IsNotNull());

    return propertyList;
}

//##ModelId=3EF189DB0111
mitk::BaseProperty::Pointer mitk::DataTreeNode::GetProperty(const char *propertyKey, const mitk::BaseRenderer* renderer) const
{
    std::map<const mitk::BaseRenderer*,mitk::PropertyList::Pointer>::const_iterator it;

    //does a renderer-specific PropertyList exist?
    it=m_MapOfPropertyLists.find(renderer);
    if(it==m_MapOfPropertyLists.end())
        //no? use the renderer-independent one!
        return m_PropertyList->GetProperty(propertyKey);

    //does the renderer-specific PropertyList contain the @a propertyKey?
    mitk::BaseProperty::Pointer property;
    property=it->second->GetProperty(propertyKey);
    if(property.IsNotNull())
        //yes? return it
        return property;

    //no? use the renderer-independent one!
    return m_PropertyList->GetProperty(propertyKey);
}//##ModelId=3EF1941C011F

bool mitk::DataTreeNode::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetProperty(name, renderer).GetPointer());
    if(colorprop.IsNull())
        return false;

    memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float));
    return true;
}

bool mitk::DataTreeNode::GetName(char &nodeName, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::StringProperty::Pointer nameProp = dynamic_cast<mitk::StringProperty*>(GetProperty(name, renderer).GetPointer());
    if(nameProp.IsNull())
    {
        nameProp = new mitk::StringProperty("Unnamed");
        GetPropertyList(renderer)->SetProperty(name,nameProp);
    }
    nodeName = (char)nameProp->GetString();
    return true;
}

//##ModelId=3EF1941E01D6
bool mitk::DataTreeNode::GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty*>(GetProperty(name, renderer).GetPointer());
    if(boolprop.IsNull())
        return false;

    visible = boolprop->GetBool();
    return true;
}

//##ModelId=3EF19420016B
bool mitk::DataTreeNode::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(name, renderer).GetPointer());
    if(opacityprop.IsNull())
        return false;

    opacity=opacityprop->GetValue();
    return true;
}

//##ModelId=3EF194220204
bool mitk::DataTreeNode::GetLevelWindow(mitk::LevelWindow &levelWindow, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast<mitk::LevelWindowProperty*>(GetProperty(name, renderer).GetPointer());
    if(levWinProp.IsNull())
        return false;

    levelWindow=levWinProp->GetLevelWindow();
    return true;
}

bool mitk::DataTreeNode::GetIntProperty(const char* propertyKey, int &intValue, mitk::BaseRenderer* renderer) const
{
    mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty*>(GetProperty(propertyKey, renderer).GetPointer());
    if(intprop.IsNull())
        return false;

    intValue = intprop->GetValue();
    return true;
}

//##ModelId=3EF19424012B
bool mitk::DataTreeNode::IsVisible(mitk::BaseRenderer* renderer, const char* name) const
{
    bool visible=true;
    GetVisibility(visible, renderer, name);
    return visible;
}

void mitk::DataTreeNode::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::ColorProperty::Pointer prop;
    prop = new mitk::ColorProperty(color);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

void mitk::DataTreeNode::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const char* name)
{
  float color[3];
  color[0]=red;
  color[1]=green;
  color[2]=blue;
  SetColor(color, renderer, name);
}

//##ModelId=3EF196360303
void mitk::DataTreeNode::SetColor(const float rgb[3], mitk::BaseRenderer* renderer, const char* name)
{
    mitk::ColorProperty::Pointer prop;
    prop = new mitk::ColorProperty(rgb);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

//##ModelId=3EF1966703D6
void mitk::DataTreeNode::SetVisibility(bool visible, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::BoolProperty::Pointer prop;
    prop = new mitk::BoolProperty(visible);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

//##ModelId=3EF196880095
void mitk::DataTreeNode::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::FloatProperty::Pointer prop;
    prop = new mitk::FloatProperty(opacity);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

//##ModelId=3EF1969A0181
void mitk::DataTreeNode::SetLevelWindow(mitk::LevelWindow levelWindow, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::LevelWindowProperty::Pointer prop;
    prop = new mitk::LevelWindowProperty(levelWindow);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

void mitk::DataTreeNode::SetIntProperty(const char* propertyKey, int intValue, mitk::BaseRenderer* renderer)
{
    mitk::IntProperty::Pointer prop;
    prop = new mitk::IntProperty(intValue);
    GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}

void mitk::DataTreeNode::SetProperty(const char *propertyKey,
                                     BaseProperty* propertyValue,
                                     const mitk::BaseRenderer* renderer)
{
    GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue);
}
<commit_msg>changed getNameMethod<commit_after>#include "DataTreeNode.h"
#include "MapperFactory.h"
#include <vtkTransform.h>

#include "mitkProperties.h"
#include "mitkFloatProperty.h"
#include "mitkStringProperty.h"
#include "mitkBoolProperty.h"
#include "mitkColorProperty.h"
#include "mitkLevelWindowProperty.h"

//##ModelId=3D6A0E8C02CC
mitk::Mapper* mitk::DataTreeNode::GetMapper(MapperSlotId id) const
{
    // TODO

    if (mappers[id].IsNull()) {

        mappers[id] = MapperFactory::CreateMapper(const_cast<DataTreeNode*>(this),id);

    }

    // mappers[id]->AddInput(GetData());

    return mappers[id];

    //  return NULL;

}

//##ModelId=3E32C49D00A8
mitk::BaseData* mitk::DataTreeNode::GetData() const
{
    return m_Data;
}

//##ModelId=3ED91D050121
vtkTransform* mitk::DataTreeNode::GetVtkTransform() const
{
  return m_VtkTransform;
}

mitk::StateMachine::Pointer mitk::DataTreeNode::GetInteractor() const
{
  return m_Interactor;
}

//##ModelId=3E33F4E4025B
void mitk::DataTreeNode::SetData(mitk::BaseData* baseData)
{
    if(m_Data!=baseData)
    {
        m_Data=baseData;
        Modified();
    }
}

void mitk::DataTreeNode::SetInteractor(mitk::StateMachine* interactor)
{
	m_Interactor = interactor;
}

//##ModelId=3E33F5D702AA
mitk::DataTreeNode::DataTreeNode() : m_Data(NULL)
{
    memset(mappers, 0, sizeof(mappers));

    m_PropertyList = PropertyList::New();

    m_VtkTransform = vtkTransform::New();
}

//##ModelId=3E33F5D702D3
mitk::DataTreeNode::~DataTreeNode()
{
    m_VtkTransform->Delete();
}

//##ModelId=3E33F5D7032D
mitk::DataTreeNode& mitk::DataTreeNode::operator=(const DataTreeNode& right)
{
    mitk::DataTreeNode* node=mitk::DataTreeNode::New();
    node->SetData(right.GetData());
    return *node;
}

mitk::DataTreeNode& mitk::DataTreeNode::operator=(mitk::BaseData* right)
{
    mitk::DataTreeNode* node=mitk::DataTreeNode::New();
    node->SetData(right);
    return *node;
}

#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::istream& mitk::operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::istream& operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
{
    dtn = mitk::DataTreeNode::New();
    //i >> av.get();
    return i;
}

#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::ostream& mitk::operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::ostream& operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
{
    if(dtn->GetData()!=NULL)
        o<<dtn->GetData()->GetNameOfClass();
    else
        o<<"empty data";
    return o;
}

//##ModelId=3E69331903C9
void mitk::DataTreeNode::SetMapper(MapperSlotId id, mitk::Mapper* mapper)
{
    mappers[id] = mapper;

    if (mapper!=NULL)
        mapper->SetInput(this);
}

//##ModelId=3E860A5C0032
void mitk::DataTreeNode::UpdateOutputInformation()
{
    if (this->GetSource())
    {
        this->GetSource()->UpdateOutputInformation();
    }
}

//##ModelId=3E860A5E011B
void mitk::DataTreeNode::SetRequestedRegionToLargestPossibleRegion()
{
}

//##ModelId=3E860A5F03D9
bool mitk::DataTreeNode::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

//##ModelId=3E860A620080
bool mitk::DataTreeNode::VerifyRequestedRegion()
{
    return GetData()!=NULL;
}

//##ModelId=3E860A640156
void mitk::DataTreeNode::SetRequestedRegion(itk::DataObject *data)
{
}

//##ModelId=3E860A6601DB
void mitk::DataTreeNode::CopyInformation(const itk::DataObject *data)
{
}
//##ModelId=3E3FE0420273
mitk::PropertyList::Pointer mitk::DataTreeNode::GetPropertyList(const mitk::BaseRenderer* renderer) const
{
    if(renderer==NULL)
        return m_PropertyList;

    mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer];

    if(propertyList.IsNull())
        propertyList = mitk::PropertyList::New();

    assert(m_MapOfPropertyLists[renderer].IsNotNull());

    return propertyList;
}

//##ModelId=3EF189DB0111
mitk::BaseProperty::Pointer mitk::DataTreeNode::GetProperty(const char *propertyKey, const mitk::BaseRenderer* renderer) const
{
    std::map<const mitk::BaseRenderer*,mitk::PropertyList::Pointer>::const_iterator it;

    //does a renderer-specific PropertyList exist?
    it=m_MapOfPropertyLists.find(renderer);
    if(it==m_MapOfPropertyLists.end())
        //no? use the renderer-independent one!
        return m_PropertyList->GetProperty(propertyKey);

    //does the renderer-specific PropertyList contain the @a propertyKey?
    mitk::BaseProperty::Pointer property;
    property=it->second->GetProperty(propertyKey);
    if(property.IsNotNull())
        //yes? return it
        return property;

    //no? use the renderer-independent one!
    return m_PropertyList->GetProperty(propertyKey);
}//##ModelId=3EF1941C011F

bool mitk::DataTreeNode::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetProperty(name, renderer).GetPointer());
    if(colorprop.IsNull())
        return false;

    memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float));
    return true;
}

bool mitk::DataTreeNode::GetName(char &nodeName, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::StringProperty::Pointer nameProp = dynamic_cast<mitk::StringProperty*>(GetProperty(name, renderer).GetPointer());
    if(nameProp.IsNull())
    {
        nameProp = new mitk::StringProperty("Unnamed");
        GetPropertyList(renderer)->SetProperty(name,nameProp);
    }
    memcpy(&nodeName, nameProp->GetString(), strlen(nameProp->GetString()) + 1 );
    return true;
}

//##ModelId=3EF1941E01D6
bool mitk::DataTreeNode::GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty*>(GetProperty(name, renderer).GetPointer());
    if(boolprop.IsNull())
        return false;

    visible = boolprop->GetBool();
    return true;
}

//##ModelId=3EF19420016B
bool mitk::DataTreeNode::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(name, renderer).GetPointer());
    if(opacityprop.IsNull())
        return false;

    opacity=opacityprop->GetValue();
    return true;
}

//##ModelId=3EF194220204
bool mitk::DataTreeNode::GetLevelWindow(mitk::LevelWindow &levelWindow, mitk::BaseRenderer* renderer, const char* name) const
{
    mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast<mitk::LevelWindowProperty*>(GetProperty(name, renderer).GetPointer());
    if(levWinProp.IsNull())
        return false;

    levelWindow=levWinProp->GetLevelWindow();
    return true;
}

bool mitk::DataTreeNode::GetIntProperty(const char* propertyKey, int &intValue, mitk::BaseRenderer* renderer) const
{
    mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty*>(GetProperty(propertyKey, renderer).GetPointer());
    if(intprop.IsNull())
        return false;

    intValue = intprop->GetValue();
    return true;
}

//##ModelId=3EF19424012B
bool mitk::DataTreeNode::IsVisible(mitk::BaseRenderer* renderer, const char* name) const
{
    bool visible=true;
    GetVisibility(visible, renderer, name);
    return visible;
}

void mitk::DataTreeNode::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::ColorProperty::Pointer prop;
    prop = new mitk::ColorProperty(color);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

void mitk::DataTreeNode::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const char* name)
{
  float color[3];
  color[0]=red;
  color[1]=green;
  color[2]=blue;
  SetColor(color, renderer, name);
}

//##ModelId=3EF196360303
void mitk::DataTreeNode::SetColor(const float rgb[3], mitk::BaseRenderer* renderer, const char* name)
{
    mitk::ColorProperty::Pointer prop;
    prop = new mitk::ColorProperty(rgb);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

//##ModelId=3EF1966703D6
void mitk::DataTreeNode::SetVisibility(bool visible, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::BoolProperty::Pointer prop;
    prop = new mitk::BoolProperty(visible);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

//##ModelId=3EF196880095
void mitk::DataTreeNode::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::FloatProperty::Pointer prop;
    prop = new mitk::FloatProperty(opacity);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

//##ModelId=3EF1969A0181
void mitk::DataTreeNode::SetLevelWindow(mitk::LevelWindow levelWindow, mitk::BaseRenderer* renderer, const char* name)
{
    mitk::LevelWindowProperty::Pointer prop;
    prop = new mitk::LevelWindowProperty(levelWindow);
    GetPropertyList(renderer)->SetProperty(name, prop);
}

void mitk::DataTreeNode::SetIntProperty(const char* propertyKey, int intValue, mitk::BaseRenderer* renderer)
{
    mitk::IntProperty::Pointer prop;
    prop = new mitk::IntProperty(intValue);
    GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}

void mitk::DataTreeNode::SetProperty(const char *propertyKey,
                                     BaseProperty* propertyValue,
                                     const mitk::BaseRenderer* renderer)
{
    GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>

const int N = 1000000;

int p[N];
pair<int, pair<int, int> >edgeList[N];

int getp(int i)
{
	return (p[i] == p[p[i]] ? p[i] : p[i] = getp(p[i]));
}

int main()
{
	int e, v, ans = 0;
	scanf("%d%d", &v, &e);
	for(int i = 0; i < e; i++)
		scanf("%d%d%d", &edgeList[i].second.first, &edgeList[i].second.second, &edgeList[i].first);

	sort(edgeList, edgeList + e);

	for(int i = 0; i < v; i++)
		p[i] = i;

	for(int i = 0; i < e; i++)
	{
		int a = getp(edgeList[i].second.first);
		int b = getp(edgeList[i].second.second);
		if(a != b)
		{
			p[b] = a;
			ans += edgeList[i].first;
		}
	}

	cout << ans << endl;
}
<commit_msg>Kruskal Updated<commit_after>#include <iostream>
#include <algorithm>
using namespace std;

const int N = 1000000;

int p[N];
pair<int, pair<int, int> >edgeList[N];

int getp(int x)
{
	return (p[x] == x ? x : p[x] = getp(p[x]));
}

int main()
{
	int e, v, ans = 0;
	cin >> v >> e;
	for(int i = 0; i < e; i++)
		cin >> edgeList[i].second.first >> edgeList[i].second.second >> edgeList[i].first;

	sort(edgeList, edgeList + e);

	for(int i = 0; i < v; i++)
		p[i] = i;

	for(int i = 0; i < e; i++)
	{
		int a = getp(edgeList[i].second.first);
		int b = getp(edgeList[i].second.second);
		if(a != b)
		{
			p[b] = a;
			ans += edgeList[i].first;
		}
	}

	cout << ans << endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

bool zero_1(int *a, int n)
{
	long *b = new long[n];
	b[0] = a[0];
	if (a[0] == 0) {
		return true;
	}
	for (int i = 1; i < n; i++) {
		b[i] = b[i - 1] + a[i];
	}
	sort(b, b + n);

	for (int i = 1; i < n; i++) {
		if (b[0] == 0) {
			return true;
		}
		if (b[i] == b[i - 1]) {
			return true;
		}
	}
	return false;
}

bool zero_2(int *a, int n)
{
	long *b = new long[n];
	b[0] = a[0];
	if (a[0] == 0) {
		return true;
	}
	for (int i = 1; i < n; i++) {
		b[i] = b[i - 1] + a[i];
	}
	map<long, int> long_int_map;
	for (int i = 0; i < n; i++) {
		if (b[i] == 0) {
			return true;
		}
		if (!long_int_map.count(b[i])) {
			long_int_map.insert(pair<long, int>(b[i], 1));
		}
		else {
			long_int_map[b[i]]++;
		}
	}
	for (map<long, int>::iterator iter = long_int_map.begin(); iter != long_int_map.end(); iter++) {
		if (iter->second >= 2) {
			return true;
		}
	}
	return false;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int k;
		cin >> k;
		int *a = new int[k];
		for (int i = 0; i < k; i++) {
			cin >> a[i];
		}
		if (zero_2(a, k)) {
			cout << "zero" << endl;
		}
		else {
			cout << "nonzero" << endl;
		}
	}
	return 0;
}<commit_msg>Delete dynamic arrays.<commit_after>#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

bool zero_1(int *a, int n)
{
	long *b = new long[n];
	b[0] = a[0];
	if (a[0] == 0) {
		return true;
	}
	for (int i = 1; i < n; i++) {
		b[i] = b[i - 1] + a[i];
	}
	sort(b, b + n);

	for (int i = 1; i < n; i++) {
		if (b[0] == 0) {
			return true;
		}
		if (b[i] == b[i - 1]) {
			return true;
		}
	}
	delete [] b;
	return false;
}

bool zero_2(int *a, int n)
{
	long *b = new long[n];
	b[0] = a[0];
	if (a[0] == 0) {
		return true;
	}
	for (int i = 1; i < n; i++) {
		b[i] = b[i - 1] + a[i];
	}
	map<long, int> long_int_map;
	for (int i = 0; i < n; i++) {
		if (b[i] == 0) {
			return true;
		}
		if (!long_int_map.count(b[i])) {
			long_int_map.insert(pair<long, int>(b[i], 1));
		}
		else {
			long_int_map[b[i]]++;
		}
	}
	for (map<long, int>::iterator iter = long_int_map.begin(); iter != long_int_map.end(); iter++) {
		if (iter->second >= 2) {
			return true;
		}
	}
	delete [] b;
	return false;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int k;
		cin >> k;
		int *a = new int[k];
		for (int i = 0; i < k; i++) {
			cin >> a[i];
		}
		if (zero_2(a, k)) {
			cout << "zero" << endl;
		}
		else {
			cout << "nonzero" << endl;
		}
		delete [] a;
	}
	return 0;
}<|endoftext|>


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

#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
#ifdef _WIN32
	#include <windows.h>
#endif
#include <amx/amx.h>
#include <amx_profiler/call_graph_writer_gv.h>
#include <amx_profiler/debug_info.h>
#include <amx_profiler/statistics_writer_html.h>
#include <amx_profiler/statistics_writer_text.h>
#include <amx_profiler/statistics_writer_xml.h>
#include <amx_profiler/profiler.h>
#include "amxpath.h"
#include "configreader.h"
#include "hook.h"
#include "plugin.h"
#include "pluginversion.h"

typedef void (*logprintf_t)(const char *format, ...);

extern void *pAMXFunctions;

static logprintf_t logprintf;

// Profiler instances.
static std::unordered_map<AMX*, std::shared_ptr<amx_profiler::Profiler>> profilers;

// List of loaded scripts, need this to fix AmxUnload bug on Windows.
static std::list<AMX*> loaded_scripts;

// Stores previously set debug hooks (if any).
static std::unordered_map<AMX*, AMX_DEBUG> old_debug_hooks;

// Plugin settings and their defauls.
namespace cfg {
	bool          profile_gamemode      = false;
	std::string   profile_filterscripts = "";
	std::string   profile_format        = "html";
	bool          call_graph            = false;
	std::string   call_graph_format     = "gv";
};

namespace hooks {

Hook amx_Exec_hook;
Hook amx_Callback_hook;

static int AMXAPI amx_Debug(AMX *amx) {
	auto profiler = ::profilers[amx];
	if (profiler) {
		profiler->DebugHook();
	}
	auto iterator = old_debug_hooks.find(amx);
	if (iterator != old_debug_hooks.end()) {
		if (iterator->second != nullptr) {
			return (iterator->second)(amx);
		}
	}
	return AMX_ERR_NONE;
}

static int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {
	Hook::ScopedRemove r(&amx_Callback_hook);
	Hook::ScopedInstall i(&amx_Exec_hook);

	auto profiler = ::profilers[amx];
	if (profiler) {
		return profiler->CallbackHook(index, result, params);
	} else {
		return ::amx_Callback(amx, index, result, params);
	}
}

static int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {
	Hook::ScopedRemove r(&amx_Exec_hook);
	Hook::ScopedInstall i(&amx_Callback_hook);

	auto profiler = ::profilers[amx];
	if (profiler) {
		return profiler->ExecHook(retval, index);
	} else {
		return ::amx_Exec(amx, retval, index);
	}
}

} // namespace hooks

static std::string ToUnixPath(const std::string &path) {
	std::string fsPath = path;
	std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
	return fsPath;
}

static bool IsGameMode(const std::string &amxName) {
	return ToUnixPath(amxName).find("gamemodes/") != std::string::npos;
}

static bool IsFilterScript(const std::string &amxName) {
	return ToUnixPath(amxName).find("filterscripts/") != std::string::npos;
}

static bool GetPublicVariable(AMX *amx, const char *name, cell &value) {
	cell amx_addr;
	if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) {
		cell *phys_addr;
		amx_GetAddr(amx, amx_addr, &phys_addr);
		value = *phys_addr;
		return true;
	}
	return false;
}

static bool WantsProfiler(const std::string &amxName) {
	std::string goodAmxName = ToUnixPath(amxName);

	if (IsGameMode(amxName)) {
		if (cfg::profile_gamemode) {
			return true;
		}
	} else if (IsFilterScript(amxName)) {
		std::string fsList = cfg::profile_filterscripts;
		std::stringstream fsStream(fsList);
		do {
			std::string fsName;
			fsStream >> fsName;
			if (goodAmxName == "filterscripts/" + fsName + ".amx"
					|| goodAmxName == "filterscripts/" + fsName) {
				return true;
			}
		} while (!fsStream.eof());
	}

	return false;
}

#ifdef _WIN32

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx);

static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
	switch (dwCtrlType) {
	case CTRL_CLOSE_EVENT:
	case CTRL_BREAK_EVENT:
		for (auto amx : loaded_scripts) {
			AmxUnload(amx);
		}
	}
	return FALSE;
}

#endif

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

static void *AMXAPI my_amx_Align(void *v) { return v; }

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];

	((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align;
	((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align;
	((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align;

	hooks::amx_Exec_hook.Install(
		((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
		(void*)hooks::amx_Exec);
	hooks::amx_Callback_hook.Install(
		((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
		(void*)hooks::amx_Callback);

	#ifdef _WIN32
		SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
	#endif

	// Read plugin settings from server.cfg.
	ConfigReader server_cfg("server.cfg");
	cfg::profile_gamemode      = server_cfg.GetOption("profile_gamemode", cfg::profile_gamemode);
	cfg::profile_filterscripts = server_cfg.GetOption("profile_filterscripts", cfg::profile_filterscripts);
	cfg::profile_format        = server_cfg.GetOption("profile_format", cfg::profile_format);
	cfg::call_graph            = server_cfg.GetOption("call_graph", cfg::call_graph);
	cfg::call_graph_format     = server_cfg.GetOption("call_graph_format", cfg::call_graph_format);

	logprintf("  Profiler v" PROJECT_VERSION_STRING " is OK.");

	return true;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
	::loaded_scripts.push_back(amx);

	std::string filename = GetAmxPath(amx);
	if (filename.empty()) {
		logprintf("[profiler] Can't find matching .amx file");
		return AMX_ERR_NONE;
	}

	cell profiler_enabled = false;
	if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled)
			&& !profiler_enabled) {
		return AMX_ERR_NONE;
	}

	if (profiler_enabled || WantsProfiler(filename)) {
		// Disable SYSREQ.D
		amx->sysreq_d = 0;

		// Store previous debug hook somewhere before setting a new one
		::old_debug_hooks[amx] = amx->debug;
		amx_SetDebugHook(amx, hooks::amx_Debug);

		// Load debug stats if available
		amx_profiler::DebugInfo debug_info;
		if (amx_profiler::HasDebugInfo(amx)) {
			debug_info.Load(filename);
			if (debug_info.IsLoaded()) {
				logprintf("[profiler] Loaded debug stats from '%s'", filename.c_str());
			} else {
				logprintf("[profiler] Error loading debug stats from '%s'", filename.c_str());
			}
		}

		::profilers[amx] = std::shared_ptr<amx_profiler::Profiler>(new amx_profiler::Profiler(amx, debug_info, cfg::call_graph));
		if (debug_info.IsLoaded()) {
			logprintf("[profiler] Attached profiler to '%s'", filename.c_str());
		} else {
			logprintf("[profiler] Attached profiler to '%s' (no debug symbols)", filename.c_str());
		}
	}

	return AMX_ERR_NONE;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
	auto profiler = ::profilers[amx];

	if (profiler) {
		std::string amx_path = GetAmxPath(amx);
		std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));

		// Convert profile_format to lower case.
		std::transform(
			cfg::profile_format.begin(),
			cfg::profile_format.end(),
			cfg::profile_format.begin(),
			::tolower
		);

		auto profile_filename = amx_name + "-profile." + cfg::profile_format;
		std::ofstream profile_stream(profile_filename);

		if (profile_stream.is_open()) {
			amx_profiler::StatisticsWriter *writer = nullptr;

			if (cfg::profile_format == "html") {
				writer = new amx_profiler::StatisticsWriterHtml;
			} else if (cfg::profile_format == "txt" || cfg::profile_format == "text") {
				writer = new amx_profiler::StatisticsWriterText;
			} else if (cfg::profile_format == "xml") {
				writer = new amx_profiler::StatisticsWriterXml;
			} else {
				logprintf("[profiler] Unknown output format '%s'", cfg::profile_format.c_str());
			}

			if (writer != nullptr) {
				logprintf("[profiler] Writing '%s'", profile_filename.c_str());
				writer->set_stream(&profile_stream);
				writer->set_script_name(amx_path);
				writer->set_print_date(true);
				writer->Write(profiler->stats());
				delete writer;
			}

			profile_stream.close();
		}

		if (cfg::call_graph) {
			auto call_graph_filename = amx_name + "-calls.gv";
			std::ofstream call_graph_stream(call_graph_filename);

			if (call_graph_stream.is_open()) {
				amx_profiler::CallGraphWriterGV *call_graph_writer = nullptr;

				if (cfg::call_graph_format == "gv") {
					call_graph_writer = new amx_profiler::CallGraphWriterGV(&call_graph_stream, amx_path, "SA-MP Server");
				} else {
					logprintf("[profiler] Unknown call graph format '%s'", cfg::call_graph_format.c_str());
				}

				if (call_graph_writer != nullptr) {
					logprintf("[profiler] Writing '%s'", call_graph_filename.c_str());
					profiler->call_graph()->Write(call_graph_writer);
					delete call_graph_writer;
				}

				call_graph_stream.close();
			}
		}

		profilers.erase(amx);
	}

	return AMX_ERR_NONE;
}
<commit_msg>Remove unused includes<commit_after>// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <unordered_map>
#ifdef _WIN32
	#include <windows.h>
#endif
#include <amx/amx.h>
#include <amx_profiler/call_graph_writer_gv.h>
#include <amx_profiler/debug_info.h>
#include <amx_profiler/statistics_writer_html.h>
#include <amx_profiler/statistics_writer_text.h>
#include <amx_profiler/statistics_writer_xml.h>
#include <amx_profiler/profiler.h>
#include "amxpath.h"
#include "configreader.h"
#include "hook.h"
#include "plugin.h"
#include "pluginversion.h"

typedef void (*logprintf_t)(const char *format, ...);

extern void *pAMXFunctions;

static logprintf_t logprintf;

// Profiler instances.
static std::unordered_map<AMX*, std::shared_ptr<amx_profiler::Profiler>> profilers;

// List of loaded scripts, need this to fix AmxUnload bug on Windows.
static std::list<AMX*> loaded_scripts;

// Stores previously set debug hooks (if any).
static std::unordered_map<AMX*, AMX_DEBUG> old_debug_hooks;

// Plugin settings and their defauls.
namespace cfg {
	bool          profile_gamemode      = false;
	std::string   profile_filterscripts = "";
	std::string   profile_format        = "html";
	bool          call_graph            = false;
	std::string   call_graph_format     = "gv";
};

namespace hooks {

Hook amx_Exec_hook;
Hook amx_Callback_hook;

static int AMXAPI amx_Debug(AMX *amx) {
	auto profiler = ::profilers[amx];
	if (profiler) {
		profiler->DebugHook();
	}
	auto iterator = old_debug_hooks.find(amx);
	if (iterator != old_debug_hooks.end()) {
		if (iterator->second != nullptr) {
			return (iterator->second)(amx);
		}
	}
	return AMX_ERR_NONE;
}

static int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {
	Hook::ScopedRemove r(&amx_Callback_hook);
	Hook::ScopedInstall i(&amx_Exec_hook);

	auto profiler = ::profilers[amx];
	if (profiler) {
		return profiler->CallbackHook(index, result, params);
	} else {
		return ::amx_Callback(amx, index, result, params);
	}
}

static int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {
	Hook::ScopedRemove r(&amx_Exec_hook);
	Hook::ScopedInstall i(&amx_Callback_hook);

	auto profiler = ::profilers[amx];
	if (profiler) {
		return profiler->ExecHook(retval, index);
	} else {
		return ::amx_Exec(amx, retval, index);
	}
}

} // namespace hooks

static std::string ToUnixPath(const std::string &path) {
	std::string fsPath = path;
	std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
	return fsPath;
}

static bool IsGameMode(const std::string &amxName) {
	return ToUnixPath(amxName).find("gamemodes/") != std::string::npos;
}

static bool IsFilterScript(const std::string &amxName) {
	return ToUnixPath(amxName).find("filterscripts/") != std::string::npos;
}

static bool GetPublicVariable(AMX *amx, const char *name, cell &value) {
	cell amx_addr;
	if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) {
		cell *phys_addr;
		amx_GetAddr(amx, amx_addr, &phys_addr);
		value = *phys_addr;
		return true;
	}
	return false;
}

static bool WantsProfiler(const std::string &amxName) {
	std::string goodAmxName = ToUnixPath(amxName);

	if (IsGameMode(amxName)) {
		if (cfg::profile_gamemode) {
			return true;
		}
	} else if (IsFilterScript(amxName)) {
		std::string fsList = cfg::profile_filterscripts;
		std::stringstream fsStream(fsList);
		do {
			std::string fsName;
			fsStream >> fsName;
			if (goodAmxName == "filterscripts/" + fsName + ".amx"
					|| goodAmxName == "filterscripts/" + fsName) {
				return true;
			}
		} while (!fsStream.eof());
	}

	return false;
}

#ifdef _WIN32

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx);

static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
	switch (dwCtrlType) {
	case CTRL_CLOSE_EVENT:
	case CTRL_BREAK_EVENT:
		for (auto amx : loaded_scripts) {
			AmxUnload(amx);
		}
	}
	return FALSE;
}

#endif

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

static void *AMXAPI my_amx_Align(void *v) { return v; }

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];

	((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align;
	((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align;
	((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align;

	hooks::amx_Exec_hook.Install(
		((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
		(void*)hooks::amx_Exec);
	hooks::amx_Callback_hook.Install(
		((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
		(void*)hooks::amx_Callback);

	#ifdef _WIN32
		SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
	#endif

	// Read plugin settings from server.cfg.
	ConfigReader server_cfg("server.cfg");
	cfg::profile_gamemode      = server_cfg.GetOption("profile_gamemode", cfg::profile_gamemode);
	cfg::profile_filterscripts = server_cfg.GetOption("profile_filterscripts", cfg::profile_filterscripts);
	cfg::profile_format        = server_cfg.GetOption("profile_format", cfg::profile_format);
	cfg::call_graph            = server_cfg.GetOption("call_graph", cfg::call_graph);
	cfg::call_graph_format     = server_cfg.GetOption("call_graph_format", cfg::call_graph_format);

	logprintf("  Profiler v" PROJECT_VERSION_STRING " is OK.");

	return true;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
	::loaded_scripts.push_back(amx);

	std::string filename = GetAmxPath(amx);
	if (filename.empty()) {
		logprintf("[profiler] Can't find matching .amx file");
		return AMX_ERR_NONE;
	}

	cell profiler_enabled = false;
	if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled)
			&& !profiler_enabled) {
		return AMX_ERR_NONE;
	}

	if (profiler_enabled || WantsProfiler(filename)) {
		// Disable SYSREQ.D
		amx->sysreq_d = 0;

		// Store previous debug hook somewhere before setting a new one
		::old_debug_hooks[amx] = amx->debug;
		amx_SetDebugHook(amx, hooks::amx_Debug);

		// Load debug stats if available
		amx_profiler::DebugInfo debug_info;
		if (amx_profiler::HasDebugInfo(amx)) {
			debug_info.Load(filename);
			if (debug_info.IsLoaded()) {
				logprintf("[profiler] Loaded debug stats from '%s'", filename.c_str());
			} else {
				logprintf("[profiler] Error loading debug stats from '%s'", filename.c_str());
			}
		}

		::profilers[amx] = std::shared_ptr<amx_profiler::Profiler>(new amx_profiler::Profiler(amx, debug_info, cfg::call_graph));
		if (debug_info.IsLoaded()) {
			logprintf("[profiler] Attached profiler to '%s'", filename.c_str());
		} else {
			logprintf("[profiler] Attached profiler to '%s' (no debug symbols)", filename.c_str());
		}
	}

	return AMX_ERR_NONE;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
	auto profiler = ::profilers[amx];

	if (profiler) {
		std::string amx_path = GetAmxPath(amx);
		std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));

		// Convert profile_format to lower case.
		std::transform(
			cfg::profile_format.begin(),
			cfg::profile_format.end(),
			cfg::profile_format.begin(),
			::tolower
		);

		auto profile_filename = amx_name + "-profile." + cfg::profile_format;
		std::ofstream profile_stream(profile_filename);

		if (profile_stream.is_open()) {
			amx_profiler::StatisticsWriter *writer = nullptr;

			if (cfg::profile_format == "html") {
				writer = new amx_profiler::StatisticsWriterHtml;
			} else if (cfg::profile_format == "txt" || cfg::profile_format == "text") {
				writer = new amx_profiler::StatisticsWriterText;
			} else if (cfg::profile_format == "xml") {
				writer = new amx_profiler::StatisticsWriterXml;
			} else {
				logprintf("[profiler] Unknown output format '%s'", cfg::profile_format.c_str());
			}

			if (writer != nullptr) {
				logprintf("[profiler] Writing '%s'", profile_filename.c_str());
				writer->set_stream(&profile_stream);
				writer->set_script_name(amx_path);
				writer->set_print_date(true);
				writer->Write(profiler->stats());
				delete writer;
			}

			profile_stream.close();
		}

		if (cfg::call_graph) {
			auto call_graph_filename = amx_name + "-calls.gv";
			std::ofstream call_graph_stream(call_graph_filename);

			if (call_graph_stream.is_open()) {
				amx_profiler::CallGraphWriterGV *call_graph_writer = nullptr;

				if (cfg::call_graph_format == "gv") {
					call_graph_writer = new amx_profiler::CallGraphWriterGV(&call_graph_stream, amx_path, "SA-MP Server");
				} else {
					logprintf("[profiler] Unknown call graph format '%s'", cfg::call_graph_format.c_str());
				}

				if (call_graph_writer != nullptr) {
					logprintf("[profiler] Writing '%s'", call_graph_filename.c_str());
					profiler->call_graph()->Write(call_graph_writer);
					delete call_graph_writer;
				}

				call_graph_stream.close();
			}
		}

		profilers.erase(amx);
	}

	return AMX_ERR_NONE;
}
<|endoftext|>


<commit_before>#include "vtkDataSet.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkGaussianSplatter.h"
#include "vtkContourFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkAxes.h"
#include "vtkTubeFilter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkFloatPoints.h"
#include "vtkFloatScalars.h"

static vtkDataSet *ReadFinancialData(char *x, char *y, char *z, char *s);
static int ParseFile(FILE *file, char *tag, float *data);

main ()
{
  float bounds[6];
  int npts;
  vtkDataSet *dataSet;

  // graphics stuff
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // read data
  dataSet = ReadFinancialData("MONTHLY_PAYMENT","INTEREST_RATE",
                              "LOAN_AMOUNT","TIME_LATE");
  if ( ! dataSet ) exit(0);

  // construct pipeline for original population
  vtkGaussianSplatter *popSplatter = vtkGaussianSplatter::New();
    popSplatter->SetInput(dataSet);
    popSplatter->SetSampleDimensions(50,50,50);
    popSplatter->SetRadius(0.05);
    popSplatter->ScalarWarpingOff();
    popSplatter->DebugOn();
  vtkContourFilter *popSurface = vtkContourFilter::New();
    popSurface->SetInput(popSplatter->GetOutput());
    popSurface->SetValue(0,0.01);
    popSurface->DebugOn();
  vtkPolyDataMapper *popMapper = vtkPolyDataMapper::New();
    popMapper->SetInput(popSurface->GetOutput());
    popMapper->ScalarVisibilityOff();
  vtkActor *popActor = vtkActor::New();
    popActor->SetMapper(popMapper);
    popActor->GetProperty()->SetRepresentationToWireframe();
    popActor->GetProperty()->SetColor(.9,.9,.9);

  // construct pipeline for delinquent population
  vtkGaussianSplatter *lateSplatter = vtkGaussianSplatter::New();
    lateSplatter->SetInput(dataSet);
    lateSplatter->SetSampleDimensions(50,50,50);
    lateSplatter->SetRadius(0.05);
    lateSplatter->SetScaleFactor(0.005);
    lateSplatter->DebugOn();
  vtkContourFilter *lateSurface = vtkContourFilter::New();
    lateSurface->SetInput(lateSplatter->GetOutput());
    lateSurface->SetValue(0,0.01);
    lateSurface->DebugOn();
  vtkPolyDataMapper *lateMapper = vtkPolyDataMapper::New();
    lateMapper->SetInput(lateSurface->GetOutput());
    lateMapper->ScalarVisibilityOff();
  vtkActor *lateActor = vtkActor::New();
    lateActor->SetMapper(lateMapper);
    lateActor->GetProperty()->SetColor(1.0,0.0,0.0);

  // create axes
  popSplatter->Update();
  popSplatter->GetOutput()->GetBounds(bounds);
  vtkAxes *axes = vtkAxes::New();
    axes->SetOrigin(bounds[0], bounds[2], bounds[4]);
    axes->SetScaleFactor(popSplatter->GetOutput()->GetLength()/5);
  vtkTubeFilter *axesTubes = vtkTubeFilter::New();
    axesTubes->SetInput(axes->GetOutput());
    axesTubes->SetRadius(axes->GetScaleFactor()/25.0);
    axesTubes->SetNumberOfSides(6);
  vtkPolyDataMapper *axesMapper = vtkPolyDataMapper::New();
    axesMapper->SetInput(axesTubes->GetOutput());
  vtkActor *axesActor = vtkActor::New();
    axesActor->SetMapper(axesMapper);

  //set up renderer
  renderer->AddActor(popActor);
  renderer->AddActor(lateActor);
  renderer->AddActor(axesActor);
  renderer->SetBackground(1,1,1);
  renWin->SetSize(1000,1000);

  // interact with data
  iren->Initialize();
  iren->Start();

  // Clean up
  renderer->Delete();
  renWin->Delete();
  iren->Delete();
  popSplatter->Delete();
  popSurface->Delete();
  popMapper->Delete();
  popActor->Delete();
  lateSplatter->Delete();
  lateSurface->Delete();
  lateMapper->Delete();
  lateActor->Delete();
  axes->Delete();
  axesTubes->Delete();
  axesMapper->Delete();
  axesActor->Delete();
  dataSet->Delete();
}

static vtkDataSet *ReadFinancialData(char *x, char *y, char *z, char *s)
{
  float xyz[3];
  FILE *file;
  int i, npts;
  char tag[80];

  if ( (file = fopen("../../../vtkdata/financial.txt","r")) == NULL )
    {
    cerr << "Can't read file!\n";
    return NULL;
    }

  fscanf (file, "%s %d", tag, &npts); // read number of points

  vtkUnstructuredGrid *dataSet = vtkUnstructuredGrid::New();
  float *xV = new float[npts];
  float *yV = new float[npts];
  float *zV = new float[npts];
  float *sV = new float[npts];

  if ( ! ParseFile(file, x, xV) || ! ParseFile(file, y, yV) ||
  ! ParseFile(file, z, zV) || ! ParseFile(file, s, sV) )
    {
    cerr << "Couldn't read data!\n";
    delete [] xV;
    delete [] yV;
    delete [] zV;
    delete [] sV;
    delete dataSet;
    return NULL;
    }

  vtkPoints *newPts = vtkPoints::New();
  vtkScalars *newScalars = vtkScalars::New();

  for (i=0; i<npts; i++)
    {
    xyz[0] = xV[i]; xyz[1] = yV[i]; xyz[2] = zV[i];
    newPts->InsertPoint(i, xyz);
    newScalars->InsertScalar(i, sV[i]);
    }

  dataSet->SetPoints(newPts);
  dataSet->GetPointData()->SetScalars(newScalars);

  newPts->Delete(); //reference counted - it's okay
  newScalars->Delete();

  return dataSet;
}

static int ParseFile(FILE *file, char *label, float *data)
{
  char tag[80];
  int i, npts, readData=0;
  float min=VTK_LARGE_FLOAT;
  float max=(-VTK_LARGE_FLOAT);

  if ( file == NULL || label == NULL ) return 0;

  rewind(file);

  fscanf(file, "%s %d", tag, &npts);

  while ( !readData && fscanf(file, "%s", tag) == 1 )
    {
    if ( ! strcmp(tag,label) )
      {
      readData = 1;
      for (i=0; i<npts; i++)
        {
        fscanf(file, "%f", data+i);
        if ( data[i] < min ) min = data[i];
        if ( data[i] > min ) max = data[i];
        }
      // normalize data
      for (i=0; i<npts; i++) data[i] = min + data[i]/(max-min);
      }
    else
      {
      for (i=0; i<npts; i++) fscanf(file, "%*f");
      }
    }

  if ( ! readData ) return 0;
  else return 1;
}
<commit_msg>ENH:Reworked to bring it up to snuff<commit_after>#include "vtkDataSet.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkGaussianSplatter.h"
#include "vtkContourFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkAxes.h"
#include "vtkTubeFilter.h"
#include "vtkUnstructuredGrid.h"
#include "vtkPoints.h"
#include "vtkScalars.h"

static vtkDataSet *ReadFinancialData(char *x, char *y, char *z, char *s);
static int ParseFile(FILE *file, char *tag, float *data);

main ()
{
  float bounds[6];
  int npts;
  vtkDataSet *dataSet;

  // read data
  dataSet = ReadFinancialData("MONTHLY_PAYMENT","INTEREST_RATE",
                              "LOAN_AMOUNT","TIME_LATE");
  if ( ! dataSet ) exit(0);

  // construct pipeline for original population
  vtkGaussianSplatter *popSplatter = vtkGaussianSplatter::New();
    popSplatter->SetInput(dataSet);
    popSplatter->SetSampleDimensions(50,50,50);
    popSplatter->SetRadius(0.05);
    popSplatter->ScalarWarpingOff();
  vtkContourFilter *popSurface = vtkContourFilter::New();
    popSurface->SetInput(popSplatter->GetOutput());
    popSurface->SetValue(0,0.01);
  vtkPolyDataMapper *popMapper = vtkPolyDataMapper::New();
    popMapper->SetInput(popSurface->GetOutput());
    popMapper->ScalarVisibilityOff();
  vtkActor *popActor = vtkActor::New();
    popActor->SetMapper(popMapper);
    popActor->GetProperty()->SetOpacity(0.3);
    popActor->GetProperty()->SetColor(.9,.9,.9);

  // construct pipeline for delinquent population
  vtkGaussianSplatter *lateSplatter = vtkGaussianSplatter::New();
    lateSplatter->SetInput(dataSet);
    lateSplatter->SetSampleDimensions(50,50,50);
    lateSplatter->SetRadius(0.05);
    lateSplatter->SetScaleFactor(0.005);
  vtkContourFilter *lateSurface = vtkContourFilter::New();
    lateSurface->SetInput(lateSplatter->GetOutput());
    lateSurface->SetValue(0,0.01);
  vtkPolyDataMapper *lateMapper = vtkPolyDataMapper::New();
    lateMapper->SetInput(lateSurface->GetOutput());
    lateMapper->ScalarVisibilityOff();
  vtkActor *lateActor = vtkActor::New();
    lateActor->SetMapper(lateMapper);
    lateActor->GetProperty()->SetColor(1.0,0.0,0.0);

  // create axes
  popSplatter->Update();
  popSplatter->GetOutput()->GetBounds(bounds);
  vtkAxes *axes = vtkAxes::New();
    axes->SetOrigin(bounds[0], bounds[2], bounds[4]);
    axes->SetScaleFactor(popSplatter->GetOutput()->GetLength()/5);
  vtkTubeFilter *axesTubes = vtkTubeFilter::New();
    axesTubes->SetInput(axes->GetOutput());
    axesTubes->SetRadius(axes->GetScaleFactor()/25.0);
    axesTubes->SetNumberOfSides(6);
  vtkPolyDataMapper *axesMapper = vtkPolyDataMapper::New();
    axesMapper->SetInput(axesTubes->GetOutput());
  vtkActor *axesActor = vtkActor::New();
    axesActor->SetMapper(axesMapper);

  // graphics stuff
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  // read data  //set up renderer
  renderer->AddActor(lateActor);
  renderer->AddActor(axesActor);
  renderer->AddActor(popActor);
  renderer->SetBackground(1,1,1);
  renWin->SetSize(500,500);

  // interact with data
  iren->Initialize();
  iren->Start();

  // Clean up
  renderer->Delete();
  renWin->Delete();
  iren->Delete();
  popSplatter->Delete();
  popSurface->Delete();
  popMapper->Delete();
  popActor->Delete();
  lateSplatter->Delete();
  lateSurface->Delete();
  lateMapper->Delete();
  lateActor->Delete();
  axes->Delete();
  axesTubes->Delete();
  axesMapper->Delete();
  axesActor->Delete();
  dataSet->Delete();
}

static vtkDataSet *ReadFinancialData(char *x, char *y, char *z, char *s)
{
  float xyz[3];
  FILE *file;
  int i, npts;
  char tag[80];

  if ( (file = fopen("../../../vtkdata/financial.txt","r")) == NULL )
    {
    cerr << "Can't read file!\n";
    return NULL;
    }

  fscanf (file, "%s %d", tag, &npts); // read number of points

  vtkUnstructuredGrid *dataSet = vtkUnstructuredGrid::New();
  float *xV = new float[npts];
  float *yV = new float[npts];
  float *zV = new float[npts];
  float *sV = new float[npts];

  if ( ! ParseFile(file, x, xV) || ! ParseFile(file, y, yV) ||
  ! ParseFile(file, z, zV) || ! ParseFile(file, s, sV) )
    {
    cerr << "Couldn't read data!\n";
    delete [] xV;
    delete [] yV;
    delete [] zV;
    delete [] sV;
    delete dataSet;
    return NULL;
    }

  vtkPoints *newPts = vtkPoints::New();
  vtkScalars *newScalars = vtkScalars::New();

  for (i=0; i<npts; i++)
    {
    xyz[0] = xV[i]; xyz[1] = yV[i]; xyz[2] = zV[i];
    newPts->InsertPoint(i, xyz);
    newScalars->InsertScalar(i, sV[i]);
    }

  dataSet->SetPoints(newPts);
  dataSet->GetPointData()->SetScalars(newScalars);

  newPts->Delete(); //reference counted - it's okay
  newScalars->Delete();

  return dataSet;
}

static int ParseFile(FILE *file, char *label, float *data)
{
  char tag[80];
  int i, npts, readData=0;
  float min=VTK_LARGE_FLOAT;
  float max=(-VTK_LARGE_FLOAT);

  if ( file == NULL || label == NULL ) return 0;

  rewind(file);

  fscanf(file, "%s %d", tag, &npts);

  while ( !readData && fscanf(file, "%s", tag) == 1 )
    {
    if ( ! strcmp(tag,label) )
      {
      readData = 1;
      for (i=0; i<npts; i++)
        {
        fscanf(file, "%f", data+i);
        if ( data[i] < min ) min = data[i];
        if ( data[i] > min ) max = data[i];
        }
      // normalize data
      for (i=0; i<npts; i++) data[i] = min + data[i]/(max-min);
      }
    else
      {
      for (i=0; i<npts; i++) fscanf(file, "%*f");
      }
    }

  if ( ! readData ) return 0;
  else return 1;
}
<|endoftext|>


<commit_before><commit_msg>Removed treating ':' as end of word in GetNearestWords as it conflicted with languages that use ':' inside identifiers. Functionality can be achieved by passing ':' as otherSeparator parameter.<commit_after><|endoftext|>


<commit_before><commit_msg>Check node before and after step for errors<commit_after><|endoftext|>


<commit_before><commit_msg>*** empty log message ***<commit_after><|endoftext|>


<commit_before>// vim: tabstop=3 expandtab shiftwidth=4 softtabstop=4

#include <catch.hpp>
#include <moar_rulez.hpp>

using moar_rulez::execute;
using moar_rulez::success;
using moar_rulez::fail;
using moar_rulez::running;
using moar_rulez::eq;
using moar_rulez::ne;
using moar_rulez::gt;
using moar_rulez::lt;
using moar_rulez::State;
using moar_rulez::make_rule;
using moar_rulez::set;

SCENARIO("All rules should work independently") {

  GIVEN("constants") {
    CHECK( success == execute(success) );
    CHECK( fail	   == execute(fail) );
    CHECK( running == execute(running) );
  }
  GIVEN("operator&&") {
    CHECK( success == execute(success && success) );
    CHECK( fail    == execute(success && fail) );
    CHECK( fail    == execute(fail && success) );
    CHECK( fail    == execute(fail && fail) );
    CHECK( fail    == execute(fail && running) );
    CHECK( running == execute(running && fail) );
    CHECK( running == execute(success && running) );
    CHECK( running == execute(running && success) );
    CHECK( running == execute(running && running) );
  }
  GIVEN("operator||") {
    CHECK( success == execute(success || success) );
    CHECK( success == execute(success || fail) );
    CHECK( success == execute(fail || success) );
    CHECK( success == execute(success || running) );
    CHECK( running == execute(running || success) );
    CHECK( fail    == execute(fail || fail) );
    CHECK( running == execute(fail || running) );
    CHECK( running == execute(running || fail) );
    CHECK( running == execute(running || running) );
  }

  GIVEN("operator~") {
    CHECK( success == execute(~fail) );
    CHECK( fail    == execute(~success) );
    CHECK( running == execute(~running) );
  }

  GIVEN("eq") {
    const auto eqvar = 5;
    CHECK( success == execute(eq(eqvar,5)) );
    CHECK( fail    == execute(eq(eqvar,7)) );
    CHECK( success == execute(eq<5>(eqvar)) );
    CHECK( fail    == execute(eq<7>(eqvar)) );
  }
  GIVEN("ne") {
    const auto nevar = 4;
    CHECK( success == execute(ne(nevar,2)) );
    CHECK( fail    == execute(ne(nevar,4)) );
    CHECK( success == execute(ne<2>(nevar)) );
    CHECK( fail    == execute(ne<4>(nevar)) );
  }
  GIVEN("gt") {
    const auto gtvar = 4;
    CHECK( success == execute(gt(gtvar,2)) );
    CHECK( fail    == execute(gt(gtvar,4)) );
    CHECK( fail    == execute(gt(gtvar,5)) );
    CHECK( success == execute(gt<2>(gtvar)) );
    CHECK( fail    == execute(gt<4>(gtvar)) );
    CHECK( fail    == execute(gt<5>(gtvar)) );
  }
  GIVEN("lt") {
    const auto ltvar = 4;
    CHECK( success == execute(lt(ltvar,5)) );
    CHECK( fail    == execute(lt(ltvar,4)) );
    CHECK( fail    == execute(lt(ltvar,2)) );
    CHECK( success == execute(lt<5>(ltvar)) );
    CHECK( fail    == execute(lt<4>(ltvar)) );
    CHECK( fail    == execute(lt<2>(ltvar)) );
  }
  GIVEN("set") {
    auto setvar = 0;
    CHECK( success == execute(set(setvar,42)) );
    CHECK( 42 == setvar );
    CHECK( success == execute(set<43>(setvar)) );
    CHECK( 43 == setvar );
  }
}

SCENARIO("Example: A dude tries to open a door") {
  auto door_open     = false;
  auto door_locked   = true;
  auto failed        = false;
  auto dude_has_key  = true;
  auto dude_position = 0;
  constexpr auto door_position = 100;

  const auto move_dude = make_rule([&]{
    dude_position += 1;
    return State::Success;
  });

  const auto unlock_door = make_rule([&]{
      if(dude_position != door_position || !dude_has_key) return State::Fail;
      door_locked = false;
      return State::Success;
  });

  const auto open_door = make_rule([&]{
      if(dude_position != door_position || door_locked) return State::Fail;
      door_open = true;
      return State::Success;
  });

  const auto try_open =
    eq(dude_position, door_position)
    && (unlock_door || set(failed,true))
    && open_door;

  const auto rules =
    try_open
    || move_dude;

  const auto run = [&]{
    while( door_locked && !failed ) execute(rules);
  };

  GIVEN("the dude has no key") {
    dude_has_key = false;
    run();
    CHECK( false == door_open );
    CHECK( true  == failed );
  }
  GIVEN("the dude has a key") {
    dude_has_key = true;
    run();
    CHECK( true  == door_open );
    CHECK( false == failed );
  }
}
<commit_msg>Added some tests for more complex sequences<commit_after>// vim: tabstop=3 expandtab shiftwidth=4 softtabstop=4

#include <catch.hpp>
#include <moar_rulez.hpp>

using moar_rulez::execute;
using moar_rulez::success;
using moar_rulez::fail;
using moar_rulez::running;
using moar_rulez::eq;
using moar_rulez::ne;
using moar_rulez::gt;
using moar_rulez::lt;
using moar_rulez::State;
using moar_rulez::make_rule;
using moar_rulez::set;

SCENARIO("All rules should work independently") {

  GIVEN("constants") {
    CHECK( success == execute(success) );
    CHECK( fail	   == execute(fail) );
    CHECK( running == execute(running) );
  }
  GIVEN("operator&&") {
    CHECK( success == execute(success && success) );
    CHECK( fail    == execute(success && fail) );
    CHECK( fail    == execute(fail && success) );
    CHECK( fail    == execute(fail && fail) );
    CHECK( fail    == execute(fail && running) );
    CHECK( running == execute(running && fail) );
    CHECK( running == execute(success && running) );
    CHECK( running == execute(running && success) );
    CHECK( running == execute(running && running) );
  }
  GIVEN("operator||") {
    CHECK( success == execute(success || success) );
    CHECK( success == execute(success || fail) );
    CHECK( success == execute(fail || success) );
    CHECK( success == execute(success || running) );
    CHECK( running == execute(running || success) );
    CHECK( fail    == execute(fail || fail) );
    CHECK( running == execute(fail || running) );
    CHECK( running == execute(running || fail) );
    CHECK( running == execute(running || running) );
  }

  GIVEN("operator~") {
    CHECK( success == execute(~fail) );
    CHECK( fail    == execute(~success) );
    CHECK( running == execute(~running) );
  }

  GIVEN("eq") {
    const auto eqvar = 5;
    CHECK( success == execute(eq(eqvar,5)) );
    CHECK( fail    == execute(eq(eqvar,7)) );
    CHECK( success == execute(eq<5>(eqvar)) );
    CHECK( fail    == execute(eq<7>(eqvar)) );
  }
  GIVEN("ne") {
    const auto nevar = 4;
    CHECK( success == execute(ne(nevar,2)) );
    CHECK( fail    == execute(ne(nevar,4)) );
    CHECK( success == execute(ne<2>(nevar)) );
    CHECK( fail    == execute(ne<4>(nevar)) );
  }
  GIVEN("gt") {
    const auto gtvar = 4;
    CHECK( success == execute(gt(gtvar,2)) );
    CHECK( fail    == execute(gt(gtvar,4)) );
    CHECK( fail    == execute(gt(gtvar,5)) );
    CHECK( success == execute(gt<2>(gtvar)) );
    CHECK( fail    == execute(gt<4>(gtvar)) );
    CHECK( fail    == execute(gt<5>(gtvar)) );
  }
  GIVEN("lt") {
    const auto ltvar = 4;
    CHECK( success == execute(lt(ltvar,5)) );
    CHECK( fail    == execute(lt(ltvar,4)) );
    CHECK( fail    == execute(lt(ltvar,2)) );
    CHECK( success == execute(lt<5>(ltvar)) );
    CHECK( fail    == execute(lt<4>(ltvar)) );
    CHECK( fail    == execute(lt<2>(ltvar)) );
  }
  GIVEN("set") {
    auto setvar = 0;
    CHECK( success == execute(set(setvar,42)) );
    CHECK( 42 == setvar );
    CHECK( success == execute(set<43>(setvar)) );
    CHECK( 43 == setvar );
  }
}

SCENARIO("Complex sequences") {
  CHECK( success == success && fail    || success );
  CHECK( fail    == success && fail    || fail );
  CHECK( running == success && running || success );
}

SCENARIO("Example: A dude tries to open a door") {
  auto door_open     = false;
  auto door_locked   = true;
  auto failed        = false;
  auto dude_has_key  = true;
  auto dude_position = 0;
  constexpr auto door_position = 100;

  const auto move_dude = make_rule([&]{
    dude_position += 1;
    return State::Success;
  });

  const auto unlock_door = make_rule([&]{
      if(dude_position != door_position || !dude_has_key) return State::Fail;
      door_locked = false;
      return State::Success;
  });

  const auto open_door = make_rule([&]{
      if(dude_position != door_position || door_locked) return State::Fail;
      door_open = true;
      return State::Success;
  });

  const auto try_open =
    eq(dude_position, door_position)
    && (unlock_door || set(failed,true))
    && open_door;

  const auto rules =
    try_open
    || move_dude;

  const auto run = [&]{
    while( door_locked && !failed ) execute(rules);
  };

  GIVEN("the dude has no key") {
    dude_has_key = false;
    run();
    CHECK( false == door_open );
    CHECK( true  == failed );
  }
  GIVEN("the dude has a key") {
    dude_has_key = true;
    run();
    CHECK( true  == door_open );
    CHECK( false == failed );
  }
}
<|endoftext|>


<commit_before>#include <common/buffer.h>

#include <config/config.h>
#include <config/config_class.h>
#include <config/config_exporter.h>
#include <config/config_object.h>
#include <config/config_type.h>
#include <config/config_type_pointer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event_callback.h>
#include <event/event_main.h>
#include <event/event_system.h>

#include <io/pipe/pipe.h>
#include <io/pipe/pipe_producer.h>
#include <io/pipe/splice.h>

#include "monitor_client.h"

class HTMLConfigExporter : public ConfigExporter {
	std::string select_;
public:
	std::ostringstream os_;

	HTMLConfigExporter(const std::string& select)
	: select_(select),
	  os_()
	{ }

	~HTMLConfigExporter()
	{ }

	void config(const Config *c)
	{
		if (select_ == "")
			os_ << "
Configuration
";
		else
			os_ << "
Configuration - " << select_ << " [up]
";
		os_ << "
";
		os_ << "
object	class	field	type	value
";
		c->marshall(this);
		os_ << "
";
	}

	void field(const ConfigValue *cv, const std::string& name)
	{
		os_ << "
" << name << "	" << cv->type_->name() << "	";
		cv->marshall(this);
		os_ << "
";
	}

	void object(const ConfigClass *cc, const ConfigObject *co)
	{
		if (select_ != "" && select_ != co->name())
			return;
		os_ << "
<a href=\"/object/" << co->name() << "\">" << co->name() << "	" << cc->name() << "
";
		cc->marshall(this, co);
	}

	void value(const ConfigValue *cv, const std::string& val)
	{
		ConfigTypePointer *ct = dynamic_cast<ConfigTypePointer *>(cv->type_);
		if (ct != NULL) {
			ConfigObject *co;
			if (ct->get(cv, &co)) {
				if (co == NULL)
					os_ << "<tt>None</tt>";
				else
					os_ << "<a href=\"/object/" << co->name() << "\">" << co->name() << "";
				return;
			}
		}
		os_ << "<tt>" << val << "</tt>";
	}
};

void
MonitorClient::handle_request(const std::string& method, const std::string& uri, HTTPProtocol::Message)
{
	if (method != "GET") {
		pipe_->send_response(HTTPProtocol::BadRequest, "Unsupported method.");
		return;
	}

	if (uri[0] != '/') {
		pipe_->send_response(HTTPProtocol::NotFound, "Invalid URI.");
		return;
	}

	std::vector<Buffer> path_components = Buffer(uri).split('/', false);
	std::string select;
	if (!path_components.empty()) {
		switch (path_components.size()) {
		case 2:
			if (!path_components[0].equal("object")) {
				pipe_->send_response(HTTPProtocol::NotFound, "Unsupported URI class.");
				return;
			}
			path_components[1].extract(select);
			break;
		default:
			pipe_->send_response(HTTPProtocol::NotFound, "Wrong number of path components in URI.");
			return;
		}
	}

	HTMLConfigExporter exporter(select);
	exporter.config(config_);
	pipe_->send_response(HTTPProtocol::OK, "<title>WANProxy Configuration Monitor</title>" + exporter.os_.str() + "", "text/html");
}
<commit_msg>Put header before each object for readingtronication.<commit_after>#include <common/buffer.h>

#include <config/config.h>
#include <config/config_class.h>
#include <config/config_exporter.h>
#include <config/config_object.h>
#include <config/config_type.h>
#include <config/config_type_pointer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event_callback.h>
#include <event/event_main.h>
#include <event/event_system.h>

#include <io/pipe/pipe.h>
#include <io/pipe/pipe_producer.h>
#include <io/pipe/splice.h>

#include "monitor_client.h"

class HTMLConfigExporter : public ConfigExporter {
	std::string select_;
public:
	std::ostringstream os_;

	HTMLConfigExporter(const std::string& select)
	: select_(select),
	  os_()
	{ }

	~HTMLConfigExporter()
	{ }

	void config(const Config *c)
	{
		if (select_ == "")
			os_ << "
Configuration
";
		else
			os_ << "
Configuration - " << select_ << " [up]
";
		os_ << "
";
		c->marshall(this);
		os_ << "
";
	}

	void field(const ConfigValue *cv, const std::string& name)
	{
		os_ << "
" << name << "	" << cv->type_->name() << "	";
		cv->marshall(this);
		os_ << "
";
	}

	void object(const ConfigClass *cc, const ConfigObject *co)
	{
		if (select_ != "" && select_ != co->name())
			return;
		os_ << "
object	class	field	type	value
";
		os_ << "
<a href=\"/object/" << co->name() << "\">" << co->name() << "	" << cc->name() << "
";
		cc->marshall(this, co);
	}

	void value(const ConfigValue *cv, const std::string& val)
	{
		ConfigTypePointer *ct = dynamic_cast<ConfigTypePointer *>(cv->type_);
		if (ct != NULL) {
			ConfigObject *co;
			if (ct->get(cv, &co)) {
				if (co == NULL)
					os_ << "<tt>None</tt>";
				else
					os_ << "<a href=\"/object/" << co->name() << "\">" << co->name() << "";
				return;
			}
		}
		os_ << "<tt>" << val << "</tt>";
	}
};

void
MonitorClient::handle_request(const std::string& method, const std::string& uri, HTTPProtocol::Message)
{
	if (method != "GET") {
		pipe_->send_response(HTTPProtocol::BadRequest, "Unsupported method.");
		return;
	}

	if (uri[0] != '/') {
		pipe_->send_response(HTTPProtocol::NotFound, "Invalid URI.");
		return;
	}

	std::vector<Buffer> path_components = Buffer(uri).split('/', false);
	std::string select;
	if (!path_components.empty()) {
		switch (path_components.size()) {
		case 2:
			if (!path_components[0].equal("object")) {
				pipe_->send_response(HTTPProtocol::NotFound, "Unsupported URI class.");
				return;
			}
			path_components[1].extract(select);
			break;
		default:
			pipe_->send_response(HTTPProtocol::NotFound, "Wrong number of path components in URI.");
			return;
		}
	}

	HTMLConfigExporter exporter(select);
	exporter.config(config_);
	pipe_->send_response(HTTPProtocol::OK, "<title>WANProxy Configuration Monitor</title>" + exporter.os_.str() + "", "text/html");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <thread>
#include <chrono>
#include <cstdint>

#include <grpc/grpc.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/security/server_credentials.h>

#include "dronecore.h"
#include "dronecore.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;
using dronecorerpc::Bool;
using dronecorerpc::Empty;
using dronecorerpc::DroneCoreRPC;
using dronecorerpc::Waypoint;

using namespace dronecore;
using namespace std::placeholders;

enum class MissionState : unsigned {
    INIT = 0,
    UPLOADING,
    UPLOADING_DONE,
    ARMING,
    ARMING_DONE,
    STARTING,
    STARTING_DONE,
    MISSION,
    MISSION_PAUSING,
    PAUSE,
    MISSION_RESUMING,
    MISSION_DONE,
    RETURN,
    RETURN_DONE,
    DONE,
    ERROR
};

class DroneCoreRPCImpl final : public DroneCoreRPC::Service
{

    Status Arm(ServerContext *context, const Empty *request,
               dronecorerpc::ActionResult *response) override
    {
        Device &device = dc.device();
        const Action::Result action_result = device.action().arm();
        response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result));
        response->set_result_str(Action::result_str(action_result));
        return Status::OK;
    }

    Status TakeOff(ServerContext *context, const Empty *request,
                   dronecorerpc::ActionResult *response) override
    {
        Device &device = dc.device();
        const Action::Result action_result = device.action().takeoff();
        response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result));
        response->set_result_str(Action::result_str(action_result));
        return Status::OK;
    }

    Status Land(ServerContext *context, const Empty *request,
                dronecorerpc::ActionResult *response) override
    {
        Device &device = dc.device();
        const Action::Result action_result = device.action().land();
        response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result));
        response->set_result_str(Action::result_str(action_result));
        return Status::OK;
    }

    Status AddWaypoint(ServerContext *context, const Waypoint *waypoint, Bool *response) override
    {
        std::shared_ptr<MissionItem> new_item(new MissionItem());
        new_item->set_position(waypoint->latitude(), waypoint->longitude());
        new_item->set_relative_altitude(waypoint->altitude());
        new_item->set_speed(waypoint->speed());
        new_item->set_fly_through(waypoint->is_fly_through());
        new_item->set_gimbal_pitch_and_yaw(waypoint->pitch(), waypoint->yaw());
        new_item->set_camera_action(static_cast<dronecore::MissionItem::CameraAction>
                                    (waypoint->camera_action()));
        mission_items.push_back(new_item);
        response->set_ret(true);
        return Status::OK;
    }

    Status FlyMission(ServerContext *context, const Empty *request, Bool *response) override
    {
        Device &device = dc.device();
        finished = false;
        _mission_state = MissionState::INIT;
        while (!finished) {
            switch (_mission_state) {
                case MissionState::INIT:
                    device.mission().send_mission_async(
                        mission_items,
                        std::bind(&receive_send_mission_result, _1));
                    _mission_state = MissionState::UPLOADING;
                    break;
                case MissionState::UPLOADING:
                    break;
                case MissionState::UPLOADING_DONE:
                    std::cout << "arming!" << std::endl;
                    if (!device.telemetry().armed()) {
                        device.action().arm_async(std::bind(&receive_arm_result, _1));
                        _mission_state = MissionState::ARMING;
                    }
                    break;
                case MissionState::ARMING:
                    break;
                case MissionState::ARMING_DONE:
                    // TODO: There can be a race here if PX4 still listens to the armed flag in
                    // the message DO_SET_MODE. Once it ignores it as in the spec, this is not
                    // needed anymore.
                    std::this_thread::sleep_for(std::chrono::seconds(2));
                    device.mission().start_mission_async(
                        std::bind(&receive_start_mission_result, _1));
                    _mission_state = MissionState::STARTING;
                    break;
                case MissionState::STARTING:
                    break;
                case MissionState::STARTING_DONE:
                    _mission_state = MissionState::MISSION;
                    device.mission().subscribe_progress(
                        std::bind(&receive_mission_progress, _1, _2));
                    break;
                case MissionState::MISSION_DONE:
                    device.action().return_to_launch_async(
                        std::bind(&receive_return_to_launch_result, _1));
                    _mission_state = MissionState::RETURN;
                    break;
                case MissionState::RETURN:
                    if (!device.telemetry().in_air()) {
                        _mission_state = MissionState::RETURN_DONE;
                    }
                    break;
                case MissionState::RETURN_DONE:
                    device.action().disarm_async(std::bind(&receive_disarm_result, _1));
                    break;
                case MissionState::DONE:
                    finished = true;
                    break;
                case MissionState::ERROR:
                    finished = true;
                    break;

            }
        }
        if (_mission_state == MissionState::DONE) {
            response->set_ret(true);
        } else {
            response->set_ret(false);
        }
        return Status::OK;
    }

public:
    DroneCore dc;
    std::vector<std::shared_ptr<MissionItem>> mission_items;
    static MissionState _mission_state;
    bool finished;

    static void receive_send_mission_result(Mission::Result result)
    {

        if (result == Mission::Result::SUCCESS) {
            _mission_state = MissionState::UPLOADING_DONE;
        } else {
            std::cerr << "Error: mission send result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_start_mission_result(Mission::Result result)
    {

        if (result == Mission::Result::SUCCESS) {
            _mission_state = MissionState::STARTING_DONE;
        } else {
            std::cerr << "Error: mission start result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_mission_progress(int current, int total)
    {
        std::cout << "Mission status update: " << current << " / " << total << std::endl;

        if (current > 0 && current == total) {
            _mission_state = MissionState::MISSION_DONE;
        }
    }

    static void receive_arm_result(Action::Result result)
    {

        if (result == Action::Result::SUCCESS) {
            _mission_state = MissionState::ARMING_DONE;
        } else {
            std::cerr << "Error: arming result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_return_to_launch_result(Action::Result result)
    {

        if (result == Action::Result::SUCCESS) {
        } else {
            std::cerr << "Error: return to land result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_disarm_result(Action::Result result)
    {

        if (result == Action::Result::SUCCESS) {
        } else {
            std::cerr << "Error: disarming result: " << unsigned(result) << std::endl;
        }

        _mission_state = MissionState::DONE;
    }
};

MissionState DroneCoreRPCImpl::_mission_state;

void RunServer()
{
    std::string server_address("0.0.0.0:50051");
    DroneCoreRPCImpl service;

    bool discovered_device = false;
    DroneCore::ConnectionResult connection_result = service.dc.add_udp_connection();
    if (connection_result != DroneCore::ConnectionResult::SUCCESS) {
        std::cout << "Connection failed: " << DroneCore::connection_result_str(
                      connection_result) << std::endl;
        return;
    }
    std::cout << "Waiting to discover device..." << std::endl;
    service.dc.register_on_discover([&discovered_device](uint64_t uuid) {
        std::cout << "Discovered device with UUID: " << uuid << std::endl;
        discovered_device = true;
    });
    // We usually receive heartbeats at 1Hz, therefore we should find a device after around 2 seconds.
    std::this_thread::sleep_for(std::chrono::seconds(2));
    if (!discovered_device) {
        std::cout << "No device found, exiting." << std::endl;
        return;
    }

    ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;
    server->Wait();
}

int main(int argc, char **argv)
{
    RunServer();
    return 0;
}
<commit_msg>dronecore_server: fix switch case compiler warning<commit_after>#include <iostream>
#include <thread>
#include <chrono>
#include <cstdint>

#include <grpc/grpc.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/security/server_credentials.h>

#include "dronecore.h"
#include "dronecore.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;
using dronecorerpc::Bool;
using dronecorerpc::Empty;
using dronecorerpc::DroneCoreRPC;
using dronecorerpc::Waypoint;

using namespace dronecore;
using namespace std::placeholders;

enum class MissionState : unsigned {
    INIT = 0,
    UPLOADING,
    UPLOADING_DONE,
    ARMING,
    ARMING_DONE,
    STARTING,
    STARTING_DONE,
    MISSION,
    MISSION_PAUSING,
    PAUSE,
    MISSION_RESUMING,
    MISSION_DONE,
    RETURN,
    RETURN_DONE,
    DONE,
    ERROR
};

class DroneCoreRPCImpl final : public DroneCoreRPC::Service
{

    Status Arm(ServerContext *context, const Empty *request,
               dronecorerpc::ActionResult *response) override
    {
        Device &device = dc.device();
        const Action::Result action_result = device.action().arm();
        response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result));
        response->set_result_str(Action::result_str(action_result));
        return Status::OK;
    }

    Status TakeOff(ServerContext *context, const Empty *request,
                   dronecorerpc::ActionResult *response) override
    {
        Device &device = dc.device();
        const Action::Result action_result = device.action().takeoff();
        response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result));
        response->set_result_str(Action::result_str(action_result));
        return Status::OK;
    }

    Status Land(ServerContext *context, const Empty *request,
                dronecorerpc::ActionResult *response) override
    {
        Device &device = dc.device();
        const Action::Result action_result = device.action().land();
        response->set_result(static_cast<dronecorerpc::ActionResult::Result>(action_result));
        response->set_result_str(Action::result_str(action_result));
        return Status::OK;
    }

    Status AddWaypoint(ServerContext *context, const Waypoint *waypoint, Bool *response) override
    {
        std::shared_ptr<MissionItem> new_item(new MissionItem());
        new_item->set_position(waypoint->latitude(), waypoint->longitude());
        new_item->set_relative_altitude(waypoint->altitude());
        new_item->set_speed(waypoint->speed());
        new_item->set_fly_through(waypoint->is_fly_through());
        new_item->set_gimbal_pitch_and_yaw(waypoint->pitch(), waypoint->yaw());
        new_item->set_camera_action(static_cast<dronecore::MissionItem::CameraAction>
                                    (waypoint->camera_action()));
        mission_items.push_back(new_item);
        response->set_ret(true);
        return Status::OK;
    }

    Status FlyMission(ServerContext *context, const Empty *request, Bool *response) override
    {
        Device &device = dc.device();
        finished = false;
        _mission_state = MissionState::INIT;
        while (!finished) {
            switch (_mission_state) {
                case MissionState::INIT:
                    device.mission().send_mission_async(
                        mission_items,
                        std::bind(&receive_send_mission_result, _1));
                    _mission_state = MissionState::UPLOADING;
                    break;
                case MissionState::UPLOADING:
                    break;
                case MissionState::UPLOADING_DONE:
                    std::cout << "arming!" << std::endl;
                    if (!device.telemetry().armed()) {
                        device.action().arm_async(std::bind(&receive_arm_result, _1));
                        _mission_state = MissionState::ARMING;
                    }
                    break;
                case MissionState::ARMING:
                    break;
                case MissionState::ARMING_DONE:
                    // TODO: There can be a race here if PX4 still listens to the armed flag in
                    // the message DO_SET_MODE. Once it ignores it as in the spec, this is not
                    // needed anymore.
                    std::this_thread::sleep_for(std::chrono::seconds(2));
                    device.mission().start_mission_async(
                        std::bind(&receive_start_mission_result, _1));
                    _mission_state = MissionState::STARTING;
                    break;
                case MissionState::STARTING:
                    break;
                case MissionState::STARTING_DONE:
                    _mission_state = MissionState::MISSION;
                    device.mission().subscribe_progress(
                        std::bind(&receive_mission_progress, _1, _2));
                    break;
                case MissionState::MISSION_DONE:
                    device.action().return_to_launch_async(
                        std::bind(&receive_return_to_launch_result, _1));
                    _mission_state = MissionState::RETURN;
                    break;
                case MissionState::RETURN:
                    if (!device.telemetry().in_air()) {
                        _mission_state = MissionState::RETURN_DONE;
                    }
                    break;
                case MissionState::RETURN_DONE:
                    device.action().disarm_async(std::bind(&receive_disarm_result, _1));
                    break;
                case MissionState::DONE:
                    finished = true;
                    break;
                case MissionState::ERROR:
                    finished = true;
                    break;

                case MissionState::MISSION:
                // FALLTHROUGH
                case MissionState::MISSION_PAUSING:
                // FALLTHROUGH
                case MissionState::PAUSE:
                // FALLTHROUGH
                case MissionState::MISSION_RESUMING:
                // FALLTHROUGH
                default:
                    // not handled
                    break;

            }
        }
        if (_mission_state == MissionState::DONE) {
            response->set_ret(true);
        } else {
            response->set_ret(false);
        }
        return Status::OK;
    }

public:
    DroneCore dc;
    std::vector<std::shared_ptr<MissionItem>> mission_items;
    static MissionState _mission_state;
    bool finished;

    static void receive_send_mission_result(Mission::Result result)
    {

        if (result == Mission::Result::SUCCESS) {
            _mission_state = MissionState::UPLOADING_DONE;
        } else {
            std::cerr << "Error: mission send result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_start_mission_result(Mission::Result result)
    {

        if (result == Mission::Result::SUCCESS) {
            _mission_state = MissionState::STARTING_DONE;
        } else {
            std::cerr << "Error: mission start result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_mission_progress(int current, int total)
    {
        std::cout << "Mission status update: " << current << " / " << total << std::endl;

        if (current > 0 && current == total) {
            _mission_state = MissionState::MISSION_DONE;
        }
    }

    static void receive_arm_result(Action::Result result)
    {

        if (result == Action::Result::SUCCESS) {
            _mission_state = MissionState::ARMING_DONE;
        } else {
            std::cerr << "Error: arming result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_return_to_launch_result(Action::Result result)
    {

        if (result == Action::Result::SUCCESS) {
        } else {
            std::cerr << "Error: return to land result: " << unsigned(result) << std::endl;
            _mission_state = MissionState::ERROR;
        }
    }

    static void receive_disarm_result(Action::Result result)
    {

        if (result == Action::Result::SUCCESS) {
        } else {
            std::cerr << "Error: disarming result: " << unsigned(result) << std::endl;
        }

        _mission_state = MissionState::DONE;
    }
};

MissionState DroneCoreRPCImpl::_mission_state;

void RunServer()
{
    std::string server_address("0.0.0.0:50051");
    DroneCoreRPCImpl service;

    bool discovered_device = false;
    DroneCore::ConnectionResult connection_result = service.dc.add_udp_connection();
    if (connection_result != DroneCore::ConnectionResult::SUCCESS) {
        std::cout << "Connection failed: " << DroneCore::connection_result_str(
                      connection_result) << std::endl;
        return;
    }
    std::cout << "Waiting to discover device..." << std::endl;
    service.dc.register_on_discover([&discovered_device](uint64_t uuid) {
        std::cout << "Discovered device with UUID: " << uuid << std::endl;
        discovered_device = true;
    });
    // We usually receive heartbeats at 1Hz, therefore we should find a device after around 2 seconds.
    std::this_thread::sleep_for(std::chrono::seconds(2));
    if (!discovered_device) {
        std::cout << "No device found, exiting." << std::endl;
        return;
    }

    ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;
    server->Wait();
}

int main(int argc, char **argv)
{
    RunServer();
    return 0;
}
<|endoftext|>


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

#include "audio_output_converter.h"

#define NUM_CHANNELS (2)

using namespace slab;

//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------

// void AudioOutputConverter::set_buffer(float * buffer, size_t bufferSize)
// {
//     m_buffer = buffer;
//     m_bufferSize = bufferSize;
// }

void AudioOutputConverter::fill_buffer(uint32_t bufferIndex, AudioOutput::Buffer & buffer)
{
    assert(m_source);
    m_source->process(m_buffer); //, m_bufferSize);

    int16_t * out = (int16_t *)buffer.data;
    int sampleCount = buffer.dataSize / sizeof(int16_t) / NUM_CHANNELS;
    assert(sampleCount <= m_buffer.get_count());

    int i;
    for (i = 0; i < sampleCount; ++i)
    {
        float sample = m_buffer[i];
        int16_t intSample = int16_t(sample * 32767.0);
        *out++ = intSample;
        *out++ = intSample;
    }
}

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

#include "audio_output_converter.h"

#define NUM_CHANNELS (2)

using namespace slab;

//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------

void AudioOutputConverter::fill_buffer(uint32_t bufferIndex, AudioOutput::Buffer & buffer)
{
    assert(m_source);
    m_source->process(m_buffer);

    int16_t * out = (int16_t *)buffer.data;
    int sampleCount = buffer.dataSize / sizeof(int16_t) / NUM_CHANNELS;
    assert(sampleCount <= m_buffer.get_count());

    int i;
    for (i = 0; i < sampleCount; ++i)
    {
        float sample = m_buffer[i];
        int16_t intSample = int16_t(sample * 32767.0);
        *out++ = intSample;
        *out++ = intSample;
    }
}

//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>Fixed problem with rasp camera command<commit_after><|endoftext|>