<commit_before>
#include "samson/common/MessagesOperations.h"

#include "samson/network/NetworkConnection.h"
#include "au/network/NetworkListener.h"
#include "au/network/SocketConnection.h"
#include "samson/network/NetworkConnection.h"

#include "CommonNetwork.h" // Own interface

namespace samson {

    void CommonNetwork::notify( engine::Notification* notification )
    {

        if (notification == NULL)
            LM_D(("notification == NULL"));

        // Check pennding packets to be removed after 1 minute disconnected
        // -------------------------------------------------------------------------------------
        NetworkManager::check();

        // Check disconnected elements to be removed ( if possible no threads or pending packets )
        // ----------------------------------------------------------------------------------------
        NetworkConnection * connection = NetworkManager::extractNextDisconnectedConnection();
        while (connection)
        {

            // Some notification about this disconnection
            NodeIdentifier node_identifier = connection->getNodeIdentifier();

            if( node_identifier.node_type == WorkerNode )
                report_worker_disconnected( node_identifier.id );

            if( node_identifier.node_type == DelilahNode )
                report_delilah_disconnected( node_identifier.id );

            // Remove connection
            delete connection;

            // Scan the next connection
            connection = NetworkManager::extractNextDisconnectedConnection();
        }

        // Check workers ( review connections , create new connections if possible , .... )
        // -------------------------------------------------------------------------------------

        if( cluster_information.getId() != 0 )
        {

            // Get a duplicate of current nodes involved in this cluster to connect to all of them
            au::vector<ClusterNode> nodes = cluster_information.getNodesToConnect( node_identifier );

            for ( size_t i = 0 ; i < nodes.size() ; i++ )
            {
                std::string name = NodeIdentifier( WorkerNode , nodes[i]->id ).getCodeName();

                LM_W(("Checking connection %s" , name.c_str() ));

                if ( !NetworkManager::isConnected(name) )
                {

                    // Connect with this worker....
                    std::string host = nodes[i]->host;
                    int port = nodes[i]->port;
                    size_t worker_id = nodes[i]->id;

                    addWorkerConnection(worker_id, host, port);
                }

            }

            // Remove nodes
            nodes.clearVector();

        }

        // -------------------------------------------------------------------------------------

    }

    std::vector<size_t> CommonNetwork::getWorkerIds()
    {
        return cluster_information.getWorkerIds();
    }

    std::vector<size_t> CommonNetwork::getConnectedWorkerIds()
    {
        std::vector<size_t> workers = getWorkerIds();
        std::vector<size_t> connected_workers;

        for ( size_t i = 0 ; i < workers.size() ; i++ )
        {
            std::string connection_name = NodeIdentifier( WorkerNode , workers[i]).getCodeName();
            if( NetworkManager::isConnected(connection_name ) )
                connected_workers.push_back( workers[i] );
        }

        return connected_workers;
    }

    std::string CommonNetwork::str()
    {
        std::ostringstream output;

        output << "-----------------------------------------------\n";
        output << "NetworkManager (" << node_identifier.str() <<  ") \n";
        output << "-----------------------------------------------\n";

        output << NetworkManager::str();

        output << "-----------------------------------------------\n";

        return output.str();
    }

    // Add a new connection agains an additional worker to be added to the cluster
    Status CommonNetwork::addWorkerConnection( size_t worker_id , std::string host , int port )
    {
        NodeIdentifier node_identifier = NodeIdentifier( WorkerNode , worker_id );
        std::string name = node_identifier.getCodeName();

        // Check if we already have this connection
        if( NetworkManager::isConnected(name) )
            return Error;

        // Init connection
        au::SocketConnection* socket_connection;
        au::Status s = au::SocketConnection::newSocketConnection(host , port , &socket_connection );

        // If there is an error, just return the error
        if( s != au::OK )
            return Error; // Generic error

        // Create network connection with this socket
        NetworkConnection* network_connection = new NetworkConnection( name , socket_connection , this );

        // Set identifier since we know this worker id
        network_connection->setNodeIdentifier( node_identifier );

        // Sent hello packages rigth now to make sure if identity us
        Packet *hello_packet = helloMessage( network_connection );
        network_connection->push( hello_packet );
        hello_packet->release();

        // Add this new connection
        Status ss = NetworkManager::add( network_connection );
        if( ss != OK )
        {
            LM_W(("Error adding new connection for worker %s" , name.c_str() ));
            delete network_connection;
            return ss;
        }

        // Notify about this connection
        report_worker_connected( worker_id );
        return OK;
    }

    Packet* CommonNetwork::helloMessage( NetworkConnection * target )
    {
        Packet* hello_packet = new Packet( Message::Hello );

        network::Hello* pb_hello =  hello_packet->message->mutable_hello();

        // Copy cluster information
        cluster_information.fill( pb_hello->mutable_cluster_information() );

        // Copy identification information
        node_identifier.fill( pb_hello->mutable_node_identifier() );

        // Copy user and password
        pb_hello->set_user( user );
        pb_hello->set_password( password );

        // Copy connection type
        pb_hello->set_connection_type(connection_type);

        if( !target )
            pb_hello->set_answer_hello_required(false);
        else
        {
            // Ask for Hello back if we still do not know who is the other...
            if(  target->getNodeIdentifier().node_type == UnknownNode )
                pb_hello->set_answer_hello_required(true);
            else
                pb_hello->set_answer_hello_required(false);
        }

        return hello_packet;
    }

    Status CommonNetwork::send( Packet* packet )
    {
        // Add more info to buffer name for debuggin
        engine::Buffer * buffer = packet->getBuffer();
        if( buffer )
            buffer->addToName( au::str(" [in packet to %s]" , packet->to.str().c_str() ));

        //LM_W(("Sending packet %s to %s" ,  packet->str().c_str() , packet->to.str().c_str() ));

        if ( packet->to == node_identifier )
        {
            // Local loop
            packet->from = node_identifier;
            schedule_receive( packet );
            return OK;
        }

        // Push a packet to a connection or eventually keep in queue to see if it connects back soon ;)
        return NetworkManager::send( packet );
    }

    // Receive a packet from a connection
    void CommonNetwork::receive( NetworkConnection* connection, Packet* packet )
    {

        if( packet->msgCode == Message::Hello )
        {
            processHello(connection, packet);
            return;
        }

        if( connection->getNodeIdentifier().node_type == UnknownNode )
            LM_X(1, ("Packet %s received from a non-identified node %s %s"
                     , packet->str().c_str()
                     , connection->getNodeIdentifier().str().c_str()
                     , connection->getName().c_str()
                     ));

        // Common interface to receive packets
        packet->from = connection->getNodeIdentifier();

        if( network_interface_receiver )
        {
            // Flush previous packets for me ( if any )
            while( pending_packets_for_me.getNumPackets() > 0 )
            {
                // Process next packet
                Packet * previous_packet = pending_packets_for_me.next();
                schedule_receive( previous_packet );
                pending_packets_for_me.pop();
            }

            // Schedule the new packet
            schedule_receive( packet );
        }
        else
            pending_packets_for_me.push( packet );

    }

    void CommonNetwork::getInfo( ::std::ostringstream& output , std::string command , std::string format)
    {
        if( command == "main" )
        {
            // Do something
        }
        if( command == "cluster" )
           cluster_information.getInfo( output , format);
        else
        {
            if (format == "xml")
                output << "<error>Unknown network element " << command << "</error>\n";
            else
                output << "  \"error\" : \"unknown network element: " << command << "\"\r\n";
        }
    }

    void CommonNetwork::report_worker_connected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_connected_worker_id(id);
        schedule_receive( packet );
        packet->release();
    }

    void CommonNetwork::report_worker_disconnected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_disconnected_worker_id(id);
        schedule_receive( packet );
        packet->release();
    }

    void CommonNetwork::report_delilah_connected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_connected_delilah_id(id);
        schedule_receive( packet );
        packet->release();
    }

    void CommonNetwork::report_delilah_disconnected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_disconnected_delilah_id(id);
        schedule_receive( packet );
        packet->release();
    }

    NodeIdentifier CommonNetwork::getMynodeIdentifier()
    {
        return node_identifier;
    }

    std::string CommonNetwork::getHostForWorker(size_t worker_id)
    {
        return cluster_information.hostForWorker( worker_id );
    }

    unsigned short CommonNetwork::getPortForWorker(size_t worker_id)
    {
        return cluster_information.portForWorker( worker_id );
    }

    au::tables::Table* CommonNetwork::getClusterConnectionsTable()
    {
        au::tables::Table* table = new au::tables::Table( au::StringVector( "Worker" , "Host" , "Status"  ) );

        if ( cluster_information.getId() == 0 )
            table->setTitle("Not connected to any cluster");
        else
        {

            au::vector<ClusterNode> nodes = cluster_information.getNodes();

            for ( size_t i = 0 ; i < nodes.size() ; i++ )
            {
                au::StringVector values;
                values.push_back( au::str("%lu" , nodes[i]->id ) );
                values.push_back( au::str("%s:%d" , nodes[i]->host.c_str() , nodes[i]->port ) );

                NodeIdentifier ni = nodes[i]->getNodeIdentifier();
                std::string connection_name = ni.getCodeName();

                if( ni == node_identifier )
                    values.push_back("me");
                else
                    values.push_back( NetworkManager::getStatusForConnection(connection_name) );

                table->addRow( values );

            }

            std::string title = au::str("Cluster %lu ( version %lu )"
                                        , cluster_information.getId()
                                        , cluster_information.getVersion()
                                        );
            table->setTitle( title );
            nodes.clearVector();
        }

        return table;

    }

    std::vector<size_t> CommonNetwork::getDelilahIds()
    {
        return NetworkManager::getDelilahIds();
    }
    network::Collection* CommonNetwork::getConnectionsCollection( Visualization* visualization )
    {
        return NetworkManager::getConnectionsCollection(visualization);
    }
    size_t CommonNetwork::get_rate_in()
    {
        return NetworkManager::get_rate_in();
    }
    size_t CommonNetwork::get_rate_out()
    {
        return NetworkManager::get_rate_out();
    }

}
<commit_msg>Remove anoying trace<commit_after>
#include "samson/common/MessagesOperations.h"

#include "samson/network/NetworkConnection.h"
#include "au/network/NetworkListener.h"
#include "au/network/SocketConnection.h"
#include "samson/network/NetworkConnection.h"

#include "CommonNetwork.h" // Own interface

namespace samson {

