<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "MWT.h"
#include "utility.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace vw_explore_tests
{
	TEST_CLASS(VWExploreUnitTests)
	{
	public:
		TEST_METHOD(EpsilonGreedyStateful)
		{
			m_mwt->Initialize_Epsilon_Greedy<int>(m_epsilon, Stateful_Default_Policy, &m_policy_func_arg);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, (u32)m_policy_func_arg);

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, (u32)m_policy_func_arg);
		}

		TEST_METHOD(EpsilonGreedyStateless)
		{
			m_mwt->Initialize_Epsilon_Greedy(m_epsilon, Stateless_Default_Policy);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, VWExploreUnitTests::Stateless_Default_Policy(m_context));
		}

		TEST_METHOD(TauFirstStateful)
		{
			m_mwt->Initialize_Tau_First<int>(m_tau, Stateful_Default_Policy, &m_policy_func_arg);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, (u32)m_policy_func_arg);

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, (u32)m_policy_func_arg);
		}

		TEST_METHOD(TauFirstStateless)
		{
			m_mwt->Initialize_Tau_First(m_tau, Stateless_Default_Policy);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, VWExploreUnitTests::Stateless_Default_Policy(m_context));
		}

		/*
		TEST_METHOD(SoftmaxStateful)
		{
			m_mwt->Initialize_Softmax<int>(m_lambda, Stateful_Default_Scorer, &m_policy_scorer_arg);
			u32 num_decisions = m_num_actions * log(NUM_ACTIONS) + c * NUM_ACTIONS;
			u8 actions[m_num_actions] = { 0 };
			u32 i;

			for (i = 0; i < num_decisions; i++)
			{
				pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
				actions[chosen_action_join_key.first]++;
			}
			// Ensure all actions are covered
			for (i = 0; i < m_num_actions; i++)
			{
				Assert::IsTrue(actions[i] > 0);
			}
		}

		TEST_METHOD(SoftmaxStateless)
		{
			m_mwt->Initialize_Epsilon_Greedy(m_epsilon, Stateless_Default_Policy);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, VWExploreUnitTests::Stateless_Default_Policy(m_context));
		}
		*/

		TEST_METHOD(PRGCoverage)
		{
			u32 const NUM_ACTIONS = 1000;
			// Using Pr(T > nlnn + cn) < 1 - exp(-e^(-c)) for the time T of the coupon collector
			// problem, setting c = 0.5 yields a failure probability of ~0.45.
			u8 const c = 0.5;

			// We're going to throw balls in bins, so 8 bits should be sufficient
			u8 actions[NUM_ACTIONS] = { 0 };
			u32 num_balls = NUM_ACTIONS * log(NUM_ACTIONS) + c * NUM_ACTIONS;
			PRG<u32> prg;
			u32 i;
			for (i = 0; i < num_balls; i++)
			{
				actions[prg.Uniform_Int(0, NUM_ACTIONS - 1)]++;
			}
			// Ensure all actions are covered
			for (i = 0; i < NUM_ACTIONS; i++)
			{
				Assert::IsTrue(actions[i] > 0);
			}
		}

		TEST_METHOD_INITIALIZE(TestInitialize)
		{
			m_num_actions = 10;
			m_app_id = "MWT Test App";
			m_mwt = new MWT(m_app_id, m_num_actions);

			//TODO: We should eventually test randomization, else we are missing code paths
			// Initialize with 0 to test deterministic result
			m_epsilon = 0;
			m_tau = 0;
			m_policy_func_arg = 101;
			m_policy_scorer_arg = 102;
			m_lambda = 0;

			m_num_features = 1;
			m_features = new feature[m_num_features];
			m_features[0].weight_index = 1;
			m_features[0].x = 0.5;
			m_context = new Context(m_features, m_num_features);

			m_unique_key = "1001";
		}

		TEST_METHOD_CLEANUP(TestCleanup)
		{
			delete m_features;
			delete m_context;
			delete m_mwt;

			m_features = nullptr;
			m_context = nullptr;
			m_mwt = nullptr;
		}

	public:
		static u32 Stateful_Default_Policy(int* stateContext, Context* applicationContext)
		{
			return *stateContext;
		}

		static u32 Stateless_Default_Policy(Context* applicationContext)
		{
			return 99;
		}

		/*
		static u32 Stateful_Default_Scorer(int* stateContext, Context* applicationContext)
		{
			return *stateContext;
		}

		static u32 Stateless_Default_Scorer(Context* applicationContext)
		{
			return 199;
		}
		*/

	private:
		char* Unique_Key() { return const_cast<char*>(m_unique_key.c_str()); }
		u32 Unique_Key_Length() { return (u32)m_unique_key.length(); }

	private:
		string m_app_id;
		MWT* m_mwt;

		float m_epsilon;
		u32 m_tau;
		float m_lambda;
		int m_policy_func_arg;
		int m_policy_scorer_arg;

		Context* m_context;
		int m_num_features;
		feature* m_features;

		int m_num_actions;
		string m_unique_key;
		int m_unique_key_length;
	};
}<commit_msg>modified existing tests for eps greedy & tau first to test logger data as well<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "MWT.h"
#include "utility.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace vw_explore_tests
{
	TEST_CLASS(VWExploreUnitTests)
	{
	public:
		TEST_METHOD(EpsilonGreedyStateful)
		{
			m_mwt->Initialize_Epsilon_Greedy<int>(m_epsilon, Stateful_Default_Policy, &m_policy_func_arg);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, (u32)m_policy_func_arg);

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, (u32)m_policy_func_arg);

			this->Test_Logger(2);
		}

		TEST_METHOD(EpsilonGreedyStateless)
		{
			m_mwt->Initialize_Epsilon_Greedy(m_epsilon, Stateless_Default_Policy);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			this->Test_Logger(2);
		}

		TEST_METHOD(TauFirstStateful)
		{
			m_mwt->Initialize_Tau_First<int>(m_tau, Stateful_Default_Policy, &m_policy_func_arg);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, (u32)m_policy_func_arg);

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, (u32)m_policy_func_arg);

			this->Test_Logger(0); // tau = 0 means no randomization and no logging
		}

		TEST_METHOD(TauFirstStateless)
		{
			m_mwt->Initialize_Tau_First(m_tau, Stateless_Default_Policy);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			this->Test_Logger(0);
		}

		/*
		TEST_METHOD(SoftmaxStateful)
		{
			m_mwt->Initialize_Softmax<int>(m_lambda, Stateful_Default_Scorer, &m_policy_scorer_arg);
			u32 num_decisions = m_num_actions * log(NUM_ACTIONS) + c * NUM_ACTIONS;
			u8 actions[m_num_actions] = { 0 };
			u32 i;

			for (i = 0; i < num_decisions; i++)
			{
				pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
				actions[chosen_action_join_key.first]++;
			}
			// Ensure all actions are covered
			for (i = 0; i < m_num_actions; i++)
			{
				Assert::IsTrue(actions[i] > 0);
			}
		}

		TEST_METHOD(SoftmaxStateless)
		{
			m_mwt->Initialize_Epsilon_Greedy(m_epsilon, Stateless_Default_Policy);

			pair<u32, u64> chosen_action_join_key = m_mwt->Choose_Action_Join_Key(*m_context);
			Assert::AreEqual(chosen_action_join_key.first, VWExploreUnitTests::Stateless_Default_Policy(m_context));

			u32 chosen_action = m_mwt->Choose_Action(*m_context, this->Unique_Key(), this->Unique_Key_Length());
			Assert::AreEqual(chosen_action, VWExploreUnitTests::Stateless_Default_Policy(m_context));
		}
		*/

		TEST_METHOD(PRGCoverage)
		{
			u32 const NUM_ACTIONS = 1000;
			// Using Pr(T > nlnn + cn) < 1 - exp(-e^(-c)) for the time T of the coupon collector
			// problem, setting c = 0.5 yields a failure probability of ~0.45.
			u8 const c = 0.5;

			// We're going to throw balls in bins, so 8 bits should be sufficient
			u8 actions[NUM_ACTIONS] = { 0 };
			u32 num_balls = NUM_ACTIONS * log(NUM_ACTIONS) + c * NUM_ACTIONS;
			PRG<u32> prg;
			u32 i;
			for (i = 0; i < num_balls; i++)
			{
				actions[prg.Uniform_Int(0, NUM_ACTIONS - 1)]++;
			}
			// Ensure all actions are covered
			for (i = 0; i < NUM_ACTIONS; i++)
			{
				Assert::IsTrue(actions[i] > 0);
			}
		}

		TEST_METHOD_INITIALIZE(TestInitialize)
		{
			m_num_actions = 10;
			m_app_id = "MWT Test App";
			m_mwt = new MWT(m_app_id, m_num_actions);

			//TODO: We should eventually test randomization, else we are missing code paths
			// Initialize with 0 to test deterministic result
			m_epsilon = 0;
			m_tau = 0;
			m_policy_func_arg = 101;
			m_policy_scorer_arg = 102;
			m_lambda = 0;

			m_num_features = 1;
			m_features = new feature[m_num_features];
			m_features[0].weight_index = 1;
			m_features[0].x = 0.5;
			m_context = new Context(m_features, m_num_features);

			m_unique_key = "1001";
		}

		TEST_METHOD_CLEANUP(TestCleanup)
		{
			delete m_features;
			delete m_context;
			delete m_mwt;

			m_features = nullptr;
			m_context = nullptr;
			m_mwt = nullptr;
		}

	public:
		static u32 Stateful_Default_Policy(int* stateContext, Context* applicationContext)
		{
			return *stateContext;
		}

		static u32 Stateless_Default_Policy(Context* applicationContext)
		{
			return 99;
		}

		/*
		static u32 Stateful_Default_Scorer(int* stateContext, Context* applicationContext)
		{
			return *stateContext;
		}

		static u32 Stateless_Default_Scorer(Context* applicationContext)
		{
			return 199;
		}
		*/

	private:
		inline void Test_Logger(int num_interactions_expected)
		{
			size_t num_interactions = 0;
			Interaction** interactions = nullptr;
			m_mwt->Get_All_Interactions(num_interactions, interactions);

			Assert::AreEqual(num_interactions_expected, (int)num_interactions);

			delete[] interactions;
		}

	private:
		char* Unique_Key() { return const_cast<char*>(m_unique_key.c_str()); }
		u32 Unique_Key_Length() { return (u32)m_unique_key.length(); }

	private:
		string m_app_id;
		MWT* m_mwt;

		float m_epsilon;
		u32 m_tau;
		float m_lambda;
		int m_policy_func_arg;
		int m_policy_scorer_arg;

		Context* m_context;
		int m_num_features;
		feature* m_features;

		int m_num_actions;
		string m_unique_key;
		int m_unique_key_length;
	};
}<|endoftext|>


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

#include <wangle/bootstrap/ServerBootstrap.h>
#include <wangle/concurrent/NamedThreadFactory.h>
#include <wangle/channel/Handler.h>
#include <folly/io/async/EventBaseManager.h>

namespace wangle {

void ServerWorkerPool::threadStarted(
  wangle::ThreadPoolExecutor::ThreadHandle* h) {
  auto worker = acceptorFactory_->newAcceptor(exec_->getEventBase(h));
  {
    Mutex::WriteHolder holder(workersMutex_.get());
    workers_->insert({h, worker});
  }

  for(auto socket : *sockets_) {
    socket->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
      [this, worker, socket](){
        socketFactory_->addAcceptCB(
          socket, worker.get(), worker->getEventBase());
    });
  }
}

