<commit_before>#include "userlayer.h"
#include <csperson.h>
#include <iostream>
using namespace std;

const string GENDER_MALE = "1";
const string GENDER_FEMALE = "2";
const string GENDER_OTHER = "3";

void invalidInput();

UserLayer::UserLayer()
{
    CSPersonService test;
}

void UserLayer::addPerson()
{

    string name, gender, comment;
    string birthYear,deathYear;

    // input and counter is for the gender input
    string input;
    int error_counter = 0;

    cout << "Enter name: ";
    cin.ignore();
    getline(cin, name);

    // TODO :IF PERSON EXISTS DISPLAY ERROR MESSAGE

    do
    {
        input = "";
        if(error_counter > 0)
        {
            cout << endl;
            invalidInput();
            cout << endl;
        }

        cout << "Select gender: " << endl;
        cout << endl;
        cout << "Enter 1 for male" << endl;
        cout << "Enter 2 for female" << endl;
        cout << "Enter 3 for other" << endl;

        cin >> input;
        if(input == GENDER_MALE)
        {
            gender = "Male";
            break;
        }
        else if(input == GENDER_FEMALE)
        {
            gender = "Female";
            break;
        }
        else if(input == GENDER_OTHER)
        {
            gender = "Other";
            break;
        }
        error_counter ++;

    }while(input != GENDER_MALE || input != GENDER_FEMALE || input != GENDER_OTHER);

    // counter is reset for next iteration.
    error_counter = 0;

    // Birth year validation
    birthYearValidation(birthYear);

    cout << "BYTESTESTEST:::" << birthYear << endl;

    cout << "Enter the year of death, 0 if this person is still alive: ";
    cin >> deathYear;
    cout << "What is this person's greatest achievement: ";
    cin >> comment;
    cout << endl;
    cout << "This person has now been added to your list." << endl;
    cout << endl;

    //CSPerson newPerson(name, gender, birthYear, deathYear, comment); TODO Lesa inn nýjan Person

    //lA.addToList(newPerson);

}

bool UserLayer::checkNumberValidity(string userInput)
{
    // numberTest becomes zero if the user input is invalid.
    int numberTest = atoi(userInput.c_str());
    if(numberTest <= 0  || numberTest >= 3000)
    {
        return true;
    }

    return false;
}

void UserLayer::birthYearValidation(string birthYear)
{
    bool birthYearValidation = true;
    while(birthYearValidation)
    {
        cout << "Enter the year of birth: ";
        cin >> birthYear;
        if(checkNumberValidity(birthYear))
        {
            cout << endl;
            cout << "Invalid input, try again." << endl;
            cout << endl;
        }
        else
        {
            birthYearValidation = false;
        }
    }
}

void UserLayer::printList()
{
    vector<CSPerson> completeList = _CSPS.getCompleteList();

    int sizeOfList = completeList.size();

    if(sizeOfList == 0)
    {
        cout << "List is empty." << endl;
        return;
    }

    // MAYBE LATER
    //cout << "Name----------------------------Gender----Year of birth----Year of death----Info-------------" << endl;

    for(int i=0;i<sizeOfList;i++)
    {
        cout << "Name        : " <<  completeList.at(i).getName() << endl;
        cout << "Gender      : " << completeList.at(i).getGender() << endl;
        cout << "Birth year  : " << completeList.at(i).getBirthYear() << endl;

        if(completeList.at(i).getPassedAwayYear() == 0)
        {
            cout << "Passed away : Alive" << endl;
        }
        else
        {
            cout << "Passed away : " << completeList.at(i).getPassedAwayYear() << endl;
        }
        cout << "Info        : " << completeList.at(i).getComments() << endl;
        cout << endl;

    }
}

<commit_msg>minor change<commit_after>#include "userlayer.h"
#include <csperson.h>
#include <iostream>
using namespace std;

const string GENDER_MALE = "1";
const string GENDER_FEMALE = "2";
const string GENDER_OTHER = "3";

void invalidInput();

UserLayer::UserLayer()
{
    CSPersonService test;
}

void UserLayer::addPerson()
{

    string name, gender, comment;
    string birthYear,deathYear;

    // input and counter is for the gender input
    string input;
    int error_counter = 0;

    cout << "Enter name: ";
    cin.ignore();
    getline(cin, name);

    // TODO :IF PERSON EXISTS DISPLAY ERROR MESSAGE

    do
    {
        input = "";
        if(error_counter > 0)
        {
            cout << endl;
            invalidInput();
            cout << endl;
        }

        cout << "Select gender: " << endl << endl;
        cout << "Enter 1 for male" << endl;
        cout << "Enter 2 for female" << endl;
        cout << "Enter 3 for other" << endl;

        cin >> input;
        if(input == GENDER_MALE)
        {
            gender = "Male";
            break;
        }
        else if(input == GENDER_FEMALE)
        {
            gender = "Female";
            break;
        }
        else if(input == GENDER_OTHER)
        {
            gender = "Other";
            break;
        }
        error_counter ++;

    }while(input != GENDER_MALE || input != GENDER_FEMALE || input != GENDER_OTHER);

    // counter is reset for next iteration.
    error_counter = 0;

    // Birth year validation
    birthYearValidation(birthYear);

    cout << "BYTESTESTEST:::" << birthYear << endl;

    cout << "Enter the year of death, 0 if this person is still alive: ";
    cin >> deathYear;
    cout << "What is this person's greatest achievement: ";
    cin >> comment;
    cout << endl;
    cout << "This person has now been added to your list." << endl;
    cout << endl;

    //CSPerson newPerson(name, gender, birthYear, deathYear, comment); TODO Lesa inn nýjan Person

    //lA.addToList(newPerson);

}

bool UserLayer::checkNumberValidity(string userInput)
{
    // numberTest becomes zero if the user input is invalid.
    int numberTest = atoi(userInput.c_str());
    if(numberTest <= 0  || numberTest >= 3000)
    {
        return true;
    }

    return false;
}

void UserLayer::birthYearValidation(string birthYear)
{
    bool birthYearValidation = true;
    while(birthYearValidation)
    {
        cout << "Enter the year of birth: ";
        cin >> birthYear;
        if(checkNumberValidity(birthYear))
        {
            cout << endl;
            cout << "Invalid input, try again." << endl;
            cout << endl;
        }
        else
        {
            birthYearValidation = false;
        }
    }
}

void UserLayer::printList()
{
    vector<CSPerson> completeList = _CSPS.getCompleteList();

    int sizeOfList = completeList.size();

    if(sizeOfList == 0)
    {
        cout << "List is empty." << endl;
        return;
    }

    // MAYBE LATER
    //cout << "Name----------------------------Gender----Year of birth----Year of death----Info-------------" << endl;

    for(int i=0;i<sizeOfList;i++)
    {
        cout << "Name        : " <<  completeList.at(i).getName() << endl;
        cout << "Gender      : " << completeList.at(i).getGender() << endl;
        cout << "Birth year  : " << completeList.at(i).getBirthYear() << endl;

        if(completeList.at(i).getPassedAwayYear() == 0)
        {
            cout << "Passed away : Alive" << endl;
        }
        else
        {
            cout << "Passed away : " << completeList.at(i).getPassedAwayYear() << endl;
        }
        cout << "Info        : " << completeList.at(i).getComments() << endl;
        cout << endl;

    }
}

<|endoftext|>


<commit_before>
#include "../Commander.hpp"
#include "math.h"
#include <iostream>

int main(int argc, char* argv[])
{
    HuboCmd::Commander cmd;
    if(!cmd.initialized())
    {
        std::cout << "Commander was not initialized successfully!" << std::endl;
        return 1;
    }

    StringArray joint_names;
    ValueArray joint_values;
    joint_names.push_back("RSP");
//    joint_names.push_back("REP");
    joint_values.resize(joint_names.size());

    IndexArray indices = cmd.get_indices(joint_names);

    cmd.claim_joints(indices);
    cmd.send_commands();
    cmd.update();

    cmd.set_modes(indices, HUBO_CMD_RIGID);

    cmd.update();

    for(size_t i=0; i<indices.size(); ++i)
    {
        if(cmd.joints[indices[i]].position != 0)
        {
            std::cout << "Joint " << cmd.description().joints[indices[i]]->info.name
                      << " is not at 0, so we will not execute this test" << std::endl;
            return 1;
        }
    }

    double T = 10, start = cmd.get_time();
    double elapsed = 0;
    while(elapsed <= T)
    {
        joint_values[0] = M_PI/4.0*sin(2*M_PI*elapsed/T);
//        joint_values[1] = -M_PI/2.0*(1.0/2.0)*(1-cos(2*M_PI*elapsed/T));

        std::cout << joint_values[0]
//                  << "\t" << joint_values[1]
                  << std::endl;

        cmd.set_positions(indices, joint_values);

        cmd.send_commands();

        HuboCan::error_result_t result = cmd.update();
        if(result != HuboCan::OKAY)
        {
            std::cout << "Update threw an error: " << result << std::endl;
            return 1;
        }
        elapsed = cmd.get_time() - start;
    }

    return 0;
}
<commit_msg>ready to test simple trajectory<commit_after>
#include "../Commander.hpp"
#include "math.h"
#include <iostream>