    void CommonNetwork::notify( engine::Notification* notification )
    {

        if (notification == NULL)
            LM_D(("notification == NULL"));

        // Check pennding packets to be removed after 1 minute disconnected
        // -------------------------------------------------------------------------------------
        NetworkManager::check();

        // Check disconnected elements to be removed ( if possible no threads or pending packets )
        // ----------------------------------------------------------------------------------------
        NetworkConnection * connection = NetworkManager::extractNextDisconnectedConnection();
        while (connection)
        {

            // Some notification about this disconnection
            NodeIdentifier node_identifier = connection->getNodeIdentifier();

            if( node_identifier.node_type == WorkerNode )
                report_worker_disconnected( node_identifier.id );

            if( node_identifier.node_type == DelilahNode )
                report_delilah_disconnected( node_identifier.id );

            // Remove connection
            delete connection;

            // Scan the next connection
            connection = NetworkManager::extractNextDisconnectedConnection();
        }

        // Check workers ( review connections , create new connections if possible , .... )
        // -------------------------------------------------------------------------------------

        if( cluster_information.getId() != 0 )
        {

            // Get a duplicate of current nodes involved in this cluster to connect to all of them
            au::vector<ClusterNode> nodes = cluster_information.getNodesToConnect( node_identifier );

            for ( size_t i = 0 ; i < nodes.size() ; i++ )
            {
                std::string name = NodeIdentifier( WorkerNode , nodes[i]->id ).getCodeName();

                if ( !NetworkManager::isConnected(name) )
                {

                    // Connect with this worker....
                    std::string host = nodes[i]->host;
                    int port = nodes[i]->port;
                    size_t worker_id = nodes[i]->id;

                    addWorkerConnection(worker_id, host, port);
                }

            }

            // Remove nodes
            nodes.clearVector();

        }

        // -------------------------------------------------------------------------------------

    }

    std::vector<size_t> CommonNetwork::getWorkerIds()
    {
        return cluster_information.getWorkerIds();
    }

    std::vector<size_t> CommonNetwork::getConnectedWorkerIds()
    {
        std::vector<size_t> workers = getWorkerIds();
        std::vector<size_t> connected_workers;

        for ( size_t i = 0 ; i < workers.size() ; i++ )
        {
            std::string connection_name = NodeIdentifier( WorkerNode , workers[i]).getCodeName();
            if( NetworkManager::isConnected(connection_name ) )
                connected_workers.push_back( workers[i] );
        }

        return connected_workers;
    }

    std::string CommonNetwork::str()
    {
        std::ostringstream output;

        output << "-----------------------------------------------\n";
        output << "NetworkManager (" << node_identifier.str() <<  ") \n";
        output << "-----------------------------------------------\n";

        output << NetworkManager::str();

        output << "-----------------------------------------------\n";

        return output.str();
    }

    // Add a new connection agains an additional worker to be added to the cluster
    Status CommonNetwork::addWorkerConnection( size_t worker_id , std::string host , int port )
    {
        NodeIdentifier node_identifier = NodeIdentifier( WorkerNode , worker_id );
        std::string name = node_identifier.getCodeName();

        // Check if we already have this connection
        if( NetworkManager::isConnected(name) )
            return Error;

        // Init connection
        au::SocketConnection* socket_connection;
        au::Status s = au::SocketConnection::newSocketConnection(host , port , &socket_connection );

        // If there is an error, just return the error
        if( s != au::OK )
            return Error; // Generic error

        // Create network connection with this socket
        NetworkConnection* network_connection = new NetworkConnection( name , socket_connection , this );

        // Set identifier since we know this worker id
        network_connection->setNodeIdentifier( node_identifier );

        // Sent hello packages rigth now to make sure if identity us
        Packet *hello_packet = helloMessage( network_connection );
        network_connection->push( hello_packet );
        hello_packet->release();

        // Add this new connection
        Status ss = NetworkManager::add( network_connection );
        if( ss != OK )
        {
            LM_W(("Error adding new connection for worker %s" , name.c_str() ));
            delete network_connection;
            return ss;
        }

        // Notify about this connection
        report_worker_connected( worker_id );
        return OK;
    }

    Packet* CommonNetwork::helloMessage( NetworkConnection * target )
    {
        Packet* hello_packet = new Packet( Message::Hello );

        network::Hello* pb_hello =  hello_packet->message->mutable_hello();

        // Copy cluster information
        cluster_information.fill( pb_hello->mutable_cluster_information() );

        // Copy identification information
        node_identifier.fill( pb_hello->mutable_node_identifier() );

        // Copy user and password
        pb_hello->set_user( user );
        pb_hello->set_password( password );

        // Copy connection type
        pb_hello->set_connection_type(connection_type);

        if( !target )
            pb_hello->set_answer_hello_required(false);
        else
        {
            // Ask for Hello back if we still do not know who is the other...
            if(  target->getNodeIdentifier().node_type == UnknownNode )
                pb_hello->set_answer_hello_required(true);
            else
                pb_hello->set_answer_hello_required(false);
        }

        return hello_packet;
    }

    Status CommonNetwork::send( Packet* packet )
    {
        // Add more info to buffer name for debuggin
        engine::Buffer * buffer = packet->getBuffer();
        if( buffer )
            buffer->addToName( au::str(" [in packet to %s]" , packet->to.str().c_str() ));

        //LM_W(("Sending packet %s to %s" ,  packet->str().c_str() , packet->to.str().c_str() ));

        if ( packet->to == node_identifier )
        {
            // Local loop
            packet->from = node_identifier;
            schedule_receive( packet );
            return OK;
        }

        // Push a packet to a connection or eventually keep in queue to see if it connects back soon ;)
        return NetworkManager::send( packet );
    }

    // Receive a packet from a connection
    void CommonNetwork::receive( NetworkConnection* connection, Packet* packet )
    {

        if( packet->msgCode == Message::Hello )
        {
            processHello(connection, packet);
            return;
        }

        if( connection->getNodeIdentifier().node_type == UnknownNode )
            LM_X(1, ("Packet %s received from a non-identified node %s %s"
                     , packet->str().c_str()
                     , connection->getNodeIdentifier().str().c_str()
                     , connection->getName().c_str()
                     ));

        // Common interface to receive packets
        packet->from = connection->getNodeIdentifier();

        if( network_interface_receiver )
        {
            // Flush previous packets for me ( if any )
            while( pending_packets_for_me.getNumPackets() > 0 )
            {
                // Process next packet
                Packet * previous_packet = pending_packets_for_me.next();
                schedule_receive( previous_packet );
                pending_packets_for_me.pop();
            }

            // Schedule the new packet
            schedule_receive( packet );
        }
        else
            pending_packets_for_me.push( packet );

    }

    void CommonNetwork::getInfo( ::std::ostringstream& output , std::string command , std::string format)
    {
        if( command == "main" )
        {
            // Do something
        }
        if( command == "cluster" )
           cluster_information.getInfo( output , format);
        else
        {
            if (format == "xml")
                output << "<error>Unknown network element " << command << "</error>\n";
            else
                output << "  \"error\" : \"unknown network element: " << command << "\"\r\n";
        }
    }

    void CommonNetwork::report_worker_connected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_connected_worker_id(id);
        schedule_receive( packet );
        packet->release();
    }

    void CommonNetwork::report_worker_disconnected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_disconnected_worker_id(id);
        schedule_receive( packet );
        packet->release();
    }

    void CommonNetwork::report_delilah_connected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_connected_delilah_id(id);
        schedule_receive( packet );
        packet->release();
    }

    void CommonNetwork::report_delilah_disconnected( size_t id )
    {
        Packet * packet = new Packet( Message::NetworkNotification );
        packet->message->mutable_network_notification()->set_disconnected_delilah_id(id);
        schedule_receive( packet );
        packet->release();
    }

    NodeIdentifier CommonNetwork::getMynodeIdentifier()
    {
        return node_identifier;
    }

    std::string CommonNetwork::getHostForWorker(size_t worker_id)
    {
        return cluster_information.hostForWorker( worker_id );
    }

    unsigned short CommonNetwork::getPortForWorker(size_t worker_id)
    {
        return cluster_information.portForWorker( worker_id );
    }

    au::tables::Table* CommonNetwork::getClusterConnectionsTable()
    {
        au::tables::Table* table = new au::tables::Table( au::StringVector( "Worker" , "Host" , "Status"  ) );

        if ( cluster_information.getId() == 0 )
            table->setTitle("Not connected to any cluster");
        else
        {

            au::vector<ClusterNode> nodes = cluster_information.getNodes();

            for ( size_t i = 0 ; i < nodes.size() ; i++ )
            {
                au::StringVector values;
                values.push_back( au::str("%lu" , nodes[i]->id ) );
                values.push_back( au::str("%s:%d" , nodes[i]->host.c_str() , nodes[i]->port ) );

                NodeIdentifier ni = nodes[i]->getNodeIdentifier();
                std::string connection_name = ni.getCodeName();

                if( ni == node_identifier )
                    values.push_back("me");
                else
                    values.push_back( NetworkManager::getStatusForConnection(connection_name) );

                table->addRow( values );

            }

            std::string title = au::str("Cluster %lu ( version %lu )"
                                        , cluster_information.getId()
                                        , cluster_information.getVersion()
                                        );
            table->setTitle( title );
            nodes.clearVector();
        }

        return table;

    }

    std::vector<size_t> CommonNetwork::getDelilahIds()
    {
        return NetworkManager::getDelilahIds();
    }
    network::Collection* CommonNetwork::getConnectionsCollection( Visualization* visualization )
    {
        return NetworkManager::getConnectionsCollection(visualization);
    }
    size_t CommonNetwork::get_rate_in()
    {
        return NetworkManager::get_rate_in();
    }
    size_t CommonNetwork::get_rate_out()
    {
        return NetworkManager::get_rate_out();
    }

}
<|endoftext|>


<commit_before>/**
 * @file detail/kdtree_impl.hpp
 * @brief VLFeat Kd-tree wrapper implementation
 * @author Paolo D'Apice
 */

#ifndef VIS_DETAIL_KDTREE_IMPL_HPP
#define VIS_DETAIL_KDTREE_IMPL_HPP

#include "traits.hpp"
#include <boost/assert.hpp>
#include <boost/serialization/array.hpp>
#include <cstdio>

