<commit_before>/*
 * This file is part of accounts-ui
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

//project
#include "add-account-page.h"
#include "service-selection-page.h"
#include "service-model.h"
#include "service-helper.h"
#include "sort-service-model.h"
#include "provider-plugin-process.h"
#include "account-sync-handler.h"
#include "genericaccountsetupform.h"
#include "account-setup-finished-page.h"

//Accounts
#include <Accounts/Account>
#include <Accounts/Manager>

//Meegotouch
#include <MLocale>
#include <MLabel>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MImageWidget>
#include <MButton>
#include <MWidgetCreator>
#include <MPannableViewport>
#include <MPositionIndicator>

//Qt
#include <QString>
#include <QSortFilterProxyModel>
#include <QRegExp>
#include <QDebug>

using namespace Accounts;

M_REGISTER_WIDGET_NO_CREATE(AccountsUI::AddAccountPage)

namespace AccountsUI {

class AddAccountPagePrivate
{
public:
    AddAccountPagePrivate()
            : context(0),
            syncHandler(0)
    {}
    ~AddAccountPagePrivate()
    {
        qDeleteAll(serviceContextList);
    }
    AbstractAccountSetupContext *context;
    QList<AbstractServiceSetupContext*> serviceContextList;
    AccountSyncHandler *syncHandler;
    QList<AbstractSetupContext*> abstractContexts;
    QString serviceType;
    Accounts::ServiceList hiddenServiceList;
};

AddAccountPage::AddAccountPage(AbstractAccountSetupContext *context,
                               QGraphicsItem *parent)
        : MApplicationPage(parent)
        , d_ptr(new AddAccountPagePrivate())
{
    Q_D(AddAccountPage);
    Q_ASSERT(context);
    setStyleName("AccountsUiPage");
    setEscapeMode(MApplicationPageModel::EscapeAuto);
    d->context = context;
    d->serviceType = context->serviceType();
    pannableViewport()->positionIndicator()->setStyleName("CommonPositionIndicatorInverted");
}

AddAccountPage::~AddAccountPage()
{
    Q_D(AddAccountPage);
    delete d;
}

void AddAccountPage::createContent()
{
    Q_D(AddAccountPage);
    Q_ASSERT(centralWidget());

    //% "Add new account"
    setTitle(qtTrId("qtn_acc_add_new_account_title"));

    // layout
    MLayout *layout = new MLayout(centralWidget());
    layout->setContentsMargins(0, 0, 0, 0);
    MLinearLayoutPolicy *layoutPolicy =
            new MLinearLayoutPolicy( layout, Qt::Vertical );

    // plugin widget has the provider info and credentials widget
    QGraphicsLayoutItem *pluginWidget = d->context->widget();
    layoutPolicy->addItem(pluginWidget);

    // TODO : this part is just for testing purposes, to jump to service selection page, without going through authentication
    if (!qgetenv("ACCOUNTSUI_SKIP_VALIDATION").isEmpty()) {
        MButton *nextButton = new MButton("Skip Validation");
        connect(nextButton, SIGNAL(clicked()), this, SLOT(navigateToServiceSelectionPage()));
        layoutPolicy->addItem(nextButton);
    }

    // login Ok, go to next page
    connect(d->context, SIGNAL(validated()), SLOT(navigateToServiceSelectionPage()));
    connect(d->context, SIGNAL(validated()), SLOT(showMenuBar()));

    //process indicator
    connect(d->context, SIGNAL(validating()), SLOT(hideMenuBar()));
    connect(d->context, SIGNAL(error(AccountsUI::ErrorCode, const QString &)),
            this, SLOT(onError(AccountsUI::ErrorCode, const QString &)));

    //cancelling
    connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
            d->context, SLOT(stopAuthSession()));
    connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
            d->context, SLOT(showMenuBar()));
}

void AddAccountPage::setHiddenServices(const Accounts::ServiceList &hiddenServices)
{
    Q_D(AddAccountPage);
    d->hiddenServiceList = hiddenServices;
}

AccountSyncHandler *AddAccountPage::accountSyncHandler()
{
    Q_D(AddAccountPage);
    return d->syncHandler;
}

void AddAccountPage::navigateToServiceSelectionPage()
{
    Q_D(AddAccountPage);
    disconnect(d->context, SIGNAL(validated()), this, SLOT(navigateToServiceSelectionPage()));

    ServiceModel *serviceModel = new ServiceModel(d->context->account(), this);

    SortServiceModel *sortModel = new SortServiceModel(this);
    sortModel->setSourceModel(serviceModel);
    sortModel->setHiddenServices(d->hiddenServiceList);
    sortModel->sort(ServiceModel::ServiceNameColumn);

    d->serviceContextList = ServiceModel::createServiceContexts(sortModel, d->context, this);

    if (d->serviceContextList.count() == 0 ||
        (d->serviceContextList.count() == 1 &&
        !d->serviceContextList.at(0)->hasMandatorySettings())) {

        d->syncHandler = new AccountSyncHandler(this);
        connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
                this, SLOT(onSyncStateChanged(const SyncState&)));
        d->context->account()->selectService(NULL);
        d->context->account()->setEnabled(true);

        d->abstractContexts.append(d->context);
        if (d->serviceContextList.count() == 1) {
            d->context->account()->selectService(d->serviceContextList.at(0)->service());
            d->context->account()->setEnabled(true);
            d->abstractContexts.append(d->serviceContextList.at(0));
        }

        setProgressIndicatorVisible(true);

        qDebug() << Q_FUNC_INFO;
        d->syncHandler->validate(d->abstractContexts);
        return;
    }

    openServiceSelectionPage(d->context, d->serviceContextList);
}

void AddAccountPage::openServiceSelectionPage(AccountsUI::AbstractAccountSetupContext *context,
                                              QList<AccountsUI::AbstractServiceSetupContext *> &serviceContextList)
{
    ServiceSelectionPage *serviceSelectionPage =
        new ServiceSelectionPage(context, serviceContextList);
    connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
            this,SLOT(appear()));
    connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
            this, SLOT(clearServiceContextList()));
    connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
            serviceSelectionPage,SLOT(deleteLater()));

    serviceSelectionPage->appear();
}

void AddAccountPage::onSyncStateChanged(const SyncState &state)
{

    qDebug() << Q_FUNC_INFO;
    Q_D(AddAccountPage);

    switch (state) {
        case NotValidated:
            qDebug() << Q_FUNC_INFO << __LINE__;
            showMenuBar();
            break;
        case NotStored:
            qDebug() << Q_FUNC_INFO << __LINE__;
            showMenuBar();
            break;
        case Validated:
            d->syncHandler->store(d->abstractContexts);
            break;
        case Stored:
            if (d->serviceType.isEmpty()) {
                connect(d->context->account(), SIGNAL(synced()),
                        ProviderPluginProcess::instance(), SLOT(quit()));
                d->context->account()->sync();
                showMenuBar();
            } else {
                d->context->account()->sync();
                AccountSetupFinishedPage *page = new AccountSetupFinishedPage(d->context);
                page->appear();
            }
            break;
        default:
            return;
    }
}

void AddAccountPage::clearServiceContextList()
{
    Q_D(AddAccountPage);
    d->serviceContextList.clear();
}

void AddAccountPage::hideMenuBar()
{
    setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Hide);
}

void AddAccountPage::showMenuBar()
{
    setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Show);
}

void AddAccountPage::onError(AccountsUI::ErrorCode, const QString &)
{
    showMenuBar();
}

} //namespace
<commit_msg>Fixes: NB#285410 - check for lastPageActions instead of service type for transitioning to SetupFinished page<commit_after>/*
 * This file is part of accounts-ui
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

//project
#include "add-account-page.h"
#include "service-selection-page.h"
#include "service-model.h"
#include "service-helper.h"
#include "sort-service-model.h"
#include "provider-plugin-process.h"
#include "account-sync-handler.h"
#include "genericaccountsetupform.h"
#include "account-setup-finished-page.h"
#include "last-page-actions.h"

//Accounts
#include <Accounts/Account>
#include <Accounts/Manager>

//Meegotouch
#include <MLocale>
#include <MLabel>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MImageWidget>
#include <MButton>
#include <MWidgetCreator>
#include <MPannableViewport>
#include <MPositionIndicator>

//Qt
#include <QString>
#include <QSortFilterProxyModel>
#include <QRegExp>
#include <QDebug>

using namespace Accounts;

M_REGISTER_WIDGET_NO_CREATE(AccountsUI::AddAccountPage)

namespace AccountsUI {

class AddAccountPagePrivate
{
public:
    AddAccountPagePrivate()
            : context(0),
            syncHandler(0)
    {}
    ~AddAccountPagePrivate()
    {
        qDeleteAll(serviceContextList);
    }
    AbstractAccountSetupContext *context;
    QList<AbstractServiceSetupContext*> serviceContextList;
    AccountSyncHandler *syncHandler;
    QList<AbstractSetupContext*> abstractContexts;
    QString serviceType;
    Accounts::ServiceList hiddenServiceList;
};

AddAccountPage::AddAccountPage(AbstractAccountSetupContext *context,
                               QGraphicsItem *parent)
        : MApplicationPage(parent)
        , d_ptr(new AddAccountPagePrivate())
{
    Q_D(AddAccountPage);
    Q_ASSERT(context);
    setStyleName("AccountsUiPage");
    setEscapeMode(MApplicationPageModel::EscapeAuto);
    d->context = context;
    d->serviceType = context->serviceType();
    pannableViewport()->positionIndicator()->setStyleName("CommonPositionIndicatorInverted");
}

AddAccountPage::~AddAccountPage()
{
    Q_D(AddAccountPage);
    delete d;
}

void AddAccountPage::createContent()
{
    Q_D(AddAccountPage);
    Q_ASSERT(centralWidget());

    //% "Add new account"
    setTitle(qtTrId("qtn_acc_add_new_account_title"));

    // layout
    MLayout *layout = new MLayout(centralWidget());
    layout->setContentsMargins(0, 0, 0, 0);
    MLinearLayoutPolicy *layoutPolicy =
            new MLinearLayoutPolicy( layout, Qt::Vertical );

    // plugin widget has the provider info and credentials widget
    QGraphicsLayoutItem *pluginWidget = d->context->widget();
    layoutPolicy->addItem(pluginWidget);

    // TODO : this part is just for testing purposes, to jump to service selection page, without going through authentication
    if (!qgetenv("ACCOUNTSUI_SKIP_VALIDATION").isEmpty()) {
        MButton *nextButton = new MButton("Skip Validation");
        connect(nextButton, SIGNAL(clicked()), this, SLOT(navigateToServiceSelectionPage()));
        layoutPolicy->addItem(nextButton);
    }

    // login Ok, go to next page
    connect(d->context, SIGNAL(validated()), SLOT(navigateToServiceSelectionPage()));
    connect(d->context, SIGNAL(validated()), SLOT(showMenuBar()));

    //process indicator
    connect(d->context, SIGNAL(validating()), SLOT(hideMenuBar()));
    connect(d->context, SIGNAL(error(AccountsUI::ErrorCode, const QString &)),
            this, SLOT(onError(AccountsUI::ErrorCode, const QString &)));

    //cancelling
    connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
            d->context, SLOT(stopAuthSession()));
    connect((GenericAccountSetupForm*)pluginWidget, SIGNAL(stopButtonPressed()),
            d->context, SLOT(showMenuBar()));
}

void AddAccountPage::setHiddenServices(const Accounts::ServiceList &hiddenServices)
{
    Q_D(AddAccountPage);
    d->hiddenServiceList = hiddenServices;
}

AccountSyncHandler *AddAccountPage::accountSyncHandler()
{
    Q_D(AddAccountPage);
    return d->syncHandler;
}

void AddAccountPage::navigateToServiceSelectionPage()
{
    Q_D(AddAccountPage);
    disconnect(d->context, SIGNAL(validated()), this, SLOT(navigateToServiceSelectionPage()));

    ServiceModel *serviceModel = new ServiceModel(d->context->account(), this);

    SortServiceModel *sortModel = new SortServiceModel(this);
    sortModel->setSourceModel(serviceModel);
    sortModel->setHiddenServices(d->hiddenServiceList);
    sortModel->sort(ServiceModel::ServiceNameColumn);

    d->serviceContextList = ServiceModel::createServiceContexts(sortModel, d->context, this);

    if (d->serviceContextList.count() == 0 ||
        (d->serviceContextList.count() == 1 &&
        !d->serviceContextList.at(0)->hasMandatorySettings())) {

        d->syncHandler = new AccountSyncHandler(this);
        connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
                this, SLOT(onSyncStateChanged(const SyncState&)));
        d->context->account()->selectService(NULL);
        d->context->account()->setEnabled(true);

        d->abstractContexts.append(d->context);
        if (d->serviceContextList.count() == 1) {
            d->context->account()->selectService(d->serviceContextList.at(0)->service());
            d->context->account()->setEnabled(true);
            d->abstractContexts.append(d->serviceContextList.at(0));
        }

        setProgressIndicatorVisible(true);

        qDebug() << Q_FUNC_INFO;
        d->syncHandler->validate(d->abstractContexts);
        return;
    }

    openServiceSelectionPage(d->context, d->serviceContextList);
}

void AddAccountPage::openServiceSelectionPage(AccountsUI::AbstractAccountSetupContext *context,
                                              QList<AccountsUI::AbstractServiceSetupContext *> &serviceContextList)
{
    ServiceSelectionPage *serviceSelectionPage =
        new ServiceSelectionPage(context, serviceContextList);
    connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
            this,SLOT(appear()));
    connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
            this, SLOT(clearServiceContextList()));
    connect(serviceSelectionPage,SIGNAL(backButtonClicked()),
            serviceSelectionPage,SLOT(deleteLater()));

    serviceSelectionPage->appear();
}

void AddAccountPage::onSyncStateChanged(const SyncState &state)
{

    qDebug() << Q_FUNC_INFO;
    Q_D(AddAccountPage);

    switch (state) {
        case NotValidated:
            qDebug() << Q_FUNC_INFO << __LINE__;
            showMenuBar();
            break;
        case NotStored:
            qDebug() << Q_FUNC_INFO << __LINE__;
            showMenuBar();
            break;
        case Validated:
            d->syncHandler->store(d->abstractContexts);
            break;
        case Stored:
            if (ProviderPluginProcess::instance()->lastPageActions()
			                    .serviceActions().isEmpty()) {
                connect(d->context->account(), SIGNAL(synced()),
                        ProviderPluginProcess::instance(), SLOT(quit()));
                d->context->account()->sync();
                showMenuBar();
            } else {
                d->context->account()->sync();
                AccountSetupFinishedPage *page = new AccountSetupFinishedPage(d->context);
                page->appear();
            }
            break;
        default:
            return;
    }
}

void AddAccountPage::clearServiceContextList()
{
    Q_D(AddAccountPage);
    d->serviceContextList.clear();
}

void AddAccountPage::hideMenuBar()
{
    setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Hide);
}

void AddAccountPage::showMenuBar()
{
    setComponentsDisplayMode(NavigationBar, MApplicationPageModel::Show);
}

void AddAccountPage::onError(AccountsUI::ErrorCode, const QString &)
{
    showMenuBar();
}

} //namespace
<|endoftext|>


<commit_before>// Copyright 2015 Matt Heard
// http://mattheard.net
// matt@mattheard.net
// @mattheard

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

using cv::Mat;

Mat buildLookUpTable(const int divideWith) {
    const int rows = 1;
    const int cols = 256;
    const int type = CV_8U;
    const Mat table(rows, cols, type);
    for (int i = 0; i < 256; ++i) {
        const int reduced = divideWith * (i / divideWith);
        table.data[i] = (uchar) reduced;
    }
    return table;
}

int main(int argc, char **argv) {
    using std::string;
    const int expectedNumArgs = 3;
    if (argc != expectedNumArgs) {
        const string cmdName = "ReduceColours";
        const string argsDesc = " <Image_Path> <Reduce_By>";
        std::cout << "Usage: " << cmdName << argsDesc << std::endl;
        return -1;
    }
    const string inputFilename = argv[1];
    const Mat srcImg = cv::imread(inputFilename);
    if (!srcImg.data) {
        const string err = "No image data";
        std::cerr << err << std::endl;
        return -1;
    }
    const int divideWith = atoi(argv[2]);
    if (divideWith < 1) {
        std::cout << "Invalid number entered for dividing." << std::endl;
        return -1;
    }
    const Mat lookUpTable = buildLookUpTable(divideWith);
    Mat dstImg;
    LUT(srcImg, lookUpTable, dstImg);
    const string outputFilename = "reduced.jpg";
    imwrite(outputFilename, dstImg);
    return 0;
}
<commit_msg>Remove unrelated, copied code<commit_after>// Copyright 2015 Matt Heard
// http://mattheard.net
// matt@mattheard.net
// @mattheard

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

int main(int argc, char **argv) {
    using std::string;
    const int expectedNumArgs = 4;
    if (argc != expectedNumArgs) {
        const string cmdName = "Blend";
        const string argsDesc = " <Image1_Path> <Image2_Path> <Alpha>";
        std::cout << "Usage: " << cmdName << argsDesc << std::endl;
        return -1;
    }
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Try another FileLock api for Linux<commit_after><|endoftext|>


<commit_before>#include "SecondLife.h"
#include <stdio.h>

int main()
{
	//Packet* packet;
	bool success;
	SecondLife* client = new SecondLife();

	if (client->loadKeywords("keywords.txt") == 0) {
		printf("Loaded keyword file\n");
	} else {
		printf("Failed to load the keyword file\n");

		delete client;
		return -1;
	}

	if (client->decryptCommFile("comm.dat", "output.txt") == 0) {
		printf("Decrypted comm file\n");
	} else {
		printf("Failed to decrypt the comm file\n");
	}

	if (client->buildProtocolMap("output.txt") == 0) {
		printf("Built protocol map\n");
	} else {
		printf("Failed to build the protocol map\n");

		delete client;
		return -2;
	}

	client->_protocol->printMap();

	//printf("Building UseCircuitCode packet\n");
	//packet = new Packet(client->_protocol);
	//success = packet->setCommand("UseCircuitCode");

	if (success) {
		//byte agentID[16] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F};
		//packet->setField("CircuitCode", 1, "ID", agentID);
		boost::asio::ipv4::address address("192.168.0.105");
		client->_network->connectSim(address, 1000, 12345, true);
	} else {
		printf("Failed to build the AddCircuitCode packet");
	}

	//delete packet;
	delete client;
	return 0;
}
<commit_msg>First alpha release * Fixed several nasty malloc/memcpy/realloc bugs * Added sleeps to the threads * Hack to make the packet flags correct (for now) * Added a default callback and fixed the callback handler * Misc. fixes<commit_after>#include "SecondLife.h"
#include <stdio.h>

SecondLife* client;

void loginHandler(loginParameters login)
{
	LLUUID tempID;

	if (login.reason.length()) {
		printf("Login failed\n");
	} else {
		// Set the variables received from login
		client->session_id((LLUUID)login.session_id);
		client->secure_session_id((LLUUID)login.secure_session_id);
		client->agent_id((LLUUID)login.agent_id);

		boost::asio::ipv4::address address(login.sim_ip);
		client->_network->connectSim(address, login.sim_port, login.circuit_code, true);

		Packet* packet = new Packet("CompleteAgentMovement", client->_protocol);

		tempID = client->agent_id();
		packet->setField("AgentData", 1, "AgentID", &tempID);
		tempID = client->session_id();
		packet->setField("AgentData", 1, "SessionID", &tempID);
		packet->setField("AgentData", 1, "CircuitCode", &login.circuit_code);

		client->_network->sendPacket(packet);

		while (1) {
			client->tick();
		}
	}
}

bool receivedPacket(std::string command, Packet* packet)
{
	byte* data = packet->rawData();
	size_t length = packet->length();

	// Debug
	printf("Received datagram, length: %u\n", length);
	for (size_t i = 0; i < length; i++) {
		printf("%02x ", data[i]);
	}
	printf("\n");

	return true;
}

int main()
{
	client = new SecondLife();

	if (client->loadKeywords("keywords.txt") == 0) {
		printf("Loaded keyword file\n");
	} else {
		printf("Failed to load the keyword file\n");

		delete client;
		return -1;
	}

	if (client->decryptCommFile("comm.dat", "output.txt") == 0) {
		printf("Decrypted comm file\n");
	} else {
		printf("Failed to decrypt the comm file\n");
	}

	if (client->buildProtocolMap("output.txt") == 0) {
		printf("Built protocol map\n");
	} else {
		printf("Failed to build the protocol map\n");

		delete client;
		return -2;
	}

	//client->_protocol->printMap();

	client->registerCallback("Default", &receivedPacket);

	client->login("First", "Last", "password", "00:00:00:00:00:00", "Win", "0", "test_app", "email@address.com", loginHandler);

	delete client;
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "chrome/browser/child_process_security_policy.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/url_request/url_request_about_job.h"
#include "net/url_request/url_request_filter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {

class AccountScreenTest : public WizardInProcessBrowserTest {
 public:
  AccountScreenTest(): WizardInProcessBrowserTest("account") {
  }

 protected:
  // Overridden from WizardInProcessBrowserTest:
  virtual void SetUpWizard() {
    HTTPTestServer* server = StartHTTPServer();
    ASSERT_TRUE(server != NULL);
    GURL new_account_page_url(server->TestServerPage("files/new_account.html"));
    AccountScreen::set_new_account_page_url(new_account_page_url);
    AccountScreen::set_check_for_https(false);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(AccountScreenTest);
};

// A basic test. It does not care how things evolve after the URL is
// loaded. Thus no message loop is started. Just check that initial
// status is expected.
IN_PROC_BROWSER_TEST_F(AccountScreenTest, TestBasic) {
  ASSERT_TRUE(controller());
  EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());
}

static void QuitUIMessageLoop() {
  MessageLoopForUI::current()->Quit();
}

static bool inspector_called = false;  // had to use global flag as
                                       // InspectorHook() doesn't have context.

static URLRequestJob* InspectorHook(URLRequest* request,
                                    const std::string& scheme) {
  LOG(INFO) << "Intercepted: " << request->url() << ", scheme: " << scheme;

  // Expect that the parameters are the same as new_account.html gave us.
  EXPECT_STREQ("cros://inspector/?param1=value1+param2",
               request->url().spec().c_str());
  inspector_called = true;
  ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
                         NewRunnableFunction(QuitUIMessageLoop));

  // Do not navigate to the given URL. Navigate to about:blank instead.
  return new URLRequestAboutJob(request);
}

IN_PROC_BROWSER_TEST_F(AccountScreenTest, TestSchemeInspector) {
  ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
      chrome::kCrosScheme);
  URLRequestFilter::GetInstance()->AddHostnameHandler(chrome::kCrosScheme,
                                                      "inspector",
                                                      &InspectorHook);
  EXPECT_FALSE(inspector_called);
  ui_test_utils::RunMessageLoop();
  EXPECT_TRUE(inspector_called);
}

}  // namespace chromeos
<commit_msg>Mark AccountScreenTest.TestSchemeInspector as flaky. <commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "chrome/browser/child_process_security_policy.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/url_request/url_request_about_job.h"
#include "net/url_request/url_request_filter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {

class AccountScreenTest : public WizardInProcessBrowserTest {
 public:
  AccountScreenTest(): WizardInProcessBrowserTest("account") {
  }

 protected:
  // Overridden from WizardInProcessBrowserTest:
  virtual void SetUpWizard() {
    HTTPTestServer* server = StartHTTPServer();
    ASSERT_TRUE(server != NULL);
    GURL new_account_page_url(server->TestServerPage("files/new_account.html"));
    AccountScreen::set_new_account_page_url(new_account_page_url);
    AccountScreen::set_check_for_https(false);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(AccountScreenTest);
};

// A basic test. It does not care how things evolve after the URL is
// loaded. Thus no message loop is started. Just check that initial
// status is expected.
IN_PROC_BROWSER_TEST_F(AccountScreenTest, TestBasic) {
  ASSERT_TRUE(controller());
  EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());
}

static void QuitUIMessageLoop() {
  MessageLoopForUI::current()->Quit();
}

static bool inspector_called = false;  // had to use global flag as
                                       // InspectorHook() doesn't have context.

static URLRequestJob* InspectorHook(URLRequest* request,
                                    const std::string& scheme) {
  LOG(INFO) << "Intercepted: " << request->url() << ", scheme: " << scheme;

  // Expect that the parameters are the same as new_account.html gave us.
  EXPECT_STREQ("cros://inspector/?param1=value1+param2",
               request->url().spec().c_str());
  inspector_called = true;
  ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
                         NewRunnableFunction(QuitUIMessageLoop));

  // Do not navigate to the given URL. Navigate to about:blank instead.
  return new URLRequestAboutJob(request);
}

IN_PROC_BROWSER_TEST_F(AccountScreenTest, FLAKY_TestSchemeInspector) {
  ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
      chrome::kCrosScheme);
  URLRequestFilter::GetInstance()->AddHostnameHandler(chrome::kCrosScheme,
                                                      "inspector",
                                                      &InspectorHook);
  EXPECT_FALSE(inspector_called);
  ui_test_utils::RunMessageLoop();
  EXPECT_TRUE(inspector_called);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#ifndef STAN_SERVICES_SAMPLE_INIT_WINDOWED_ADAPT_HPP
#define STAN_SERVICES_SAMPLE_INIT_WINDOWED_ADAPT_HPP

#include <stan/interface_callbacks/writer/base_writer.hpp>
#include <stan/mcmc/base_mcmc.hpp>
#include <stan/services/arguments/categorical_argument.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/services/sample/init_adapt.hpp>
#include <ostream>

namespace stan {
  namespace services {
    namespace sample {

      template<class Sampler>
      bool
      init_windowed_adapt(stan::mcmc::base_mcmc* sampler,
                          stan::services::categorical_argument* adapt,
                          unsigned int num_warmup,
                          const Eigen::VectorXd& cont_params,
                          interface_callbacks::writer::base_writer& writer) {
        init_adapt<Sampler>(sampler, adapt, cont_params, writer);

        unsigned int init_buffer
          = dynamic_cast<u_int_argument*>(adapt->arg("init_buffer"))->value();
        unsigned int term_buffer
          = dynamic_cast<u_int_argument*>(adapt->arg("term_buffer"))->value();
        unsigned int window
          = dynamic_cast<u_int_argument*>(adapt->arg("window"))->value();

        dynamic_cast<Sampler*>(sampler)
          ->set_window_params(num_warmup, init_buffer, term_buffer,
                              window, writer);

        return true;
      }

    }
  }
}
#endif
<commit_msg>Adding one more use of an error writer<commit_after>#ifndef STAN_SERVICES_SAMPLE_INIT_WINDOWED_ADAPT_HPP
#define STAN_SERVICES_SAMPLE_INIT_WINDOWED_ADAPT_HPP

#include <stan/interface_callbacks/writer/base_writer.hpp>
#include <stan/mcmc/base_mcmc.hpp>
#include <stan/services/arguments/categorical_argument.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/services/sample/init_adapt.hpp>
#include <ostream>

namespace stan {
  namespace services {
    namespace sample {

      template<class Sampler>
      bool
      init_windowed_adapt(stan::mcmc::base_mcmc* sampler,
                          stan::services::categorical_argument* adapt,
                          unsigned int num_warmup,
                          const Eigen::VectorXd& cont_params,
                          interface_callbacks::writer::base_writer& info_writer,
                          interface_callbacks::writer::base_writer& error_writer) {
        init_adapt<Sampler>(sampler, adapt, cont_params, info_writer, error_writer);

        unsigned int init_buffer
          = dynamic_cast<u_int_argument*>(adapt->arg("init_buffer"))->value();
        unsigned int term_buffer
          = dynamic_cast<u_int_argument*>(adapt->arg("term_buffer"))->value();
        unsigned int window
          = dynamic_cast<u_int_argument*>(adapt->arg("window"))->value();

        dynamic_cast<Sampler*>(sampler)
          ->set_window_params(num_warmup, init_buffer, term_buffer,
                              window, info_writer);

        return true;
      }

    }
  }
}
#endif
<|endoftext|>


<commit_before>#include <stdint.h>
#include "receiver.h"

Receiver::Receiver(
    uint8_t spiClockPin,
    uint8_t spiDataPin,
    uint8_t spiSelectPin
) {
    this->driver.init(spiClockPin, spiDataPin, spiSelectPin);
}

void Receiver::setFrequency(uint16_t frequency) {
    uint16_t flO = (frequency - 479) / 2;
    uint16_t regN = frequency / 32;
    uint16_t regA = frequency % 32;
    uint16_t synthRegB = (regN << 7) | regA;

    this->driver.setSynthRegisterB(synthRegB);
}

<commit_msg>Fix broken synth reg A gen<commit_after>#include <stdint.h>
#include "receiver.h"

Receiver::Receiver(
    uint8_t spiClockPin,
    uint8_t spiDataPin,
    uint8_t spiSelectPin
) {
    this->driver.init(spiClockPin, spiDataPin, spiSelectPin);
}

void Receiver::setFrequency(uint16_t frequency) {
    uint16_t fLo = (frequency - 479) / 2;
    uint16_t regN = fLo / 32;
    uint16_t regA = fLo % 32;
    uint16_t synthRegB = (regN << 7) | regA;

    this->driver.setSynthRegisterB(synthRegB);
}

<|endoftext|>


<commit_before>#include "client.h"
#include "duckchat.h"

//#include <stdio.h>
//#include <sys/socket.h>
//#include <string.h>
//#include <netinet/in.h>
//#include <stdlib.h>

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <netinet/in.h>

//using namespace std;

//enum Commands {EXIT, JOIN, LEAVE, LIST, WHO, SWITCH};
int kClientPort = 5001;
struct sockaddr_in client_addr;
struct sockaddr_in server_addr;
int client_socket;
std::vector<char *> delete_queue;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

//char *StringToCharStar(std::string input) {
//  char *tmp = new char[input.length() + 1];
//  strcpy(tmp, input.c_str());
//
//  return tmp;
//}

void Connect(char *server, int port) {
  printf("Connecting to %s\n", server);

  memset((char *) &client_addr, 0, sizeof(client_addr));
  client_addr.sin_family = AF_INET;
  client_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  client_addr.sin_port = htons(kClientPort);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // TODO figure out how to handle ex: ix.cs.uoregon.edu
  server_addr.sin_port = htons(port);

  if ((client_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("client: can't open socket\n");
  }

  if (bind(client_socket, (struct sockaddr *) &client_addr, sizeof(client_addr)) < 0) {
    Error("client: bind failed\n");
  }
}

void Send(std::string input) {
  char *message = new char[input.length() + 1];
  strcpy(message, input.c_str());

  if (sendto(client_socket, message, strlen(message), 0, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("client: failed to send message\n");
  }

  delete message;
}

std::vector<std::string> StringSplit(std::string input) {
  std::istringstream iss(input);
  std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};

  return result;
}

bool ProcessInput(std::string input) {
  std::vector<std::string> inputs = StringSplit(input);
  bool result = true;

  if (inputs[0] == "/exit") {
    Send(inputs[0]);
    result = false;
  } else if (inputs[0] == "/list") {

  } else if (inputs[0] == "/join") {

  } else if (inputs[0] == "/leave") {

  } else if (inputs[0] == "/who") {

  } else if (inputs[0] == "/switch") {

  } else {
    std::cout << "Invalid command" << std::endl;
  }

  return result;
}

int main(int argc, char *argv[]) {
  char *server;
  int port;
  std::string username;
  std::string input;
//  delete_queue = std::vector<char *>();

  if (argc < 4) {
    fprintf(stderr,"usage: client [server name] [port] [username]\n");
    exit(1);
  }

  server = argv[1];
  port = atoi(argv[2]);
  username = argv[3];

  Connect(server, port);

  Send(username);

  // TODO handle response from send

  while(1) {
    std::cout << "> ";
    getline(std::cin, input);

    if (input[0] == '/') {
      if (!ProcessInput(input)) {
        break;
      }
    } else {
      // Sending chat messages
      Send(input);
    }

  }

  return 0;
}
<commit_msg>Client now sends login to server<commit_after>#include "client.h"
#include "duckchat.h"

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <netinet/in.h>

int kClientPort = 5001;
struct sockaddr_in client_addr;
struct sockaddr_in server_addr;
int client_socket;
std::vector<char *> delete_queue;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void Connect(char *server, int port) {
  printf("Connecting to %s\n", server);

  memset((char *) &client_addr, 0, sizeof(client_addr));
  client_addr.sin_family = AF_INET;
  client_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  client_addr.sin_port = htons(kClientPort);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // TODO figure out how to handle ex: ix.cs.uoregon.edu
  server_addr.sin_port = htons(port);

  if ((client_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("client: can't open socket\n");
  }

  if (bind(client_socket, (struct sockaddr *) &client_addr, sizeof(client_addr)) < 0) {
    Error("client: bind failed\n");
  }
}

int SendLogin(struct request_login user_login) {
  void* message[sizeof(struct request_login)];
  memcpy(message, &user_login, sizeof(struct request_login));

  if (sendto(client_socket, message, sizeof(struct request_login), 0, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("client: failed to send message\n");
    return 1;
  }

  return 0;
}

std::vector<std::string> StringSplit(std::string input) {
  std::istringstream iss(input);
  std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};

  return result;
}

bool ProcessInput(std::string input) {
  std::vector<std::string> inputs = StringSplit(input);
  bool result = true;

  if (inputs[0] == "/exit") {
//    Send(inputs[0]);
    result = false;
  } else if (inputs[0] == "/list") {

  } else if (inputs[0] == "/join") {

  } else if (inputs[0] == "/leave") {

  } else if (inputs[0] == "/who") {

  } else if (inputs[0] == "/switch") {

  } else {
    std::cout << "Invalid command" << std::endl;
  }

  return result;
}

int main(int argc, char *argv[]) {
  char *server;
  int port;
  char *username;
  std::string input;

  if (argc < 4) {
    fprintf(stderr,"usage: client [server name] [port] [username]\n");
    exit(1);
  }

  server = argv[1];
  port = atoi(argv[2]);
  username = argv[3];

  Connect(server, port);

  struct request_login user_login;
  memset((char *) &user_login, 0, sizeof(user_login));
  user_login.req_type = REQ_LOGIN;
  strncpy(user_login.req_username, username, USERNAME_MAX);

  SendLogin(user_login);

  // TODO handle response from send

  while(1) {
    std::cout << "> ";
    getline(std::cin, input);

    if (input[0] == '/') {
      if (!ProcessInput(input)) {
        break;
      }
    } else {
      // Sending chat messages
//      Send(input);
    }

  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/message_loop.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace chromeos {

class AccountScreenTest : public InProcessBrowserTest {
 public:
  AccountScreenTest() {
  }

 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitchWithValue(switches::kLoginScreen, L"account");
    command_line->AppendSwitchWithValue(switches::kLoginScreenSize,
                                        L"1024,600");
  }

  virtual Browser* CreateBrowser(Profile* profile) {
    return NULL;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(AccountScreenTest);
};

IN_PROC_BROWSER_TEST_F(AccountScreenTest, TestBasic) {
  WizardController* controller = WizardController::default_controller();
  ASSERT_TRUE(NULL != controller);
  EXPECT_EQ(controller->GetAccountScreen(), controller->current_screen());
  // Close login manager windows.
  MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
  // End the message loop to quit the test since there's no browser window
  // created.
  MessageLoop::current()->Quit();
}

}  // namespace chromeos

<commit_msg>Mark AccountScreenTest.TestBasic as flaky.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/message_loop.h"
#include "chrome/browser/chromeos/login/account_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace chromeos {

class AccountScreenTest : public InProcessBrowserTest {
 public:
  AccountScreenTest() {
  }

 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitchWithValue(switches::kLoginScreen, L"account");
    command_line->AppendSwitchWithValue(switches::kLoginScreenSize,
                                        L"1024,600");
  }

  virtual Browser* CreateBrowser(Profile* profile) {
    return NULL;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(AccountScreenTest);
};

IN_PROC_BROWSER_TEST_F(AccountScreenTest, FLAKY_TestBasic) {
  WizardController* controller = WizardController::default_controller();
  ASSERT_TRUE(NULL != controller);
  EXPECT_EQ(controller->GetAccountScreen(), controller->current_screen());
  // Close login manager windows.
  MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
  // End the message loop to quit the test since there's no browser window
  // created.
  MessageLoop::current()->Quit();
}

}  // namespace chromeos
<|endoftext|>


<commit_before><commit_msg>fix for multiple faces by sorting faces vector left to right and using vectors for labels/colors (#159)<commit_after><|endoftext|>


<commit_before>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the "Instituto Nokia de Tecnologia" and
// is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//

#include "ARMTargetMachine.h"
#include "ARMTargetAsmInfo.h"
#include "ARMFrameInfo.h"
#include "ARM.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;

static cl::opt<bool> DisableLdStOpti("disable-arm-loadstore-opti", cl::Hidden,
                              cl::desc("Disable load store optimization pass"));

namespace {
  // Register the target.
  RegisterTarget<ARMTargetMachine> X("arm", "  ARM");
}

/// TargetMachine ctor - Create an ILP32 architecture model
///
ARMTargetMachine::ARMTargetMachine(const Module &M, const std::string &FS)
  : Subtarget(M, FS),
    DataLayout(Subtarget.isTargetDarwin() ?
               std::string("e-p:32:32-d:32-l:32") :
               std::string("e-p:32:32-d:64-l:64")),
    InstrInfo(Subtarget),
    FrameInfo(Subtarget) {}

unsigned ARMTargetMachine::getModuleMatchQuality(const Module &M) {
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 4 && std::string(TT.begin(), TT.begin()+4) == "arm-")
    return 20;

  if (M.getPointerSize() == Module::Pointer32)
    return 1;
  else
    return 0;
}

const TargetAsmInfo *ARMTargetMachine::createTargetAsmInfo() const {
  return new ARMTargetAsmInfo(*this);
}

// Pass Pipeline Configuration
bool ARMTargetMachine::addInstSelector(FunctionPassManager &PM, bool Fast) {
  PM.add(createARMISelDag(*this));
  return false;
}

bool ARMTargetMachine::addPreEmitPass(FunctionPassManager &PM, bool Fast) {
  // FIXME: temporarily disabling load / store optimization pass for Thumb mode.
  if (!Fast && !DisableLdStOpti && !Subtarget.isThumb())
    PM.add(createARMLoadStoreOptimizationPass());

  PM.add(createARMConstantIslandPass());
  return true;
}

bool ARMTargetMachine::addAssemblyEmitter(FunctionPassManager &PM, bool Fast,
                                          std::ostream &Out) {
  // Output assembly language.
  PM.add(createARMCodePrinterPass(Out, *this));
  return false;
}
<commit_msg>ARM AAPCS abi (Linux, etc.) requires 8-byte double / long alignment; Mac requires 4-bytes alignment.<commit_after>//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the "Instituto Nokia de Tecnologia" and
// is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//

#include "ARMTargetMachine.h"
#include "ARMTargetAsmInfo.h"
#include "ARMFrameInfo.h"
#include "ARM.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;

static cl::opt<bool> DisableLdStOpti("disable-arm-loadstore-opti", cl::Hidden,
                              cl::desc("Disable load store optimization pass"));

namespace {
  // Register the target.
  RegisterTarget<ARMTargetMachine> X("arm", "  ARM");
}

/// TargetMachine ctor - Create an ILP32 architecture model
///
ARMTargetMachine::ARMTargetMachine(const Module &M, const std::string &FS)
  : Subtarget(M, FS),
    DataLayout(Subtarget.isTargetDarwin() ?
               std::string("e-p:32:32-d:32:32-l:32:32") :
               std::string("e-p:32:32-d:32:64-l:32:64")),
    InstrInfo(Subtarget),
    FrameInfo(Subtarget) {}

unsigned ARMTargetMachine::getModuleMatchQuality(const Module &M) {
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 4 && std::string(TT.begin(), TT.begin()+4) == "arm-")
    return 20;

  if (M.getPointerSize() == Module::Pointer32)
    return 1;
  else
    return 0;
}

const TargetAsmInfo *ARMTargetMachine::createTargetAsmInfo() const {
  return new ARMTargetAsmInfo(*this);
}

// Pass Pipeline Configuration
bool ARMTargetMachine::addInstSelector(FunctionPassManager &PM, bool Fast) {
  PM.add(createARMISelDag(*this));
  return false;
}

bool ARMTargetMachine::addPreEmitPass(FunctionPassManager &PM, bool Fast) {
  // FIXME: temporarily disabling load / store optimization pass for Thumb mode.
  if (!Fast && !DisableLdStOpti && !Subtarget.isThumb())
    PM.add(createARMLoadStoreOptimizationPass());

  PM.add(createARMConstantIslandPass());
  return true;
}

bool ARMTargetMachine::addAssemblyEmitter(FunctionPassManager &PM, bool Fast,
                                          std::ostream &Out) {
  // Output assembly language.
  PM.add(createARMCodePrinterPass(Out, *this));
  return false;
}
<|endoftext|>


<commit_before>/**
 * @file BackProject_Demo2.cpp
 * @brief Sample code for backproject function usage ( a bit more elaborated )
 * @author OpenCV team
 */

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