int main(int argc, char* argv[])
{
    HuboCmd::Commander cmd;
    if(!cmd.initialized())
    {
        std::cout << "Commander was not initialized successfully!" << std::endl;
        return 1;
    }

    StringArray joint_names;
    ValueArray joint_values;
    joint_names.push_back("RSP");
    joint_names.push_back("REP");
    joint_values.resize(joint_names.size());

    IndexArray indices = cmd.get_indices(joint_names);

    cmd.claim_joints(indices);
    cmd.send_commands();
    cmd.update();

    cmd.set_modes(indices, HUBO_CMD_RIGID);

    cmd.update();

    for(size_t i=0; i<indices.size(); ++i)
    {
        if(cmd.joints[indices[i]].position != 0)
        {
            std::cout << "Joint " << cmd.description().joints[indices[i]]->info.name
                      << " is not at 0, so we will not execute this test" << std::endl;
            return 1;
        }
    }

    double T = 10, start = cmd.get_time();
    double elapsed = 0;
    while(elapsed <= T)
    {
        joint_values[0] = M_PI/4.0*sin(2*M_PI*elapsed/T);
        joint_values[1] = -M_PI/2.0*(1.0/2.0)*(1-cos(2*M_PI*elapsed/T));

        std::cout << joint_values[0]
                  << "\t" << joint_values[1]
                  << std::endl;

        cmd.set_positions(indices, joint_values);

        cmd.send_commands();

        HuboCan::error_result_t result = cmd.update();
        if(result != HuboCan::OKAY)
        {
            std::cout << "Update threw an error: " << result << std::endl;
            return 1;
        }
        elapsed = cmd.get_time() - start;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 Copyright (C) 2012 by Ivan Safrin

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#include "PolycodeEditor.h"

extern PolycodeClipboard *globalClipboard;

PolycodeEditorFactory::PolycodeEditorFactory() {

}

PolycodeEditorFactory::~PolycodeEditorFactory() {

}

bool PolycodeEditorFactory::canHandleExtension(String extension) {
	for(int i=0; i < extensions.size(); i++) {
		if(extension == extensions[i])
		   return true;
	}
	return false;
}

void PolycodeEditor::setFilePath(String newPath) {
	filePath = newPath;
}

PolycodeEditor::PolycodeEditor(bool _isReadOnly) : ScreenEntity(), ClipboardProvider() {
	this->_isReadOnly = _isReadOnly;
	enableScissor = true;
	processInputEvents = true;
	_hasChanges = false;

	Core *core = CoreServices::getInstance()->getCore();

	core->addEventListener(this, Core::EVENT_COPY);
	core->addEventListener(this, Core::EVENT_PASTE);
}

void PolycodeEditor::setHasChanges(bool newVal) {
	if(_hasChanges != newVal) {
		_hasChanges = newVal;
		dispatchEvent(new Event(), Event::CHANGE_EVENT);
	}
}

void PolycodeEditor::handleEvent(Event *event) {
	if(event->getDispatcher() == CoreServices::getInstance()->getCore()) {
		switch(event->getEventCode()) {
			case Core::EVENT_COPY:
			{
				void *data = NULL;
				String dataType = Copy(&data);
				if(data) {
					globalClipboard->setData(data, dataType, this);
				}
			}
			break;
			case Core::EVENT_PASTE:
			{
				if(globalClipboard->getData()) {
					Paste(globalClipboard->getData(), globalClipboard->getType());
				}
			}
			break;
		}
	}
}

void PolycodeEditor::Resize(int x, int y) {
	editorSize = Vector2(x,y);
	Vector2 pos = getScreenPosition();
	scissorBox.setRect(pos.x,pos.y, x, y);
}

PolycodeEditor::~PolycodeEditor() {

}

<commit_msg>Added a clarification about copy events.<commit_after>/*
 Copyright (C) 2012 by Ivan Safrin

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#include "PolycodeEditor.h"

extern PolycodeClipboard *globalClipboard;

PolycodeEditorFactory::PolycodeEditorFactory() {

}

PolycodeEditorFactory::~PolycodeEditorFactory() {

}

bool PolycodeEditorFactory::canHandleExtension(String extension) {
	for(int i=0; i < extensions.size(); i++) {
		if(extension == extensions[i])
		   return true;
	}
	return false;
}

void PolycodeEditor::setFilePath(String newPath) {
	filePath = newPath;
}

PolycodeEditor::PolycodeEditor(bool _isReadOnly) : ScreenEntity(), ClipboardProvider() {
	this->_isReadOnly = _isReadOnly;
	enableScissor = true;
	processInputEvents = true;
	_hasChanges = false;

	Core *core = CoreServices::getInstance()->getCore();

	core->addEventListener(this, Core::EVENT_COPY);
	core->addEventListener(this, Core::EVENT_PASTE);
}

void PolycodeEditor::setHasChanges(bool newVal) {
	if(_hasChanges != newVal) {
		_hasChanges = newVal;
		dispatchEvent(new Event(), Event::CHANGE_EVENT);
	}
}

void PolycodeEditor::handleEvent(Event *event) {
	if(event->getDispatcher() == CoreServices::getInstance()->getCore()) {
		switch(event->getEventCode()) {

			// Only copypaste of more complex IDE entities is handled here.
			// Pure text copy/paste is handled in:
			// Modules/Contents/UI/Source/PolyUITextInput.cpp
			case Core::EVENT_COPY:
			{
				void *data = NULL;
				String dataType = Copy(&data);
				if(data) {
					globalClipboard->setData(data, dataType, this);
				}
			}
			break;
			case Core::EVENT_PASTE:
			{
				if(globalClipboard->getData()) {
					Paste(globalClipboard->getData(), globalClipboard->getType());
				}
			}
			break;
		}
	}
}

void PolycodeEditor::Resize(int x, int y) {
	editorSize = Vector2(x,y);
	Vector2 pos = getScreenPosition();
	scissorBox.setRect(pos.x,pos.y, x, y);
}

PolycodeEditor::~PolycodeEditor() {

}

<|endoftext|>


<commit_before>#include <UnmanagedSymPrv.h>
#include <llvm/Demangle/Demangle.h>
#include <stdlib.h>

extern "C" {
	char* __cxa_demangle(const char* mangled_name,
		char* buf,
		size_t* n,
		int* status);
}

bool DemumbleDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	size_t NameLen;
	int status;
	size_t MbstowcsStatus = 0;
	char *AsciiUndecoratedName = NULL;

	char *DecoratedNameAscii = (char*)malloc(DecoratedNameLen * sizeof(wchar_t));
	sprintf_s(DecoratedNameAscii, DecoratedNameLen * sizeof(wchar_t), "%ws", DecoratedName);

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	*UndecoratedNameLen = 0;
	NameLen = DecoratedNameLen;

	AsciiUndecoratedName = __cxa_demangle(
		DecoratedNameAscii,
		NULL,
		&NameLen,
		&status
	);

	if (!status) {
		*UndecoratedName = (wchar_t*)malloc(NameLen * sizeof(wchar_t) + sizeof(wchar_t));

		mbstowcs_s(
			&MbstowcsStatus,
			*UndecoratedName,
			NameLen,
			AsciiUndecoratedName,
			STRUNCATE
		);

		*UndecoratedNameLen = NameLen * sizeof(wchar_t);
	}

	free(DecoratedNameAscii);

	// UNIX-style error code
	return status == 0;
}

bool LLVMItaniumDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	size_t NameLen;
	int status;
	size_t MbstowcsStatus = 0;
	char *AsciiUndecoratedName = NULL;

	char *DecoratedNameAscii = (char*)malloc(DecoratedNameLen * sizeof(wchar_t));
	sprintf_s(DecoratedNameAscii, DecoratedNameLen * sizeof(wchar_t), "%ws", DecoratedName);

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	*UndecoratedNameLen = 0;
	NameLen = DecoratedNameLen;

	AsciiUndecoratedName = llvm::itaniumDemangle(
		DecoratedNameAscii,
		nullptr,
		&NameLen,
		&status
	);

	if (!status) {
		*UndecoratedName = (wchar_t*)malloc(NameLen * sizeof(wchar_t) + sizeof(wchar_t));

		mbstowcs_s(
			&MbstowcsStatus,
			*UndecoratedName,
			NameLen,
			AsciiUndecoratedName,
			STRUNCATE
		);

		*UndecoratedNameLen = NameLen * sizeof(wchar_t);
	}

	free(DecoratedNameAscii);

	// UNIX-style error code
	return status == 0;
}

bool LLVMMicrosoftDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	size_t NameLen;
	int status;
	size_t MbstowcsStatus = 0;
	char *AsciiUndecoratedName = NULL;

	char *DecoratedNameAscii = (char*)malloc(DecoratedNameLen * sizeof(wchar_t));
	sprintf_s(DecoratedNameAscii, DecoratedNameLen * sizeof(wchar_t), "%ws", DecoratedName);

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	*UndecoratedNameLen = 0;
	NameLen = DecoratedNameLen;

	AsciiUndecoratedName = llvm::microsoftDemangle(
		DecoratedNameAscii,
		nullptr,
		&NameLen,
		&status
	);

	if (!status) {
		*UndecoratedName = (wchar_t*)malloc(NameLen * sizeof(wchar_t) + sizeof(wchar_t));

		mbstowcs_s(
			&MbstowcsStatus,
			*UndecoratedName,
			NameLen,
			AsciiUndecoratedName,
			STRUNCATE
		);

		*UndecoratedNameLen = NameLen * sizeof(wchar_t);
	}

	free(DecoratedNameAscii);

	// UNIX-style error code
	return status == 0;
}

bool UndecorateSymbolDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	PPH_STRING PhUndecoratedName = NULL;

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	PhUndecoratedName = PhUndecorateNameW(
		obj->m_SymbolProvider,
		DecoratedName
	);

	if (!PhUndecoratedName)
		return false;

	*UndecoratedNameLen = PhUndecoratedName->Length;
	*UndecoratedName = (wchar_t*)malloc(PhUndecoratedName->Length + sizeof(wchar_t));

	memset(*UndecoratedName, 0, PhUndecoratedName->Length + sizeof(wchar_t));
	memcpy(*UndecoratedName, PhUndecoratedName->Buffer, PhUndecoratedName->Length);

	PhDereferenceObject(PhUndecoratedName);
	return true;
}

bool UnmanagedSymPrv::DemangleName(
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{

	// try to undecorate GCC/LLVM symbols using demumble
	if (DemumbleDemangleName(
		this,
		DecoratedName,
		DecoratedNameLen,
		UndecoratedName,
		UndecoratedNameLen
	)) {
		return true;
	}

	// try llvm-demangler. the heuristic is copied from .\llvm-7.0.0.src\lib\DebugInfo\Symbolize\Symbolize.cpp: LLVMSymbolizer::DemangleName
	if (!_wcsnicmp(DecoratedName, L"_Z", 2))
	{
		if (LLVMItaniumDemangleName(
			this,
			DecoratedName,
			DecoratedNameLen,
			UndecoratedName,
			UndecoratedNameLen
		)) {
			return true;
		}
	}

	// try to undecorate MSVC symbols using UndecorateName
	if (UndecorateSymbolDemangleName(
		this,
		DecoratedName,
		DecoratedNameLen,
		UndecoratedName,
		UndecoratedNameLen
	)) {
		return true;
	}

	// use llvm::microsoftDemangle as a last chance
	if (LLVMMicrosoftDemangleName(
		this,
		DecoratedName,
		DecoratedNameLen,
		UndecoratedName,
		UndecoratedNameLen
	)) {
		return true;
	}

	// Could not demangle name
	*UndecoratedNameLen =  0;
	*UndecoratedName = NULL;
	return false;
}

<commit_msg>Check if the symbol has been correctly undecorated<commit_after>#include <UnmanagedSymPrv.h>
#include <llvm/Demangle/Demangle.h>
#include <stdlib.h>

extern "C" {
	char* __cxa_demangle(const char* mangled_name,
		char* buf,
		size_t* n,
		int* status);
}

bool DemumbleDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	size_t NameLen;
	int status;
	size_t MbstowcsStatus = 0;
	char *AsciiUndecoratedName = NULL;

	char *DecoratedNameAscii = (char*)malloc(DecoratedNameLen * sizeof(wchar_t));
	sprintf_s(DecoratedNameAscii, DecoratedNameLen * sizeof(wchar_t), "%ws", DecoratedName);

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	*UndecoratedNameLen = 0;
	NameLen = DecoratedNameLen;

	AsciiUndecoratedName = __cxa_demangle(
		DecoratedNameAscii,
		NULL,
		&NameLen,
		&status
	);

	if (!status) {
		*UndecoratedName = (wchar_t*)malloc(NameLen * sizeof(wchar_t) + sizeof(wchar_t));

		mbstowcs_s(
			&MbstowcsStatus,
			*UndecoratedName,
			NameLen,
			AsciiUndecoratedName,
			STRUNCATE
		);

		*UndecoratedNameLen = NameLen * sizeof(wchar_t);
	}

	free(DecoratedNameAscii);

	// UNIX-style error code
	return status == 0;
}

bool LLVMItaniumDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	size_t NameLen;
	int status;
	size_t MbstowcsStatus = 0;
	char *AsciiUndecoratedName = NULL;

	char *DecoratedNameAscii = (char*)malloc(DecoratedNameLen * sizeof(wchar_t));
	sprintf_s(DecoratedNameAscii, DecoratedNameLen * sizeof(wchar_t), "%ws", DecoratedName);

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	*UndecoratedNameLen = 0;
	NameLen = DecoratedNameLen;

	AsciiUndecoratedName = llvm::itaniumDemangle(
		DecoratedNameAscii,
		nullptr,
		&NameLen,
		&status
	);

	if (!status) {
		*UndecoratedName = (wchar_t*)malloc(NameLen * sizeof(wchar_t) + sizeof(wchar_t));

		mbstowcs_s(
			&MbstowcsStatus,
			*UndecoratedName,
			NameLen,
			AsciiUndecoratedName,
			STRUNCATE
		);

		*UndecoratedNameLen = NameLen * sizeof(wchar_t);
	}

	free(DecoratedNameAscii);

	// UNIX-style error code
	return status == 0;
}

bool LLVMMicrosoftDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	size_t NameLen;
	int status;
	size_t MbstowcsStatus = 0;
	char *AsciiUndecoratedName = NULL;

	char *DecoratedNameAscii = (char*)malloc(DecoratedNameLen * sizeof(wchar_t));
	sprintf_s(DecoratedNameAscii, DecoratedNameLen * sizeof(wchar_t), "%ws", DecoratedName);

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	*UndecoratedNameLen = 0;
	NameLen = DecoratedNameLen;

	AsciiUndecoratedName = llvm::microsoftDemangle(
		DecoratedNameAscii,
		nullptr,
		&NameLen,
		&status
	);

	if (!status) {
		*UndecoratedName = (wchar_t*)malloc(NameLen * sizeof(wchar_t) + sizeof(wchar_t));

		mbstowcs_s(
			&MbstowcsStatus,
			*UndecoratedName,
			NameLen,
			AsciiUndecoratedName,
			STRUNCATE
		);

		*UndecoratedNameLen = NameLen * sizeof(wchar_t);
	}

	free(DecoratedNameAscii);

	// UNIX-style error code
	return status == 0;
}

bool UndecorateSymbolDemangleName(
	_In_ UnmanagedSymPrv* obj,
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{
	PPH_STRING PhUndecoratedName = NULL;

	if ((!UndecoratedName) || (!UndecoratedNameLen)) {
		return false;
	}

	PhUndecoratedName = PhUndecorateNameW(
		obj->m_SymbolProvider,
		DecoratedName
	);

	if ((!PhUndecoratedName) || wcsncmp(PhUndecoratedName->Buffer, DecoratedName, PhUndecoratedName->Length))
	{
		PhDereferenceObject(PhUndecoratedName);
		return false;
	}

	*UndecoratedNameLen = PhUndecoratedName->Length;
	*UndecoratedName = (wchar_t*)malloc(PhUndecoratedName->Length + sizeof(wchar_t));

	memset(*UndecoratedName, 0, PhUndecoratedName->Length + sizeof(wchar_t));
	memcpy(*UndecoratedName, PhUndecoratedName->Buffer, PhUndecoratedName->Length);

	PhDereferenceObject(PhUndecoratedName);
	return true;
}

bool UnmanagedSymPrv::DemangleName(
	_In_ wchar_t* DecoratedName,
	_In_ size_t DecoratedNameLen,
	_Out_ wchar_t** UndecoratedName,
	_Out_ size_t* UndecoratedNameLen
)
{

	// try to undecorate GCC/LLVM symbols using demumble
	if (DemumbleDemangleName(
		this,
		DecoratedName,
		DecoratedNameLen,
		UndecoratedName,
		UndecoratedNameLen
	)) {
		return true;
	}

	// try llvm-demangler. the heuristic is copied from .\llvm-7.0.0.src\lib\DebugInfo\Symbolize\Symbolize.cpp: LLVMSymbolizer::DemangleName
	if (!_wcsnicmp(DecoratedName, L"_Z", 2))
	{
		if (LLVMItaniumDemangleName(
			this,
			DecoratedName,
			DecoratedNameLen,
			UndecoratedName,
			UndecoratedNameLen
		)) {
			return true;
		}
	}

	// try to undecorate MSVC symbols using UndecorateName
	if (UndecorateSymbolDemangleName(
		this,
		DecoratedName,
		DecoratedNameLen,
		UndecoratedName,
		UndecoratedNameLen
	)) {
		return true;
	}

	// use llvm::microsoftDemangle as a last chance
	if (LLVMMicrosoftDemangleName(
		this,
		DecoratedName,
		DecoratedNameLen,
		UndecoratedName,
		UndecoratedNameLen
	)) {
		return true;
	}

	// Could not demangle name
	*UndecoratedNameLen =  0;
	*UndecoratedName = NULL;
	return false;
}

<|endoftext|>


<commit_before>#include<stdio.h>
#include<stdlib.h>
#include<cilk/cilk.h>
#include<omp.h>
//#define cilk_for for

int main(int argc, char** argv){
	int n,i,j,cont;
	float* vector;
	float* result;
	float* tmp;
	double time;

//Size of the vector
	scanf("%d",&n);
//Allocating memory for vectors
	vector = (float *)malloc(n*sizeof(float));
	if(!vector){
		printf("Insufficient memory!");
		return(0);
	}
	result = (float *)calloc(n,sizeof(float));
        if(!result){
                printf("Insufficient memory!");
                return(0);
        }
//Data input
	for(i=0;i<n;i=i+1){
		scanf("%f",vector+i);
	}
//Start time counter befor the sorting step
	time = omp_get_wtime();
//Parallel sorting
	cilk_for(int i=0;i<n;i=i+1){
		int cont = 0;
		for(j=0;j<n;j=j+1){
			if(vector[i] > vector[j]){
				cont = cont + 1;
			}
			else if ( (vector[i] == vector[j]) && (i > j) ){
				cont = cont + 1;
			}
		}
		result[cont] = vector[i];
	}
//Print the sorted vector
//	for(i=0;i<n;i++){
//		printf("%.2f ",result[i]);
//	}
//Print time
	printf("\n%lf\n",omp_get_wtime()-time);
	free(vector);
	free(result);
	return(0);
}
<commit_msg>Some details<commit_after>#include<stdio.h>
#include<stdlib.h>
#include<cilk/cilk.h>
#include<omp.h>
//#define cilk_for for
int main(int argc, char** argv){
	int n,i,j,cont;
	float* vector;
	float* result;
	float* tmp;
	double time;

//Uma porcaria o tempo de execução no PC testado

//Size of the vector
	scanf("%d",&n);
//Allocating memory for vectors
	vector = (float *)malloc(n*sizeof(float));
	if(!vector){
		printf("Insufficient memory!");
		return(0);
	}
	result = (float *)calloc(n,sizeof(float));
        if(!result){
                printf("Insufficient memory!");
                return(0);
        }
//Data input
	for(i=0;i<n;i=i+1){
		scanf("%f",vector+i);
	}
//Start time counter befor the sorting step
	time = omp_get_wtime();
//Parallel sorting
	cilk_for(int i=0;i<n;i=i+1){
		int cont = 0;
		for(j=0;j<n;j=j+1){
			if(vector[i] > vector[j]){
				cont = cont + 1;
			}
			else if ( (vector[i] == vector[j]) && (i > j) ){
				cont = cont + 1;
			}
		}
		result[cont] = vector[i];
	}
//Print the sorted vector
//	for(i=0;i<n;i++){
//		printf("%.2f ",result[i]);
//	}
//Print time
	printf("\n%lf\n",omp_get_wtime()-time);
	free(vector);
	free(result);
	return(0);
}
<|endoftext|>


<commit_before>#include "BaseRenderer.h"
#include "PlaneGeometry.h"
#include "EventMapper.h"
#include "PositionEvent.h"
#include "mitkDisplayPositionEvent.h"
#include "mitkSmartPointerProperty.h"
#include <vtkTransform.h>

//##ModelId=3D6A1791038B
void mitk::BaseRenderer::SetData(mitk::DataTreeIterator* iterator)
{
  if(m_DataTreeIterator != iterator)
  {
    delete m_DataTreeIterator;
    m_DataTreeIterator = NULL;

    if (iterator != NULL) {
      m_DataTreeIterator = iterator->clone();
    }
    Modified();
  }
}

//##ModelId=3E3314720003
void mitk::BaseRenderer::SetWindowId(void *id)
{
}

//##ModelId=3E330C4D0395
const MapperSlotId mitk::BaseRenderer::defaultMapper = 1;

//##ModelId=3E33162C00D0
void mitk::BaseRenderer::Paint()
{
}

//##ModelId=3E331632031E
void mitk::BaseRenderer::Initialize()
{
}

//##ModelId=3E33163703D9
void mitk::BaseRenderer::Resize(int w, int h)
{
  m_Size[0] = w;
  m_Size[1] = h;

  if(m_CameraController)
    m_CameraController->Resize(w, h);

  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
  //@FIXME: die nchste Zeile ist nur da, weil der Anpassungsvorgang in SetSizeInDisplayUnits leider noch nicht richtig funktioniert.
  GetDisplayGeometry()->Fit();
}

//##ModelId=3E33163A0261
void mitk::BaseRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
  m_RenderWindow = renderwindow;
}

//##ModelId=3E3799250397
void mitk::BaseRenderer::InitSize(int w, int h)
{
  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false);
  GetDisplayGeometry()->Fit();
}

//##ModelId=3E3D2F120050
mitk::BaseRenderer::BaseRenderer() : m_DataTreeIterator(NULL), m_RenderWindow(NULL), m_LastUpdateTime(0), m_MapperID(defaultMapper), m_CameraController(NULL), m_Focused(false)
{
  SmartPointerProperty::Pointer rendererProp = new SmartPointerProperty((itk::Object*)this);

  m_WorldGeometry = mitk::PlaneGeometry::New();

  m_WorldGeometryData = mitk::Geometry2DData::New();
  m_WorldGeometryData->SetGeometry2D(m_WorldGeometry);
  m_WorldGeometryNode = mitk::DataTreeNode::New();
  m_WorldGeometryNode->SetData(m_WorldGeometryData);
  m_WorldGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_WorldGeometryTransformTime = m_WorldGeometryNode->GetVtkTransform()->GetMTime();

  m_DisplayGeometry = mitk::DisplayGeometry::New();
  m_DisplayGeometry->SetWorldGeometry(m_WorldGeometry);
  m_DisplayGeometryData = mitk::Geometry2DData::New();
  m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
  m_DisplayGeometryNode = mitk::DataTreeNode::New();
  m_DisplayGeometryNode->SetData(m_DisplayGeometryData);
  m_DisplayGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime();
}

//##ModelId=3E3D2F12008C
mitk::BaseRenderer::~BaseRenderer()
{
  delete m_DataTreeIterator;
}

//##ModelId=3E66CC590379
void mitk::BaseRenderer::SetWorldGeometry(const mitk::Geometry2D* geometry2d)
{
  itkDebugMacro("setting WorldGeometry to " << geometry2d);
  if (m_WorldGeometry != geometry2d)
  {
    m_WorldGeometry = geometry2d;
    m_WorldGeometryData->SetGeometry2D(m_WorldGeometry);
    m_DisplayGeometry->SetWorldGeometry(m_WorldGeometry);
    Modified();
  }
}

//##ModelId=3E66CC59026B
void mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d)
{
  itkDebugMacro("setting DisplayGeometry to " << geometry2d);
  if (m_DisplayGeometry != geometry2d)
  {
    m_DisplayGeometry = geometry2d;
    m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
    Modified();
  }
}

//##ModelId=3E6D5DD30322
void mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
    m_CameraController->MousePressEvent(me);
  if(m_MapperID==1)
  {
    Point2D p(me->x(), me->y());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    return;
    Point2D p(me->x(), me->y());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    mitk::DisplayPositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    mitk::EventMapper::MapEvent(&event);
  }
}

//##ModelId=3E6D5DD30372
void mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
    m_CameraController->MouseReleaseEvent(me);

  if(m_MapperID==1)
  {
    Point2D p(me->x(), me->y());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    return;
    Point2D p(me->x(), me->y());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    mitk::DisplayPositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    mitk::EventMapper::MapEvent(&event);
  }
}

//##ModelId=3E6D5DD303C2
void mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
    m_CameraController->MouseMoveEvent(me);
  if(m_MapperID==1)
  {
    Point2D p(me->x(), me->y());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    return;
    Point2D p(me->x(), me->y());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    mitk::DisplayPositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    mitk::EventMapper::MapEvent(&event);
  }
}

//##ModelId=3E6D5DD4002A
void mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke)
{
  if (m_CameraController)
    m_CameraController->KeyPressEvent(ke);
  mitk::Event event(this, ke->type(), Qt::NoButton, Qt::NoButton, ke->key());
  mitk::EventMapper::MapEvent(&event);
}

//##ModelId=3EF1627503C4
void mitk::BaseRenderer::MakeCurrent()
{
}
<commit_msg>re-activated firing of DisplayPositionEvents<commit_after>#include "BaseRenderer.h"
#include "PlaneGeometry.h"
#include "EventMapper.h"
#include "PositionEvent.h"
#include "mitkDisplayPositionEvent.h"
#include "mitkSmartPointerProperty.h"
#include <vtkTransform.h>

//##ModelId=3D6A1791038B
void mitk::BaseRenderer::SetData(mitk::DataTreeIterator* iterator)
{
  if(m_DataTreeIterator != iterator)
  {
    delete m_DataTreeIterator;
    m_DataTreeIterator = NULL;

    if (iterator != NULL) {
      m_DataTreeIterator = iterator->clone();
    }
    Modified();
  }
}

//##ModelId=3E3314720003
void mitk::BaseRenderer::SetWindowId(void *id)
{
}

//##ModelId=3E330C4D0395
const MapperSlotId mitk::BaseRenderer::defaultMapper = 1;

//##ModelId=3E33162C00D0
void mitk::BaseRenderer::Paint()
{
}

//##ModelId=3E331632031E
void mitk::BaseRenderer::Initialize()
{
}

//##ModelId=3E33163703D9
void mitk::BaseRenderer::Resize(int w, int h)
{
  m_Size[0] = w;
  m_Size[1] = h;

  if(m_CameraController)
    m_CameraController->Resize(w, h);

  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
  //@FIXME: die nchste Zeile ist nur da, weil der Anpassungsvorgang in SetSizeInDisplayUnits leider noch nicht richtig funktioniert.
  GetDisplayGeometry()->Fit();
}

//##ModelId=3E33163A0261
void mitk::BaseRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
  m_RenderWindow = renderwindow;
}

//##ModelId=3E3799250397
void mitk::BaseRenderer::InitSize(int w, int h)
{
  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false);
  GetDisplayGeometry()->Fit();
}

//##ModelId=3E3D2F120050
mitk::BaseRenderer::BaseRenderer() : m_DataTreeIterator(NULL), m_RenderWindow(NULL), m_LastUpdateTime(0), m_MapperID(defaultMapper), m_CameraController(NULL), m_Focused(false)
{
  SmartPointerProperty::Pointer rendererProp = new SmartPointerProperty((itk::Object*)this);

  m_WorldGeometry = mitk::PlaneGeometry::New();

  m_WorldGeometryData = mitk::Geometry2DData::New();
  m_WorldGeometryData->SetGeometry2D(m_WorldGeometry);
  m_WorldGeometryNode = mitk::DataTreeNode::New();
  m_WorldGeometryNode->SetData(m_WorldGeometryData);
  m_WorldGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_WorldGeometryTransformTime = m_WorldGeometryNode->GetVtkTransform()->GetMTime();

  m_DisplayGeometry = mitk::DisplayGeometry::New();
  m_DisplayGeometry->SetWorldGeometry(m_WorldGeometry);
  m_DisplayGeometryData = mitk::Geometry2DData::New();
  m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
  m_DisplayGeometryNode = mitk::DataTreeNode::New();
  m_DisplayGeometryNode->SetData(m_DisplayGeometryData);
  m_DisplayGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp);
  m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime();
}

//##ModelId=3E3D2F12008C
mitk::BaseRenderer::~BaseRenderer()
{
  delete m_DataTreeIterator;
}

//##ModelId=3E66CC590379
void mitk::BaseRenderer::SetWorldGeometry(const mitk::Geometry2D* geometry2d)
{
  itkDebugMacro("setting WorldGeometry to " << geometry2d);
  if (m_WorldGeometry != geometry2d)
  {
    m_WorldGeometry = geometry2d;
    m_WorldGeometryData->SetGeometry2D(m_WorldGeometry);
    m_DisplayGeometry->SetWorldGeometry(m_WorldGeometry);
    Modified();
  }
}

//##ModelId=3E66CC59026B
void mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d)
{
  itkDebugMacro("setting DisplayGeometry to " << geometry2d);
  if (m_DisplayGeometry != geometry2d)
  {
    m_DisplayGeometry = geometry2d;
    m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);
    Modified();
  }
}

//##ModelId=3E6D5DD30322
void mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
    m_CameraController->MousePressEvent(me);
  if(m_MapperID==1)
  {
    Point2D p(me->x(), me->y());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->x(), me->y());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    std::cout << "press event!" << std::endl;
    mitk::DisplayPositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    if (! mitk::EventMapper::MapEvent(&event))
        std::cerr << "error, event was not mapped!" << std::endl;
  }
}

//##ModelId=3E6D5DD30372
void mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
    m_CameraController->MouseReleaseEvent(me);

  if(m_MapperID==1)
  {
    Point2D p(me->x(), me->y());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->x(), me->y());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    mitk::DisplayPositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    mitk::EventMapper::MapEvent(&event);
  }
}

//##ModelId=3E6D5DD303C2
void mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me)
{
  if (m_CameraController)
    m_CameraController->MouseMoveEvent(me);
  if(m_MapperID==1)
  {
    Point2D p(me->x(), me->y());
    Point2D p_mm;
    Point3D position;
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    GetDisplayGeometry()->DisplayToMM(p, p_mm);
    GetDisplayGeometry()->Map(p_mm, position);
    mitk::PositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p, position);
    mitk::EventMapper::MapEvent(&event);
  }
  else if(m_MapperID==2)
  {
    Point2D p(me->x(), me->y());
    GetDisplayGeometry()->ULDisplayToDisplay(p,p);
    mitk::DisplayPositionEvent event(this, me->type(), me->button(), me->state(), Qt::Key_unknown, p);
    mitk::EventMapper::MapEvent(&event);
  }
}

//##ModelId=3E6D5DD4002A
void mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke)
{
  if (m_CameraController)
    m_CameraController->KeyPressEvent(ke);
  mitk::Event event(this, ke->type(), Qt::NoButton, Qt::NoButton, ke->key());
  mitk::EventMapper::MapEvent(&event);
}

//##ModelId=3EF1627503C4
void mitk::BaseRenderer::MakeCurrent()
{
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2013  Martin Klapetek <mklapetek@kde.org>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "kpeopletranslationproxy.h"

#include <KPeople/PersonsModel>

#include <kpeople/personpluginmanager.h>

#include "KTp/im-persons-data-source.h"
#include "KTp/types.h"

#include <KDebug>
#include <KIconLoader>

#include <QPixmapCache>

using namespace KPeople;

KPeopleTranslationProxy::KPeopleTranslationProxy(QObject *parent)
    : QIdentityProxyModel(parent)
{
}

KPeopleTranslationProxy::~KPeopleTranslationProxy()
{
}

QVariant KPeopleTranslationProxy::data(const QModelIndex &proxyIndex, int role) const
{
    if (!proxyIndex.isValid()) {
        return QVariant();
    }

    IMPersonsDataSource *imPlugin = qobject_cast<IMPersonsDataSource*>(PersonPluginManager::presencePlugin());

    if (!imPlugin) {
        kWarning() << "No imPlugin";
        return QVariant();
    }

    switch (role) {
        case KTp::ContactPresenceTypeRole:
            return translatePresence(mapToSource(proxyIndex).data(PersonsModel::PresenceTypeRole));
        case KTp::ContactPresenceIconRole:
            return mapToSource(proxyIndex).data(PersonsModel::PresenceIconNameRole);
        case KTp::ContactPresenceNameRole:
            return mapToSource(proxyIndex).data(PersonsModel::PresenceDisplayRole);
        case Qt::DisplayRole:
            return mapToSource(proxyIndex).data(Qt::DisplayRole);
        case KTp::RowTypeRole:
            if (sourceModel()->rowCount(mapToSource(proxyIndex)) <= 1) {
                return KTp::ContactRowType;
            } else {
                return KTp::PersonRowType;
            }
        case KTp::ContactAvatarPathRole:
            return mapToSource(proxyIndex).data(PersonsModel::PhotosRole);
        case KTp::ContactAvatarPixmapRole:
            return contactPixmap(proxyIndex);
        case KTp::IdRole:
            return mapToSource(proxyIndex).data(PersonsModel::IMsRole);
        case KTp::HeaderTotalUsersRole:
            return sourceModel()->rowCount(mapToSource(proxyIndex));
        case KTp::ContactGroupsRole:
            return mapToSource(proxyIndex).data(PersonsModel::GroupsRole);
    }

    QVariantList ret;

    int j = sourceModel()->rowCount(mapToSource(proxyIndex));
    bool isChildContact = false;
    if (j == 0) {
        isChildContact = true;
        j = 1;
    }

    for (int i = 0; i < j; i++) {
        const QString contactId = isChildContact ? mapToSource(proxyIndex).data(PersonsModel::IMsRole).toString()
        : mapToSource(proxyIndex).data(PersonsModel::IMsRole).toList().at(i).toString();
        const KTp::ContactPtr contact = imPlugin->contactForContactId(contactId);

        if (!contact.isNull()) {
            switch (role) {
                case KTp::ContactRole:
                    ret += QVariant::fromValue<KTp::ContactPtr>(contact);
                    break;
                case KTp::AccountRole:
                    ret += QVariant::fromValue<Tp::AccountPtr>(imPlugin->accountForContact(contact));
                    break;
                case KTp::ContactPresenceMessageRole:
                    ret += contact->presence().statusMessage();
                    break;
                case KTp::ContactIsBlockedRole:
                    ret += contact->isBlocked();
                    break;
                case KTp::ContactCanTextChatRole:
                    ret += true;
                    break;
                case KTp::ContactCanAudioCallRole:
                    ret += contact->audioCallCapability();
                    break;
                case KTp::ContactCanVideoCallRole:
                    ret += contact->videoCallCapability();
                    break;
                case KTp::ContactCanFileTransferRole:
                    ret += contact->fileTransferCapability();
                    break;
                case KTp::ContactClientTypesRole:
                    ret += contact->clientTypes();
                    break;
            }
        } else if (contact.isNull() && role == KTp::AccountRole) {
            //if the KTp contact is null, we still need the Tp account for that contact
            //so we can either group it properly or bring that account online if user
            //starts a chat with a contact that belongs to offline account
            ret += QVariant::fromValue<Tp::AccountPtr>(imPlugin->accountForContactId(contactId));
        }
    }

    return ret;
}

QVariant KPeopleTranslationProxy::translatePresence(const QVariant &presenceName) const
{
    if (presenceName == QLatin1String("available")) {
        return Tp::ConnectionPresenceTypeAvailable;
    }

    if (presenceName == QLatin1String("away")) {
        return Tp::ConnectionPresenceTypeAway;
    }

    if (presenceName == QLatin1String("busy") || presenceName == QLatin1String("dnd")) {
        return Tp::ConnectionPresenceTypeBusy;
    }

    if (presenceName == QLatin1String("xa")) {
        return Tp::ConnectionPresenceTypeExtendedAway;
    }

    if (presenceName == QLatin1String("hidden")) {
        return Tp::ConnectionPresenceTypeHidden;
    }

    return Tp::ConnectionPresenceTypeOffline;
}

QPixmap KPeopleTranslationProxy::contactPixmap(const QModelIndex &index) const
{
    QPixmap avatar;

    int presenceType = index.data(KTp::ContactPresenceTypeRole).toInt();
    const QVariantList ids = index.data(KTp::IdRole).toList();
    QString id;
    if (!ids.isEmpty()) {
        id = ids.first().toString();
    }

    const QString keyCache = id + (presenceType == Tp::ConnectionPresenceTypeOffline ? QLatin1String("-offline") : QLatin1String("-online"));

    //check pixmap cache for the avatar, if not present, load the avatar
    if (!QPixmapCache::find(keyCache, avatar)){
        const QVariantList files = index.data(KTp::ContactAvatarPathRole).toList();
        QString file;
        if (!files.isEmpty()) {
            file = files.first().toUrl().toLocalFile();
        }

        //QPixmap::load() checks for empty path
        avatar.load(file);

        //if the above didn't succeed, we need to load the generic icon
        if (avatar.isNull()) {
            avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::NoGroup, 96);
        }

        //if the contact is offline, gray it out
        if (presenceType == Tp::ConnectionPresenceTypeOffline) {
            QImage image = avatar.toImage();
            const QPixmap alpha = avatar.alphaChannel();
            for (int i = 0; i < image.width(); ++i) {
                for (int j = 0; j < image.height(); ++j) {
                    int colour = qGray(image.pixel(i, j));
                    image.setPixel(i, j, qRgb(colour, colour, colour));
                }
            }
            avatar = avatar.fromImage(image);
            avatar.setAlphaChannel(alpha);
        }

        //insert the contact into pixmap cache for faster lookup
        QPixmapCache::insert(keyCache, avatar);
    }

    return avatar;
}
<commit_msg>Return the most online KTp::ContactPtr for persons<commit_after>/*
    Copyright (C) 2013  Martin Klapetek <mklapetek@kde.org>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "kpeopletranslationproxy.h"

#include <KPeople/PersonsModel>

#include <kpeople/personpluginmanager.h>

#include "KTp/im-persons-data-source.h"
#include "KTp/types.h"

#include <KDebug>
#include <KIconLoader>

#include <QPixmapCache>

using namespace KPeople;

KPeopleTranslationProxy::KPeopleTranslationProxy(QObject *parent)
    : QIdentityProxyModel(parent)
{
}

KPeopleTranslationProxy::~KPeopleTranslationProxy()
{
}

QVariant KPeopleTranslationProxy::data(const QModelIndex &proxyIndex, int role) const
{
    if (!proxyIndex.isValid()) {
        return QVariant();
    }

    IMPersonsDataSource *imPlugin = qobject_cast<IMPersonsDataSource*>(PersonPluginManager::presencePlugin());

    if (!imPlugin) {
        kWarning() << "No imPlugin";
        return QVariant();
    }

    switch (role) {
        case KTp::ContactPresenceTypeRole:
            return translatePresence(mapToSource(proxyIndex).data(PersonsModel::PresenceTypeRole));
        case KTp::ContactPresenceIconRole:
            return mapToSource(proxyIndex).data(PersonsModel::PresenceIconNameRole);
        case KTp::ContactPresenceNameRole:
            return mapToSource(proxyIndex).data(PersonsModel::PresenceDisplayRole);
        case Qt::DisplayRole:
            return mapToSource(proxyIndex).data(Qt::DisplayRole);
        case KTp::RowTypeRole:
            if (sourceModel()->rowCount(mapToSource(proxyIndex)) <= 1) {
                return KTp::ContactRowType;
            } else {
                return KTp::PersonRowType;
            }
        case KTp::ContactAvatarPathRole:
            return mapToSource(proxyIndex).data(PersonsModel::PhotosRole);
        case KTp::ContactAvatarPixmapRole:
            return contactPixmap(proxyIndex);
        case KTp::IdRole:
            return mapToSource(proxyIndex).data(PersonsModel::IMsRole);
        case KTp::HeaderTotalUsersRole:
            return sourceModel()->rowCount(mapToSource(proxyIndex));
        case KTp::ContactGroupsRole:
            return mapToSource(proxyIndex).data(PersonsModel::GroupsRole);
    }

    int j = sourceModel()->rowCount(mapToSource(proxyIndex));
    }

    KTp::ContactPtr contact;

    if (j > 0) {
        KTp::ContactPtr mostOnlineContact;

        Q_FOREACH(const QVariant &v, mapToSource(proxyIndex).data(PersonsModel::IMsRole).toList()) {
            KTp::ContactPtr c = imPlugin->contactForContactId(v.toString());
            if (mostOnlineContact.isNull() && !c.isNull()) {
                mostOnlineContact = c;
                continue;
            }
            if (!c.isNull()) {
                if (c->presence() < mostOnlineContact->presence()) {
                    mostOnlineContact = c;
                }
            }
        }
        contact = mostOnlineContact;
    } else if (j == 0) {
        contact = imPlugin->contactForContactId(mapToSource(proxyIndex).data(PersonsModel::IMsRole).toString());
    }

    if (!contact.isNull()) {
        switch (role) {
            case KTp::ContactRole:
                return QVariant::fromValue<KTp::ContactPtr>(contact);
                break;
            case KTp::AccountRole:
                return QVariant::fromValue<Tp::AccountPtr>(imPlugin->accountForContact(contact));
                break;
            case KTp::ContactPresenceMessageRole:
                return contact->presence().statusMessage();
                break;
            case KTp::ContactIsBlockedRole:
                return contact->isBlocked();
                break;
            case KTp::ContactCanTextChatRole:
                return true;
                break;
            case KTp::ContactCanAudioCallRole:
                return contact->audioCallCapability();
                break;
            case KTp::ContactCanVideoCallRole:
                return contact->videoCallCapability();
                break;
            case KTp::ContactCanFileTransferRole:
                return contact->fileTransferCapability();
                break;
            case KTp::ContactClientTypesRole:
                return contact->clientTypes();
                break;
        }
    } else if (contact.isNull() && role == KTp::AccountRole) {
        //if the KTp contact is null, we still need the Tp account for that contact
        //so we can either group it properly or bring that account online if user
        //starts a chat with a contact that belongs to offline account
        QString contactId = j > 0 ? mapToSource(proxyIndex).data(PersonsModel::IMsRole).toList().first().toString()
                                  : mapToSource(proxyIndex).data(PersonsModel::IMsRole).toString();
        return QVariant::fromValue<Tp::AccountPtr>(imPlugin->accountForContactId(contactId));
    }
//     }

    return mapToSource(proxyIndex).data(role);
}

QVariant KPeopleTranslationProxy::translatePresence(const QVariant &presenceName) const
{
    if (presenceName == QLatin1String("available")) {
        return Tp::ConnectionPresenceTypeAvailable;
    }

    if (presenceName == QLatin1String("away")) {
        return Tp::ConnectionPresenceTypeAway;
    }

    if (presenceName == QLatin1String("busy") || presenceName == QLatin1String("dnd")) {
        return Tp::ConnectionPresenceTypeBusy;
    }

    if (presenceName == QLatin1String("xa")) {
        return Tp::ConnectionPresenceTypeExtendedAway;
    }

    if (presenceName == QLatin1String("hidden")) {
        return Tp::ConnectionPresenceTypeHidden;
    }

    return Tp::ConnectionPresenceTypeOffline;
}

QPixmap KPeopleTranslationProxy::contactPixmap(const QModelIndex &index) const
{
    QPixmap avatar;

    int presenceType = index.data(KTp::ContactPresenceTypeRole).toInt();
    const QVariantList ids = index.data(KTp::IdRole).toList();
    QString id;
    if (!ids.isEmpty()) {
        id = ids.first().toString();
    }

    const QString keyCache = id + (presenceType == Tp::ConnectionPresenceTypeOffline ? QLatin1String("-offline") : QLatin1String("-online"));

    //check pixmap cache for the avatar, if not present, load the avatar
    if (!QPixmapCache::find(keyCache, avatar)){
        const QVariantList files = index.data(KTp::ContactAvatarPathRole).toList();
        QString file;
        if (!files.isEmpty()) {
            file = files.first().toUrl().toLocalFile();
        }

        //QPixmap::load() checks for empty path
        avatar.load(file);

        //if the above didn't succeed, we need to load the generic icon
        if (avatar.isNull()) {
            avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::NoGroup, 96);
        }

        //if the contact is offline, gray it out
        if (presenceType == Tp::ConnectionPresenceTypeOffline) {
            QImage image = avatar.toImage();
            const QPixmap alpha = avatar.alphaChannel();
            for (int i = 0; i < image.width(); ++i) {
                for (int j = 0; j < image.height(); ++j) {
                    int colour = qGray(image.pixel(i, j));
                    image.setPixel(i, j, qRgb(colour, colour, colour));
                }
            }
            avatar = avatar.fromImage(image);
            avatar.setAlphaChannel(alpha);
        }

        //insert the contact into pixmap cache for faster lookup
        QPixmapCache::insert(keyCache, avatar);
    }

    return avatar;
}
<|endoftext|>


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

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

#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <unsupported/Eigen/SparseExtra>

#include <amgcl/runtime.hpp>
#include <amgcl/backend/eigen.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/profiler.hpp>

typedef Eigen::SparseMatrix<double, Eigen::RowMajor, int> EigenMatrix;
typedef Eigen::Matrix<double, Eigen::Dynamic, 1>          EigenVector;

namespace amgcl {
profiler<> prof;
} // namespace amgcl

//---------------------------------------------------------------------------
template<typename Matrix>
void mmread(Matrix &vec, const std::string &fname) {
    typedef typename Matrix::Scalar Scalar;

    using amgcl::precondition;

    std::ifstream in(fname.c_str());
    precondition(in, "Failed to open file \"" + fname + "\"");

    std::string line;
    int n = 0, col = 0;

    // Skip comments
    do {
        precondition(
                std::getline(in, line),
                "Format error in " + fname
                );
    } while (line[0] == '%');

    std::istringstream newline(line);
    newline >> n >> col;
    precondition(n > 0 && col > 0, "Wrong dimensions in Null-space file");
    vec.resize(n, col);

    for(int j = 0; j < col; ++j) {
        for(int i = 0; i < n; ++i) {
            Scalar v;
            precondition(
                    in >> v,
                    "Format error in " + fname
                    );

            vec(i, j) = v;
        }
    }
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    using amgcl::prof;
    using amgcl::precondition;

    // Read configuration from command line
    amgcl::runtime::coarsening::type coarsening = amgcl::runtime::coarsening::smoothed_aggregation;
    amgcl::runtime::relaxation::type relaxation = amgcl::runtime::relaxation::spai0;
    amgcl::runtime::solver::type     solver     = amgcl::runtime::solver::bicgstab;
    std::string parameter_file;
    std::string A_file;
    std::string rhs_file;
    std::string null_file;
    std::string out_file = "out.mtx";

    namespace po = boost::program_options;
    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
        (
         "coarsening,c",
         po::value<amgcl::runtime::coarsening::type>(&coarsening)->default_value(coarsening),
         "ruge_stuben, aggregation, smoothed_aggregation, smoothed_aggr_emin"
        )
        (
         "relaxation,r",
         po::value<amgcl::runtime::relaxation::type>(&relaxation)->default_value(relaxation),
         "gauss_seidel, ilu0, damped_jacobi, spai0, chebyshev"
        )
        (
         "solver,s",
         po::value<amgcl::runtime::solver::type>(&solver)->default_value(solver),
         "cg, bicgstab, bicgstabl, gmres"
        )
        (
         "params,p",
         po::value<std::string>(&parameter_file),
         "parameter file in json format"
        )
        (
         "matrix,A",
         po::value<std::string>(&A_file)->required(),
         "The system matrix in MatrixMarket format"
        )
        (
         "rhs,b",
         po::value<std::string>(&rhs_file),
         "The right-hand side in MatrixMarket format"
        )
        (
         "null,Z",
         po::value<std::string>(&null_file),
         "Zero energy mode vectors in MatrixMarket format"
        )
        (
         "output,o",
         po::value<std::string>(&out_file),
         "The output file (saved in MatrixMarket format)"
        )
        ;

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

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

    boost::property_tree::ptree prm;
    if (vm.count("params")) read_json(parameter_file, prm);

    // Read the matrix and the right-hand side.
    prof.tic("read");
    EigenMatrix A;
    precondition(
            Eigen::loadMarket(A, A_file),
            "Failed to load matrix file (" + A_file + ")"
            );

    EigenVector rhs;
    if (vm.count("rhs")) {
        precondition(
                Eigen::loadMarketVector(rhs, rhs_file),
                "Failed to load RHS file (" + rhs_file + ")"
                );
    } else {
        std::cout << "RHS was not provided; using default value of 1" << std::endl;
        rhs = EigenVector::Constant(A.rows(), 1);
    }

    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Z;
    if (vm.count("null")) {
        mmread(Z, null_file);

        precondition(
                Z.rows() == A.rows(),
                "Inconsistent dimensions in Null-space file"
                );

        prm.put("amg.coarsening.nullspace.cols", Z.cols());
        prm.put("amg.coarsening.nullspace.rows", Z.rows());
        prm.put("amg.coarsening.nullspace.B",    Z.data());
    }

    precondition(A.rows() == rhs.size(), "Matrix and RHS sizes differ");
    prof.toc("read");

    // Setup solver
    prof.tic("setup");
    typedef
        amgcl::runtime::make_solver< amgcl::backend::builtin<double> >
        Solver;

    Solver solve(coarsening, relaxation, solver, A, prm);
    prof.toc("setup");

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

    // Solve the problem
    std::vector<double> f(&rhs[0], &rhs[0] + rhs.size());
    std::vector<double> x(rhs.size(), 0);

    prof.tic("solve");
    size_t iters;
    double resid;
    boost::tie(iters, resid) = solve(f, x);
    prof.toc("solve");

    // Check the real error
    double error = (rhs - A * Eigen::Map<EigenVector>(x.data(), x.size())).norm() / rhs.norm();

    if (vm.count("out")) {
        prof.tic("write");
        Eigen::saveMarketVector(Eigen::Map<EigenVector>(x.data(), x.size()), out_file);
        prof.toc("write");
    }

    std::cout << "Iterations:     " << iters << std::endl
              << "Reported Error: " << resid << std::endl
              << "Real error:     " << error << std::endl
              << prof                        << std::endl
              ;
}
<commit_msg>Fix help option in solve_mm<commit_after>#include <iostream>
#include <string>

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

#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <unsupported/Eigen/SparseExtra>

#include <amgcl/runtime.hpp>
#include <amgcl/backend/eigen.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/profiler.hpp>

typedef Eigen::SparseMatrix<double, Eigen::RowMajor, int> EigenMatrix;
typedef Eigen::Matrix<double, Eigen::Dynamic, 1>          EigenVector;

namespace amgcl {
profiler<> prof;
} // namespace amgcl

//---------------------------------------------------------------------------
template<typename Matrix>
void mmread(Matrix &vec, const std::string &fname) {
    typedef typename Matrix::Scalar Scalar;

    using amgcl::precondition;

    std::ifstream in(fname.c_str());
    precondition(in, "Failed to open file \"" + fname + "\"");

    std::string line;
    int n = 0, col = 0;

    // Skip comments
    do {
        precondition(
                std::getline(in, line),
                "Format error in " + fname
                );
    } while (line[0] == '%');

    std::istringstream newline(line);
    newline >> n >> col;
    precondition(n > 0 && col > 0, "Wrong dimensions in Null-space file");
    vec.resize(n, col);

    for(int j = 0; j < col; ++j) {
        for(int i = 0; i < n; ++i) {
            Scalar v;
            precondition(
                    in >> v,
                    "Format error in " + fname
                    );

            vec(i, j) = v;
        }
    }
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    using amgcl::prof;
    using amgcl::precondition;

    // Read configuration from command line
    amgcl::runtime::coarsening::type coarsening = amgcl::runtime::coarsening::smoothed_aggregation;
    amgcl::runtime::relaxation::type relaxation = amgcl::runtime::relaxation::spai0;
    amgcl::runtime::solver::type     solver     = amgcl::runtime::solver::bicgstab;
    std::string parameter_file;
    std::string A_file;
    std::string rhs_file;
    std::string null_file;
    std::string out_file = "out.mtx";

    namespace po = boost::program_options;
    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
        (
         "coarsening,c",
         po::value<amgcl::runtime::coarsening::type>(&coarsening)->default_value(coarsening),
         "ruge_stuben, aggregation, smoothed_aggregation, smoothed_aggr_emin"
        )
        (
         "relaxation,r",
         po::value<amgcl::runtime::relaxation::type>(&relaxation)->default_value(relaxation),
         "gauss_seidel, ilu0, damped_jacobi, spai0, chebyshev"
        )
        (
         "solver,s",
         po::value<amgcl::runtime::solver::type>(&solver)->default_value(solver),
         "cg, bicgstab, bicgstabl, gmres"
        )
        (
         "params,p",
         po::value<std::string>(&parameter_file),
         "parameter file in json format"
        )
        (
         "matrix,A",
         po::value<std::string>(&A_file)->required(),
         "The system matrix in MatrixMarket format"
        )
        (
         "rhs,b",
         po::value<std::string>(&rhs_file),
         "The right-hand side in MatrixMarket format"
        )
        (
         "null,Z",
         po::value<std::string>(&null_file),
         "Zero energy mode vectors in MatrixMarket format"
        )
        (
         "output,o",
         po::value<std::string>(&out_file),
         "The output file (saved in MatrixMarket format)"
        )
        ;

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

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

    po::notify(vm);

    boost::property_tree::ptree prm;
    if (vm.count("params")) read_json(parameter_file, prm);

    // Read the matrix and the right-hand side.
    prof.tic("read");
    EigenMatrix A;
    precondition(
            Eigen::loadMarket(A, A_file),
            "Failed to load matrix file (" + A_file + ")"
            );

    EigenVector rhs;
    if (vm.count("rhs")) {
        precondition(
                Eigen::loadMarketVector(rhs, rhs_file),
                "Failed to load RHS file (" + rhs_file + ")"
                );
    } else {
        std::cout << "RHS was not provided; using default value of 1" << std::endl;
        rhs = EigenVector::Constant(A.rows(), 1);
    }

    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Z;
    if (vm.count("null")) {
        mmread(Z, null_file);

        precondition(
                Z.rows() == A.rows(),
                "Inconsistent dimensions in Null-space file"
                );

        prm.put("amg.coarsening.nullspace.cols", Z.cols());
        prm.put("amg.coarsening.nullspace.rows", Z.rows());
        prm.put("amg.coarsening.nullspace.B",    Z.data());
    }

    precondition(A.rows() == rhs.size(), "Matrix and RHS sizes differ");
    prof.toc("read");

    // Setup solver
    prof.tic("setup");
    typedef
        amgcl::runtime::make_solver< amgcl::backend::builtin<double> >
        Solver;

    Solver solve(coarsening, relaxation, solver, A, prm);
    prof.toc("setup");

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

    // Solve the problem
    std::vector<double> f(&rhs[0], &rhs[0] + rhs.size());
    std::vector<double> x(rhs.size(), 0);

    prof.tic("solve");
    size_t iters;
    double resid;
    boost::tie(iters, resid) = solve(f, x);
    prof.toc("solve");

    // Check the real error
    double error = (rhs - A * Eigen::Map<EigenVector>(x.data(), x.size())).norm() / rhs.norm();

    if (vm.count("out")) {
        prof.tic("write");
        Eigen::saveMarketVector(Eigen::Map<EigenVector>(x.data(), x.size()), out_file);
        prof.toc("write");
    }

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


<commit_before>/*
    Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com>
    Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com>
    Copyright (C) 2009 Fathi Boudra <fabo@kde.org>
    Copyright (C) 2009-2010 vlc-phonon AUTHORS
    Copyright (C) 2011 Harald Sitter <sitter@kde.org>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "devicemanager.h"

#ifdef PHONON_PULSESUPPORT
#  include <phonon/pulsesupport.h>
#endif

#include <vlc/vlc.h>

#include "backend.h"
#include "utils/debug.h"
#include "utils/libvlc.h"
#include "utils/vstring.h"

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace VLC
{

/*
 * Device Info
 */

DeviceInfo::DeviceInfo(const QString &name, bool isAdvanced)
{
    // Get an id
    static int counter = 0;
    m_id = counter++;

    // Get name and description for the device
    m_name = name;
    m_isAdvanced = isAdvanced;
    m_capabilities = None;

    // A default device should never be advanced
    if (name.startsWith("default", Qt::CaseInsensitive))
        m_isAdvanced = false;
}

int DeviceInfo::id() const
{
    return m_id;
}

const QString& DeviceInfo::name() const
{
    return m_name;
}

const QString& DeviceInfo::description() const
{
    return m_description;
}

bool DeviceInfo::isAdvanced() const
{
    return m_isAdvanced;
}

void DeviceInfo::setAdvanced(bool advanced)
{
    m_isAdvanced = advanced;
}

const DeviceAccessList& DeviceInfo::accessList() const
{
    return m_accessList;
}

void DeviceInfo::addAccess(const DeviceAccess& access)
{
    if (m_accessList.isEmpty())
        m_description = access.first + ": " + access.second;
    m_accessList.append(access);
}

quint16 DeviceInfo::capabilities() const
{
    return m_capabilities;
}

void DeviceInfo::setCapabilities(quint16 cap)
{
    m_capabilities = cap;
}

/*
 * Device Manager
 */

DeviceManager::DeviceManager(Backend *parent)
    : QObject(parent)
    , m_backend(parent)
{
    Q_ASSERT(parent);
    updateDeviceList();
}

DeviceManager::~DeviceManager()
{
}

QList<int> DeviceManager::deviceIds(ObjectDescriptionType type)
{
    DeviceInfo::Capability capability = DeviceInfo::None;
    switch (type) {
    case Phonon::AudioOutputDeviceType:
        capability = DeviceInfo::AudioOutput;
        break;
    case Phonon::AudioCaptureDeviceType:
        capability = DeviceInfo::AudioCapture;
        break;
    case Phonon::VideoCaptureDeviceType:
        capability = DeviceInfo::VideoCapture;
        break;
    default: ;
    }

    QList<int> ids;
    foreach (const DeviceInfo &device, m_devices) {
        if (device.capabilities() & capability)
            ids.append(device.id());
    }

    return ids;
}

QHash<QByteArray, QVariant> DeviceManager::deviceProperties(int id)
{
    QHash<QByteArray, QVariant> properties;

    foreach (const DeviceInfo &device, m_devices) {
        if (device.id() == id) {
            properties.insert("name", device.name());
            properties.insert("description", device.description());
            properties.insert("isAdvanced", device.isAdvanced());
            properties.insert("deviceAccessList", QVariant::fromValue<Phonon::DeviceAccessList>(device.accessList()));
            properties.insert("discovererIcon", "vlc");

            if (device.capabilities() & DeviceInfo::AudioOutput) {
                properties.insert("icon", QLatin1String("audio-card"));
            }

            if (device.capabilities() & DeviceInfo::AudioCapture) {
                properties.insert("hasaudio", true);
                properties.insert("icon", QLatin1String("audio-input-microphone"));
            }

            if (device.capabilities() & DeviceInfo::VideoCapture) {
                properties.insert("hasvideo", true);
                properties.insert("icon", QLatin1String("camera-web"));
            }
            break;
        }
    }

    return properties;
}

const DeviceInfo *DeviceManager::device(int id) const
{
    for (int i = 0; i < m_devices.size(); i ++) {
        if (m_devices[i].id() == id)
            return &m_devices[i];
    }

    return NULL;
}

static QList<QByteArray> vlcAudioOutBackends()
{
    QList<QByteArray> ret;

    libvlc_audio_output_t *firstAudioOut = libvlc_audio_output_list_get(libvlc);
    if (!firstAudioOut) {
        error() << "libVLC:" << LibVLC::errorMessage();
        return ret;
    }
    for (libvlc_audio_output_t *audioOut = firstAudioOut; audioOut; audioOut = audioOut->p_next) {
        ret.append(QByteArray(audioOut->psz_name));
    }
    libvlc_audio_output_list_release(firstAudioOut);

    return ret;
}

void DeviceManager::updateDeviceList()
{
    QList<DeviceInfo> newDeviceList;

    if (!LibVLC::self || !libvlc)
        return;

    QList<QByteArray> audioOutBackends = vlcAudioOutBackends();

#ifdef PHONON_PULSESUPPORT
    PulseSupport *pulse = PulseSupport::getInstance();
    if (pulse && pulse->isActive()) {
        if (audioOutBackends.contains("pulse")) {
            DeviceInfo defaultAudioOutputDevice(tr("Default"), false);
            defaultAudioOutputDevice.setCapabilities(DeviceInfo::AudioOutput);
            defaultAudioOutputDevice.addAccess(DeviceAccess("pulse", "default"));
            newDeviceList.append(defaultAudioOutputDevice);
            return;
        } else {
            pulse->enable(false);
        }
    }
#endif

    QList<QByteArray> knownSoundSystems;
    knownSoundSystems << "alsa" << "oss";
    foreach (const QByteArray &soundSystem, knownSoundSystems) {
        if (audioOutBackends.contains(soundSystem)) {
            const int deviceCount = libvlc_audio_output_device_count(libvlc, soundSystem);

            for (int i = 0; i < deviceCount; i++) {
                VString idName(libvlc_audio_output_device_id(libvlc, soundSystem, i));
                VString longName(libvlc_audio_output_device_longname(libvlc, soundSystem, i));

                DeviceInfo device(longName, true);
                device.addAccess(DeviceAccess(soundSystem, idName));
                device.setCapabilities(DeviceInfo::AudioOutput);
                newDeviceList.append(device);
            }

            // libVLC gives no devices for some sound systems, like OSS
            if (!deviceCount) {
                DeviceInfo device(QString("Default %1").arg(QString(soundSystem)), true);
                device.addAccess(DeviceAccess(soundSystem, ""));
                device.setCapabilities(DeviceInfo::AudioOutput);
                newDeviceList.append(device);
            }
        }
    }

    /*
     * Compares the list with the devices available at the moment with the last list. If
     * a new device is seen, a signal is emitted. If a device disappeared, another signal
     * is emitted.
     */

    // Search for added devices
    for (int i = 0; i < newDeviceList.count(); ++i) {
        int id = newDeviceList[i].id();
        if (!listContainsDevice(m_devices, id)) {
            // This is a new device, add it
            m_devices.append(newDeviceList[i]);
            emit deviceAdded(id);

            debug() << "Added backend device" << newDeviceList[i].name();
        }
    }

    // Search for removed devices
    for (int i = m_devices.count() - 1; i >= 0; --i) {
        int id = m_devices[i].id();
        if (!listContainsDevice(newDeviceList, id)) {
            emit deviceRemoved(id);
            m_devices.removeAt(i);
        }
    }
}

bool DeviceManager::listContainsDevice(const QList<DeviceInfo> &list, int id)
{
    foreach (const DeviceInfo &d, list) {
        if (d.id() == id)
            return true;
    }
    return false;
}

}
}