namespace vis {

namespace kdtree {
    static const VlVectorComparisonType distance = VlDistanceL2;
    static const VlKDTreeThresholdingMethod thresholdingMethod = VL_KDTREE_MEDIAN;
}

template <typename T>
void
printInfo(const VlKDForest* forest, vl_size numSamples) {
    printf("vl_kdforestbuild: data %s [%llu x %llu]\n",
            vl_get_type_name(VlType<T>::type),
            vl_kdforest_get_data_dimension(forest),
            numSamples);
    printf("vl_kdforestbuild: threshold selection method: %s\n", "median") ;
    printf("vl_kdforestbuild: number of trees: %llu\n",
            vl_kdforest_get_num_trees(forest));
    printf("vl_kdforestbuild: distance: %s\n",
            vl_get_vector_comparison_type_name(kdtree::distance));
}

template <typename T>
KDTree<T>::KDTree() {
    forest = NULL;
    dataPtr = NULL;
    dataSize = 0;
}

template <typename T>
KDTree<T>::KDTree(const T* data, vl_size numDimensions, vl_size numSamples,
        vl_size numTrees, bool verbose) {
    dataPtr = NULL;
    dataSize = 0;

    forest = vl_kdforest_new(VlType<T>::type, numDimensions, numTrees, kdtree::distance) ;
    vl_kdforest_set_thresholding_method(forest, kdtree::thresholdingMethod);

    if (verbose) printInfo<T>(forest, numSamples);
    BOOST_ASSERT(numDimensions == vl_kdforest_get_data_dimension(forest));

    vl_kdforest_build(forest, numSamples, data);
}

template <typename T>
KDTree<T>::KDTree(const cv::Mat& d, vl_size numTrees, bool verbose) {
    BOOST_ASSERT_MSG(d.depth() == cv::DataType<T>::type, "Data is not of type T");
    BOOST_ASSERT_MSG(d.isContinuous(), "Data is not continuous");

    vl_size numDimensions = d.rows;
    vl_size numSamples = d.cols;

    dataSize = numDimensions * numSamples;
    dataPtr = (T*) vl_calloc(sizeof(T), dataSize);

    cv::Mat dt = d.t();
    std::copy(dt.begin<T>(), dt.end<T>(), dataPtr);

    forest = vl_kdforest_new(VlType<T>::type, numDimensions, numTrees, kdtree::distance) ;
    vl_kdforest_set_thresholding_method(forest, kdtree::thresholdingMethod);

    if (verbose) printInfo<T>(forest, numSamples);
    BOOST_ASSERT(numDimensions == vl_kdforest_get_data_dimension(forest));

    vl_kdforest_build(forest, numSamples, dataPtr);
}

template <typename T>
KDTree<T>::~KDTree() {
    vl_kdforest_delete(forest);
    if (dataPtr != NULL) vl_free(dataPtr);
}

template <typename T>
std::vector<KDTreeNeighbor>
KDTree<T>::search(const T* query, vl_size numQueries, vl_size numNeighbors, vl_size maxNumComparisons) {
    vl_kdforest_set_max_num_comparisons(forest, maxNumComparisons);

    BOOST_ASSERT_MSG(numQueries == 1, "Multiple queries not yet supported");

    vl_uint32* indexes = (vl_uint32*) vl_calloc(sizeof(vl_uint32), numNeighbors * numQueries);
    double* distances = (double*) vl_calloc(sizeof(double), numNeighbors * numQueries);

    std::vector<KDTreeNeighbor> results;
    getResults(query, numQueries, numNeighbors, results);

    return results;
}

template <typename T>
std::vector<KDTreeNeighbor>
KDTree<T>::search(const cv::Mat& query, vl_size numNeighbors, vl_size maxNumComparisons) {
    vl_kdforest_set_max_num_comparisons(forest, maxNumComparisons);

    BOOST_ASSERT_MSG(query.depth() == cv::DataType<T>::type, "Query is not of type T");
    BOOST_ASSERT_MSG(query.isContinuous(), "Query is not continuous");
    BOOST_ASSERT_MSG(query.cols == 1, "Multiple queries not yet supported");

    vl_size numQueries = query.cols;
    T* queryPtr = (T*) vl_calloc(sizeof(T), vl_kdforest_get_data_dimension(forest));
    std::copy(query.begin<T>(), query.end<T>(), queryPtr);

    std::vector<KDTreeNeighbor> results;
    getResults(queryPtr, numQueries, numNeighbors, results);

    vl_free(queryPtr);
    return results;
}

template <typename T>
void
KDTree<T>::getResults(const T* query, vl_size numQueries, vl_size numNeighbors,
        std::vector<KDTreeNeighbor>& results) {
    vl_uint32* indexes = (vl_uint32*) vl_calloc(sizeof(vl_uint32), numNeighbors * numQueries);
    double* distances = (double*) vl_calloc(sizeof(double), numNeighbors * numQueries);

    vl_kdforest_query_with_array(forest, indexes, numNeighbors, numQueries, distances, query);

    // TODO get results from multiple queries
    for (int i = 0; i < numNeighbors; ++i) {
        KDTreeNeighbor item;
        item.index = indexes[i];
        item.distance = distances[i]; // TODO do not set if not requested

        results.push_back(item);
    }

    vl_free(indexes);
    vl_free(distances);
}

template <typename T>
template <typename Archive>
void
KDTree<T>::save(Archive& ar, const unsigned int version) const {
    ar & forest;

    BOOST_ASSERT_MSG(dataSize > 0, "KDTree has no data");
    ar & dataSize;

    BOOST_ASSERT_MSG(dataPtr != NULL, "dataPtr is NULL");
    ar & boost::serialization::make_array(dataPtr, dataSize);
}

template <typename T>
template <typename Archive>
void
KDTree<T>::load(Archive& ar, const unsigned int version) {
    ar & forest;

    ar & dataSize;
    BOOST_ASSERT_MSG(dataSize > 0, "KDTree has no data");

    dataPtr = new T[dataSize];

    ar & boost::serialization::make_array(dataPtr, dataSize);
    BOOST_ASSERT_MSG(dataPtr != NULL, "dataPtr is NULL");

    forest->data = dataPtr;
}

} /* namespace vis */

#endif /* VIS_DETAIL_KDTREE_IMPL_HPP */

<commit_msg>Added verbosity to kdtree<commit_after>/**
 * @file detail/kdtree_impl.hpp
 * @brief VLFeat Kd-tree wrapper implementation
 * @author Paolo D'Apice
 */

#ifndef VIS_DETAIL_KDTREE_IMPL_HPP
#define VIS_DETAIL_KDTREE_IMPL_HPP

#include "traits.hpp"
#include <boost/assert.hpp>
#include <boost/serialization/array.hpp>
#include <cstdio>

namespace vis {

namespace kdtree {
    static const VlVectorComparisonType distance = VlDistanceL2;
    static const VlKDTreeThresholdingMethod thresholdingMethod = VL_KDTREE_MEDIAN;
}

template <typename T>
void
printInfo(const VlKDForest* forest, vl_size numSamples) {
    printf("vl_kdforestbuild: data %s [%llu x %llu]\n",
            vl_get_type_name(VlType<T>::type),
            vl_kdforest_get_data_dimension(forest),
            numSamples);
    printf("vl_kdforestbuild: threshold selection method: %s\n", "median") ;
    printf("vl_kdforestbuild: number of trees: %llu\n",
            vl_kdforest_get_num_trees(forest));
    printf("vl_kdforestbuild: distance: %s\n",
            vl_get_vector_comparison_type_name(kdtree::distance));
}

void
printTreeInfo(const VlKDForest* forest) {
    for (vl_uindex ti = 0; ti < vl_kdforest_get_num_trees(forest); ++ti) {
        printf("vl_kdforestbuild: tree %llu: depth %llu, num nodes %llu\n",
                ti,
                vl_kdforest_get_depth_of_tree(forest, ti),
                vl_kdforest_get_num_nodes_of_tree(forest, ti));
    }
}

template <typename T>
KDTree<T>::KDTree() {
    forest = NULL;
    dataPtr = NULL;
    dataSize = 0;
}

template <typename T>
KDTree<T>::KDTree(const T* data, vl_size numDimensions, vl_size numSamples,
        vl_size numTrees, bool verbose) {
    dataPtr = NULL;
    dataSize = 0;

    forest = vl_kdforest_new(VlType<T>::type, numDimensions, numTrees, kdtree::distance) ;
    vl_kdforest_set_thresholding_method(forest, kdtree::thresholdingMethod);

    if (verbose) printInfo<T>(forest, numSamples);
    BOOST_ASSERT(numDimensions == vl_kdforest_get_data_dimension(forest));

    vl_kdforest_build(forest, numSamples, data);
    if (verbose) printTreeInfo(forest);
}

template <typename T>
KDTree<T>::KDTree(const cv::Mat& d, vl_size numTrees, bool verbose) {
    BOOST_ASSERT_MSG(d.depth() == cv::DataType<T>::type, "Data is not of type T");
    BOOST_ASSERT_MSG(d.isContinuous(), "Data is not continuous");

    vl_size numDimensions = d.rows;
    vl_size numSamples = d.cols;

    dataSize = numDimensions * numSamples;
    dataPtr = (T*) vl_calloc(sizeof(T), dataSize);

    cv::Mat dt = d.t();
    std::copy(dt.begin<T>(), dt.end<T>(), dataPtr);

    forest = vl_kdforest_new(VlType<T>::type, numDimensions, numTrees, kdtree::distance) ;
    vl_kdforest_set_thresholding_method(forest, kdtree::thresholdingMethod);

    if (verbose) printInfo<T>(forest, numSamples);
    BOOST_ASSERT(numDimensions == vl_kdforest_get_data_dimension(forest));

    vl_kdforest_build(forest, numSamples, dataPtr);
    if (verbose) printTreeInfo(forest);
}

template <typename T>
KDTree<T>::~KDTree() {
    vl_kdforest_delete(forest);
    if (dataPtr != NULL) vl_free(dataPtr);
}

template <typename T>
std::vector<KDTreeNeighbor>
KDTree<T>::search(const T* query, vl_size numQueries, vl_size numNeighbors, vl_size maxNumComparisons) {
    vl_kdforest_set_max_num_comparisons(forest, maxNumComparisons);

    BOOST_ASSERT_MSG(numQueries == 1, "Multiple queries not yet supported");

    vl_uint32* indexes = (vl_uint32*) vl_calloc(sizeof(vl_uint32), numNeighbors * numQueries);
    double* distances = (double*) vl_calloc(sizeof(double), numNeighbors * numQueries);

    std::vector<KDTreeNeighbor> results;
    getResults(query, numQueries, numNeighbors, results);

    return results;
}

template <typename T>
std::vector<KDTreeNeighbor>
KDTree<T>::search(const cv::Mat& query, vl_size numNeighbors, vl_size maxNumComparisons) {
    vl_kdforest_set_max_num_comparisons(forest, maxNumComparisons);

    BOOST_ASSERT_MSG(query.depth() == cv::DataType<T>::type, "Query is not of type T");
    BOOST_ASSERT_MSG(query.isContinuous(), "Query is not continuous");
    BOOST_ASSERT_MSG(query.cols == 1, "Multiple queries not yet supported");

    vl_size numQueries = query.cols;
    T* queryPtr = (T*) vl_calloc(sizeof(T), vl_kdforest_get_data_dimension(forest));
    std::copy(query.begin<T>(), query.end<T>(), queryPtr);

    std::vector<KDTreeNeighbor> results;
    getResults(queryPtr, numQueries, numNeighbors, results);

    vl_free(queryPtr);
    return results;
}

template <typename T>
void
KDTree<T>::getResults(const T* query, vl_size numQueries, vl_size numNeighbors,
        std::vector<KDTreeNeighbor>& results) {
    vl_uint32* indexes = (vl_uint32*) vl_calloc(sizeof(vl_uint32), numNeighbors * numQueries);
    double* distances = (double*) vl_calloc(sizeof(double), numNeighbors * numQueries);

    vl_kdforest_query_with_array(forest, indexes, numNeighbors, numQueries, distances, query);

    // TODO get results from multiple queries
    for (int i = 0; i < numNeighbors; ++i) {
        KDTreeNeighbor item;
        item.index = indexes[i];
        item.distance = distances[i]; // TODO do not set if not requested

        results.push_back(item);
    }

    vl_free(indexes);
    vl_free(distances);
}

template <typename T>
template <typename Archive>
void
KDTree<T>::save(Archive& ar, const unsigned int version) const {
    ar & forest;

    BOOST_ASSERT_MSG(dataSize > 0, "KDTree has no data");
    ar & dataSize;

    BOOST_ASSERT_MSG(dataPtr != NULL, "dataPtr is NULL");
    ar & boost::serialization::make_array(dataPtr, dataSize);
}

template <typename T>
template <typename Archive>
void
KDTree<T>::load(Archive& ar, const unsigned int version) {
    ar & forest;

    ar & dataSize;
    BOOST_ASSERT_MSG(dataSize > 0, "KDTree has no data");

    dataPtr = new T[dataSize];

    ar & boost::serialization::make_array(dataPtr, dataSize);
    BOOST_ASSERT_MSG(dataPtr != NULL, "dataPtr is NULL");

    forest->data = dataPtr;
}

} /* namespace vis */