/// Global Variables
Mat src; Mat hsv; Mat hue;
Mat mask;

int lo = 20; int up = 20;
char* window_image = "Source image";

/// Function Headers
void Hist_and_Backproj( );
void pickPoint (int event, int x, int y, int, void* );

/**
 * @function main
 */
int main( int argc, char** argv )
{
  /// Read the image
  src = imread( argv[1], 1 );
  /// Transform it to HSV
  cvtColor( src, hsv, CV_BGR2HSV );

  /// Use only the Hue value
  hue.create( hsv.size(), hsv.depth() );

  int ch[] = { 0, 0 };
  mixChannels( &hsv, 1, &hue, 1, ch, 1 );

  /// Show the image
  namedWindow( window_image, CV_WINDOW_AUTOSIZE );
  imshow( window_image, src );

  /// Set Trackbars for floodfill thresholds
  createTrackbar( "Low thresh", window_image, &lo, 255, 0 );
  createTrackbar( "High thresh", window_image, &up, 255, 0 );
  /// Set a Mouse Callback
  setMouseCallback( window_image, pickPoint, 0 );

  waitKey(0);
  return 0;
}

/**
 * @function pickPoint
 */
void pickPoint (int event, int x, int y, int, void* )
{
  if( event != CV_EVENT_LBUTTONDOWN )
    { return; }

  // Fill and get the mask
  Point seed = Point( x, y );

  int newMaskVal = 255;
  Scalar newVal = Scalar( 120, 120, 120 );

  int connectivity = 8;
  int flags = connectivity + (newMaskVal << 8 ) + FLOODFILL_FIXED_RANGE + FLOODFILL_MASK_ONLY;

  Mat mask2 = Mat::zeros( src.rows + 2, src.cols + 2, CV_8UC1 );
  floodFill( src, mask2, seed, newVal, 0, Scalar( lo, lo, lo ), Scalar( up, up, up), flags );
  mask = mask2( Range( 1, mask2.rows - 1 ), Range( 1, mask2.cols - 1 ) );
  cout<<"rows: "<<mask.rows<<" columns: "<<mask.cols<<endl;
  imshow( "Mask", mask );

  Hist_and_Backproj( );
}