void ServerWorkerPool::threadStopped(
  wangle::ThreadPoolExecutor::ThreadHandle* h) {
  auto worker = [&] {
    Mutex::WriteHolder holder(workersMutex_.get());
    auto workerIt = workers_->find(h);
    CHECK(workerIt != workers_->end());
    auto w = std::move(workerIt->second);
    workers_->erase(workerIt);
    return w;
  }();

  for (auto socket : *sockets_) {
    socket->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
      [&]() {
        socketFactory_->removeAcceptCB(
          socket, worker.get(), nullptr);
    });
  }

  worker->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
    [&]() {
      worker->dropAllConnections();
    });
}

} // namespace wangle
<commit_msg>Destroy the acceptor in the evb thread to avoid an assertion<commit_after>/*
 * Copyright 2017-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <wangle/bootstrap/ServerBootstrap.h>
#include <wangle/concurrent/NamedThreadFactory.h>
#include <wangle/channel/Handler.h>
#include <folly/io/async/EventBaseManager.h>

namespace wangle {

void ServerWorkerPool::threadStarted(
  wangle::ThreadPoolExecutor::ThreadHandle* h) {
  auto worker = acceptorFactory_->newAcceptor(exec_->getEventBase(h));
  {
    Mutex::WriteHolder holder(workersMutex_.get());
    workers_->insert({h, worker});
  }

  for(auto socket : *sockets_) {
    socket->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
      [this, worker, socket](){
        socketFactory_->addAcceptCB(
          socket, worker.get(), worker->getEventBase());
    });
  }
}

void ServerWorkerPool::threadStopped(
  wangle::ThreadPoolExecutor::ThreadHandle* h) {
  auto worker = [&] {
    Mutex::WriteHolder holder(workersMutex_.get());
    auto workerIt = workers_->find(h);
    CHECK(workerIt != workers_->end());
    auto w = std::move(workerIt->second);
    workers_->erase(workerIt);
    return w;
  }();

  for (auto socket : *sockets_) {
    socket->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait(
      [&]() {
        socketFactory_->removeAcceptCB(
          socket, worker.get(), nullptr);
    });
  }

  auto evb = worker->getEventBase();

  evb->runImmediatelyOrRunInEventBaseThreadAndWait(
    [w = std::move(worker)]() mutable {
      w->dropAllConnections();
      w.reset();
    });
}

} // namespace wangle
<|endoftext|>


<commit_before>/*
  This file is part of KNotes.

  Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>

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

  This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA  02111-1307, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt.  If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
*/

#include "resourcemanager.h"
#include "resourcelocal.h"
#include "knotesapp.h"
#include "knote.h"
#include "version.h"

#include <libkcal/journal.h>
#include <libkcal/attachment.h>

#include <klocale.h>
#include <kstandarddirs.h>
#include <kio/netaccess.h>

#include <qdir.h>

ResourceManager::ResourceManager( KNotesApp* app )
    : QObject( app, "Resource Manager" ), m_app( app )
{
    m_noteList.setAutoDelete( true );

    m_manager = new KRES::Manager<ResourceNotes>( "notes" );
    m_manager->addObserver( this );
    m_manager->readConfig();
}

ResourceManager::~ResourceManager()
{
    blockSignals( true );
    m_noteList.clear();
    blockSignals( false );
}

void ResourceManager::load()
{
    if ( !m_manager->standardResource() ) {
        kdDebug() << "Warning! No standard resource yet." << endl;
        ResourceNotes *resource = new ResourceLocal( 0 );
        m_manager->add( resource );
        m_manager->setStandardResource( resource );
    }

    // Open all active resources
    KRES::Manager<ResourceNotes>::ActiveIterator it;
    for ( it = m_manager->activeBegin(); it != m_manager->activeEnd(); ++it ) {
        kdDebug() << "Opening resource " + (*it)->resourceName() << endl;
        (*it)->setManager( this );
        if ( (*it)->open() )
            (*it)->load();
    }
}

void ResourceManager::save()
{
    KRES::Manager<ResourceNotes>::ActiveIterator it;
    for ( it = m_manager->activeBegin(); it != m_manager->activeEnd(); ++it )
        (*it)->save();
}

void ResourceManager::saveConfigs()
{
    QDictIterator<KNote> it( m_noteList );
    for ( ; it.current(); ++it )
        it.current()->saveConfig();
}

QString ResourceManager::newNote( const QString& name, const QString& text )
{
    // create the new note
    KCal::Journal *note = new KCal::Journal();

    // new notes have the current date/time as title if none was given
    if ( !name.isEmpty() )
        note->setSummary( name );
    else
        note->setSummary( KGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );
    note->setDescription( text );

    // TODO: Make this be configurable
    ResourceNotes* resource = m_manager->standardResource();
    if ( resource )
        resource->addNote( note );
    else
        kdDebug(5800) << "ResourceManager::newNote(): no resource" << endl;

    return note->uid();
}