#endif /* VIS_DETAIL_KDTREE_IMPL_HPP */

<|endoftext|>


<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: outputoption.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "outputoption.h"
#include "ui_outputoption.h"
#include "liteapp_global.h"
#include <QFontDatabase>
#include <QStandardItemModel>
#include <QStandardItem>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

OutputOption::OutputOption(LiteApi::IApplication *app,QObject *parent) :
    LiteApi::IOption(parent),
    m_liteApp(app),
    m_widget(new QWidget),
    ui(new Ui::OutputOption)
{
    ui->setupUi(m_widget);

    QFontDatabase db;
    const QStringList families = db.families();
    ui->familyComboBox->addItems(families);

#if defined(Q_OS_WIN)
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Courier").toString();
#elif defined(Q_OS_LINUX)
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Monospace").toString();
#elif defined(Q_OS_MAC)
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Menlo").toString();
#else
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Monospace").toString();
#endif
    m_fontSize = m_liteApp->settings()->value(OUTPUT_FONTSIZE,12).toInt();

    int fontZoom = m_liteApp->settings()->value(OUTPUT_FONTZOOM,100).toInt();

    bool antialias = m_liteApp->settings()->value(OUTPUT_ANTIALIAS,true).toBool();
    ui->antialiasCheckBox->setChecked(antialias);

    const int idx = families.indexOf(m_fontFamily);
    ui->familyComboBox->setCurrentIndex(idx);

    updatePointSizes();

    ui->fontZoomSpinBox->setValue(fontZoom);

    bool useColorScheme = m_liteApp->settings()->value(OUTPUT_USECOLORSCHEME,true).toBool();
    ui->useColorSchemeCheckBox->setChecked(useColorScheme);

    int maxLines = m_liteApp->settings()->value(OUTPUT_MAXLINES,5000).toInt();
    ui->spinBoxOutputMaxLines->setValue(maxLines);
}

OutputOption::~OutputOption()
{
    delete m_widget;
    delete ui;
}

QWidget *OutputOption::widget()
{
    return m_widget;
}

QString OutputOption::name() const
{
    return "LiteOutput";
}

QString OutputOption::mimeType() const
{
    return OPTION_LITEOUTPUT;
}

void OutputOption::apply()
{
    m_fontFamily = ui->familyComboBox->currentText();
    if (ui->sizeComboBox->count()) {
        const QString curSize = ui->sizeComboBox->currentText();
        bool ok = true;
        int size = curSize.toInt(&ok);
        if (ok) {
            m_fontSize = size;
        }
    }

    int fontZoom = ui->fontZoomSpinBox->value();
    if (fontZoom <= 10) {
        fontZoom = 10;
    }
    m_liteApp->settings()->setValue(OUTPUT_FAMILY,m_fontFamily);
    m_liteApp->settings()->setValue(OUTPUT_FONTSIZE,m_fontSize);
    m_liteApp->settings()->setValue(OUTPUT_FONTZOOM,fontZoom);

    bool colorScheme = ui->useColorSchemeCheckBox->isChecked();
    int maxLines = ui->spinBoxOutputMaxLines->value();

    m_liteApp->settings()->setValue(OUTPUT_USECOLORSCHEME,colorScheme);
    m_liteApp->settings()->setValue(OUTPUT_MAXLINES,maxLines);
}

void OutputOption::updatePointSizes()
{
    // Update point sizes
    const int oldSize = m_fontSize;
    if (ui->sizeComboBox->count()) {
        ui->sizeComboBox->clear();
    }
    const QList<int> sizeLst = pointSizesForSelectedFont();
    int idx = 0;
    int i = 0;
    for (; i < sizeLst.count(); ++i) {
        if (idx == 0 && sizeLst.at(i) >= oldSize)
            idx = i;
        ui->sizeComboBox->addItem(QString::number(sizeLst.at(i)));
    }
    if (ui->sizeComboBox->count())
        ui->sizeComboBox->setCurrentIndex(idx);
}

QList<int> OutputOption::pointSizesForSelectedFont() const
{
    QFontDatabase db;
    const QString familyName = ui->familyComboBox->currentText();
    QList<int> sizeLst = db.pointSizes(familyName);
    if (!sizeLst.isEmpty())
        return sizeLst;

    QStringList styles = db.styles(familyName);
    if (!styles.isEmpty())
        sizeLst = db.pointSizes(familyName, styles.first());
    if (sizeLst.isEmpty())
        sizeLst = QFontDatabase::standardSizes();

    return sizeLst;
}

<commit_msg>fix #1007 liteoutput antialias setup invalid<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: outputoption.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "outputoption.h"
#include "ui_outputoption.h"
#include "liteapp_global.h"
#include <QFontDatabase>
#include <QStandardItemModel>
#include <QStandardItem>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

OutputOption::OutputOption(LiteApi::IApplication *app,QObject *parent) :
    LiteApi::IOption(parent),
    m_liteApp(app),
    m_widget(new QWidget),
    ui(new Ui::OutputOption)
{
    ui->setupUi(m_widget);

    QFontDatabase db;
    const QStringList families = db.families();
    ui->familyComboBox->addItems(families);

#if defined(Q_OS_WIN)
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Courier").toString();
#elif defined(Q_OS_LINUX)
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Monospace").toString();
#elif defined(Q_OS_MAC)
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Menlo").toString();
#else
    m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Monospace").toString();
#endif
    m_fontSize = m_liteApp->settings()->value(OUTPUT_FONTSIZE,12).toInt();

    int fontZoom = m_liteApp->settings()->value(OUTPUT_FONTZOOM,100).toInt();

    bool antialias = m_liteApp->settings()->value(OUTPUT_ANTIALIAS,true).toBool();
    ui->antialiasCheckBox->setChecked(antialias);

    const int idx = families.indexOf(m_fontFamily);
    ui->familyComboBox->setCurrentIndex(idx);

    updatePointSizes();

    ui->fontZoomSpinBox->setValue(fontZoom);

    bool useColorScheme = m_liteApp->settings()->value(OUTPUT_USECOLORSCHEME,true).toBool();
    ui->useColorSchemeCheckBox->setChecked(useColorScheme);

    int maxLines = m_liteApp->settings()->value(OUTPUT_MAXLINES,5000).toInt();
    ui->spinBoxOutputMaxLines->setValue(maxLines);
}

OutputOption::~OutputOption()
{
    delete m_widget;
    delete ui;
}

QWidget *OutputOption::widget()
{
    return m_widget;
}

QString OutputOption::name() const
{
    return "LiteOutput";
}

QString OutputOption::mimeType() const
{
    return OPTION_LITEOUTPUT;
}

void OutputOption::apply()
{
    m_fontFamily = ui->familyComboBox->currentText();
    if (ui->sizeComboBox->count()) {
        const QString curSize = ui->sizeComboBox->currentText();
        bool ok = true;
        int size = curSize.toInt(&ok);
        if (ok) {
            m_fontSize = size;
        }
    }

    int fontZoom = ui->fontZoomSpinBox->value();
    if (fontZoom <= 10) {
        fontZoom = 10;
    }
    m_liteApp->settings()->setValue(OUTPUT_FAMILY,m_fontFamily);
    m_liteApp->settings()->setValue(OUTPUT_FONTSIZE,m_fontSize);
    m_liteApp->settings()->setValue(OUTPUT_FONTZOOM,fontZoom);

    bool antialias = ui->antialiasCheckBox->isChecked();
    m_liteApp->settings()->setValue(OUTPUT_ANTIALIAS,antialias);

    bool colorScheme = ui->useColorSchemeCheckBox->isChecked();
    int maxLines = ui->spinBoxOutputMaxLines->value();

    m_liteApp->settings()->setValue(OUTPUT_USECOLORSCHEME,colorScheme);
    m_liteApp->settings()->setValue(OUTPUT_MAXLINES,maxLines);
}

void OutputOption::updatePointSizes()
{
    // Update point sizes
    const int oldSize = m_fontSize;
    if (ui->sizeComboBox->count()) {
        ui->sizeComboBox->clear();
    }
    const QList<int> sizeLst = pointSizesForSelectedFont();
    int idx = 0;
    int i = 0;
    for (; i < sizeLst.count(); ++i) {
        if (idx == 0 && sizeLst.at(i) >= oldSize)
            idx = i;
        ui->sizeComboBox->addItem(QString::number(sizeLst.at(i)));
    }
    if (ui->sizeComboBox->count())
        ui->sizeComboBox->setCurrentIndex(idx);
}

QList<int> OutputOption::pointSizesForSelectedFont() const
{
    QFontDatabase db;
    const QString familyName = ui->familyComboBox->currentText();
    QList<int> sizeLst = db.pointSizes(familyName);
    if (!sizeLst.isEmpty())
        return sizeLst;

    QStringList styles = db.styles(familyName);
    if (!styles.isEmpty())
        sizeLst = db.pointSizes(familyName, styles.first());
    if (sizeLst.isEmpty())
        sizeLst = QFontDatabase::standardSizes();

    return sizeLst;
}

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "swissknife_lease.h"

#include <algorithm>
#include <vector>

#include "gateway_util.h"
#include "logging.h"
#include "swissknife_lease_curl.h"
#include "swissknife_lease_json.h"
#include "util/posix.h"
#include "util/string.h"

namespace {

bool CheckParams(const swissknife::CommandLease::Parameters& p) {
  if (p.action != "acquire" && p.action != "drop") {
    return false;
  }

  return true;
}

}  // namespace