/**
 * @function Hist_and_Backproj
 */
void Hist_and_Backproj( )
{
  MatND hist;
  int h_bins = 30; int s_bins = 32;
  int histSize[] = { h_bins, s_bins };

  float h_range[] = { 0, 179 };
  float s_range[] = { 0, 255 };
  const float* ranges[] = { h_range, s_range };

  int channels[] = { 0, 1 };

  /// Get the Histogram and normalize it
  calcHist( &hsv, 1, channels, mask, hist, 2, histSize, ranges, true, false );

  normalize( hist, hist, 0, 255, NORM_MINMAX, -1, Mat() );

  /// Get Backprojection
  MatND backproj;
  calcBackProject( &hsv, 1, channels, hist, backproj, ranges, 1, true );

  /// Draw the backproj
  imshow( "BackProj", backproj );

}
<commit_msg>Fixed small inconsistency in sample code calcBackProject_Demo2.cpp<commit_after>/**
 * @file BackProject_Demo2.cpp
 * @brief Sample code for backproject function usage ( a bit more elaborated )
 * @author OpenCV team
 */

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

/// Global Variables
Mat src; Mat hsv;
Mat mask;

int lo = 20; int up = 20;
char* window_image = "Source image";

/// Function Headers
void Hist_and_Backproj( );
void pickPoint (int event, int x, int y, int, void* );