QT_END_NAMESPACE
<commit_msg>don't duplicate entires in the vlc aout list<commit_after>/*
    Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com>
    Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com>
    Copyright (C) 2009 Fathi Boudra <fabo@kde.org>
    Copyright (C) 2009-2010 vlc-phonon AUTHORS
    Copyright (C) 2011 Harald Sitter <sitter@kde.org>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "devicemanager.h"

#ifdef PHONON_PULSESUPPORT
#  include <phonon/pulsesupport.h>
#endif

#include <vlc/vlc.h>

#include "backend.h"
#include "utils/debug.h"
#include "utils/libvlc.h"
#include "utils/vstring.h"

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace VLC
{

/*
 * Device Info
 */

DeviceInfo::DeviceInfo(const QString &name, bool isAdvanced)
{
    // Get an id
    static int counter = 0;
    m_id = counter++;

    // Get name and description for the device
    m_name = name;
    m_isAdvanced = isAdvanced;
    m_capabilities = None;

    // A default device should never be advanced
    if (name.startsWith("default", Qt::CaseInsensitive))
        m_isAdvanced = false;
}

int DeviceInfo::id() const
{
    return m_id;
}

const QString& DeviceInfo::name() const
{
    return m_name;
}

const QString& DeviceInfo::description() const
{
    return m_description;
}

bool DeviceInfo::isAdvanced() const
{
    return m_isAdvanced;
}

void DeviceInfo::setAdvanced(bool advanced)
{
    m_isAdvanced = advanced;
}

const DeviceAccessList& DeviceInfo::accessList() const
{
    return m_accessList;
}

void DeviceInfo::addAccess(const DeviceAccess& access)
{
    if (m_accessList.isEmpty())
        m_description = access.first + ": " + access.second;
    m_accessList.append(access);
}

quint16 DeviceInfo::capabilities() const
{
    return m_capabilities;
}

void DeviceInfo::setCapabilities(quint16 cap)
{
    m_capabilities = cap;
}

/*
 * Device Manager
 */

DeviceManager::DeviceManager(Backend *parent)
    : QObject(parent)
    , m_backend(parent)
{
    Q_ASSERT(parent);
    updateDeviceList();
}

DeviceManager::~DeviceManager()
{
}

QList<int> DeviceManager::deviceIds(ObjectDescriptionType type)
{
    DeviceInfo::Capability capability = DeviceInfo::None;
    switch (type) {
    case Phonon::AudioOutputDeviceType:
        capability = DeviceInfo::AudioOutput;
        break;
    case Phonon::AudioCaptureDeviceType:
        capability = DeviceInfo::AudioCapture;
        break;
    case Phonon::VideoCaptureDeviceType:
        capability = DeviceInfo::VideoCapture;
        break;
    default: ;
    }

    QList<int> ids;
    foreach (const DeviceInfo &device, m_devices) {
        if (device.capabilities() & capability)
            ids.append(device.id());
    }

    return ids;
}

QHash<QByteArray, QVariant> DeviceManager::deviceProperties(int id)
{
    QHash<QByteArray, QVariant> properties;

    foreach (const DeviceInfo &device, m_devices) {
        if (device.id() == id) {
            properties.insert("name", device.name());
            properties.insert("description", device.description());
            properties.insert("isAdvanced", device.isAdvanced());
            properties.insert("deviceAccessList", QVariant::fromValue<Phonon::DeviceAccessList>(device.accessList()));
            properties.insert("discovererIcon", "vlc");

            if (device.capabilities() & DeviceInfo::AudioOutput) {
                properties.insert("icon", QLatin1String("audio-card"));
            }

            if (device.capabilities() & DeviceInfo::AudioCapture) {
                properties.insert("hasaudio", true);
                properties.insert("icon", QLatin1String("audio-input-microphone"));
            }

            if (device.capabilities() & DeviceInfo::VideoCapture) {
                properties.insert("hasvideo", true);
                properties.insert("icon", QLatin1String("camera-web"));
            }
            break;
        }
    }

    return properties;
}

const DeviceInfo *DeviceManager::device(int id) const
{
    for (int i = 0; i < m_devices.size(); i ++) {
        if (m_devices[i].id() == id)
            return &m_devices[i];
    }

    return NULL;
}

static QList<QByteArray> vlcAudioOutBackends()
{
    QList<QByteArray> ret;

    libvlc_audio_output_t *firstAudioOut = libvlc_audio_output_list_get(libvlc);
    if (!firstAudioOut) {
        error() << "libVLC:" << LibVLC::errorMessage();
        return ret;
    }
    for (libvlc_audio_output_t *audioOut = firstAudioOut; audioOut; audioOut = audioOut->p_next) {
        QByteArray name(audioOut->psz_name);
        if (!ret.contains(name))
            ret.append(name);
    }
    libvlc_audio_output_list_release(firstAudioOut);

    return ret;
}

void DeviceManager::updateDeviceList()
{
    QList<DeviceInfo> newDeviceList;

    if (!LibVLC::self || !libvlc)
        return;

    QList<QByteArray> audioOutBackends = vlcAudioOutBackends();

#ifdef PHONON_PULSESUPPORT
    PulseSupport *pulse = PulseSupport::getInstance();
    if (pulse && pulse->isActive()) {
        if (audioOutBackends.contains("pulse")) {
            DeviceInfo defaultAudioOutputDevice(tr("Default"), false);
            defaultAudioOutputDevice.setCapabilities(DeviceInfo::AudioOutput);
            defaultAudioOutputDevice.addAccess(DeviceAccess("pulse", "default"));
            newDeviceList.append(defaultAudioOutputDevice);
            return;
        } else {
            pulse->enable(false);
        }
    }
#endif

    QList<QByteArray> knownSoundSystems;
    knownSoundSystems << "alsa" << "oss";
    foreach (const QByteArray &soundSystem, knownSoundSystems) {
        if (audioOutBackends.contains(soundSystem)) {
            const int deviceCount = libvlc_audio_output_device_count(libvlc, soundSystem);

            for (int i = 0; i < deviceCount; i++) {
                VString idName(libvlc_audio_output_device_id(libvlc, soundSystem, i));
                VString longName(libvlc_audio_output_device_longname(libvlc, soundSystem, i));

                DeviceInfo device(longName, true);
                device.addAccess(DeviceAccess(soundSystem, idName));
                device.setCapabilities(DeviceInfo::AudioOutput);
                newDeviceList.append(device);
            }

            // libVLC gives no devices for some sound systems, like OSS
            if (!deviceCount) {
                DeviceInfo device(QString("Default %1").arg(QString(soundSystem)), true);
                device.addAccess(DeviceAccess(soundSystem, ""));
                device.setCapabilities(DeviceInfo::AudioOutput);
                newDeviceList.append(device);
            }
        }
    }

    /*
     * Compares the list with the devices available at the moment with the last list. If
     * a new device is seen, a signal is emitted. If a device disappeared, another signal
     * is emitted.
     */

    // Search for added devices
    for (int i = 0; i < newDeviceList.count(); ++i) {
        int id = newDeviceList[i].id();
        if (!listContainsDevice(m_devices, id)) {
            // This is a new device, add it
            m_devices.append(newDeviceList[i]);
            emit deviceAdded(id);

            debug() << "Added backend device" << newDeviceList[i].name();
        }
    }

    // Search for removed devices
    for (int i = m_devices.count() - 1; i >= 0; --i) {
        int id = m_devices[i].id();
        if (!listContainsDevice(newDeviceList, id)) {
            emit deviceRemoved(id);
            m_devices.removeAt(i);
        }
    }
}

bool DeviceManager::listContainsDevice(const QList<DeviceInfo> &list, int id)
{
    foreach (const DeviceInfo &d, list) {
        if (d.id() == id)
            return true;
    }
    return false;
}

}
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include "trafficgraphwidget.h"
#include "clientmodel.h"