namespace swissknife {

enum LeaseError {
  kLeaseSuccess = 0,
  kLeaseUnused = 1,
  kLeaseParamError = 2,
  kLeaseCurlInitError = 3,
  kLeaseFileOpenError = 4,
  kLeaseFileDeleteError = 5,
  kLeaseParseError = 6,
  kLeaseCurlReqError = 7,
};

CommandLease::~CommandLease() {}

ParameterList CommandLease::GetParams() const {
  ParameterList r;
  r.push_back(Parameter::Mandatory('u', "repo service url"));
  r.push_back(Parameter::Mandatory('a', "action (acquire or drop)"));
  r.push_back(Parameter::Mandatory('k', "key file"));
  r.push_back(Parameter::Mandatory('p', "lease path"));
  return r;
}

int CommandLease::Main(const ArgumentList& args) {
  Parameters params;

  params.repo_service_url = *(args.find('u')->second);
  params.action = *(args.find('a')->second);
  params.key_file = *(args.find('k')->second);

  params.lease_path = *(args.find('p')->second);
  std::vector<std::string> tokens = SplitString(params.lease_path, '/');
  const std::string lease_fqdn = tokens.front();

  // Remove the fqdn from the list of tokens and join them with "_" to make the
  // token file suffix
  tokens.erase(tokens.begin());
  params.token_file_suffix = JoinStrings(tokens, "_");

  if (!CheckParams(params)) {
    return kLeaseParamError;
  }

  // Initialize curl
  if (curl_global_init(CURL_GLOBAL_ALL)) {
    return kLeaseCurlInitError;
  }

  std::string key_id;
  std::string secret;
  if (!gateway::ReadKeys(params.key_file, &key_id, &secret)) {
    LogCvmfs(kLogCvmfs, kLogStderr, "Error reading key file %s.",
             params.key_file.c_str());
    return 1;
  }

  LeaseError ret = kLeaseSuccess;
  if (params.action == "acquire") {
    CurlBuffer buffer;
    if (MakeAcquireRequest(key_id, secret, params.lease_path,
                           params.repo_service_url, &buffer)) {
      std::string session_token;
      if (buffer.data.size() > 0 && ParseAcquireReply(buffer, &session_token)) {
        // Save session token to
        // /var/spool/cvmfs/<REPO_NAME>/session_token_<SUBPATH>
        // TODO(radu): Is there a special way to access the scratch directory?
        const std::string token_file_name = "/var/spool/cvmfs/" + lease_fqdn +
                                            "/session_token_" +
                                            params.token_file_suffix;
        if (!SafeWriteToFile(session_token, token_file_name, 0600)) {
          LogCvmfs(kLogCvmfs, kLogStderr, "Error opening file: %s",
                   std::strerror(errno));
          ret = kLeaseFileOpenError;
        }
      } else {
        ret = kLeaseParseError;
      }
    } else {
      ret = kLeaseCurlReqError;
    }
  } else if (params.action == "drop") {
    // Try to read session token from repository scratch directory
    std::string session_token;
    std::string token_file_name = "/var/spool/cvmfs/" + lease_fqdn +
                                  "/session_token_" + params.token_file_suffix;
    FILE* token_file = std::fopen(token_file_name.c_str(), "r");
    if (token_file) {
      GetLineFile(token_file, &session_token);
      LogCvmfs(kLogCvmfs, kLogStderr, "Read session token from file: %s",
               session_token.c_str());

      CurlBuffer buffer;
      if (MakeEndRequest("DELETE", key_id, secret, session_token,
                         params.repo_service_url, "", &buffer)) {
        if (buffer.data.size() > 0 && ParseDropReply(buffer)) {
          std::fclose(token_file);
          if (unlink(token_file_name.c_str())) {
            LogCvmfs(kLogCvmfs, kLogStderr,
                     "Error deleting session token file");
            ret = kLeaseFileDeleteError;
          }
        } else {
          LogCvmfs(kLogCvmfs, kLogStderr, "Could not drop active lease");
          ret = kLeaseParseError;
        }
      } else {
        LogCvmfs(kLogCvmfs, kLogStderr, "Error making DELETE request");
        ret = kLeaseCurlReqError;
      }

      fclose(token_file);
    } else {
      LogCvmfs(kLogCvmfs, kLogStderr, "Error reading session token from file");
      ret = kLeaseFileOpenError;
    }
  }

  return ret;
}

}  // namespace swissknife
<commit_msg>Fixing memory error in swissknife_lease.cc<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "swissknife_lease.h"

#include <algorithm>
#include <vector>

#include "gateway_util.h"
#include "logging.h"
#include "swissknife_lease_curl.h"
#include "swissknife_lease_json.h"
#include "util/posix.h"
#include "util/string.h"

namespace {

bool CheckParams(const swissknife::CommandLease::Parameters& p) {
  if (p.action != "acquire" && p.action != "drop") {
    return false;
  }

  return true;
}

}  // namespace

namespace swissknife {

enum LeaseError {
  kLeaseSuccess,
  kLeaseUnused,
  kLeaseParamError,
  kLeaseKeyParseError,
  kLeaseCurlInitError,
  kLeaseFileOpenError,
  kLeaseParseError,
  kLeaseCurlReqError,
};

CommandLease::~CommandLease() {}

ParameterList CommandLease::GetParams() const {
  ParameterList r;
  r.push_back(Parameter::Mandatory('u', "repo service url"));
  r.push_back(Parameter::Mandatory('a', "action (acquire or drop)"));
  r.push_back(Parameter::Mandatory('k', "key file"));
  r.push_back(Parameter::Mandatory('p', "lease path"));
  return r;
}

int CommandLease::Main(const ArgumentList& args) {
  Parameters params;

  params.repo_service_url = *(args.find('u')->second);
  params.action = *(args.find('a')->second);
  params.key_file = *(args.find('k')->second);

  params.lease_path = *(args.find('p')->second);
  std::vector<std::string> tokens = SplitString(params.lease_path, '/');
  const std::string lease_fqdn = tokens.front();

  // Remove the fqdn from the list of tokens and join them with "_" to make the
  // token file suffix
  tokens.erase(tokens.begin());
  params.token_file_suffix = JoinStrings(tokens, "_");

  if (!CheckParams(params)) {
    return kLeaseParamError;
  }

  // Initialize curl
  if (curl_global_init(CURL_GLOBAL_ALL)) {
    return kLeaseCurlInitError;
  }

  std::string key_id;
  std::string secret;
  if (!gateway::ReadKeys(params.key_file, &key_id, &secret)) {
    LogCvmfs(kLogCvmfs, kLogStderr, "Error reading key file %s.",
             params.key_file.c_str());
    return kLeaseKeyParseError;
  }

  LeaseError ret = kLeaseSuccess;
  if (params.action == "acquire") {
    CurlBuffer buffer;
    if (MakeAcquireRequest(key_id, secret, params.lease_path,
                           params.repo_service_url, &buffer)) {
      std::string session_token;
      if (buffer.data.size() > 0 && ParseAcquireReply(buffer, &session_token)) {
        // Save session token to
        // /var/spool/cvmfs/<REPO_NAME>/session_token_<SUBPATH>
        // TODO(radu): Is there a special way to access the scratch directory?
        const std::string token_file_name = "/var/spool/cvmfs/" + lease_fqdn +
                                            "/session_token_" +
                                            params.token_file_suffix;
        if (!SafeWriteToFile(session_token, token_file_name, 0600)) {
          LogCvmfs(kLogCvmfs, kLogStderr, "Error opening file: %s",
                   std::strerror(errno));
          ret = kLeaseFileOpenError;
        }
      } else {
        ret = kLeaseParseError;
      }
    } else {
      ret = kLeaseCurlReqError;
    }
  } else if (params.action == "drop") {
    // Try to read session token from repository scratch directory
    std::string session_token;
    std::string token_file_name = "/var/spool/cvmfs/" + lease_fqdn +
                                  "/session_token_" + params.token_file_suffix;
    FILE* token_file = std::fopen(token_file_name.c_str(), "r");
    if (token_file) {
      GetLineFile(token_file, &session_token);
      LogCvmfs(kLogCvmfs, kLogStderr, "Read session token from file: %s",
               session_token.c_str());

      CurlBuffer buffer;
      if (MakeEndRequest("DELETE", key_id, secret, session_token,
                         params.repo_service_url, "", &buffer)) {
        if (!buffer.data.empty() && ParseDropReply(buffer)) {
          std::fclose(token_file);
          if (unlink(token_file_name.c_str())) {
            LogCvmfs(kLogCvmfs, kLogStderr, "Warning - Could not delete session token file.");
          }
          return kLeaseSuccess;
        } else {
          LogCvmfs(kLogCvmfs, kLogStderr, "Could not drop active lease");
          ret = kLeaseParseError;
        }
      } else {
        LogCvmfs(kLogCvmfs, kLogStderr, "Error making DELETE request");
        ret = kLeaseCurlReqError;
      }

      std::fclose(token_file);
    } else {
      LogCvmfs(kLogCvmfs, kLogStderr, "Error reading session token from file");
      ret = kLeaseFileOpenError;
    }
  }

  return ret;
}

}  // namespace swissknife
<|endoftext|>


<commit_before>#include <iostream>

#include <SFML/Graphics.hpp>
#include "game.h"

Game::Game():
    playing(true),
    screen(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close),
    map(nullptr)
    //map_camera(nullptr),
    //unitRepository(nullptr)
{
    screen.setFramerateLimit(60); //comment out for fps benchmarks

    init();
}

int Game::execute() {

  while(playing) {
    sf::Event event;
    while(screen.pollEvent(event)) {
      onEvent(event);
    }

    updateState();
    render();
  }

  return 0;
}

int Game::init() {
  if (!terrain.loadFromFile("graphics/terrain.png")) {
    std::cout << "Failed to read graphics/terrain.png data" << std::endl;
    return false;
  }

  sf::Image temp;
  if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
    std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
    return false;
  }

  temp.createMaskFromColor(sf::Color(255, 0, 255));
  shroud_edges.loadFromImage(temp);

  map.reset(new Map(terrain, shroud_edges));
  map->load("maps/4PL_Mountains.ini");

  camera.reset({0,0,800,600});
  screen.setView(camera);

  //shroud_edges = Surface::load("graphics/shroud_edges.bmp");

  //if (shroud_edges == NULL) {
    //cout << "Failed to read graphics/shroud_edges.bmp data" << endl;
    //return false;
  //}

  //shroud_edges_shadow = Surface::load("graphics/shroud_edges_shadow.bmp");

  //if (shroud_edges_shadow == NULL) {
    //cout << "Failed to read graphics/shroud_edges_shadow.bmp data" << endl;
    //return false;
  //}

  //mouse.init(screen);

  //map_camera.reset(new MapCamera(0, 0, screen, &map));
  //map.load("maps/4PL_Mountains.ini");
  //unitRepository.reset(new UnitRepository(&map));

  ////init two players
  //int idCount = 0;
  //players.emplace_back(House::Sardaukar, idCount++);
  //players.emplace_back(House::Harkonnen, idCount++);

  //units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));

  //// soldiers
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));

  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));

  return true;
}