/**
 * @function main
 */
int main( int argc, char** argv )
{
  /// Read the image
  src = imread( argv[1], 1 );
  /// Transform it to HSV
  cvtColor( src, hsv, CV_BGR2HSV );

  /// Show the image
  namedWindow( window_image, CV_WINDOW_AUTOSIZE );
  imshow( window_image, src );

  /// Set Trackbars for floodfill thresholds
  createTrackbar( "Low thresh", window_image, &lo, 255, 0 );
  createTrackbar( "High thresh", window_image, &up, 255, 0 );
  /// Set a Mouse Callback
  setMouseCallback( window_image, pickPoint, 0 );

  waitKey(0);
  return 0;
}

/**
 * @function pickPoint
 */
void pickPoint (int event, int x, int y, int, void* )
{
  if( event != CV_EVENT_LBUTTONDOWN )
    { return; }

  // Fill and get the mask
  Point seed = Point( x, y );

  int newMaskVal = 255;
  Scalar newVal = Scalar( 120, 120, 120 );

  int connectivity = 8;
  int flags = connectivity + (newMaskVal << 8 ) + FLOODFILL_FIXED_RANGE + FLOODFILL_MASK_ONLY;

  Mat mask2 = Mat::zeros( src.rows + 2, src.cols + 2, CV_8UC1 );
  floodFill( src, mask2, seed, newVal, 0, Scalar( lo, lo, lo ), Scalar( up, up, up), flags );
  mask = mask2( Range( 1, mask2.rows - 1 ), Range( 1, mask2.cols - 1 ) );

  imshow( "Mask", mask );

  Hist_and_Backproj( );
}