#include <QPainter>
#include <QColor>
#include <QTimer>

#include <cmath>

#define DESIRED_SAMPLES         800

#define XMARGIN                 10
#define YMARGIN                 10

TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
    QWidget(parent),
    timer(0),
    fMax(0.0f),
    nMins(0),
    vSamplesIn(),
    vSamplesOut(),
    nLastBytesIn(0),
    nLastBytesOut(0),
    clientModel(0)
{
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}

void TrafficGraphWidget::setClientModel(ClientModel *model)
{
    clientModel = model;
    if(model) {
        nLastBytesIn = model->getTotalBytesRecv();
        nLastBytesOut = model->getTotalBytesSent();
    }
}

int TrafficGraphWidget::getGraphRangeMins() const
{
    return nMins;
}

void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
    int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
    int sampleCount = samples.size(), x = XMARGIN + w, y;
    if(sampleCount > 0) {
        path.moveTo(x, YMARGIN + h);
        for(int i = 0; i < sampleCount; ++i) {
            x = XMARGIN + w - w * i / DESIRED_SAMPLES;
            y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
            path.lineTo(x, y);
        }
        path.lineTo(x, YMARGIN + h);
    }
}

void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    if(fMax <= 0.0f) return;

    QColor axisCol(Qt::gray);
    int h = height() - YMARGIN * 2;
    painter.setPen(axisCol);
    painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);

    // decide what order of magnitude we are
    int base = floor(log10(fMax));
    float val = pow(10.0f, base);

    const QString units = tr("KB/s");
    // draw lines
    painter.setPen(axisCol);
    painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units));
    for(float y = val; y < fMax; y += val) {
        int yy = YMARGIN + h - h * y / fMax;
        painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
    }
    // if we drew 3 or fewer lines, break them up at the next lower order of magnitude
    if(fMax / val <= 3.0f) {
        axisCol = axisCol.darker();
        val = pow(10.0f, base - 1);
        painter.setPen(axisCol);
        painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units));
        int count = 1;
        for(float y = val; y < fMax; y += val, count++) {
            // don't overwrite lines drawn above
            if(count % 10 == 0)
                continue;
            int yy = YMARGIN + h - h * y / fMax;
            painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
        }
    }

    if(!vSamplesIn.empty()) {
        QPainterPath p;
        paintPath(p, vSamplesIn);
        painter.fillPath(p, QColor(0, 255, 0, 128));
        painter.setPen(Qt::green);
        painter.drawPath(p);
    }
    if(!vSamplesOut.empty()) {
        QPainterPath p;
        paintPath(p, vSamplesOut);
        painter.fillPath(p, QColor(255, 0, 0, 128));
        painter.setPen(Qt::red);
        painter.drawPath(p);
    }
}