void ResourceManager::registerNote( ResourceNotes* resource,
                                    KCal::Journal* journal, bool loaded )
{
    // KOrganizers journals don't have attachments -> use default
    // display config
    if ( journal->attachments(CONFIG_MIME).isEmpty() ) {
        // Set the name of the config file...
        QDir noteDir( KGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
        QString file = noteDir.absFilePath( journal->uid() );
        KURL src = KGlobal::dirs()->findResource( "config", "knotesrc" );
        KURL dst = file;

        // ...and "fill" it with the default config
        KIO::NetAccess::file_copy( src, dst, -1, true, m_app );
        journal->addAttachment( new KCal::Attachment( file, CONFIG_MIME ) );
    }

    if ( journal->summary().isNull() && journal->dtStart().isValid() ) {
        QString s = KGlobal::locale()->formatDateTime( journal->dtStart() );
        journal->setSummary( s );
    }

    KNote* newNote = new KNote( m_app, m_app->domDocument(), journal );
    m_noteList.insert( newNote->noteId(), newNote );
    m_resourceMap[ newNote ] = resource;

    connect( newNote, SIGNAL(sigNewNote()), m_app, SLOT(slotNewNote()) );
    connect( newNote, SIGNAL(sigKillNote( KCal::Journal* )),
             this,    SLOT(slotNoteKilled( KCal::Journal* )) );
    connect( newNote, SIGNAL(sigNameChanged()),
             m_app, SLOT(updateNoteActions()) );
    connect( newNote, SIGNAL(sigSaveData()), m_app, SLOT(saveNotes()) );

    if( !loaded ) {
        // This is a new note
        m_app->updateNoteActions();
        m_app->showNote( newNote );
    }
}

void ResourceManager::slotNoteKilled( KCal::Journal* journal )
{
    // Remove the journal from the resource it came from
    m_resourceMap[ m_noteList[ journal->uid() ] ]->deleteNote( journal );
    m_resourceMap.remove( m_noteList[ journal->uid() ] );

    // Kill the KNote object
    m_noteList.remove( journal->uid() );

    QString configFile = journal->attachments( CONFIG_MIME ).first()->uri();
    if ( !QDir::home().remove( configFile ) )
        kdError(5500) << "Can't remove the note config: "
                      << configFile << endl;

    m_app->updateNoteActions();
}

int ResourceManager::count()
{
    return m_noteList.count();
}

QMap<QString,QString> ResourceManager::notes() const
{
    QMap<QString,QString> notes;
    QDictIterator<KNote> it( m_noteList );

    for ( ; it.current(); ++it )
        notes.insert( it.current()->noteId(), it.current()->name() );

    return notes;
}

void ResourceManager::sync( const QString& app )
{
    QDictIterator<KNote> it( m_noteList );

    for ( ; it.current(); ++it )
        it.current()->sync( app );
}

KNote* ResourceManager::first()
{
    QDictIterator<KNote> it( m_noteList );
    return it.toFirst();
}

void ResourceManager::showNextNote()
{
    // show next note
    QDictIterator<KNote> it( m_noteList );
    KNote* first = it.toFirst();
    for ( ; it.current(); ++it )
        if ( it.current()->hasFocus() )
        {
            if ( ++it )
                m_app->showNote( it.current() );
            else
                m_app->showNote( first );
            break;
        }
}

KNote* ResourceManager::note( const QString& id )
{
    return m_noteList[id];
}

void ResourceManager::resourceAdded( ResourceNotes* resource )
{
  kdDebug() << "Resource added: " << resource->resourceName() << endl;

  if ( !resource->isActive() ) return;

  resource->setManager( this );
  if ( resource->open() ) {
    resource->load();
  }
}

void ResourceManager::resourceModified( ResourceNotes* /*resource*/ )
{
}

void ResourceManager::resourceDeleted( ResourceNotes* /*resource*/ )
{
}

#include "resourcemanager.moc"
<commit_msg>compile with explicit KURL()<commit_after>/*
  This file is part of KNotes.

  Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>

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

  This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA  02111-1307, USA.

  In addition, as a special exception, the copyright holders give
  permission to link the code of this program with any edition of
  the Qt library by Trolltech AS, Norway (or with modified versions
  of Qt that use the same license as Qt), and distribute linked
  combinations including the two.  You must obey the GNU General
  Public License in all respects for all of the code used other than
  Qt.  If you modify this file, you may extend this exception to
  your version of the file, but you are not obligated to do so.  If
  you do not wish to do so, delete this exception statement from
  your version.
*/

#include "resourcemanager.h"
#include "resourcelocal.h"
#include "knotesapp.h"
#include "knote.h"
#include "version.h"

#include <libkcal/journal.h>
#include <libkcal/attachment.h>

#include <klocale.h>
#include <kstandarddirs.h>
#include <kio/netaccess.h>

#include <qdir.h>

ResourceManager::ResourceManager( KNotesApp* app )
    : QObject( app, "Resource Manager" ), m_app( app )
{
    m_noteList.setAutoDelete( true );

    m_manager = new KRES::Manager<ResourceNotes>( "notes" );
    m_manager->addObserver( this );
    m_manager->readConfig();
}

ResourceManager::~ResourceManager()
{
    blockSignals( true );
    m_noteList.clear();
    blockSignals( false );
}

void ResourceManager::load()
{
    if ( !m_manager->standardResource() ) {
        kdDebug() << "Warning! No standard resource yet." << endl;
        ResourceNotes *resource = new ResourceLocal( 0 );
        m_manager->add( resource );
        m_manager->setStandardResource( resource );
    }

    // Open all active resources
    KRES::Manager<ResourceNotes>::ActiveIterator it;
    for ( it = m_manager->activeBegin(); it != m_manager->activeEnd(); ++it ) {
        kdDebug() << "Opening resource " + (*it)->resourceName() << endl;
        (*it)->setManager( this );
        if ( (*it)->open() )
            (*it)->load();
    }
}

void ResourceManager::save()
{
    KRES::Manager<ResourceNotes>::ActiveIterator it;
    for ( it = m_manager->activeBegin(); it != m_manager->activeEnd(); ++it )
        (*it)->save();
}

void ResourceManager::saveConfigs()
{
    QDictIterator<KNote> it( m_noteList );
    for ( ; it.current(); ++it )
        it.current()->saveConfig();
}

QString ResourceManager::newNote( const QString& name, const QString& text )
{
    // create the new note
    KCal::Journal *note = new KCal::Journal();

    // new notes have the current date/time as title if none was given
    if ( !name.isEmpty() )
        note->setSummary( name );
    else
        note->setSummary( KGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );
    note->setDescription( text );

    // TODO: Make this be configurable
    ResourceNotes* resource = m_manager->standardResource();
    if ( resource )
        resource->addNote( note );
    else
        kdDebug(5800) << "ResourceManager::newNote(): no resource" << endl;

    return note->uid();
}

void ResourceManager::registerNote( ResourceNotes* resource,
                                    KCal::Journal* journal, bool loaded )
{
    // KOrganizers journals don't have attachments -> use default
    // display config
    if ( journal->attachments(CONFIG_MIME).isEmpty() ) {
        // Set the name of the config file...
        QDir noteDir( KGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
        QString file = noteDir.absFilePath( journal->uid() );
        KURL src ( KGlobal::dirs()->findResource( "config", "knotesrc" ) );
        KURL dst ( file );

        // ...and "fill" it with the default config
        KIO::NetAccess::file_copy( src, dst, -1, true, m_app );
        journal->addAttachment( new KCal::Attachment( file, CONFIG_MIME ) );
    }

    if ( journal->summary().isNull() && journal->dtStart().isValid() ) {
        QString s = KGlobal::locale()->formatDateTime( journal->dtStart() );
        journal->setSummary( s );
    }

    KNote* newNote = new KNote( m_app, m_app->domDocument(), journal );
    m_noteList.insert( newNote->noteId(), newNote );
    m_resourceMap[ newNote ] = resource;

    connect( newNote, SIGNAL(sigNewNote()), m_app, SLOT(slotNewNote()) );
    connect( newNote, SIGNAL(sigKillNote( KCal::Journal* )),
             this,    SLOT(slotNoteKilled( KCal::Journal* )) );
    connect( newNote, SIGNAL(sigNameChanged()),
             m_app, SLOT(updateNoteActions()) );
    connect( newNote, SIGNAL(sigSaveData()), m_app, SLOT(saveNotes()) );

    if( !loaded ) {
        // This is a new note
        m_app->updateNoteActions();
        m_app->showNote( newNote );
    }
}

void ResourceManager::slotNoteKilled( KCal::Journal* journal )
{
    // Remove the journal from the resource it came from
    m_resourceMap[ m_noteList[ journal->uid() ] ]->deleteNote( journal );
    m_resourceMap.remove( m_noteList[ journal->uid() ] );

    // Kill the KNote object
    m_noteList.remove( journal->uid() );

    QString configFile = journal->attachments( CONFIG_MIME ).first()->uri();
    if ( !QDir::home().remove( configFile ) )
        kdError(5500) << "Can't remove the note config: "
                      << configFile << endl;

    m_app->updateNoteActions();
}

int ResourceManager::count()
{
    return m_noteList.count();
}

QMap<QString,QString> ResourceManager::notes() const
{
    QMap<QString,QString> notes;
    QDictIterator<KNote> it( m_noteList );

    for ( ; it.current(); ++it )
        notes.insert( it.current()->noteId(), it.current()->name() );

    return notes;
}

void ResourceManager::sync( const QString& app )
{
    QDictIterator<KNote> it( m_noteList );

    for ( ; it.current(); ++it )
        it.current()->sync( app );
}

KNote* ResourceManager::first()
{
    QDictIterator<KNote> it( m_noteList );
    return it.toFirst();
}

void ResourceManager::showNextNote()
{
    // show next note
    QDictIterator<KNote> it( m_noteList );
    KNote* first = it.toFirst();
    for ( ; it.current(); ++it )
        if ( it.current()->hasFocus() )
        {
            if ( ++it )
                m_app->showNote( it.current() );
            else
                m_app->showNote( first );
            break;
        }
}

KNote* ResourceManager::note( const QString& id )
{
    return m_noteList[id];
}

void ResourceManager::resourceAdded( ResourceNotes* resource )
{
  kdDebug() << "Resource added: " << resource->resourceName() << endl;

  if ( !resource->isActive() ) return;

  resource->setManager( this );
  if ( resource->open() ) {
    resource->load();
  }
}

void ResourceManager::resourceModified( ResourceNotes* /*resource*/ )
{
}

void ResourceManager::resourceDeleted( ResourceNotes* /*resource*/ )
{
}

#include "resourcemanager.moc"
<|endoftext|>


<commit_before>/*
 *  PlayState.cpp
 *  Normal "play" state
 *
 *  Created by Marcelo Cohen on 08/13.
 *  Copyright 2013 PUCRS. All rights reserved.
 *
 */

#include <iostream>
#include <cmath>
#include "Game.h"
#include "PlayState.h"
#include "MenuState.h"
#include "InputManager.h"

PlayState PlayState::m_PlayState;

using namespace std;

void PlayState::init()
{
    player.loadXML("data/img/hunter.xml");
    player.setPosition(50,100);
    player.loadAnimation("data/img/hunteranim.xml");
    player.setAnimRate(15);

    bullet.load("data/img/Char27.png");
    bullet.setXspeed(100);
    bullet.setMirror(true);
    bullet.setPosition(100, 100);

    map = new tmx::MapLoader("data/maps");
    map->Load("dungeon-tilesets2.tmx");

    dirx = 0; // direção do sprite: para a direita (1), esquerda (-1)
    diry = 0;

    im = cgf::InputManager::instance();

    im->addKeyInput("left", sf::Keyboard::Left);
    im->addKeyInput("right", sf::Keyboard::Right);
    im->addKeyInput("up", sf::Keyboard::Up);
    im->addKeyInput("down", sf::Keyboard::Down);
    im->addKeyInput("quit", sf::Keyboard::Escape);
    im->addKeyInput("zoomin", sf::Keyboard::Z);
    im->addKeyInput("zoomout", sf::Keyboard::X);
    im->addMouseInput("rightclick", sf::Mouse::Right);

    if (!font.loadFromFile("data/fonts/arial.ttf"))
    {
        cout << "Cannot load arial.ttf font!" << endl;
        exit(1);
    }

    // select the font
    text.setFont(font);
    text.setString(L"Teste de texto gráfico");
    text.setCharacterSize(24); // in pixels, not points!
    text.setColor(sf::Color::Red);
    text.setStyle(sf::Text::Bold | sf::Text::Underlined);

    ammo = 10;
    bullets.reserve(ammo);

	cout << "PlayState Init Successful" << endl;
}

void PlayState::cleanup()
{
	cout << "PlayState Clean Successful" << endl;
	delete map;
}

void PlayState::pause()
{
	cout << "PlayState Paused" << endl;
}

void PlayState::resume()
{
	cout << "PlayState Resumed" << endl;
}

void PlayState::handleEvents(cgf::Game* game)
{
    sf::Event event;
    sf::View view = screen->getView();

    while (screen->pollEvent(event))
    {
        if(event.type == sf::Event::Closed)
            game->quit();
        if(event.type == sf::Event::KeyPressed)
            if(event.key.code == sf::Keyboard::S)
                game->toggleStats();
            else if (event.key.code == sf::Keyboard::Space)
                shoot(game);
    }

    dirx = diry = 0;

    if(im->testEvent("left")) {
        if(player.getXspeed() >= 0) {
            player.setAnimation("walk-left");
            player.play();
        }
        dirx = -1;
    }
    else
    if(im->testEvent("right")) {
        if(player.getXspeed() <= 0) {
            player.setAnimation("walk-right");
            player.play();
        }
        dirx = 1;
    }

    if(im->testEvent("up")) {
        if(player.getYspeed() >= 0) {
            player.setAnimation("walk-up");
            player.play();
        }
        diry = -1;
    }

    if(im->testEvent("down")) {
        if(player.getYspeed() <= 0) {
            player.setAnimation("walk-down");
            player.play();
        }
        diry = 1;
    }

    if(!dirx && !diry) // parado?
    {
        player.setCurrentFrame(0);
        player.pause();
    }

    if(im->testEvent("quit") || im->testEvent("rightclick"))
        game->quit();

    if(im->testEvent("zoomin"))
    {
        view.zoom(1.01);
        screen->setView(view);
    }
    else if(im->testEvent("zoomout"))
    {
        view.zoom(0.99);
        screen->setView(view);
    }

    player.setXspeed(dirx*100);
    player.setYspeed(diry*100);
}

void PlayState::shoot(cgf::Game* game)
{
    if (ammo == 0) {
        //bullet.load("data/img/Char27.png");
        //bullet.setXspeed(100);
        //bullet.setMirror(true);
        //bullet.setPosition(100, 100);
        cout << "Out of ammo" << endl;
    } else {
        ammo--;
        cout << "SHOOT!" << endl;
    }
}

void PlayState::update(cgf::Game* game)
{
    screen = game->getScreen();
    checkCollision(2, game, &player);
    centerMapOnPlayer();
    if (checkCollision(2, game, &bullet)) {
        bullet.setXspeed(bullet.getXspeed() * -1);
        bullet.setMirror(!bullet.getMirror());
    } else if (bullet.circleCollision(player)) {
        game->changeState(MenuState::instance());
    }
}

bool PlayState::checkCollision(u_int8_t layer, cgf::Game* game, cgf::Sprite* obj)
{
    int i, x1, x2, y1, y2;
    bool bump = false;

    // Get the limits of the map
    sf::Vector2u mapsize = map->GetMapSize();
    // Get the width and height of a single tile
    sf::Vector2u tilesize = map->GetMapTileSize();

    mapsize.x /= tilesize.x;
    mapsize.y /= tilesize.y;
    mapsize.x--;
    mapsize.y--;

    // Get the height and width of the object (in this case, 100% of a tile)
    sf::Vector2u objsize = obj->getSize();
    objsize.x *= obj->getScale().x;
    objsize.y *= obj->getScale().y;

    float px = obj->getPosition().x;
    float py = obj->getPosition().y;

    double deltaTime = game->getUpdateInterval();

    sf::Vector2f offset(obj->getXspeed()/1000 * deltaTime, obj->getYspeed()/1000 * deltaTime);

    float vx = offset.x;
    float vy = offset.y;

    // Test the horizontal movement first
    i = objsize.y > tilesize.y ? tilesize.y : objsize.y;

    for (;;)
    {
        x1 = (px + vx) / tilesize.x;
        x2 = (px + vx + objsize.x - 1) / tilesize.x;

        y1 = (py) / tilesize.y;
        y2 = (py + i - 1) / tilesize.y;

        if (x1 >= 0 && x2 < mapsize.x && y1 >= 0 && y2 < mapsize.y)
        {
            if (vx > 0)
            {
                // Trying to move right

                int upRight   = getCellFromMap(layer, x2*tilesize.x, y1*tilesize.y);
                int downRight = getCellFromMap(layer, x2*tilesize.x, y2*tilesize.y);
                if (upRight || downRight)
                {
                    // Place the player as close to the solid tile as possible
                    px = x2 * tilesize.x;
                    px -= objsize.x;// + 1;
                    vx = 0;
                    bump = true;
                }
            }

            else if (vx < 0)
            {
                // Trying to move left

                int upLeft   = getCellFromMap(layer, x1*tilesize.x, y1*tilesize.y);
                int downLeft = getCellFromMap(layer, x1*tilesize.x, y2*tilesize.y);
                if (upLeft || downLeft)
                {
                    // Place the player as close to the solid tile as possible
                    px = (x1+1) * tilesize.x;
                    vx = 0;
                    bump = true;
                }
            }
        }

        if (i == objsize.y) // Checked player height with all tiles ?
        {
            break;
        }

        i += tilesize.y; // done, check next tile upwards

        if (i > objsize.y)
        {
            i = objsize.y;
        }
    }

    // Now test the vertical movement

    i = objsize.x > tilesize.x ? tilesize.x : objsize.x;

    for (;;)
    {
        x1 = (px / tilesize.x);
        x2 = ((px + i-1) / tilesize.x);

        y1 = ((py + vy) / tilesize.y);
        y2 = ((py + vy + objsize.y-1) / tilesize.y);

        if (x1 >= 0 && x2 < mapsize.x && y1 >= 0 && y2 < mapsize.y)
        {
            if (vy > 0)
            {
                // Trying to move down
                int downLeft  = getCellFromMap(layer, x1*tilesize.x, y2*tilesize.y);
                int downRight = getCellFromMap(layer, x2*tilesize.x, y2*tilesize.y);
                if (downLeft || downRight)
                {
                    // Place the player as close to the solid tile as possible
                    py = y2 * tilesize.y;
                    py -= objsize.y;
                    vy = 0;
                    bump = true;
                }
            }

            else if (vy < 0)
            {
                // Trying to move up

                int upLeft  = getCellFromMap(layer, x1*tilesize.x, y1*tilesize.y);
                int upRight = getCellFromMap(layer, x2*tilesize.x, y1*tilesize.y);
                if (upLeft || upRight)
                {
                    // Place the player as close to the solid tile as possible
                    py = (y1 + 1) * tilesize.y;
                    vy = 0;
                    bump = true;
                }
            }
        }

        if (i == objsize.x)
        {
            break;
        }

        i += tilesize.x; // done, check next tile to the right

        if (i > objsize.x)
        {
            i = objsize.x;
        }
    }

    // Now apply the movement and animation

    obj->setPosition(px+vx,py+vy);
    px = obj->getPosition().x;
    py = obj->getPosition().y;

    obj->update(deltaTime, false); // only update animation

    // Check collision with edges of map
    if (px < 0)
        obj->setPosition(px,py);
    else if (px + objsize.x >= mapsize.x * tilesize.x)
        obj->setPosition(mapsize.x*tilesize.x - objsize.x - 1,py);

    if(py < 0)
        obj->setPosition(px,0);
    else if(py + objsize.y >= mapsize.y * tilesize.y)
        obj->setPosition(px, mapsize.y*tilesize.y - objsize.y - 1);

    return bump;
}

sf::Uint16 PlayState::getCellFromMap(uint8_t layernum, float x, float y)
{
    auto layers = map->GetLayers();
    tmx::MapLayer& layer = layers[layernum];
    sf::Vector2u mapsize = map->GetMapSize();
    sf::Vector2u tilesize = map->GetMapTileSize();
    mapsize.x /= tilesize.x;
    mapsize.y /= tilesize.y;
    int col = floor(x / tilesize.x);
    int row = floor(y / tilesize.y);
    return layer.tiles[row*mapsize.x + col].gid;
}

void PlayState::centerMapOnPlayer()
{
    sf::View view = screen->getView();
    sf::Vector2u mapsize = map->GetMapSize();
    sf::Vector2f viewsize = view.getSize();
    viewsize.x /= 2;
    viewsize.y /= 2;
    sf::Vector2f pos = player.getPosition();

    float panX = viewsize.x; // minimum pan
    if(pos.x >= viewsize.x)
        panX = pos.x;

    if(panX >= mapsize.x - viewsize.x)
        panX = mapsize.x - viewsize.x;

    float panY = viewsize.y; // minimum pan
    if(pos.y >= viewsize.y)
        panY = pos.y;

    if(panY >= mapsize.y - viewsize.y)
        panY = mapsize.y - viewsize.y;

    view.setCenter(sf::Vector2f(panX,panY));
    screen->setView(view);
}

void PlayState::draw(cgf::Game* game)
{
    //sf::View view = screen->getView();

    screen->clear(sf::Color(0,0,0));

    map->Draw(*screen, 0);
    screen->draw(player);
    screen->draw(bullet);
    map->Draw(*screen, 1);

    screen->draw(text);
}
<commit_msg>Fire some dumb bullets when space gets pressed<commit_after>/*
 *  PlayState.cpp
 *  Normal "play" state
 *
 *  Created by Marcelo Cohen on 08/13.
 *  Copyright 2013 PUCRS. All rights reserved.
 *
 */

#include <iostream>
#include <cmath>
#include "Game.h"
#include "PlayState.h"
#include "MenuState.h"
#include "InputManager.h"

PlayState PlayState::m_PlayState;

using namespace std;

void PlayState::init()
{
    player.loadXML("data/img/hunter.xml");
    player.setPosition(50,100);
    player.loadAnimation("data/img/hunteranim.xml");
    player.setAnimRate(15);

    bullet.load("data/img/Char27.png");
    bullet.setXspeed(100);
    bullet.setMirror(true);
    bullet.setPosition(100, 100);

    bullets.clear();

    map = new tmx::MapLoader("data/maps");
    map->Load("dungeon-tilesets2.tmx");

    dirx = 0; // direção do sprite: para a direita (1), esquerda (-1)
    diry = 0;

    im = cgf::InputManager::instance();

    im->addKeyInput("left", sf::Keyboard::Left);
    im->addKeyInput("right", sf::Keyboard::Right);
    im->addKeyInput("up", sf::Keyboard::Up);
    im->addKeyInput("down", sf::Keyboard::Down);
    im->addKeyInput("quit", sf::Keyboard::Escape);
    im->addKeyInput("zoomin", sf::Keyboard::Z);
    im->addKeyInput("zoomout", sf::Keyboard::X);
    im->addMouseInput("rightclick", sf::Mouse::Right);

    if (!font.loadFromFile("data/fonts/arial.ttf"))
    {
        cout << "Cannot load arial.ttf font!" << endl;
        exit(1);
    }

    // select the font
    text.setFont(font);
    text.setString(L"Teste de texto gráfico");
    text.setCharacterSize(24); // in pixels, not points!
    text.setColor(sf::Color::Red);
    text.setStyle(sf::Text::Bold | sf::Text::Underlined);

    ammo = 10;

	cout << "PlayState Init Successful" << endl;
}

void PlayState::cleanup()
{
	cout << "PlayState Clean Successful" << endl;
	delete map;
}

void PlayState::pause()
{
	cout << "PlayState Paused" << endl;
}

void PlayState::resume()
{
	cout << "PlayState Resumed" << endl;
}

void PlayState::handleEvents(cgf::Game* game)
{
    sf::Event event;
    sf::View view = screen->getView();
    bool performShoot = false;

    while (screen->pollEvent(event))
    {
        if(event.type == sf::Event::Closed)
            game->quit();
        if(event.type == sf::Event::KeyPressed)
            if(event.key.code == sf::Keyboard::S)
                game->toggleStats();
            else if (event.key.code == sf::Keyboard::Space)
                // Keep track if we want to shoot
                performShoot = true;
    }

    dirx = diry = 0;

    if(im->testEvent("left")) {
        if(player.getXspeed() >= 0) {
            player.setAnimation("walk-left");
            player.play();
        }
        dirx = -1;
    }
    else
    if(im->testEvent("right")) {
        if(player.getXspeed() <= 0) {
            player.setAnimation("walk-right");
            player.play();
        }
        dirx = 1;
    }

    if(im->testEvent("up")) {
        if(player.getYspeed() >= 0) {
            player.setAnimation("walk-up");
            player.play();
        }
        diry = -1;
    }

    if(im->testEvent("down")) {
        if(player.getYspeed() <= 0) {
            player.setAnimation("walk-down");
            player.play();
        }
        diry = 1;
    }

    if(!dirx && !diry) // parado?
    {
        player.setCurrentFrame(0);
        player.pause();
    }

    if(im->testEvent("quit") || im->testEvent("rightclick"))
        game->quit();

    if(im->testEvent("zoomin"))
    {
        view.zoom(1.01);
        screen->setView(view);
    }
    else if(im->testEvent("zoomout"))
    {
        view.zoom(0.99);
        screen->setView(view);
    }

    player.setXspeed(dirx*100);
    player.setYspeed(diry*100);

    if (performShoot)
        shoot(game);
}

void PlayState::shoot(cgf::Game* game)
{
    if (ammo == 0) {
        cout << "Out of ammo" << endl;
    } else {
        ammo--;
        cgf::Sprite newBullet;
        newBullet.load("data/img/Char27.png");
        newBullet.setMirror(true);
        newBullet.setPosition(100, 100+ammo*10);
        newBullet.setXspeed(100);
        bullets.push_back(newBullet);
        cout << "SHOOT!" << endl;
    }
}

void PlayState::update(cgf::Game* game)
{
    screen = game->getScreen();
    checkCollision(2, game, &player);
    centerMapOnPlayer();
    if (checkCollision(2, game, &bullet)) {
        bullet.setXspeed(bullet.getXspeed() * -1);
        bullet.setMirror(!bullet.getMirror());
    } else if (bullet.circleCollision(player)) {
        game->changeState(MenuState::instance());
    }

    for(std::vector<int>::size_type i = 0; i != bullets.size(); i++) {
        bullets[i].update(game->getUpdateInterval(), true);
        screen->draw(bullets[i]);
    }
}

bool PlayState::checkCollision(u_int8_t layer, cgf::Game* game, cgf::Sprite* obj)
{
    int i, x1, x2, y1, y2;
    bool bump = false;

    // Get the limits of the map
    sf::Vector2u mapsize = map->GetMapSize();
    // Get the width and height of a single tile
    sf::Vector2u tilesize = map->GetMapTileSize();

    mapsize.x /= tilesize.x;
    mapsize.y /= tilesize.y;
    mapsize.x--;
    mapsize.y--;

    // Get the height and width of the object (in this case, 100% of a tile)
    sf::Vector2u objsize = obj->getSize();
    objsize.x *= obj->getScale().x;
    objsize.y *= obj->getScale().y;

    float px = obj->getPosition().x;
    float py = obj->getPosition().y;

    double deltaTime = game->getUpdateInterval();

    sf::Vector2f offset(obj->getXspeed()/1000 * deltaTime, obj->getYspeed()/1000 * deltaTime);

    float vx = offset.x;
    float vy = offset.y;

    // Test the horizontal movement first
    i = objsize.y > tilesize.y ? tilesize.y : objsize.y;

    for (;;)
    {
        x1 = (px + vx) / tilesize.x;
        x2 = (px + vx + objsize.x - 1) / tilesize.x;

        y1 = (py) / tilesize.y;
        y2 = (py + i - 1) / tilesize.y;

        if (x1 >= 0 && x2 < mapsize.x && y1 >= 0 && y2 < mapsize.y)
        {
            if (vx > 0)
            {
                // Trying to move right

                int upRight   = getCellFromMap(layer, x2*tilesize.x, y1*tilesize.y);
                int downRight = getCellFromMap(layer, x2*tilesize.x, y2*tilesize.y);
                if (upRight || downRight)
                {
                    // Place the player as close to the solid tile as possible
                    px = x2 * tilesize.x;
                    px -= objsize.x;// + 1;
                    vx = 0;
                    bump = true;
                }
            }

            else if (vx < 0)
            {
                // Trying to move left

                int upLeft   = getCellFromMap(layer, x1*tilesize.x, y1*tilesize.y);
                int downLeft = getCellFromMap(layer, x1*tilesize.x, y2*tilesize.y);
                if (upLeft || downLeft)
                {
                    // Place the player as close to the solid tile as possible
                    px = (x1+1) * tilesize.x;
                    vx = 0;
                    bump = true;
                }
            }
        }

        if (i == objsize.y) // Checked player height with all tiles ?
        {
            break;
        }

        i += tilesize.y; // done, check next tile upwards

        if (i > objsize.y)
        {
            i = objsize.y;
        }
    }

    // Now test the vertical movement

    i = objsize.x > tilesize.x ? tilesize.x : objsize.x;

    for (;;)
    {
        x1 = (px / tilesize.x);
        x2 = ((px + i-1) / tilesize.x);

        y1 = ((py + vy) / tilesize.y);
        y2 = ((py + vy + objsize.y-1) / tilesize.y);

        if (x1 >= 0 && x2 < mapsize.x && y1 >= 0 && y2 < mapsize.y)
        {
            if (vy > 0)
            {
                // Trying to move down
                int downLeft  = getCellFromMap(layer, x1*tilesize.x, y2*tilesize.y);
                int downRight = getCellFromMap(layer, x2*tilesize.x, y2*tilesize.y);
                if (downLeft || downRight)
                {
                    // Place the player as close to the solid tile as possible
                    py = y2 * tilesize.y;
                    py -= objsize.y;
                    vy = 0;
                    bump = true;
                }
            }

            else if (vy < 0)
            {
                // Trying to move up

                int upLeft  = getCellFromMap(layer, x1*tilesize.x, y1*tilesize.y);
                int upRight = getCellFromMap(layer, x2*tilesize.x, y1*tilesize.y);
                if (upLeft || upRight)
                {
                    // Place the player as close to the solid tile as possible
                    py = (y1 + 1) * tilesize.y;
                    vy = 0;
                    bump = true;
                }
            }
        }

        if (i == objsize.x)
        {
            break;
        }

        i += tilesize.x; // done, check next tile to the right

        if (i > objsize.x)
        {
            i = objsize.x;
        }
    }

    // Now apply the movement and animation

    obj->setPosition(px+vx,py+vy);
    px = obj->getPosition().x;
    py = obj->getPosition().y;

    obj->update(deltaTime, false); // only update animation

    // Check collision with edges of map
    if (px < 0)
        obj->setPosition(px,py);
    else if (px + objsize.x >= mapsize.x * tilesize.x)
        obj->setPosition(mapsize.x*tilesize.x - objsize.x - 1,py);

    if(py < 0)
        obj->setPosition(px,0);
    else if(py + objsize.y >= mapsize.y * tilesize.y)
        obj->setPosition(px, mapsize.y*tilesize.y - objsize.y - 1);

    return bump;
}

sf::Uint16 PlayState::getCellFromMap(uint8_t layernum, float x, float y)
{
    auto layers = map->GetLayers();
    tmx::MapLayer& layer = layers[layernum];
    sf::Vector2u mapsize = map->GetMapSize();
    sf::Vector2u tilesize = map->GetMapTileSize();
    mapsize.x /= tilesize.x;
    mapsize.y /= tilesize.y;
    int col = floor(x / tilesize.x);
    int row = floor(y / tilesize.y);
    return layer.tiles[row*mapsize.x + col].gid;
}

void PlayState::centerMapOnPlayer()
{
    sf::View view = screen->getView();
    sf::Vector2u mapsize = map->GetMapSize();
    sf::Vector2f viewsize = view.getSize();
    viewsize.x /= 2;
    viewsize.y /= 2;
    sf::Vector2f pos = player.getPosition();

    float panX = viewsize.x; // minimum pan
    if(pos.x >= viewsize.x)
        panX = pos.x;

    if(panX >= mapsize.x - viewsize.x)
        panX = mapsize.x - viewsize.x;

    float panY = viewsize.y; // minimum pan
    if(pos.y >= viewsize.y)
        panY = pos.y;

    if(panY >= mapsize.y - viewsize.y)
        panY = mapsize.y - viewsize.y;

    view.setCenter(sf::Vector2f(panX,panY));
    screen->setView(view);
}

void PlayState::draw(cgf::Game* game)
{
    //sf::View view = screen->getView();

    screen->clear(sf::Color(0,0,0));

    map->Draw(*screen, 0);
    screen->draw(player);
    screen->draw(bullet);

    for(std::vector<int>::size_type i = 0; i != bullets.size(); i++) {
        screen->draw(bullets[i]);
    }
    map->Draw(*screen, 1);

    screen->draw(text);
}
<|endoftext|>


<commit_before>/* main-test.cc                         KPilot
**
** Copyright (C) 2001 by Dan Pilone
** Copyright (C) 2001,2002,2003,2004 by Adriaan de Groot
**
** This is the main program for kpilotTest, which shows a SyncLog and
** exercises the KPilotDeviceLink class. It's intended to test if the
** Palm hardware and the KPilot software are functioning correctly to
** some extent.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org.
*/
static const char *test_id =
	"$Id$";

#include "options.h"

#include <stdlib.h>
#include <time.h>
#include <iostream>

#include <qpushbutton.h>
#include <qhbox.h>
#include <qtimer.h>

#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kservice.h>
#include <kservicetype.h>
#include <kuserprofile.h>

#include <pi-version.h>

#include "logWidget.h"
#include "kpilotConfig.h"
#include "syncStack.h"
#include "hotSync.h"
#include "interactiveSync.h"

static KCmdLineOptions kpilotoptions[] = {
	{"p",0,0},
	{"port <device>",
		I18N_NOOP("Path to Pilot device node"),
		"/dev/pilot"},
	{"l",0,0},
	{"list", I18N_NOOP("List DBs (default)"), 0},
	{"b",0,0},
	{"backup", I18N_NOOP("Backup instead of list DBs"), 0},
	{"r",0,0},
	{"restore", I18N_NOOP("Restore Pilot from backup"), 0},
	{"L",0,0},
	{ "conduit-list", I18N_NOOP("List available conduits"), 0},
	{"E",0,0},
	{ "conduit-exec <filename>",
		I18N_NOOP("Run conduit from desktop file <filename>"),
		0 },
	{ "T",0,0},
	{ "notest",
		I18N_NOOP("*Really* run the conduit, not in test mode."),
		0 } ,
	{ "F",0,0},
	{ "test-local",
		I18N_NOOP("Run the conduit in file-test mode."),
		0 } ,
	{ "HHtoPC",
		I18N_NOOP("Copy Pilot to Desktop."),
		0 } ,
	{ "PCtoHH",
		I18N_NOOP("Copy Desktop to Pilot."),
		0 } ,
#ifdef DEBUG
	{"debug <level>", I18N_NOOP("Set debugging level"), "0"},
#endif
	KCmdLineLastOption
};

static LogWidget *logWidget = 0L;
static QPushButton *resetButton = 0L;

void createLogWidget()
{
	LogWidget *w = new LogWidget(0L);

	w->resize(300, 300);
	w->show();
	w->setShowTime(true);
	kapp->setMainWidget(w);
	logWidget = w;

	resetButton = new QPushButton(i18n("Reset"),w->buttonBox());
}

static KPilotDeviceLink *deviceLink = 0L;

void createLink()
{
	FUNCTIONSETUP;

	deviceLink = new KPilotDeviceLink(0, "deviceLink");

	QObject::connect(deviceLink, SIGNAL(logError(const QString &)),
		logWidget, SLOT(addError(const QString &)));
	QObject::connect(deviceLink, SIGNAL(logMessage(const QString &)),
		logWidget, SLOT(addMessage(const QString &)));
	QObject::connect(deviceLink,SIGNAL(logProgress(const QString &,int)),
		logWidget, SLOT(addProgress(const QString &,int)));

}

static ActionQueue *syncStack = 0L;

void connectStack()
{
	FUNCTIONSETUP;

	QObject::connect(syncStack, SIGNAL(logError(const QString &)),
		logWidget, SLOT(addError(const QString &)));
	QObject::connect(syncStack, SIGNAL(logMessage(const QString &)),
		logWidget, SLOT(addMessage(const QString &)));
	QObject::connect(syncStack,SIGNAL(logProgress(const QString &,int)),
		logWidget, SLOT(addProgress(const QString &,int)));

	QObject::connect(deviceLink, SIGNAL(deviceReady(KPilotDeviceLink*)), syncStack, SLOT(execConduit()));

	QObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),
		logWidget, SLOT(syncDone()));
	QObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),
		deviceLink, SLOT(close()));

	QObject::connect(resetButton,SIGNAL(clicked()),deviceLink,SLOT(reset()));
}