/**
 * @function Hist_and_Backproj
 */
void Hist_and_Backproj( )
{
  MatND hist;
  int h_bins = 30; int s_bins = 32;
  int histSize[] = { h_bins, s_bins };

  float h_range[] = { 0, 179 };
  float s_range[] = { 0, 255 };
  const float* ranges[] = { h_range, s_range };

  int channels[] = { 0, 1 };

  /// Get the Histogram and normalize it
  calcHist( &hsv, 1, channels, mask, hist, 2, histSize, ranges, true, false );

  normalize( hist, hist, 0, 255, NORM_MINMAX, -1, Mat() );

  /// Get Backprojection
  MatND backproj;
  calcBackProject( &hsv, 1, channels, hist, backproj, ranges, 1, true );

  /// Draw the backproj
  imshow( "BackProj", backproj );

}
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQExpressionWidget.cpp,v $
//   $Revision: 1.32 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2009/01/08 16:07:44 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <iostream>

#include <qlabel.h>
#include <qcombobox.h>
//Added by qt3to4:
#include <QKeyEvent>

#include "CQExpressionWidget.h"
#include "CQMessageBox.h"
#include "CCopasiSelectionDialog.h"
#include "qtUtilities.h"

#include "copasi.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "function/CExpression.h"
#include "utilities/CAnnotatedMatrix.h"
#include "model/CModel.h"
#include "CQMatrixDialog.h"
#include "qtUtilities.h"