void TrafficGraphWidget::updateRates()
{
    if(!clientModel) return;

    quint64 bytesIn = clientModel->getTotalBytesRecv(),
            bytesOut = clientModel->getTotalBytesSent();
    float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
    float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
    vSamplesIn.push_front(inRate);
    vSamplesOut.push_front(outRate);
    nLastBytesIn = bytesIn;
    nLastBytesOut = bytesOut;

    while(vSamplesIn.size() > DESIRED_SAMPLES) {
        vSamplesIn.pop_back();
    }
    while(vSamplesOut.size() > DESIRED_SAMPLES) {
        vSamplesOut.pop_back();
    }

    float tmax = 0.0f;
    foreach(float f, vSamplesIn) {
        if(f > tmax) tmax = f;
    }
    foreach(float f, vSamplesOut) {
        if(f > tmax) tmax = f;
    }
    fMax = tmax;
    update();
}

void TrafficGraphWidget::setGraphRangeMins(int mins)
{
    nMins = mins;
    int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
    timer->stop();
    timer->setInterval(msecsPerSample);

    clear();
}

void TrafficGraphWidget::clear()
{
    timer->stop();

    vSamplesOut.clear();
    vSamplesIn.clear();
    fMax = 0.0f;

    if(clientModel) {
        nLastBytesIn = clientModel->getTotalBytesRecv();
        nLastBytesOut = clientModel->getTotalBytesSent();
    }
    timer->start();
}
<commit_msg>Qt: Network-Traffic-Graph: make some distance between line and text<commit_after>#include "trafficgraphwidget.h"
#include "clientmodel.h"