void createConnection(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	QString devicePath = p->getOption("port");

	if (devicePath.isEmpty())
	{
		devicePath = "/dev/pilot";
	}

	deviceLink->reset(devicePath);
}

int syncTest(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	createLogWidget();
	createLink();

	syncStack = new ActionQueue(deviceLink);

	if (p->isSet("backup"))
	{
		syncStack->queueInit();
		syncStack->addAction(new BackupAction(deviceLink,true));
	}
	else if (p->isSet("restore"))
	{
		syncStack->queueInit(0);
		syncStack->addAction(new RestoreAction(deviceLink));
	}
	else
	{
		syncStack->queueInit();
		syncStack->addAction(new TestLink(deviceLink));
	}
	syncStack->queueCleanup();

	connectStack();
	createConnection(p);
	return kapp->exec();
}

int execConduit(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	// get --exec-conduit value
	QString s = p->getOption("conduit-exec");
	if (s.isEmpty()) return 1;
	QStringList l;
	l.append(s);

	createLogWidget();
	createLink();

	SyncAction::SyncMode syncMode = SyncAction::eHotSync;
	if (p->isSet("test")) syncMode = SyncAction::eTest;
	if (p->isSet("HHtoPC")) syncMode = SyncAction::eCopyHHToPC;
	if (p->isSet("PCtoHH")) syncMode = SyncAction::eCopyPCToHH;

	syncStack = new ActionQueue(deviceLink);
	syncStack->queueInit();
	syncStack->queueConduits(l,syncMode,false);
	syncStack->queueCleanup();

	connectStack();
	createConnection(p);

	return kapp->exec();
}