CQExpressionHighlighter::CQExpressionHighlighter(CQExpressionWidget* ew)
    : Q3SyntaxHighlighter(ew)
{}

int CQExpressionHighlighter::highlightParagraph (const QString & text, int /* endStateOfLastPara */)
{
  int pos = 0;
  int oldpos = -1;
  int delta;

  while (true)
    {
      pos = text.find("<", pos);
      if (pos == -1)
        delta = 0;
      else
        delta = pos - oldpos - 1;
      setFormat(oldpos + 1, delta, QColor(0, 0, 0));
      if (pos == -1) break;
      oldpos = pos;

      pos = text.find(">", pos);
      while (pos > 0 && text[pos - 1] == '\\')
        pos = text.find(">", pos + 1);

      if (pos == -1)
        delta = 0;
      else
        delta = pos - oldpos + 1;

      setFormat(oldpos, delta, QColor(100, 0, 200));
      if (pos == -1) break;
      oldpos = pos;
    }
  return 0;
}

//***********************************************************************

CQValidatorExpression::CQValidatorExpression(Q3TextEdit * parent, const char * name, bool isBoolean):
    CQValidator< Q3TextEdit >(parent, name),
    mExpression()
{
  mExpression.setBoolean(isBoolean);
}

/**
  *  This function ensures that any characters on Expression Widget are validated
  *  to go to further processes.
  */
QValidator::State CQValidatorExpression::validate(QString & input, int & pos) const
  {
    if (const_cast< CExpression * >(&mExpression)->setInfix(TO_UTF8(input)) &&
        const_cast< CExpression * >(&mExpression)->compile())
      {
        QString Input = mpLineEdit->text();
        return CQValidator< Q3TextEdit >::validate(Input, pos);
      }

    setColor(Invalid);
    return Intermediate;
  }

/**
  * Function to get CExpression object
  */
CExpression *CQValidatorExpression::getExpression()
{
  //  return const_cast< CExpression * >(&mExpression);
  return &mExpression;
}

//***********************************************************************

CQExpressionWidget::CQExpressionWidget(QWidget * parent, const char * name, bool isBoolean)
    : Q3TextEdit(parent, name),
    mOldPar(0),
    mOldPos(0),
    mExpressionType(CCopasiSimpleSelectionTree::TRANSIENT_EXPRESSION),
    mpCurrentObject(NULL),
    mNewName("")
{
  setTextFormat(Qt::PlainText);
  setTabChangesFocus(true);

  new CQExpressionHighlighter(this);

  int h, s, v;

  mSavedColor = paletteBackgroundColor();
  mSavedColor.getHsv(&h, &s, &v);

  if (s < 20) s = 20;
  mChangedColor.setHsv(240, s, v);

  mpValidator = new CQValidatorExpression(this, "", isBoolean);
  mpValidator->revalidate();

  connect(this, SIGNAL(cursorPositionChanged(int, int)),
          this, SLOT(slotCursorPositionChanged(int, int)));
  connect(this, SIGNAL(selectionChanged()),
          this, SLOT(slotSelectionChanged()));
  connect(this, SIGNAL(textChanged()),
          this, SLOT(slotTextChanged()));
}

void CQExpressionWidget::keyPressEvent (QKeyEvent * e)
{
  //filter "<" and ">"
  if (e->text() == "<")
    return;
  if (e->text() == ">")
    return;

  Q3TextEdit::keyPressEvent(e);
}

void CQExpressionWidget::slotSelectionChanged()
{
  int par1, par2, pos1, pos2;
  getSelection(&par1, &pos1, &par2, &pos2);

  if (par1 == -1) //no selection, do nothing
    {
      getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2);
      return;
    }

  //make sure a selection contains an object completely or not at all
  //TODO
  bool iio1 = isInObject(par1, pos1);
  bool iio2 = isInObject(par2, pos2);

  //if both borders are outside do nothing.

  //if at least one is inside clear selection
  if (iio1 || iio2)
    removeSelection();

  //TODO: right now the any invalid selection is just cleared.
  //in some cases it would be nicer for the user if it would be
  //extended instead

  getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2);
}

/**
  *  This slot checks any characters that are newly typed on Expression Widget.
  */
void CQExpressionWidget::slotTextChanged()
{
  int pos = 0;
  QString Expression = FROM_UTF8(getExpression());
  emit valid(mpValidator->validate(Expression, pos) == QValidator::Acceptable);
}