#include <QPainter>
#include <QColor>
#include <QTimer>

#include <cmath>

#define DESIRED_SAMPLES         800

#define XMARGIN                 10
#define YMARGIN                 10

TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
    QWidget(parent),
    timer(0),
    fMax(0.0f),
    nMins(0),
    vSamplesIn(),
    vSamplesOut(),
    nLastBytesIn(0),
    nLastBytesOut(0),
    clientModel(0)
{
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}

void TrafficGraphWidget::setClientModel(ClientModel *model)
{
    clientModel = model;
    if(model) {
        nLastBytesIn = model->getTotalBytesRecv();
        nLastBytesOut = model->getTotalBytesSent();
    }
}

int TrafficGraphWidget::getGraphRangeMins() const
{
    return nMins;
}

void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
    int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
    int sampleCount = samples.size(), x = XMARGIN + w, y;
    if(sampleCount > 0) {
        path.moveTo(x, YMARGIN + h);
        for(int i = 0; i < sampleCount; ++i) {
            x = XMARGIN + w - w * i / DESIRED_SAMPLES;
            y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
            path.lineTo(x, y);
        }
        path.lineTo(x, YMARGIN + h);
    }
}

void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    if(fMax <= 0.0f) return;

    QColor axisCol(Qt::gray);
    int h = height() - YMARGIN * 2;
    painter.setPen(axisCol);
    painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);

    // decide what order of magnitude we are
    int base = floor(log10(fMax));
    float val = pow(10.0f, base);

    const QString units     = tr("KB/s");
    const float yMarginText = 2.0;

    // draw lines
    painter.setPen(axisCol);
    painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units));
    for(float y = val; y < fMax; y += val) {
        int yy = YMARGIN + h - h * y / fMax;
        painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
    }
    // if we drew 3 or fewer lines, break them up at the next lower order of magnitude
    if(fMax / val <= 3.0f) {
        axisCol = axisCol.darker();
        val = pow(10.0f, base - 1);
        painter.setPen(axisCol);
        painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units));
        int count = 1;
        for(float y = val; y < fMax; y += val, count++) {
            // don't overwrite lines drawn above
            if(count % 10 == 0)
                continue;
            int yy = YMARGIN + h - h * y / fMax;
            painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
        }
    }

    if(!vSamplesIn.empty()) {
        QPainterPath p;
        paintPath(p, vSamplesIn);
        painter.fillPath(p, QColor(0, 255, 0, 128));
        painter.setPen(Qt::green);
        painter.drawPath(p);
    }
    if(!vSamplesOut.empty()) {
        QPainterPath p;
        paintPath(p, vSamplesOut);
        painter.fillPath(p, QColor(255, 0, 0, 128));
        painter.setPen(Qt::red);
        painter.drawPath(p);
    }
}