int testConduit(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	// get --exec-conduit value
	QString s = p->getOption("conduit-exec");
	if (s.isEmpty()) return 1;

	createLogWidget();
	createLink();

	syncStack = new ActionQueue(deviceLink);
	syncStack->queueConduits(QStringList(s),SyncAction::eTest,true);

	connectStack();

	QTimer::singleShot(10,syncStack,SLOT(execConduit()));

	return kapp->exec();
}

int listConduits(KCmdLineArgs *)
{
	FUNCTIONSETUP;

	KServiceTypeProfile::OfferList offers =
		KServiceTypeProfile::offers(CSL1("KPilotConduit"));

	// Now actually fill the two list boxes, just make
	// sure that nothing gets listed in both.
	//
	//
	QValueListIterator < KServiceOffer > availList(offers.begin());
	while (availList != offers.end())
	{
		KSharedPtr < KService > o = (*availList).service();

		std::cout << o->desktopEntryName().latin1() << std::endl;
		std::cout << "\t" << o->name().latin1()  << std::endl;
		if (!o->library().isEmpty())
		{
			std::cout << "\tIn "
				<< o->library().latin1()
				<< std::endl;
		}

		++availList;
	}

	return 0;
}

int main(int argc, char **argv)
{
	FUNCTIONSETUP;
	KAboutData about("kpilotTest",
		I18N_NOOP("KPilotTest"),
		KPILOT_VERSION,
		"KPilot Tester",
		KAboutData::License_GPL, "(C) 2001-2004, Adriaan de Groot");
	about.addAuthor("Adriaan de Groot",
		I18N_NOOP("KPilot Maintainer"),
		"groot@kde.org", "http://www.cs.kun.nl/~adridg/kpilot/");

	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions(kpilotoptions, "kpilottest");
	KApplication::addCmdLineOptions();

	KCmdLineArgs *p = KCmdLineArgs::parsedArgs();

	KApplication a;
#ifdef DEBUG
	KPilotConfig::getDebugLevel(p);
#endif

	if (p->isSet("backup") || p->isSet("restore") || p->isSet("list"))
	{
		return syncTest(p);
	}

	if (p->isSet("conduit-list"))
	{
		return listConduits(p);
	}

	if (p->isSet("conduit-exec"))
	{
		if (p->isSet("test-local"))
		{
			return testConduit(p);
		}
		else
		{
			return execConduit(p);
		}
	}

	// The default is supposed to be "list"
	return syncTest(p);
	/* NOTREACHED */
	(void) test_id;
}

<commit_msg>Add a timout-testing scenario.<commit_after>/* main-test.cc                         KPilot
**
** Copyright (C) 2001 by Dan Pilone
** Copyright (C) 2001,2002,2003,2004 by Adriaan de Groot
**
** This is the main program for kpilotTest, which shows a SyncLog and
** exercises the KPilotDeviceLink class. It's intended to test if the
** Palm hardware and the KPilot software are functioning correctly to
** some extent.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org.
*/
static const char *test_id =
	"$Id$";

#include "options.h"

#include <stdlib.h>
#include <time.h>
#include <iostream>

#include <qpushbutton.h>
#include <qhbox.h>
#include <qtimer.h>

#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kservice.h>
#include <kservicetype.h>
#include <kuserprofile.h>

#include <pi-version.h>

#include "logWidget.h"
#include "kpilotConfig.h"
#include "syncStack.h"
#include "hotSync.h"
#include "interactiveSync.h"

static KCmdLineOptions kpilotoptions[] = {
	{"p",0,0},
	{"port <device>",
		I18N_NOOP("Path to Pilot device node"),
		"/dev/pilot"},
	{"l",0,0},
	{"list", I18N_NOOP("List DBs (default)"), 0},
	{"b",0,0},
	{"backup", I18N_NOOP("Backup instead of list DBs"), 0},
	{"r",0,0},
	{"restore", I18N_NOOP("Restore Pilot from backup"), 0},
	{"L",0,0},
	{ "conduit-list", I18N_NOOP("List available conduits"), 0},
	{"E",0,0},
	{ "conduit-exec <filename>",
		I18N_NOOP("Run conduit from desktop file <filename>"),
		0 },
	{ "T",0,0},
	{ "notest",
		I18N_NOOP("*Really* run the conduit, not in test mode."),
		0 } ,
	{ "F",0,0},
	{ "test-local",
		I18N_NOOP("Run the conduit in file-test mode."),
		0 } ,
	{ "HHtoPC",
		I18N_NOOP("Copy Pilot to Desktop."),
		0 } ,
	{ "PCtoHH",
		I18N_NOOP("Copy Desktop to Pilot."),
		0 } ,
	{ "bug-timeout",
		I18N_NOOP("Run conduit specially designed to timeout."),
		0 } ,
#ifdef DEBUG
	{"debug <level>", I18N_NOOP("Set debugging level"), "0"},
#endif
	KCmdLineLastOption
};