void CQExpressionWidget::slotCursorPositionChanged(int para, int pos)
{
  //check if we are inside an object
  if (isInObject(para, pos))
    {
      int newpos;
      //first decide in which direction we want to leave the object
      if (compareCursorPositions(mOldPar, mOldPos, para, pos))
        {
          //move right
          newpos = text(para).find(">", pos);
          if (newpos != -1)
            setCursorPosition(para, newpos + 1);
        }
      else
        {
          //move left
          newpos = text(para).findRev("<", pos);
          if (newpos != -1)
            setCursorPosition(para, newpos);
        }
    }

  getCursorPosition(&mOldPar, &mOldPos);
}

bool CQExpressionWidget::isInObject()
{
  int para, pos;
  getCursorPosition(&para, &pos);
  return isInObject(para, pos);

  /*  //the following code assumes the presence of the syntax highlighter
    if (color() == QColor(0,0,0)) return false;

    if (pos==0) return false;

    QString t = text(para);
    if (t[pos-1] == '>') return false;

    return true;*/
}

bool CQExpressionWidget::isInObject(int par, int pos)
{
  if (pos == 0) return false;

  bool result = false;

  QString tmp = text(par);

  //first look to the left
  int lo, lc;
  lo = tmp.findRev('<', pos - 1);
  lc = tmp.findRev('>', pos - 1);
  while (lc > 0 && tmp[lc - 1] == '\\')
    lc = tmp.findRev('>', lc - 1);

  if ((lo == -1) && (lc == -1))
    result = false;
  else if (lc == -1)
    result = true;
  else if (lo == -1)
    {
      result = false;
    }
  else if (lo < lc)
    result = false;
  else // lo > lc
    result = true;

  //TODO: we could implement a consistency check by trying to find the same
  //information from looking to the right.

  return result;
}

bool CQExpressionWidget::compareCursorPositions(int parold, int posold, int par, int pos)
{
  if (par > parold) return true;
  if (par < parold) return false;

  //we are in the same paragraph
  if (pos > posold) return true;
  return false;
}

void CQExpressionWidget::doKeyboardAction(Q3TextEdit::KeyboardAction action)
{
  int para, pos;
  getCursorPosition(&para, &pos);

  //handle backspace and delete. All other actions are ignored
  switch (action)
    {
    case Q3TextEdit::ActionBackspace:
      if (pos == 0) return;
      if (text(para)[pos - 1] == '>')
        {
          QString tmp = text(para);
          int left = tmp.findRev('<', pos);
          setSelection(para, left, para, pos);
          removeSelectedText();
        }
      else
        Q3TextEdit::doKeyboardAction(action);
      break;

    case Q3TextEdit::ActionDelete:
      if ((unsigned int) pos == text().length()) return;
      if (text(para)[pos] == '<')
        {
          QString tmp = text(para);
          int right = tmp.find('>', pos);
          setSelection(para, pos, para, right + 1);
          removeSelectedText();
        }
      else
        Q3TextEdit::doKeyboardAction(action);
      break;

    default:
      Q3TextEdit::doKeyboardAction(action);
      break;
    }
}

void CQExpressionWidget::setExpression(const std::string & expression)
{
  // Reset the parse list.
  mParseList.clear();

  std::string Expression = expression;
  std::string out_str = "";

  unsigned C_INT32 i = 0;

  while (i < Expression.length())
    {
      if (Expression[i] == '<')
        {
          i++;
          std::string objectName = "";

          while (Expression[i] != '>' && i < Expression.length())
            {
              if (Expression[i] == '\\')
                objectName += Expression[i++];

              objectName += Expression[i];
              i++;
            }

          CCopasiObjectName temp_CN(objectName);
          CCopasiObject * temp_object = const_cast<CCopasiObject *>(RootContainer.getObject(temp_CN));
          if (temp_object != NULL)
            {
              std::string DisplayName = temp_object->getObjectDisplayName();
              mParseList[DisplayName] = temp_object;

              // We need to escape >
              std::string::size_type pos = DisplayName.find_first_of("\\>");
              while (pos != std::string::npos)
                {
                  DisplayName.insert(pos, "\\");
                  pos += 2;
                  pos = DisplayName.find_first_of("\\>", pos);
                }

              out_str += "<" + DisplayName + ">";
            }
          continue;
        }

      else if (Expression[i] == '>')
        {
          //do nothing
        }

      else
        {
          out_str += Expression[i];
        }

      i++;
    }

  setText(FROM_UTF8(out_str));

  mpValidator->saved();

  return;
}

std::string CQExpressionWidget::getExpression() const
  {
    std::string DisplayName = "";
    std::string InfixCN = "";

    std::string InfixDispayName = TO_UTF8(text());
    std::map< std::string, const CCopasiObject *>::const_iterator it;

    unsigned int i;
    for (i = 0; i < InfixDispayName.length(); i++)
      {
        InfixCN += InfixDispayName[i];
        DisplayName = "";

        if (InfixDispayName[i] == '<')
          {
            i++;
            while (i < InfixDispayName.length() && InfixDispayName[i] != '>')
              {
                if (InfixDispayName[i] == '\\') // '\' is an escape character.
                  i++;

                DisplayName += InfixDispayName[i++];
              }

            it = mParseList.find(DisplayName);

            if (it != mParseList.end())
              InfixCN += it->second->getCN() + ">";
            else
              InfixCN = InfixCN.substr(0, InfixCN.length() - 1);
          }
      }

    return InfixCN;
  }
/*
CExpression *CQExpressionWidget::getExpression()
{
//  return const_cast< CExpression * >(&mExpression);
  return &(mpValidator->mExpression);
}*/

void CQExpressionWidget::setExpressionType(const CCopasiSimpleSelectionTree::SelectionFlag & expressionType)
{
  mExpressionType = expressionType;
}

void CQExpressionWidget::slotSelectObject()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this, mExpressionType);

  if (pObject)
    {
      // Check whether the object is valid
      if (!CCopasiSimpleSelectionTree::filter(mExpressionType, pObject))
        {
          CQMessageBox::critical(this, "Invalid Selection",
                                 "The use of the selected object is not allowed in this type of expression.");
          return;
        }

      std::string Insert = pObject->getObjectDisplayName();
      mParseList[Insert] = pObject;

      // We need to escape >
      std::string::size_type pos = Insert.find_first_of("\\>");
      while (pos != std::string::npos)
        {
          Insert.insert(pos, "\\");
          pos += 2;
          pos = Insert.find_first_of("\\>", pos);
        }

      insert(FROM_UTF8("<" + Insert + ">"));
    }
}
<commit_msg>Fixed warning message.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQExpressionWidget.cpp,v $
//   $Revision: 1.33 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2009/01/08 17:53:44 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <iostream>

#include <qlabel.h>
#include <qcombobox.h>
//Added by qt3to4:
#include <QKeyEvent>

#include "CQExpressionWidget.h"
#include "CQMessageBox.h"
#include "CCopasiSelectionDialog.h"
#include "qtUtilities.h"

#include "copasi.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "function/CExpression.h"
#include "utilities/CAnnotatedMatrix.h"
#include "model/CModel.h"
#include "CQMatrixDialog.h"
#include "qtUtilities.h"

CQExpressionHighlighter::CQExpressionHighlighter(CQExpressionWidget* ew)
    : Q3SyntaxHighlighter(ew)
{}

int CQExpressionHighlighter::highlightParagraph (const QString & text, int /* endStateOfLastPara */)
{
  int pos = 0;
  int oldpos = -1;
  int delta;

  while (true)
    {
      pos = text.find("<", pos);
      if (pos == -1)
        delta = 0;
      else
        delta = pos - oldpos - 1;
      setFormat(oldpos + 1, delta, QColor(0, 0, 0));
      if (pos == -1) break;
      oldpos = pos;

      pos = text.find(">", pos);
      while (pos > 0 && text[pos - 1] == '\\')
        pos = text.find(">", pos + 1);

      if (pos == -1)
        delta = 0;
      else
        delta = pos - oldpos + 1;

      setFormat(oldpos, delta, QColor(100, 0, 200));
      if (pos == -1) break;
      oldpos = pos;
    }
  return 0;
}

//***********************************************************************

CQValidatorExpression::CQValidatorExpression(Q3TextEdit * parent, const char * name, bool isBoolean):
    CQValidator< Q3TextEdit >(parent, name),
    mExpression()
{
  mExpression.setBoolean(isBoolean);
}

/**
  *  This function ensures that any characters on Expression Widget are validated
  *  to go to further processes.
  */
QValidator::State CQValidatorExpression::validate(QString & input, int & pos) const
  {
    if (const_cast< CExpression * >(&mExpression)->setInfix(TO_UTF8(input)) &&
        const_cast< CExpression * >(&mExpression)->compile())
      {
        QString Input = mpLineEdit->text();
        return CQValidator< Q3TextEdit >::validate(Input, pos);
      }

    setColor(Invalid);
    return Intermediate;
  }

/**
  * Function to get CExpression object
  */
CExpression *CQValidatorExpression::getExpression()
{
  //  return const_cast< CExpression * >(&mExpression);
  return &mExpression;
}

//***********************************************************************