void TrafficGraphWidget::updateRates()
{
    if(!clientModel) return;

    quint64 bytesIn = clientModel->getTotalBytesRecv(),
            bytesOut = clientModel->getTotalBytesSent();
    float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
    float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
    vSamplesIn.push_front(inRate);
    vSamplesOut.push_front(outRate);
    nLastBytesIn = bytesIn;
    nLastBytesOut = bytesOut;

    while(vSamplesIn.size() > DESIRED_SAMPLES) {
        vSamplesIn.pop_back();
    }
    while(vSamplesOut.size() > DESIRED_SAMPLES) {
        vSamplesOut.pop_back();
    }

    float tmax = 0.0f;
    foreach(float f, vSamplesIn) {
        if(f > tmax) tmax = f;
    }
    foreach(float f, vSamplesOut) {
        if(f > tmax) tmax = f;
    }
    fMax = tmax;
    update();
}

void TrafficGraphWidget::setGraphRangeMins(int mins)
{
    nMins = mins;
    int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
    timer->stop();
    timer->setInterval(msecsPerSample);

    clear();
}

void TrafficGraphWidget::clear()
{
    timer->stop();

    vSamplesOut.clear();
    vSamplesIn.clear();
    fMax = 0.0f;

    if(clientModel) {
        nLastBytesIn = clientModel->getTotalBytesRecv();
        nLastBytesOut = clientModel->getTotalBytesSent();
    }
    timer->start();
}
<|endoftext|>