static LogWidget *logWidget = 0L;
static QPushButton *resetButton = 0L;

/**
*** Conduits - sync actions - for testing specific scenarios.
**/

class TimeoutAction : public SyncAction
{
public:
	TimeoutAction(KPilotDeviceLink *p) ;
protected:
	virtual bool exec();
} ;

TimeoutAction::TimeoutAction(KPilotDeviceLink *p) :
	SyncAction(p)
{
	FUNCTIONSETUP;
}

bool TimeoutAction::exec()
{
	FUNCTIONSETUP;

	for (int i = 0; i<3; i++)
	{
		logMessage( CSL1("Hup two %1").arg(i) );
		fHandle->tickle();
		qApp->processEvents();
		sleep(1);
	}

	logMessage( CSL1("Now sleeping 65") );
	qApp->processEvents();
	sleep(65);
	return delayDone();
}

void createLogWidget()
{
	LogWidget *w = new LogWidget(0L);

	w->resize(300, 300);
	w->show();
	w->setShowTime(true);
	kapp->setMainWidget(w);
	logWidget = w;

	resetButton = new QPushButton(i18n("Reset"),w->buttonBox());
}

static KPilotDeviceLink *deviceLink = 0L;

void createLink()
{
	FUNCTIONSETUP;

	deviceLink = new KPilotDeviceLink(0, "deviceLink");

	QObject::connect(deviceLink, SIGNAL(logError(const QString &)),
		logWidget, SLOT(addError(const QString &)));
	QObject::connect(deviceLink, SIGNAL(logMessage(const QString &)),
		logWidget, SLOT(addMessage(const QString &)));
	QObject::connect(deviceLink,SIGNAL(logProgress(const QString &,int)),
		logWidget, SLOT(addProgress(const QString &,int)));

}

static ActionQueue *syncStack = 0L;

void connectStack()
{
	FUNCTIONSETUP;

	QObject::connect(syncStack, SIGNAL(logError(const QString &)),
		logWidget, SLOT(addError(const QString &)));
	QObject::connect(syncStack, SIGNAL(logMessage(const QString &)),
		logWidget, SLOT(addMessage(const QString &)));
	QObject::connect(syncStack,SIGNAL(logProgress(const QString &,int)),
		logWidget, SLOT(addProgress(const QString &,int)));

	QObject::connect(deviceLink, SIGNAL(deviceReady(KPilotDeviceLink*)), syncStack, SLOT(execConduit()));

	QObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),
		logWidget, SLOT(syncDone()));
	QObject::connect(syncStack, SIGNAL(syncDone(SyncAction *)),
		deviceLink, SLOT(close()));

	QObject::connect(resetButton,SIGNAL(clicked()),deviceLink,SLOT(reset()));
}

void createConnection(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	QString devicePath = p->getOption("port");

	if (devicePath.isEmpty())
	{
		devicePath = "/dev/pilot";
	}

	deviceLink->reset(devicePath);
}

int syncTest(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	createLogWidget();
	createLink();

	syncStack = new ActionQueue(deviceLink);

	if (p->isSet("backup"))
	{
		syncStack->queueInit();
		syncStack->addAction(new BackupAction(deviceLink,true));
	}
	else if (p->isSet("restore"))
	{
		syncStack->queueInit(0);
		syncStack->addAction(new RestoreAction(deviceLink));
	}
	else if (p->isSet("bug-timeout"))
	{
		syncStack->queueInit();
		syncStack->addAction( new TimeoutAction(deviceLink) );
		syncStack->addAction( new TimeoutAction(deviceLink) );
	}
	else
	{
		syncStack->queueInit();
		syncStack->addAction(new TestLink(deviceLink));
	}
	syncStack->queueCleanup();

	connectStack();
	createConnection(p);
	return kapp->exec();
}

int execConduit(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	// get --exec-conduit value
	QString s = p->getOption("conduit-exec");
	if (s.isEmpty()) return 1;
	QStringList l;
	l.append(s);

	createLogWidget();
	createLink();

	SyncAction::SyncMode syncMode = SyncAction::eHotSync;
	if (p->isSet("test")) syncMode = SyncAction::eTest;
	if (p->isSet("HHtoPC")) syncMode = SyncAction::eCopyHHToPC;
	if (p->isSet("PCtoHH")) syncMode = SyncAction::eCopyPCToHH;

	syncStack = new ActionQueue(deviceLink);
	syncStack->queueInit();
	syncStack->queueConduits(l,syncMode,false);
	syncStack->queueCleanup();

	connectStack();
	createConnection(p);

	return kapp->exec();
}

int testConduit(KCmdLineArgs *p)
{
	FUNCTIONSETUP;

	// get --exec-conduit value
	QString s = p->getOption("conduit-exec");
	if (s.isEmpty()) return 1;

	createLogWidget();
	createLink();

	syncStack = new ActionQueue(deviceLink);
	syncStack->queueConduits(QStringList(s),SyncAction::eTest,true);

	connectStack();

	QTimer::singleShot(10,syncStack,SLOT(execConduit()));

	return kapp->exec();
}

int listConduits(KCmdLineArgs *)
{
	FUNCTIONSETUP;

	KServiceTypeProfile::OfferList offers =
		KServiceTypeProfile::offers(CSL1("KPilotConduit"));

	// Now actually fill the two list boxes, just make
	// sure that nothing gets listed in both.
	//
	//
	QValueListIterator < KServiceOffer > availList(offers.begin());
	while (availList != offers.end())
	{
		KSharedPtr < KService > o = (*availList).service();

		std::cout << o->desktopEntryName().latin1() << std::endl;
		std::cout << "\t" << o->name().latin1()  << std::endl;
		if (!o->library().isEmpty())
		{
			std::cout << "\tIn "
				<< o->library().latin1()
				<< std::endl;
		}

		++availList;
	}

	return 0;
}

int main(int argc, char **argv)
{
	FUNCTIONSETUP;
	KAboutData about("kpilotTest",
		I18N_NOOP("KPilotTest"),
		KPILOT_VERSION,
		"KPilot Tester",
		KAboutData::License_GPL, "(C) 2001-2004, Adriaan de Groot");
	about.addAuthor("Adriaan de Groot",
		I18N_NOOP("KPilot Maintainer"),
		"groot@kde.org", "http://www.cs.kun.nl/~adridg/kpilot/");

	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions(kpilotoptions, "kpilottest");
	KApplication::addCmdLineOptions();

	KCmdLineArgs *p = KCmdLineArgs::parsedArgs();

	KApplication a;
#ifdef DEBUG
	KPilotConfig::getDebugLevel(p);
#endif

	if ( p->isSet("backup") ||
		p->isSet("restore") ||
		p->isSet("list") ||
		p->isSet("bug-timeout") )
	{
		return syncTest(p);
	}

	if (p->isSet("conduit-list"))
	{
		return listConduits(p);
	}

	if (p->isSet("conduit-exec"))
	{
		if (p->isSet("test-local"))
		{
			return testConduit(p);
		}
		else
		{
			return execConduit(p);
		}
	}

	// The default is supposed to be "list"
	return syncTest(p);
	/* NOTREACHED */
	(void) test_id;
}

<|endoftext|>


<commit_before>#ifndef MIMOSA_REF_COUNTABLE_HH
# define MIMOSA_REF_COUNTABLE_HH

# include "ref-counted-ptr.hh"

namespace mimosa
{
  class RefCountableBase
  {
  public:
    inline RefCountableBase()
      : ref_count_(0)
    {
    }

    inline RefCountableBase(const RefCountableBase & /*other*/)
      : ref_count_(0)
    {
    }

    virtual ~RefCountableBase() {}

    inline RefCountableBase & operator=(const RefCountableBase & /*other*/)
    {
      return *this;
    }

    inline int addRef() const
    {
      return __sync_add_and_fetch(&ref_count_, 1);
    }

    inline int releaseRef() const
    {
      return __sync_add_and_fetch(&ref_count_, -1);
    }

    mutable int ref_count_;
  };

  inline void addRef(const RefCountableBase * obj)
  {
    obj->addRef();
  }

  inline void releaseRef(const RefCountableBase * obj)
  {
    if (obj->releaseRef() == 0)
      delete obj;
  }

  template <typename T>
  class RefCountable : public RefCountableBase
  {
  public:
    typedef RefCountedPtr<T> Ptr;
    typedef RefCountedPtr<const T> ConstPtr;
  };
}

#endif /* !MIMOSA_REF_COUNTABLE_HH */
<commit_msg>Factorized the Ptr and ConstPtr declaration<commit_after>#ifndef MIMOSA_REF_COUNTABLE_HH
# define MIMOSA_REF_COUNTABLE_HH

# include "ref-counted-ptr.hh"

namespace mimosa
{
  class RefCountableBase
  {
  public:
    inline RefCountableBase()
      : ref_count_(0)
    {
    }

    inline RefCountableBase(const RefCountableBase & /*other*/)
      : ref_count_(0)
    {
    }

    virtual ~RefCountableBase() {}

    inline RefCountableBase & operator=(const RefCountableBase & /*other*/)
    {
      return *this;
    }

    inline int addRef() const
    {
      return __sync_add_and_fetch(&ref_count_, 1);
    }

    inline int releaseRef() const
    {
      return __sync_add_and_fetch(&ref_count_, -1);
    }

    mutable int ref_count_;
  };

  inline void addRef(const RefCountableBase * obj)
  {
    obj->addRef();
  }

  inline void releaseRef(const RefCountableBase * obj)
  {
    if (obj->releaseRef() == 0)
      delete obj;
  }

  template <typename T>
  class Ptr
  {
  public:
    typedef RefCountedPtr<T> Ptr;
    typedef RefCountedPtr<const T> ConstPtr;
  };

  template <typename T>
  class RefCountable : public RefCountableBase,
                       public Ptr<T>
  {
  };
}

#endif /* !MIMOSA_REF_COUNTABLE_HH */
<|endoftext|>


<commit_before>#include "data.h"

#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include "third_party/eos_portable_archive/portable_iarchive.hpp"
#include "third_party/eos_portable_archive/portable_oarchive.hpp"
#include "lz4_filter/filter.h"
#include "utils/functions.h"
#include "utils/exception.h"

namespace pt = boost::posix_time;