CQExpressionWidget::CQExpressionWidget(QWidget * parent, const char * name, bool isBoolean)
    : Q3TextEdit(parent, name),
    mOldPar(0),
    mOldPos(0),
    mExpressionType(CCopasiSimpleSelectionTree::TRANSIENT_EXPRESSION),
    mpCurrentObject(NULL),
    mNewName("")
{
  setTextFormat(Qt::PlainText);
  setTabChangesFocus(true);

  new CQExpressionHighlighter(this);

  int h, s, v;

  mSavedColor = paletteBackgroundColor();
  mSavedColor.getHsv(&h, &s, &v);

  if (s < 20) s = 20;
  mChangedColor.setHsv(240, s, v);

  mpValidator = new CQValidatorExpression(this, "", isBoolean);
  mpValidator->revalidate();

  connect(this, SIGNAL(cursorPositionChanged(int, int)),
          this, SLOT(slotCursorPositionChanged(int, int)));
  connect(this, SIGNAL(selectionChanged()),
          this, SLOT(slotSelectionChanged()));
  connect(this, SIGNAL(textChanged()),
          this, SLOT(slotTextChanged()));
}

void CQExpressionWidget::keyPressEvent (QKeyEvent * e)
{
  //filter "<" and ">"
  if (e->text() == "<")
    return;
  if (e->text() == ">")
    return;

  Q3TextEdit::keyPressEvent(e);
}

void CQExpressionWidget::slotSelectionChanged()
{
  int par1, par2, pos1, pos2;
  getSelection(&par1, &pos1, &par2, &pos2);

  if (par1 == -1) //no selection, do nothing
    {
      getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2);
      return;
    }

  //make sure a selection contains an object completely or not at all
  //TODO
  bool iio1 = isInObject(par1, pos1);
  bool iio2 = isInObject(par2, pos2);

  //if both borders are outside do nothing.

  //if at least one is inside clear selection
  if (iio1 || iio2)
    removeSelection();

  //TODO: right now the any invalid selection is just cleared.
  //in some cases it would be nicer for the user if it would be
  //extended instead

  getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2);
}

/**
  *  This slot checks any characters that are newly typed on Expression Widget.
  */
void CQExpressionWidget::slotTextChanged()
{
  int pos = 0;
  QString Expression = FROM_UTF8(getExpression());
  emit valid(mpValidator->validate(Expression, pos) == QValidator::Acceptable);
}

void CQExpressionWidget::slotCursorPositionChanged(int para, int pos)
{
  //check if we are inside an object
  if (isInObject(para, pos))
    {
      int newpos;
      //first decide in which direction we want to leave the object
      if (compareCursorPositions(mOldPar, mOldPos, para, pos))
        {
          //move right
          newpos = text(para).find(">", pos);
          if (newpos != -1)
            setCursorPosition(para, newpos + 1);
        }
      else
        {
          //move left
          newpos = text(para).findRev("<", pos);
          if (newpos != -1)
            setCursorPosition(para, newpos);
        }
    }

  getCursorPosition(&mOldPar, &mOldPos);
}

bool CQExpressionWidget::isInObject()
{
  int para, pos;
  getCursorPosition(&para, &pos);
  return isInObject(para, pos);

  /*  //the following code assumes the presence of the syntax highlighter
    if (color() == QColor(0,0,0)) return false;

    if (pos==0) return false;

    QString t = text(para);
    if (t[pos-1] == '>') return false;

    return true;*/
}

bool CQExpressionWidget::isInObject(int par, int pos)
{
  if (pos == 0) return false;

  bool result = false;

  QString tmp = text(par);

  //first look to the left
  int lo, lc;
  lo = tmp.findRev('<', pos - 1);
  lc = tmp.findRev('>', pos - 1);
  while (lc > 0 && tmp[lc - 1] == '\\')
    lc = tmp.findRev('>', lc - 1);

  if ((lo == -1) && (lc == -1))
    result = false;
  else if (lc == -1)
    result = true;
  else if (lo == -1)
    {
      result = false;
    }
  else if (lo < lc)
    result = false;
  else // lo > lc
    result = true;

  //TODO: we could implement a consistency check by trying to find the same
  //information from looking to the right.

  return result;
}

bool CQExpressionWidget::compareCursorPositions(int parold, int posold, int par, int pos)
{
  if (par > parold) return true;
  if (par < parold) return false;

  //we are in the same paragraph
  if (pos > posold) return true;
  return false;
}

void CQExpressionWidget::doKeyboardAction(Q3TextEdit::KeyboardAction action)
{
  int para, pos;
  getCursorPosition(&para, &pos);

  //handle backspace and delete. All other actions are ignored
  switch (action)
    {
    case Q3TextEdit::ActionBackspace:
      if (pos == 0) return;
      if (text(para)[pos - 1] == '>')
        {
          QString tmp = text(para);
          int left = tmp.findRev('<', pos);
          setSelection(para, left, para, pos);
          removeSelectedText();
        }
      else
        Q3TextEdit::doKeyboardAction(action);
      break;

    case Q3TextEdit::ActionDelete:
      if (pos == text().length()) return;
      if (text(para)[pos] == '<')
        {
          QString tmp = text(para);
          int right = tmp.find('>', pos);
          setSelection(para, pos, para, right + 1);
          removeSelectedText();
        }
      else
        Q3TextEdit::doKeyboardAction(action);
      break;

    default:
      Q3TextEdit::doKeyboardAction(action);
      break;
    }
}

void CQExpressionWidget::setExpression(const std::string & expression)
{
  // Reset the parse list.
  mParseList.clear();

  std::string Expression = expression;
  std::string out_str = "";

  unsigned C_INT32 i = 0;

  while (i < Expression.length())
    {
      if (Expression[i] == '<')
        {
          i++;
          std::string objectName = "";

          while (Expression[i] != '>' && i < Expression.length())
            {
              if (Expression[i] == '\\')
                objectName += Expression[i++];

              objectName += Expression[i];
              i++;
            }

          CCopasiObjectName temp_CN(objectName);
          CCopasiObject * temp_object = const_cast<CCopasiObject *>(RootContainer.getObject(temp_CN));
          if (temp_object != NULL)
            {
              std::string DisplayName = temp_object->getObjectDisplayName();
              mParseList[DisplayName] = temp_object;

              // We need to escape >
              std::string::size_type pos = DisplayName.find_first_of("\\>");
              while (pos != std::string::npos)
                {
                  DisplayName.insert(pos, "\\");
                  pos += 2;
                  pos = DisplayName.find_first_of("\\>", pos);
                }

              out_str += "<" + DisplayName + ">";
            }
          continue;
        }

      else if (Expression[i] == '>')
        {
          //do nothing
        }

      else
        {
          out_str += Expression[i];
        }

      i++;
    }

  setText(FROM_UTF8(out_str));

  mpValidator->saved();

  return;
}

std::string CQExpressionWidget::getExpression() const
  {
    std::string DisplayName = "";
    std::string InfixCN = "";

    std::string InfixDispayName = TO_UTF8(text());
    std::map< std::string, const CCopasiObject *>::const_iterator it;

    unsigned int i;
    for (i = 0; i < InfixDispayName.length(); i++)
      {
        InfixCN += InfixDispayName[i];
        DisplayName = "";

        if (InfixDispayName[i] == '<')
          {
            i++;
            while (i < InfixDispayName.length() && InfixDispayName[i] != '>')
              {
                if (InfixDispayName[i] == '\\') // '\' is an escape character.
                  i++;

                DisplayName += InfixDispayName[i++];
              }

            it = mParseList.find(DisplayName);

            if (it != mParseList.end())
              InfixCN += it->second->getCN() + ">";
            else
              InfixCN = InfixCN.substr(0, InfixCN.length() - 1);
          }
      }

    return InfixCN;
  }
/*
CExpression *CQExpressionWidget::getExpression()
{
//  return const_cast< CExpression * >(&mExpression);
  return &(mpValidator->mExpression);
}*/

void CQExpressionWidget::setExpressionType(const CCopasiSimpleSelectionTree::SelectionFlag & expressionType)
{
  mExpressionType = expressionType;
}

void CQExpressionWidget::slotSelectObject()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this, mExpressionType);

  if (pObject)
    {
      // Check whether the object is valid
      if (!CCopasiSimpleSelectionTree::filter(mExpressionType, pObject))
        {
          CQMessageBox::critical(this, "Invalid Selection",
                                 "The use of the selected object is not allowed in this type of expression.");
          return;
        }

      std::string Insert = pObject->getObjectDisplayName();
      mParseList[Insert] = pObject;

      // We need to escape >
      std::string::size_type pos = Insert.find_first_of("\\>");
      while (pos != std::string::npos)
        {
          Insert.insert(pos, "\\");
          pos += 2;
          pos = Insert.find_first_of("\\>", pos);
        }

      insert(FROM_UTF8("<" + Insert + ">"));
    }
}
<|endoftext|>