void Game::onEvent(sf::Event event) {

  switch (event.type){
    case sf::Event::Closed:
      playing = false; break;
    case sf::Event::KeyPressed:
      switch (event.key.code) {
        case sf::Keyboard::Q:
          playing = false; break;
        default:
          break;
      }
      break;
    default:
      break;
  }

  //mouse.onEvent(event);
  //keyboard.onEvent(event);

  //map_camera->onEvent(event);

  //if (event->type == SDL_USEREVENT) {
    //if (event->user.code == D2TM_SELECT) {
      //std::unique_ptr<D2TMSelectStruct> s(static_cast<D2TMSelectStruct*>(event->user.data1));

      //Point p = map_camera->toWorldCoordinates(s->screen_position);

      //if (mouse.is_pointing()) {
        //Unit* selected_unit = NULL;
        //for (auto& unit : units){
            //if (unit->is_point_within(p)){
                //selected_unit = unit.get();
                //break;
            //}

        //}
        //if (selected_unit != NULL) {
          //deselectAllUnits();
          //selected_unit->select();
          //mouse.state_order_move();
        //}
      //}
    //} else if (event->user.code == D2TM_DESELECT) {
      //mouse.state_pointing();
      //deselectAllUnits();
    //} else if (event->user.code == D2TM_BOX_SELECT) {
      //std::unique_ptr<D2TMBoxSelectStruct> s(static_cast<D2TMBoxSelectStruct*>(event->user.data1));

      //Rectangle rectangle = map_camera->toWorldCoordinates(s->rectangle);

      //if (mouse.is_pointing()) {
        //mouse.state_pointing();

        //deselectAllUnits();
        //for (auto& unit : units){
            //if (unit->is_within(rectangle)){
                //unit->select();
                //mouse.state_order_move();
            //}
        //}
      //}
    //} else if (event->user.code == D2TM_MOVE_UNIT) {
      //std::unique_ptr<D2TMMoveUnitStruct> s(static_cast<D2TMMoveUnitStruct*>(event->user.data1));
      //Point p = map_camera->toWorldCoordinates(s->screen_position);

      //for (auto& unit : units){
          //if (unit->is_selected())
              //unit->order_move(p);
      //}
    //}

  //}

}

void Game::render() {
  screen.clear();
  screen.draw(*map);
  map->drawShrouded(screen, sf::RenderStates::Default);

  //map_camera->draw(&map, terrain, screen);

  //for (auto& unit : units){
      //if (unit->is_on_ground_layer()) map_camera->draw(unit.get(), screen);
  //}
  //for (auto& unit : units){
      //if (unit->is_on_air_layer()) map_camera->draw(unit.get(), screen);
  //}

  //map_camera->drawShroud(&map, shroud_edges, shroud_edges_shadow, screen);

  //mouse.draw(screen);

  screen.display();
}

void Game::updateState() {
  static const float cameraSpeed = 10.f;
  float vec_x = 0.f, vec_y = 0.f;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) vec_y -= cameraSpeed;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) vec_y += cameraSpeed;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) vec_x -= cameraSpeed;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) vec_x += cameraSpeed;

  camera.move(vec_x, vec_y);
  screen.setView(camera);

  //keyboard.updateState();
  //mouse.updateState();
  //map_camera->updateState();

  //for (auto& unit: units){
      //unit->updateState();
  //}
}

//void Game::deselectAllUnits() {
    //for (auto& unit : units)
        //unit->unselect();
//}

//bool Game::playerHasUnits(const Player &player) const
//{
    //for (const auto& unit : units){
        //if (unit->getOwner()==player)
            //return true; //unit belonging to player found
    //}
    //return false;
//}

<commit_msg>added guard against uninit game<commit_after>#include <iostream>

#include <SFML/Graphics.hpp>
#include "game.h"

Game::Game():
    playing(true),
    screen(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close),
    map(nullptr)
    //map_camera(nullptr),
    //unitRepository(nullptr)
{
    screen.setFramerateLimit(60); //comment out for fps benchmarks

    if (!init()){
        std::cerr << "Failed to initialized game.";
        playing = false;
    }
}

int Game::execute() {

  while(playing) {
    sf::Event event;
    while(screen.pollEvent(event)) {
      onEvent(event);
    }

    updateState();
    render();
  }

  return 0;
}

bool Game::init() {
  if (!terrain.loadFromFile("graphics/terrain.png")) {
    std::cout << "Failed to read graphics/terrain.png data" << std::endl;
    return false;
  }

  sf::Image temp;
  if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
    std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
    return false;
  }

  temp.createMaskFromColor(sf::Color(255, 0, 255));
  shroud_edges.loadFromImage(temp);

  map.reset(new Map(terrain, shroud_edges));
  map->load("maps/4PL_Mountains.ini");

  camera.reset({0,0,800,600});
  screen.setView(camera);

  //shroud_edges = Surface::load("graphics/shroud_edges.bmp");

  //if (shroud_edges == NULL) {
    //cout << "Failed to read graphics/shroud_edges.bmp data" << endl;
    //return false;
  //}

  //shroud_edges_shadow = Surface::load("graphics/shroud_edges_shadow.bmp");

  //if (shroud_edges_shadow == NULL) {
    //cout << "Failed to read graphics/shroud_edges_shadow.bmp data" << endl;
    //return false;
  //}

  //mouse.init(screen);

  //map_camera.reset(new MapCamera(0, 0, screen, &map));
  //map.load("maps/4PL_Mountains.ini");
  //unitRepository.reset(new UnitRepository(&map));

  ////init two players
  //int idCount = 0;
  //players.emplace_back(House::Sardaukar, idCount++);
  //players.emplace_back(House::Harkonnen, idCount++);

  //units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));

  //// soldiers
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));

  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));
  //units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));

  return true;
}

void Game::onEvent(sf::Event event) {

  switch (event.type){
    case sf::Event::Closed:
      playing = false; break;
    case sf::Event::KeyPressed:
      switch (event.key.code) {
        case sf::Keyboard::Q:
          playing = false; break;
        default:
          break;
      }
      break;
    default:
      break;
  }

  //mouse.onEvent(event);
  //keyboard.onEvent(event);

  //map_camera->onEvent(event);

  //if (event->type == SDL_USEREVENT) {
    //if (event->user.code == D2TM_SELECT) {
      //std::unique_ptr<D2TMSelectStruct> s(static_cast<D2TMSelectStruct*>(event->user.data1));

      //Point p = map_camera->toWorldCoordinates(s->screen_position);

      //if (mouse.is_pointing()) {
        //Unit* selected_unit = NULL;
        //for (auto& unit : units){
            //if (unit->is_point_within(p)){
                //selected_unit = unit.get();
                //break;
            //}

        //}
        //if (selected_unit != NULL) {
          //deselectAllUnits();
          //selected_unit->select();
          //mouse.state_order_move();
        //}
      //}
    //} else if (event->user.code == D2TM_DESELECT) {
      //mouse.state_pointing();
      //deselectAllUnits();
    //} else if (event->user.code == D2TM_BOX_SELECT) {
      //std::unique_ptr<D2TMBoxSelectStruct> s(static_cast<D2TMBoxSelectStruct*>(event->user.data1));

      //Rectangle rectangle = map_camera->toWorldCoordinates(s->rectangle);

      //if (mouse.is_pointing()) {
        //mouse.state_pointing();

        //deselectAllUnits();
        //for (auto& unit : units){
            //if (unit->is_within(rectangle)){
                //unit->select();
                //mouse.state_order_move();
            //}
        //}
      //}
    //} else if (event->user.code == D2TM_MOVE_UNIT) {
      //std::unique_ptr<D2TMMoveUnitStruct> s(static_cast<D2TMMoveUnitStruct*>(event->user.data1));
      //Point p = map_camera->toWorldCoordinates(s->screen_position);

      //for (auto& unit : units){
          //if (unit->is_selected())
              //unit->order_move(p);
      //}
    //}

  //}

}

void Game::render() {
  screen.clear();
  screen.draw(*map);
  map->drawShrouded(screen, sf::RenderStates::Default);

  //map_camera->draw(&map, terrain, screen);

  //for (auto& unit : units){
      //if (unit->is_on_ground_layer()) map_camera->draw(unit.get(), screen);
  //}
  //for (auto& unit : units){
      //if (unit->is_on_air_layer()) map_camera->draw(unit.get(), screen);
  //}

  //map_camera->drawShroud(&map, shroud_edges, shroud_edges_shadow, screen);

  //mouse.draw(screen);

  screen.display();
}

void Game::updateState() {
  static const float cameraSpeed = 10.f;
  float vec_x = 0.f, vec_y = 0.f;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) vec_y -= cameraSpeed;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) vec_y += cameraSpeed;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) vec_x -= cameraSpeed;
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) vec_x += cameraSpeed;

  camera.move(vec_x, vec_y);
  screen.setView(camera);

  //keyboard.updateState();
  //mouse.updateState();
  //map_camera->updateState();

  //for (auto& unit: units){
      //unit->updateState();
  //}
}

//void Game::deselectAllUnits() {
    //for (auto& unit : units)
        //unit->unselect();
//}

//bool Game::playerHasUnits(const Player &player) const
//{
    //for (const auto& unit : units){
        //if (unit->getOwner()==player)
            //return true; //unit belonging to player found
    //}
    //return false;
//}

<|endoftext|>


<commit_before>// $Id: surface.C,v 1.7 2000/06/30 06:02:13 oliver Exp $

#include <BALL/MATHS/surface.h>

using namespace std;

namespace BALL
{

	Surface::Surface()
		:	valid_(false)
	{
	}

	Surface::Surface(const Surface& surface)
		:	vertex(surface.vertex),
			normal(surface.normal),
			triangle(surface.triangle),
			valid_(surface.valid_)
	{
	}

	Surface::~Surface()
	{
		valid_ = false;
	}

	void Surface::clear()
	{
		valid_ = true;
		vertex.clear();
		normal.clear();
		triangle.clear();
	}

	void Surface::destroy()
	{
		clear();
	}

	void Surface::set(const Surface& surface)
	{
		vertex = surface.vertex;
		normal = surface.normal;
		triangle = surface.triangle;
		valid_ = surface.valid_;
	}

	void Surface::get(Surface& surface) const
	{
		surface.vertex = vertex;
		surface.normal = normal;
		surface.triangle = triangle;
		surface.valid_ = valid_;
	}