namespace navitia { namespace type {

Data& Data::operator=(Data&& other){
    version = other.version;
    loaded.store(other.loaded.load());
    meta = other.meta;
    pt_data = std::move(other.pt_data);
    geo_ref = other.geo_ref;
    dataRaptor = other.dataRaptor;
    last_load = other.last_load;
    last_load_at = other.last_load_at;

    return *this;
}

bool Data::load(const std::string & filename) {
    log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
    try {
        this->load_lz4(filename);
        this->build_raptor();
        last_load_at = pt::microsec_clock::local_time();
        last_load = true;
        loaded = true;
    } catch(const std::exception& ex) {
        LOG4CPLUS_ERROR(logger, boost::format("le chargement des données à échoué: %s") % ex.what());
        last_load = false;
    } catch(...) {
        LOG4CPLUS_ERROR(logger, "le chargement des données à échoué");
        last_load = false;
    }
    return this->last_load;
}

void Data::load_lz4(const std::string & filename) {
    std::ifstream ifs(filename.c_str(),  std::ios::in | std::ios::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(LZ4Decompressor(2048*500),8192*500, 8192*500);
    in.push(ifs);
    eos::portable_iarchive ia(in);
    ia >> *this;
}

void Data::save(const std::string & filename){
    log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
    this->save_lz4(filename);
}

void Data::save_lz4(const std::string & filename) {
    auto logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
    boost::filesystem::path p(filename);
    boost::filesystem::path dir = p.parent_path();
    try {
       boost::filesystem::is_directory(p);
    } catch(const boost::filesystem::filesystem_error& e)
    {
       if(e.code() == boost::system::errc::permission_denied)
           LOG4CPLUS_ERROR(logger, "Search permission is denied for " << p);
       else
           LOG4CPLUS_ERROR(logger, "is_directory(" << p << ") failed with "
                     << e.code().message());
       throw navitia::exception("Unable to write file");
    }
    try {
        std::ofstream ofs(filename.c_str(),std::ios::out|std::ios::binary|std::ios::trunc);
        boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
        out.push(LZ4Compressor(2048*500), 1024*500, 1024*500);
        out.push(ofs);
        eos::portable_oarchive oa(out);
        oa << *this;
    } catch(const boost::filesystem::filesystem_error &e) {
        if(e.code() == boost::system::errc::permission_denied)
            LOG4CPLUS_ERROR(logger, "Writing permission is denied for " << p);
        else if(e.code() == boost::system::errc::file_too_large)
            LOG4CPLUS_ERROR(logger, "The file " << filename << " is too large");
        else if(e.code() == boost::system::errc::interrupted)
            LOG4CPLUS_ERROR(logger, "Writing was interrupted for " << p);
        else if(e.code() == boost::system::errc::no_buffer_space)
            LOG4CPLUS_ERROR(logger, "No buffer space while writing " << p);
        else if(e.code() == boost::system::errc::not_enough_memory)
            LOG4CPLUS_ERROR(logger, "Not enough memory while writing " << p);
        else if(e.code() == boost::system::errc::no_space_on_device)
            LOG4CPLUS_ERROR(logger, "No space on device while writing " << p);
        else if(e.code() == boost::system::errc::operation_not_permitted)
            LOG4CPLUS_ERROR(logger, "Operation not permitted while writing " << p);
        LOG4CPLUS_ERROR(logger, e.what());
       throw navitia::exception("Unable to write file");
    }
}

void Data::build_uri(){
#define CLEAR_EXT_CODE(type_name, collection_name) this->pt_data.collection_name##_map.clear();
ITERATE_NAVITIA_PT_TYPES(CLEAR_EXT_CODE)
    this->pt_data.build_uri();
    geo_ref.build_pois();
    geo_ref.build_poitypes();
    geo_ref.normalize_extcode_way();
    geo_ref.normalize_extcode_admin();
}

void Data::build_proximity_list(){
    this->pt_data.build_proximity_list();
    this->geo_ref.build_proximity_list();
    int nb_matched = this->geo_ref.project_stop_points(this->pt_data.stop_points);
    std::cout << "Nombre de stop_points accrochés au filaire de voirie : "
              << nb_matched << " sur "
              << this->pt_data.stop_points.size() << std::endl;
}

void Data::build_autocomplete(){
    pt_data.build_autocomplete(geo_ref);
    geo_ref.build_autocomplete_list();
    pt_data.compute_score_autocomplete(geo_ref);
}

void Data::build_raptor() {
    dataRaptor.load(this->pt_data);
}

ValidityPattern* Data::get_or_create_validity_pattern(ValidityPattern* ref_validity_pattern, const uint32_t time){

    if(time > 24*3600) {
        std::bitset<366> tmp_days = ref_validity_pattern->days;
        tmp_days <<= 1;
        auto find_vp_predicate = [&](ValidityPattern* vp1) { return ((tmp_days == vp1->days) && (ref_validity_pattern->beginning_date == vp1->beginning_date));};
        auto it = std::find_if(this->pt_data.validity_patterns.begin(),
                            this->pt_data.validity_patterns.end(), find_vp_predicate);
        if(it != this->pt_data.validity_patterns.end()) {
            return *(it);
        } else {
            ValidityPattern* tmp_vp = new ValidityPattern(ref_validity_pattern->beginning_date, tmp_days.to_string());
            tmp_vp->idx = this->pt_data.validity_patterns.size();
            this->pt_data.validity_patterns.push_back(tmp_vp);
            return tmp_vp;
        }
    }
    return ref_validity_pattern;
}

void Data::build_midnight_interchange(){
    for(VehicleJourney* vj : this->pt_data.vehicle_journeys){
        for(StopTime* stop : vj->stop_time_list){
            // Théorique
            stop->departure_validity_pattern = get_or_create_validity_pattern(vj->validity_pattern, stop->departure_time);
            stop->arrival_validity_pattern = get_or_create_validity_pattern(vj->validity_pattern, stop->arrival_time);
            // Adapté
            stop->departure_adapted_validity_pattern = get_or_create_validity_pattern(vj->adapted_validity_pattern, stop->departure_time);
            stop->arrival_adapted_validity_pattern = get_or_create_validity_pattern(vj->adapted_validity_pattern, stop->arrival_time);
        }
    }
}

#define GET_DATA(type_name, collection_name)\
template<> std::vector<type_name*> & \
Data::get_data<type_name>() {\
    return this->pt_data.collection_name;\
}\
template<> std::vector<type_name *> \
Data::get_data<type_name>() const {\
    return this->pt_data.collection_name;\
}
ITERATE_NAVITIA_PT_TYPES(GET_DATA)

template<> std::vector<georef::POI*> &
Data::get_data<georef::POI>() {
    return this->geo_ref.pois;
}
template<> std::vector<georef::POI*>
Data::get_data<georef::POI>() const {
    return this->geo_ref.pois;
}

template<> std::vector<georef::POIType*> &
Data::get_data<georef::POIType>() {
    return this->geo_ref.poitypes;
}
template<> std::vector<georef::POIType*>
Data::get_data<georef::POIType>() const {
    return this->geo_ref.poitypes;
}

template<> std::vector<StopPointConnection*> &
Data::get_data<StopPointConnection>() {
    return this->pt_data.stop_point_connections;
}
template<> std::vector<StopPointConnection*>
Data::get_data<StopPointConnection>() const {
    return this->pt_data.stop_point_connections;
}

std::vector<idx_t> Data::get_all_index(Type_e type) const {
    size_t num_elements = 0;
    switch(type){
    #define GET_NUM_ELEMENTS(type_name, collection_name)\
    case Type_e::type_name:\
        num_elements = this->pt_data.collection_name.size();break;
    ITERATE_NAVITIA_PT_TYPES(GET_NUM_ELEMENTS)
    case Type_e::POI: num_elements = this->geo_ref.pois.size(); break;
    case Type_e::POIType: num_elements = this->geo_ref.poitypes.size(); break;
    case Type_e::Connection:
        num_elements = this->pt_data.stop_point_connections.size(); break;
    default:  break;
    }
    std::vector<idx_t> indexes(num_elements);
    for(size_t i=0; i < num_elements; i++)
        indexes[i] = i;
    return indexes;
}

std::vector<idx_t>
Data::get_target_by_source(Type_e source, Type_e target,
                           std::vector<idx_t> source_idx) const {
    std::vector<idx_t> result;
    result.reserve(source_idx.size());
    for(idx_t idx : source_idx) {
        std::vector<idx_t> tmp;
        tmp = get_target_by_one_source(source, target, idx);
        result.insert(result.end(), tmp.begin(), tmp.end());
    }
    return result;
}

std::vector<idx_t>
Data::get_target_by_one_source(Type_e source, Type_e target,
                               idx_t source_idx) const {
    std::vector<idx_t> result;
    if(source_idx == invalid_idx)
        return result;
    if(source == target){
        result.push_back(source_idx);
        return result;
    }
    switch(source) {
    #define GET_INDEXES(type_name, collection_name)\
        case Type_e::type_name:\
            result = pt_data.collection_name[source_idx]->get(target, pt_data);\
            break;
    ITERATE_NAVITIA_PT_TYPES(GET_INDEXES)
        case Type_e::POI:
            result = geo_ref.pois[source_idx]->get(target, geo_ref);
        case Type_e::POIType:
            result = geo_ref.poitypes[source_idx]->get(target, geo_ref);
        default: break;
    }
    return result;
}

Type_e Data::get_type_of_id(const std::string & id) const {
    if(id.size()>6 && id.substr(0,6) == "coord:")
        return Type_e::Coord;
    if(id.size()>6 && id.substr(0,8) == "address:")
        return Type_e::Address;
    if(id.size()>6 && id.substr(0,6) == "admin:")
        return Type_e::Admin;
    #define GET_TYPE(type_name, collection_name) \
    auto collection_name##_map = pt_data.collection_name##_map;\
    if(collection_name##_map.find(id) != collection_name##_map.end())\
        return Type_e::type_name;
    ITERATE_NAVITIA_PT_TYPES(GET_TYPE)
    if(geo_ref.poitype_map.find(id) != geo_ref.poitype_map.end())
        return Type_e::POIType;
    if(geo_ref.poi_map.find(id) != geo_ref.poi_map.end())
        return Type_e::POI;
    if(geo_ref.way_map.find(id) != geo_ref.way_map.end())
        return Type_e::Address;
    if(geo_ref.admin_map.find(id) != geo_ref.admin_map.end())
        return Type_e::Admin;
    return Type_e::Unknown;
}

}} //namespace navitia::type
<commit_msg>ed : normalize uri in insert to databases<commit_after>#include "data.h"

#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include "third_party/eos_portable_archive/portable_iarchive.hpp"
#include "third_party/eos_portable_archive/portable_oarchive.hpp"
#include "lz4_filter/filter.h"
#include "utils/functions.h"
#include "utils/exception.h"

namespace pt = boost::posix_time;

namespace navitia { namespace type {

Data& Data::operator=(Data&& other){
    version = other.version;
    loaded.store(other.loaded.load());
    meta = other.meta;
    pt_data = std::move(other.pt_data);
    geo_ref = other.geo_ref;
    dataRaptor = other.dataRaptor;
    last_load = other.last_load;
    last_load_at = other.last_load_at;

    return *this;
}

bool Data::load(const std::string & filename) {
    log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
    try {
        this->load_lz4(filename);
        this->build_raptor();
        last_load_at = pt::microsec_clock::local_time();
        last_load = true;
        loaded = true;
    } catch(const std::exception& ex) {
        LOG4CPLUS_ERROR(logger, boost::format("le chargement des données à échoué: %s") % ex.what());
        last_load = false;
    } catch(...) {
        LOG4CPLUS_ERROR(logger, "le chargement des données à échoué");
        last_load = false;
    }
    return this->last_load;
}

void Data::load_lz4(const std::string & filename) {
    std::ifstream ifs(filename.c_str(),  std::ios::in | std::ios::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(LZ4Decompressor(2048*500),8192*500, 8192*500);
    in.push(ifs);
    eos::portable_iarchive ia(in);
    ia >> *this;
}

void Data::save(const std::string & filename){
    log4cplus::Logger logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
    this->save_lz4(filename);
}

void Data::save_lz4(const std::string & filename) {
    auto logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("logger"));
    boost::filesystem::path p(filename);
    boost::filesystem::path dir = p.parent_path();
    try {
       boost::filesystem::is_directory(p);
    } catch(const boost::filesystem::filesystem_error& e)
    {
       if(e.code() == boost::system::errc::permission_denied)
           LOG4CPLUS_ERROR(logger, "Search permission is denied for " << p);
       else
           LOG4CPLUS_ERROR(logger, "is_directory(" << p << ") failed with "
                     << e.code().message());
       throw navitia::exception("Unable to write file");
    }
    try {
        std::ofstream ofs(filename.c_str(),std::ios::out|std::ios::binary|std::ios::trunc);
        boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
        out.push(LZ4Compressor(2048*500), 1024*500, 1024*500);
        out.push(ofs);
        eos::portable_oarchive oa(out);
        oa << *this;
    } catch(const boost::filesystem::filesystem_error &e) {
        if(e.code() == boost::system::errc::permission_denied)
            LOG4CPLUS_ERROR(logger, "Writing permission is denied for " << p);
        else if(e.code() == boost::system::errc::file_too_large)
            LOG4CPLUS_ERROR(logger, "The file " << filename << " is too large");
        else if(e.code() == boost::system::errc::interrupted)
            LOG4CPLUS_ERROR(logger, "Writing was interrupted for " << p);
        else if(e.code() == boost::system::errc::no_buffer_space)
            LOG4CPLUS_ERROR(logger, "No buffer space while writing " << p);
        else if(e.code() == boost::system::errc::not_enough_memory)
            LOG4CPLUS_ERROR(logger, "Not enough memory while writing " << p);
        else if(e.code() == boost::system::errc::no_space_on_device)
            LOG4CPLUS_ERROR(logger, "No space on device while writing " << p);
        else if(e.code() == boost::system::errc::operation_not_permitted)
            LOG4CPLUS_ERROR(logger, "Operation not permitted while writing " << p);
        LOG4CPLUS_ERROR(logger, e.what());
       throw navitia::exception("Unable to write file");
    }
}

void Data::build_uri(){
#define CLEAR_EXT_CODE(type_name, collection_name) this->pt_data.collection_name##_map.clear();
ITERATE_NAVITIA_PT_TYPES(CLEAR_EXT_CODE)
    this->pt_data.build_uri();
    geo_ref.build_pois();
    geo_ref.build_poitypes();
}

void Data::build_proximity_list(){
    this->pt_data.build_proximity_list();
    this->geo_ref.build_proximity_list();
    int nb_matched = this->geo_ref.project_stop_points(this->pt_data.stop_points);
    std::cout << "Nombre de stop_points accrochés au filaire de voirie : "
              << nb_matched << " sur "
              << this->pt_data.stop_points.size() << std::endl;
}

void Data::build_autocomplete(){
    pt_data.build_autocomplete(geo_ref);
    geo_ref.build_autocomplete_list();
    pt_data.compute_score_autocomplete(geo_ref);
}

void Data::build_raptor() {
    dataRaptor.load(this->pt_data);
}

ValidityPattern* Data::get_or_create_validity_pattern(ValidityPattern* ref_validity_pattern, const uint32_t time){

    if(time > 24*3600) {
        std::bitset<366> tmp_days = ref_validity_pattern->days;
        tmp_days <<= 1;
        auto find_vp_predicate = [&](ValidityPattern* vp1) { return ((tmp_days == vp1->days) && (ref_validity_pattern->beginning_date == vp1->beginning_date));};
        auto it = std::find_if(this->pt_data.validity_patterns.begin(),
                            this->pt_data.validity_patterns.end(), find_vp_predicate);
        if(it != this->pt_data.validity_patterns.end()) {
            return *(it);
        } else {
            ValidityPattern* tmp_vp = new ValidityPattern(ref_validity_pattern->beginning_date, tmp_days.to_string());
            tmp_vp->idx = this->pt_data.validity_patterns.size();
            this->pt_data.validity_patterns.push_back(tmp_vp);
            return tmp_vp;
        }
    }
    return ref_validity_pattern;
}

void Data::build_midnight_interchange(){
    for(VehicleJourney* vj : this->pt_data.vehicle_journeys){
        for(StopTime* stop : vj->stop_time_list){
            // Théorique
            stop->departure_validity_pattern = get_or_create_validity_pattern(vj->validity_pattern, stop->departure_time);
            stop->arrival_validity_pattern = get_or_create_validity_pattern(vj->validity_pattern, stop->arrival_time);
            // Adapté
            stop->departure_adapted_validity_pattern = get_or_create_validity_pattern(vj->adapted_validity_pattern, stop->departure_time);
            stop->arrival_adapted_validity_pattern = get_or_create_validity_pattern(vj->adapted_validity_pattern, stop->arrival_time);
        }
    }
}

#define GET_DATA(type_name, collection_name)\
template<> std::vector<type_name*> & \
Data::get_data<type_name>() {\
    return this->pt_data.collection_name;\
}\
template<> std::vector<type_name *> \
Data::get_data<type_name>() const {\
    return this->pt_data.collection_name;\
}
ITERATE_NAVITIA_PT_TYPES(GET_DATA)

template<> std::vector<georef::POI*> &
Data::get_data<georef::POI>() {
    return this->geo_ref.pois;
}
template<> std::vector<georef::POI*>
Data::get_data<georef::POI>() const {
    return this->geo_ref.pois;
}

template<> std::vector<georef::POIType*> &
Data::get_data<georef::POIType>() {
    return this->geo_ref.poitypes;
}
template<> std::vector<georef::POIType*>
Data::get_data<georef::POIType>() const {
    return this->geo_ref.poitypes;
}

template<> std::vector<StopPointConnection*> &
Data::get_data<StopPointConnection>() {
    return this->pt_data.stop_point_connections;
}
template<> std::vector<StopPointConnection*>
Data::get_data<StopPointConnection>() const {
    return this->pt_data.stop_point_connections;
}

std::vector<idx_t> Data::get_all_index(Type_e type) const {
    size_t num_elements = 0;
    switch(type){
    #define GET_NUM_ELEMENTS(type_name, collection_name)\
    case Type_e::type_name:\
        num_elements = this->pt_data.collection_name.size();break;
    ITERATE_NAVITIA_PT_TYPES(GET_NUM_ELEMENTS)
    case Type_e::POI: num_elements = this->geo_ref.pois.size(); break;
    case Type_e::POIType: num_elements = this->geo_ref.poitypes.size(); break;
    case Type_e::Connection:
        num_elements = this->pt_data.stop_point_connections.size(); break;
    default:  break;
    }
    std::vector<idx_t> indexes(num_elements);
    for(size_t i=0; i < num_elements; i++)
        indexes[i] = i;
    return indexes;
}

std::vector<idx_t>
Data::get_target_by_source(Type_e source, Type_e target,
                           std::vector<idx_t> source_idx) const {
    std::vector<idx_t> result;
    result.reserve(source_idx.size());
    for(idx_t idx : source_idx) {
        std::vector<idx_t> tmp;
        tmp = get_target_by_one_source(source, target, idx);
        result.insert(result.end(), tmp.begin(), tmp.end());
    }
    return result;
}

std::vector<idx_t>
Data::get_target_by_one_source(Type_e source, Type_e target,
                               idx_t source_idx) const {
    std::vector<idx_t> result;
    if(source_idx == invalid_idx)
        return result;
    if(source == target){
        result.push_back(source_idx);
        return result;
    }
    switch(source) {
    #define GET_INDEXES(type_name, collection_name)\
        case Type_e::type_name:\
            result = pt_data.collection_name[source_idx]->get(target, pt_data);\
            break;
    ITERATE_NAVITIA_PT_TYPES(GET_INDEXES)
        case Type_e::POI:
            result = geo_ref.pois[source_idx]->get(target, geo_ref);
        case Type_e::POIType:
            result = geo_ref.poitypes[source_idx]->get(target, geo_ref);
        default: break;
    }
    return result;
}

Type_e Data::get_type_of_id(const std::string & id) const {
    if(id.size()>6 && id.substr(0,6) == "coord:")
        return Type_e::Coord;
    if(id.size()>6 && id.substr(0,8) == "address:")
        return Type_e::Address;
    if(id.size()>6 && id.substr(0,6) == "admin:")
        return Type_e::Admin;
    #define GET_TYPE(type_name, collection_name) \
    auto collection_name##_map = pt_data.collection_name##_map;\
    if(collection_name##_map.find(id) != collection_name##_map.end())\
        return Type_e::type_name;
    ITERATE_NAVITIA_PT_TYPES(GET_TYPE)
    if(geo_ref.poitype_map.find(id) != geo_ref.poitype_map.end())
        return Type_e::POIType;
    if(geo_ref.poi_map.find(id) != geo_ref.poi_map.end())
        return Type_e::POI;
    if(geo_ref.way_map.find(id) != geo_ref.way_map.end())
        return Type_e::Address;
    if(geo_ref.admin_map.find(id) != geo_ref.admin_map.end())
        return Type_e::Admin;
    return Type_e::Unknown;
}

}} //namespace navitia::type
<|endoftext|>


<commit_before>#include "ProgramOptions.ih"

ProgramOptions::ProgramOptions(int argc, char *argv[])
	: d_n(1), d_ngramExpansion(true), d_expansionFactorAlpha(0.0),
	d_frequency(2), d_smoothing(false), d_smoothingBeta(0.1),
	d_sortAlgorithm(SuffixArray<int>::SSORT), d_suspFrequency(0),
	d_suspThreshold(0.0), d_threshold(0.001), d_verbose(false),
	d_arguments(new vector<string>())
{
	d_programName = argv[0];

	// We will do our own error reporting.
	opterr = 0;

	int opt;
	while ((opt = getopt(argc, argv, "b:ce:f:n:o:s:t:u:v")) != -1)
	{
		switch (opt)
		{
		case 'b':
			d_smoothing = true;
			d_smoothingBeta = parseString<double>(optarg);
			break;
		case 'c':
			d_ngramExpansion = false;
			break;
		case 'e':
			d_expansionFactorAlpha = parseString<double>(optarg);
			break;
		case 'f':
			d_frequency = parseString<size_t>(optarg);
			break;
		case 'n':
			d_n = parseString<size_t>(optarg);
			break;
		case 'o':
			{
				string algo(optarg);
				if (algo == "stlsort")
					d_sortAlgorithm = SuffixArray<int>::STLSORT;
				else if (algo != "ssort")
					throw string("Unknown suffix sorting algorithm: " + algo);
			}
			break;
		case 's':
			d_suspThreshold = parseString<double>(optarg);
			break;
		case 't':
			d_threshold = parseString<double>(optarg);
			break;
		case 'u':
			d_suspFrequency = parseString<size_t>(optarg);
			break;
		case 'v':
			d_verbose = true;
			break;
		case ':':
			throw string("Missing option argument for: -") +
				static_cast<char>(optopt);
			break;
		default:
			throw string("Unknown option: -") + static_cast<char>(optopt);
		}
	}

	copy(argv + optind, argv + argc, back_inserter(*d_arguments));
}
<commit_msg>Change default options: expansionfactor and form removal.<commit_after>#include "ProgramOptions.ih"

ProgramOptions::ProgramOptions(int argc, char *argv[])
	: d_n(1), d_ngramExpansion(true), d_expansionFactorAlpha(1.0),
	d_frequency(2), d_smoothing(false), d_smoothingBeta(0.1),
	d_sortAlgorithm(SuffixArray<int>::SSORT), d_suspFrequency(0),
	d_suspThreshold(0.001), d_threshold(0.001), d_verbose(false),
	d_arguments(new vector<string>())
{
	d_programName = argv[0];

	// We will do our own error reporting.
	opterr = 0;

	int opt;
	while ((opt = getopt(argc, argv, "b:ce:f:n:o:s:t:u:v")) != -1)
	{
		switch (opt)
		{
		case 'b':
			d_smoothing = true;
			d_smoothingBeta = parseString<double>(optarg);
			break;
		case 'c':
			d_ngramExpansion = false;
			break;
		case 'e':
			d_expansionFactorAlpha = parseString<double>(optarg);
			break;
		case 'f':
			d_frequency = parseString<size_t>(optarg);
			break;
		case 'n':
			d_n = parseString<size_t>(optarg);
			break;
		case 'o':
			{
				string algo(optarg);
				if (algo == "stlsort")
					d_sortAlgorithm = SuffixArray<int>::STLSORT;
				else if (algo != "ssort")
					throw string("Unknown suffix sorting algorithm: " + algo);
			}
			break;
		case 's':
			d_suspThreshold = parseString<double>(optarg);
			break;
		case 't':
			d_threshold = parseString<double>(optarg);
			break;
		case 'u':
			d_suspFrequency = parseString<size_t>(optarg);
			break;
		case 'v':
			d_verbose = true;
			break;
		case ':':
			throw string("Missing option argument for: -") +
				static_cast<char>(optopt);
			break;
		default:
			throw string("Unknown option: -") + static_cast<char>(optopt);
		}
	}

	copy(argv + optind, argv + argc, back_inserter(*d_arguments));
}
<|endoftext|>