	void Surface::readMSMSFile
		(const String& vert_filename, const String& face_filename)
	{
		// delete old contents
		normal.clear();
		vertex.clear();
		triangle.clear();

		ifstream file(vert_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, vert_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		String line;
		while ((line.countFields() != 9) && file)
		{
			line.getline(file);
		}

		String s[6];
		while (file && (line.countFields() == 9))
		{
			// read the vertex coordinates and the normal vector
			line.split(s, 6);
			vertex.push_back(Vector3(s[0].toFloat(), s[1].toFloat(), s[2].toFloat()));
			normal.push_back(Vector3(s[3].toFloat(), s[4].toFloat(), s[5].toFloat()));

			// read the next line
			line.getline(file);
		}
		file.close();
		// workaround for trouble in File
		file.clear();

		// now read the faces file:
		file.open(face_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, face_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		while ((line.countFields() != 5) && file)
		{
			line.getline(file);
		}

		Triangle t;
		Size number_of_vertices = vertex.size();
		while (file && (line.countFields() == 5))
		{
			// read the vertex indices
			line.split(s, 5);
			t.v1 = (Index)s[0].toInt() - 1;
			t.v2 = (Index)s[1].toInt() - 1;
			t.v3 = (Index)s[2].toInt() - 1;

			// if all three vertex indices are valid, insert the triangle
			if ((t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0))
			{
				triangle.push_back(t);
			}

			// read the next line
			line.getline(file);
		}
		file.close();
	}

	float Surface::getArea() const
	{
		float area = 0;
		// add the areas of all triangles
		for (Size i = 0; i < triangle.size(); i++)
		{
			//Vector3 v1 = vertex[triangle[i].v1];
			//Vector3 v2 = vertex[triangle[i].v2];
			//Vector3 v3 = vertex[triangle[i].v3];

			// projection of v3 onto v1-v2
			//Vector3	v4 =
			// BAUSTELLE
		}

		return area;
	}

	bool Surface::isValid() const
	{
		return valid_;
	}

} // namespace BALL
<commit_msg>fixed: operator = () is now implemented<commit_after>// $Id: surface.C,v 1.8 2000/08/03 12:24:52 anker Exp $

#include <BALL/MATHS/surface.h>

using namespace std;

namespace BALL
{

	Surface::Surface()
		:	valid_(false)
	{
	}

	Surface::Surface(const Surface& surface)
		:	vertex(surface.vertex),
			normal(surface.normal),
			triangle(surface.triangle),
			valid_(surface.valid_)
	{
	}

	Surface::~Surface()
	{
		valid_ = false;
	}

	void Surface::clear()
	{
		valid_ = true;
		vertex.clear();
		normal.clear();
		triangle.clear();
	}

	void Surface::destroy()
	{
		clear();
	}

	void Surface::set(const Surface& surface)
	{
		vertex = surface.vertex;
		normal = surface.normal;
		triangle = surface.triangle;
		valid_ = surface.valid_;
	}

	const Surface& Surface::operator = (const Surface& surface)
	{
		vertex = surface.vertex;
		normal = surface.normal;
		triangle = surface.triangle;
		valid_ = surface.valid_;
		return *this;
	}

	void Surface::get(Surface& surface) const
	{
		surface.vertex = vertex;
		surface.normal = normal;
		surface.triangle = triangle;
		surface.valid_ = valid_;
	}

	void Surface::readMSMSFile
		(const String& vert_filename, const String& face_filename)
	{
		// delete old contents
		normal.clear();
		vertex.clear();
		triangle.clear();

		ifstream file(vert_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, vert_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		String line;
		while ((line.countFields() != 9) && file)
		{
			line.getline(file);
		}

		String s[6];
		while (file && (line.countFields() == 9))
		{
			// read the vertex coordinates and the normal vector
			line.split(s, 6);
			vertex.push_back(Vector3(s[0].toFloat(), s[1].toFloat(), s[2].toFloat()));
			normal.push_back(Vector3(s[3].toFloat(), s[4].toFloat(), s[5].toFloat()));

			// read the next line
			line.getline(file);
		}
		file.close();
		// workaround for trouble in File
		file.clear();

		// now read the faces file:
		file.open(face_filename.c_str());
		if (!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, face_filename);
		}

		// there are two formats: one with three lines of
		// header and one without
		while ((line.countFields() != 5) && file)
		{
			line.getline(file);
		}

		Triangle t;
		Size number_of_vertices = vertex.size();
		while (file && (line.countFields() == 5))
		{
			// read the vertex indices
			line.split(s, 5);
			t.v1 = (Index)s[0].toInt() - 1;
			t.v2 = (Index)s[1].toInt() - 1;
			t.v3 = (Index)s[2].toInt() - 1;

			// if all three vertex indices are valid, insert the triangle
			if ((t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0)
					&& (t.v1 < (Index)number_of_vertices) && (t.v1 >= 0))
			{
				triangle.push_back(t);
			}

			// read the next line
			line.getline(file);
		}
		file.close();
	}

	float Surface::getArea() const
	{
		float area = 0;
		// add the areas of all triangles
		for (Size i = 0; i < triangle.size(); i++)
		{
			//Vector3 v1 = vertex[triangle[i].v1];
			//Vector3 v2 = vertex[triangle[i].v2];
			//Vector3 v3 = vertex[triangle[i].v3];

			// projection of v3 onto v1-v2
			//Vector3	v4 =
			// BAUSTELLE
		}

		return area;
	}

	bool Surface::isValid() const
	{
		return valid_;
	}

} // namespace BALL
<|endoftext|>


<commit_before><commit_msg>got nnlocalizer working<commit_after><|endoftext|>


<commit_before>#ifndef PARABOLIC_RHS_ASSEMBLER_HH
#define PARABOLIC_RHS_ASSEMBLER_HH

namespace Dune {

/**
 * build the right hand side for a discrete parabolic problem that is solved with backward Euler:
     Note that in comparison to the elliptic case:
     1. f needs to be muliplied with the time step size and
     2. the solution u_H^{(k)} of the preceeding time step needs to be added to the right hand side

     Wir haben die rechte Seite = f, wollen darauf aber noch eine discrete Function aufaddieren, die wir discFuncToAdd
     nennen.
     am Ende soll also nicht nur die rechte Seite durch f gebildet werden, sondern durch f+discFuncToAdd
     der Wert wird in discreteFunction gespeichert
     add discreteFunction is an output parameter (kind of return value)
     \todo nothing here is ever instantiated...
 */
template< class DiscreteFunctionImp >
class ParambolicRightHandSideAssembler{
template< int polOrd, class FirstSourceTypeType >
void assembleParabolic(const FirstSourceTypeType& f,
                       const RangeType& time_step_size,
                       const DiscreteFunctionType& u_H_k,
                       DiscreteFunctionType& rhsVector) const {
  // rhsVector is the vector that occurs on the right hand side of the linear system of equations that is to solve
  const DiscreteFunctionSpaceType& discreteFunctionSpace
    = rhsVector.space();

  // set rhs to zero:
  rhsVector.clear();

  const IteratorType endit = discreteFunctionSpace.end();
  for (IteratorType it = discreteFunctionSpace.begin(); it != endit; ++it)
  {
    // it* Pointer auf ein Element der Entity
    const GeometryType& geometry = (*it).geometry(); // Referenz auf Geometrie
    LocalFunctionType elementOfRHS = rhsVector.localFunction(*it);
    LocalFunctionType elementOf_u_H_k = u_H_k.localFunction(*it);

    const BaseFunctionSetType baseSet // BaseFunctions leben immer auf Refernzelement!!!
      = discreteFunctionSpace.baseFunctionSet(*it);

    const CachingQuadrature< GridPartType, 0 > quadrature(*it, polOrd);   // 0 --> codim 0

    const int numDofs = elementOfRHS.numDofs(); // Dofs = Freiheitsgrade (also die Unbekannten)
    for (int i = 0; i < numDofs; ++i)  // Laufe ueber alle Knoten des entity-elements auf dem wir uns befinden
    {
      // the return values:
      RangeType f_x, phi_x;

      JacobianRangeType gradientPhi;

      const int numQuadraturePoints = quadrature.nop();
      for (int quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint)
      {
        const double det
          = geometry.integrationElement( quadrature.point(quadraturePoint) );

        // evaluate the Right Hand Side Function f at the current quadrature point and save its value in 'f_x':
        f.evaluate(geometry.global( quadrature.point(quadraturePoint) ), f_x);

        // evaluate the current base function at the current quadrature point and save its value in 'phi_x':
        baseSet.evaluate(i, quadrature[quadraturePoint], phi_x);   // i = i'te Basisfunktion;

        // evaluate the gradient of the current base function at the current quadrature point and save its value in
        // 'returnGradient':
        baseSet.jacobian(i, quadrature[quadraturePoint], gradientPhi);
        // Bis jetzt nur der Gradient auf dem Referenzelement!!!!!!! Es muss noch transformiert werden, um den
        // Gradienten auf dem echten Element zu bekommen! Das passiert folgendermassen:

        const FieldMatrix< double, dimension, dimension >& inv
          = geometry.jacobianInverseTransposed( quadrature.point(quadraturePoint) );

        // multiply with transpose of jacobian inverse
        gradientPhi[0] = FMatrixHelp::mult(inv, gradientPhi[0]);

        // value of u_H_k:
        RangeType val_to_add;
        elementOf_u_H_k.evaluate(quadrature, quadraturePoint, val_to_add);

        elementOfRHS[i] += time_step_size * det * quadrature.weight(quadraturePoint) * (f_x * phi_x);

        // add the local value of discFuncToAdd to the right hand side
        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * val_to_add * phi_x;
      }
    }
  }
}  // end method

template< int polOrd, class FirstSourceTypeType >
void assembleParabolic(const FirstSourceTypeType& f,
                       const TimeType& t,
                       const RangeType& time_step_size,
                       const DiscreteFunctionType& u_H_k,
                       DiscreteFunctionType& rhsVector) const {
  const DiscreteFunctionSpaceType& discreteFunctionSpace
    = rhsVector.space();

  // set rhs to zero:
  rhsVector.clear();

  const IteratorType endit = discreteFunctionSpace.end();
  for (IteratorType it = discreteFunctionSpace.begin(); it != endit; ++it)
  {
    // it* Pointer auf ein Element der Entity
    const GeometryType& geometry = (*it).geometry(); // Referenz auf Geometrie

    LocalFunctionType elementOfRHS = rhsVector.localFunction(*it);
    const LocalFunctionType elementOf_u_H_k = u_H_k.localFunction(*it);

    const BaseFunctionSetType baseSet // BaseFunctions leben immer auf Refernzelement!!!
      = discreteFunctionSpace.baseFunctionSet(*it);
    const CachingQuadrature< GridPartType, 0 > quadrature(*it, polOrd);   // 0 --> codim 0

    const int numDofs = elementOfRHS.numDofs(); // Dofs = Freiheitsgrade (also die Unbekannten)
    for (int i = 0; i < numDofs; ++i)  // Laufe ueber alle Knoten des entity-elements auf dem wir uns befinden
    {
      // the return values:
      RangeType f_x, phi_x;

      JacobianRangeType gradientPhi;

      const int numQuadraturePoints = quadrature.nop();
      for (int quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint)
      {
        const double det
          = geometry.integrationElement( quadrature.point(quadraturePoint) );

        // evaluate the Right Hand Side Function f at the current quadrature point and save its value in 'f_x':
        f.evaluate(geometry.global( quadrature.point(quadraturePoint) ), t, f_x);

        // evaluate the current base function at the current quadrature point and save its value in 'phi_x':
        baseSet.evaluate(i, quadrature[quadraturePoint], phi_x);   // i = i'te Basisfunktion;

        // evaluate the gradient of the current base function at the current quadrature point and save its value in
        // 'returnGradient':
        baseSet.jacobian(i, quadrature[quadraturePoint], gradientPhi);
        // Bis jetzt nur der Gradient auf dem Referenzelement!!!!!!! Es muss noch transformiert werden, um den
        // Gradienten auf dem echten Element zu bekommen! Das passiert folgendermassen:

        const FieldMatrix< double, dimension, dimension >& inv
          = geometry.jacobianInverseTransposed( quadrature.point(quadraturePoint) );

        // multiply with transpose of jacobian inverse
        gradientPhi[0] = FMatrixHelp::mult(inv, gradientPhi[0]);

        // value of u_H_k:
        RangeType val_to_add;
        elementOf_u_H_k.evaluate(quadrature, quadraturePoint, val_to_add);

        elementOfRHS[i] += time_step_size * det * quadrature.weight(quadraturePoint) * (f_x * phi_x);

        // add the local value of discFuncToAdd to the right hand side
        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * val_to_add * phi_x;
      }
    }
  }
}  // end method

template< int polOrd, class FirstSourceTypeType, class SecondSourceType >
void assembleParabolic(const FirstSourceTypeType& f,
                       const SecondSourceType& G,
                       const RangeType& time_step_size,
                       const DiscreteFunctionType& u_H_k,
                       DiscreteFunctionType& rhsVector) const {
  const DiscreteFunctionSpaceType& discreteFunctionSpace
    = rhsVector.space();

  // set rhs to zero:
  rhsVector.clear();

  const IteratorType endit = discreteFunctionSpace.end();
  for (IteratorType it = discreteFunctionSpace.begin(); it != endit; ++it)
  {
    // it* Pointer auf ein Element der Entity
    const GeometryType& geometry = (*it).geometry(); // Referenz auf Geometrie

    LocalFunctionType elementOfRHS = rhsVector.localFunction(*it);
    const LocalFunctionType elementOf_u_H_k = u_H_k.localFunction(*it);

    const BaseFunctionSetType baseSet // BaseFunctions leben immer auf Refernzelement!!!
      = discreteFunctionSpace.baseFunctionSet(*it);
    const CachingQuadrature< GridPartType, 0 > quadrature(*it, polOrd);   // 0 --> codim 0

    const int numDofs = elementOfRHS.numDofs(); // Dofs = Freiheitsgrade (also die Unbekannten)
    for (int i = 0; i < numDofs; ++i)  // Laufe ueber alle Knoten des entity-elements auf dem wir uns befinden
    {
      // the return values:
      RangeType f_x, phi_x;

      RangeType a[dimension][dimension];

      JacobianRangeType gradientPhi;

      // to save: A \nabla PHI_H
      RangeType G_x[dimension];

      // to save: G \cdot \nabla phi_H
      RangeType val = 0;

      const int numQuadraturePoints = quadrature.nop();
      for (int quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint)
      {
        const double det
          = geometry.integrationElement( quadrature.point(quadraturePoint) );

        // evaluate the Right Hand Side Function f at the current quadrature point and save its value in 'f_x':
        f.evaluate(geometry.global( quadrature.point(quadraturePoint) ), f_x);

        // evaluate the current base function at the current quadrature point and save its value in 'phi_x':
        baseSet.evaluate(i, quadrature[quadraturePoint], phi_x);   // i = i'te Basisfunktion;

        // evaluate the gradient of the current base function at the current quadrature point and save its value in
        // 'returnGradient':
        baseSet.jacobian(i, quadrature[quadraturePoint], gradientPhi);
        // Bis jetzt nur der Gradient auf dem Referenzelement!!!!!!! Es muss noch transformiert werden, um den
        // Gradienten auf dem echten Element zu bekommen! Das passiert folgendermassen:

        const FieldMatrix< double, dimension, dimension >& inv
          = geometry.jacobianInverseTransposed( quadrature.point(quadraturePoint) );

        // multiply with transpose of jacobian inverse
        gradientPhi[0] = FMatrixHelp::mult(inv, gradientPhi[0]);

        // set all entries of G_x to zero to delete old data of a former loop cycle
        for (int k = 0; k < dimension; ++k)
        {
          G_x[k] = 0;
        }

        // the same for val:
        val = 0;

        // evaluate the gradient of Phi_H at the current quadrature point and save its value in 'G_x':
        for (int k = 0; k < dimension; ++k)
        {
          G.evaluate(k, geometry.global( quadrature.point(quadraturePoint) ), G_x[k]);
        }

        for (int k = 0; k < dimension; ++k)
        {
          val += G_x[k] * gradientPhi[0][k];
        }

        // value of u_H_k:
        RangeType val_to_add;
        elementOf_u_H_k.evaluate(quadrature, quadraturePoint, val_to_add);

        elementOfRHS[i] += time_step_size * det * quadrature.weight(quadraturePoint) * (f_x * phi_x);

        // add the local value of discFuncToAdd to the right hand side
        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * val_to_add * phi_x;

        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * val;
      }
    }
  }
}  // end method

template< int polOrd, class FirstSourceTypeType, class SecondSourceType >
void assembleParabolic(const FirstSourceTypeType& f,
                       const SecondSourceType& G,
                       const TimeType& t,
                       const RangeType& time_step_size,
                       const DiscreteFunctionType& u_H_k,
                       DiscreteFunctionType& rhsVector) const {
  const DiscreteFunctionSpaceType& discreteFunctionSpace
    = rhsVector.space();

  // set rhs to zero:
  rhsVector.clear();

  const IteratorType endit = discreteFunctionSpace.end();
  for (IteratorType it = discreteFunctionSpace.begin(); it != endit; ++it)
  {
    // it* Pointer auf ein Element der Entity
    const GeometryType& geometry = (*it).geometry(); // Referenz auf Geometrie

    LocalFunctionType elementOfRHS = rhsVector.localFunction(*it);
    const LocalFunctionType elementOf_u_H_k = u_H_k.localFunction(*it);

    const BaseFunctionSetType baseSet // BaseFunctions leben immer auf Refernzelement!!!
      = discreteFunctionSpace.baseFunctionSet(*it);
    const CachingQuadrature< GridPartType, 0 > quadrature(*it, polOrd);   // 0 --> codim 0

    const int numDofs = elementOfRHS.numDofs(); // Dofs = Freiheitsgrade (also die Unbekannten)
    for (int i = 0; i < numDofs; ++i)  // Laufe ueber alle Knoten des entity-elements auf dem wir uns befinden
    {
      // the return values:
      RangeType f_x, phi_x;

      RangeType a[dimension][dimension];

      JacobianRangeType gradientPhi;

      // to save: A \nabla PHI_H
      RangeType G_x[dimension];

      // to save: G \cdot \nabla phi_H
      RangeType val = 0;

      const int numQuadraturePoints = quadrature.nop();
      for (int quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint)
      {
        const double det
          = geometry.integrationElement( quadrature.point(quadraturePoint) );

        // evaluate the Right Hand Side Function f at the current quadrature point and save its value in 'f_x':
        f.evaluate(geometry.global( quadrature.point(quadraturePoint) ), t, f_x);

        // evaluate the current base function at the current quadrature point and save its value in 'phi_x':
        baseSet.evaluate(i, quadrature[quadraturePoint], phi_x);   // i = i'te Basisfunktion;

        // evaluate the gradient of the current base function at the current quadrature point and save its value in
        // 'returnGradient':
        baseSet.jacobian(i, quadrature[quadraturePoint], gradientPhi);
        // Bis jetzt nur der Gradient auf dem Referenzelement!!!!!!! Es muss noch transformiert werden, um den
        // Gradienten auf dem echten Element zu bekommen! Das passiert folgendermassen:

        const FieldMatrix< double, dimension, dimension >& inv
          = geometry.jacobianInverseTransposed( quadrature.point(quadraturePoint) );

        // multiply with transpose of jacobian inverse
        gradientPhi[0] = FMatrixHelp::mult(inv, gradientPhi[0]);

        val = 0;
        for (int k = 0; k < dimension; ++k)
        {
          G_x[k] = 0;
          G.evaluate(k, geometry.global( quadrature.point(quadraturePoint) ), t, G_x[k]);
          val += G_x[k] * gradientPhi[0][k];
        }

        // value of u_H_k:
        RangeType val_to_add;
        elementOf_u_H_k.evaluate(quadrature, quadraturePoint, val_to_add);

        elementOfRHS[i] += time_step_size * det * quadrature.weight(quadraturePoint) * (f_x * phi_x);

        // add the local value of discFuncToAdd to the right hand side
        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * val_to_add * phi_x;

        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * val;
      }
    }
  }
}  // end method

template< int polOrd, class FirstSourceType, class InitialValueType >
void assembleParabolic(const FirstSourceType& f,
                       const RangeType& time_step_size,
                       const InitialValueType& v_0,
                       DiscreteFunctionType& rhsVector) const {
  // rhsVector is the vector that occurs on the right hand side of the linear system of equations that is to solve
  // rhs ist der Rueckgabewert der funktion 'assemble'. Hierin wird sozusagen die rechte Seite gespeichert
  const DiscreteFunctionSpaceType& discreteFunctionSpace
    = rhsVector.space();

  // set rhs to zero:
  rhsVector.clear();

  const IteratorType endit = discreteFunctionSpace.end();
  for (IteratorType it = discreteFunctionSpace.begin(); it != endit; ++it)
  {
    const GeometryType& geometry = (*it).geometry(); // Referenz auf Geometrie
    LocalFunctionType elementOfRHS = rhsVector.localFunction(*it);
    const BaseFunctionSetType baseSet // BaseFunctions leben immer auf Refernzelement!!!
      = discreteFunctionSpace.baseFunctionSet(*it);
    const CachingQuadrature< GridPartType, 0 > quadrature(*it, polOrd);   // 0 --> codim 0

    const int numDofs = elementOfRHS.numDofs(); // Dofs = Freiheitsgrade (also die Unbekannten)
    for (int i = 0; i < numDofs; ++i)  // Laufe ueber alle Knoten des entity-elements auf dem wir uns befinden
    {
      // the return values:
      RangeType f_x, v_0_x, phi_x;

      JacobianRangeType gradientPhi;

      const int numQuadraturePoints = quadrature.nop();
      for (int quadraturePoint = 0; quadraturePoint < numQuadraturePoints; ++quadraturePoint)
      {
        const double det
          = geometry.integrationElement( quadrature.point(quadraturePoint) );

        // evaluate the Right Hand Side Function f at the current quadrature point and save its value in 'f_x':
        f.evaluate(geometry.global( quadrature.point(quadraturePoint) ), 0.0, f_x);      // t = 0.0

        // evaluate the Initial Value v_0 at the current quadrature point and save its value in 'v_0_x':
        v_0.evaluate(geometry.global( quadrature.point(quadraturePoint) ), v_0_x);

        // evaluate the current base function at the current quadrature point and save its value in 'phi_x':
        baseSet.evaluate(i, quadrature[quadraturePoint], phi_x);   // i = i'te Basisfunktion;

        // evaluate the gradient of the current base function at the current quadrature point and save its value in
        // 'returnGradient':
        baseSet.jacobian(i, quadrature[quadraturePoint], gradientPhi);
        // Bis jetzt nur der Gradient auf dem Referenzelement!!!!!!! Es muss noch transformiert werden, um den
        // Gradienten auf dem echten Element zu bekommen! Das passiert folgendermassen:

        const FieldMatrix< double, dimension, dimension >& inv
          = geometry.jacobianInverseTransposed( quadrature.point(quadraturePoint) );

        // multiply with transpose of jacobian inverse
        gradientPhi[0] = FMatrixHelp::mult(inv, gradientPhi[0]);

        elementOfRHS[i] += time_step_size * det * quadrature.weight(quadraturePoint) * (f_x * phi_x);

        // add the local initial value to the right hand side
        elementOfRHS[i] += det * quadrature.weight(quadraturePoint) * v_0_x * phi_x;
      }
    }
  }
}  // end method
};
#endif // PARABOLIC_RHS_ASSEMBLER_HH
<commit_msg>removes never used parabolic_rhs_assembler.hh<commit_after><|endoftext|>