<commit_before>#include "sherwood_mex.h"

#if USE_OPENMP == 1
#include <omp.h>
#endif

using namespace MicrosoftResearch::Cambridge::Sherwood;

template<typename F>
class FeatureFactory: public IFeatureResponseFactory<F>
{
public:

  FeatureFactory(unsigned int dimensions, std::vector<Stats> featureStats)
  : dimensions(dimensions), featureStats(featureStats)
  {};

  F CreateRandom(Random& random)
  {
    return F::CreateRandom(random, dimensions, featureStats);
  }
private:
  unsigned int dimensions;
  std::vector<Stats> featureStats;
};

// F: Feature Response
// S: StatisticsAggregator
template<typename F, typename S>
void sherwood_train(int nlhs, 		    /* number of expected outputs */
        mxArray        *plhs[],	    /* mxArray output pointer array */
        int            nrhs, 		/* number of inputs */
        const mxArray  *prhs[],		/* mxArray input pointer array */
				Options options)
{
	unsigned int curarg = 0;

	// Features along rows
	// Examples along columns
	const matrix<float> features = prhs[curarg++];
	const matrix<unsigned char> labels 	= prhs[curarg++];

  // Supervised classification
  TrainingParameters trainingParameters;
  trainingParameters.MaxDecisionLevels = options.MaxDecisionLevels;
  trainingParameters.NumberOfCandidateFeatures = options.NumberOfCandidateFeatures;
  trainingParameters.NumberOfCandidateThresholdsPerFeature = options.NumberOfCandidateThresholdsPerFeature;
  trainingParameters.NumberOfTrees = options.NumberOfTrees;
  trainingParameters.Verbose = false;

	// Point class
	DataPointCollection trainingData(features,labels);

	if (options.Verbose) {
		mexPrintf("Training data has: %d features %d classes and %d examples.\n",
              trainingData.Dimensions(), trainingData.CountClasses(), trainingData.Count());
  }

  Random random;

  // The range for each feature
  std::vector<Stats> featureStats;
  featureStats.reserve(trainingData.Dimensions());

  if (!options.FeatureScaling) {
     mexPrintf("No feature scaling is performed: make sure your features are scaled. \n");
  } else {
    for (unsigned int d = 0; d < trainingData.Dimensions(); ++d) {
      featureStats.push_back(trainingData.GetStats(d));

      if (options.Verbose) {
        mexPrintf("Feature: %d mean: %f stdev: %f. \n", d, featureStats[d].mean, featureStats[d].stdev);
      }
    }
  }

  FeatureFactory<F> featureFactory(trainingData.Dimensions(), featureStats);

	ClassificationTrainingContext<F>
		classificationContext(trainingData.CountClasses(), &featureFactory);

  // Without OPENMP no multi threading.
  #if USE_OPENMP == 0
    if (options.MaxThreads > 1) {
      mexPrintf("Compiled without OpenMP flags, falling back to single thread code.\n");
    }

    options.MaxThreads = 1;
  #endif

  std::auto_ptr<Forest<F, S> > forest ;

	// Create forest
  if (options.MaxThreads == 1)
  {
    ProgressStream progressStream(std::cout, Silent);

    mexPrintf("Using 1 thread.\n");

    forest = ForestTrainer<F, S>::TrainForest
    (random, trainingParameters, classificationContext, trainingData, &progressStream );
  }

  // Parallel
  // ParallelForestTrainer.h segfaults using gcc.
  else
  {
    #if USE_OPENMP == 1
      omp_set_num_threads(options.MaxThreads);

      unsigned int current_num_threads = 0;
      if (options.Verbose)
      {
        int current_num_threads;

        #pragma omp parallel
          current_num_threads = omp_get_num_threads();

        mexPrintf("Using OpenMP with %d threads (maximum %d) \n ",current_num_threads,omp_get_max_threads());
      }

      forest = std::auto_ptr<Forest<F,S> >(new Forest<F,S>());

      omp_lock_t writelock;
      omp_init_lock(&writelock);

      #pragma omp parallel for
      for (int t = 0; t < trainingParameters.NumberOfTrees; t++)
      {
        std::auto_ptr<Tree<F,S> > tree = TreeTrainer<F,S>::TrainTree(random,
            classificationContext, trainingParameters, trainingData);

        omp_set_lock(&writelock);
        forest->AddTree(tree);
        omp_unset_lock(&writelock);
      }

      omp_destroy_lock(&writelock);

    #endif
  }

  // Saving the forest
  std::ofstream o(options.ForestName.c_str(), std::ios_base::binary);
	forest->Serialize(o);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray  *prhs[])
{
	MexParams params(1, prhs+2);
	Options options(params);

  if (!options.WeakLearner.compare("axis-aligned-hyperplane") && !options.FeatureScaling)
    sherwood_train<AxisAlignedFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if  (!options.WeakLearner.compare("axis-aligned-hyperplane") && options.FeatureScaling)
    sherwood_train<AxisAlignedFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if (!options.WeakLearner.compare("random-hyperplane") && !options.FeatureScaling)
    sherwood_train<RandomHyperplaneFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if (!options.WeakLearner.compare("random-hyperplane") && options.FeatureScaling)
    sherwood_train<RandomHyperplaneFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else
   mexErrMsgTxt("Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane");
}<commit_msg>Suppressing some output.<commit_after>#include "sherwood_mex.h"

#if USE_OPENMP == 1
#include <omp.h>
#endif

using namespace MicrosoftResearch::Cambridge::Sherwood;

template<typename F>
class FeatureFactory: public IFeatureResponseFactory<F>
{
public:

  FeatureFactory(unsigned int dimensions, std::vector<Stats> featureStats)
  : dimensions(dimensions), featureStats(featureStats)
  {};

  F CreateRandom(Random& random)
  {
    return F::CreateRandom(random, dimensions, featureStats);
  }
private:
  unsigned int dimensions;
  std::vector<Stats> featureStats;
};

// F: Feature Response
// S: StatisticsAggregator
template<typename F, typename S>
void sherwood_train(int nlhs, 		    /* number of expected outputs */
        mxArray        *plhs[],	    /* mxArray output pointer array */
        int            nrhs, 		/* number of inputs */
        const mxArray  *prhs[],		/* mxArray input pointer array */
				Options options)
{
	unsigned int curarg = 0;

	// Features along rows
	// Examples along columns
	const matrix<float> features = prhs[curarg++];
	const matrix<unsigned char> labels 	= prhs[curarg++];

  // Supervised classification
  TrainingParameters trainingParameters;
  trainingParameters.MaxDecisionLevels = options.MaxDecisionLevels;
  trainingParameters.NumberOfCandidateFeatures = options.NumberOfCandidateFeatures;
  trainingParameters.NumberOfCandidateThresholdsPerFeature = options.NumberOfCandidateThresholdsPerFeature;
  trainingParameters.NumberOfTrees = options.NumberOfTrees;
  trainingParameters.Verbose = false;

	// Point class
	DataPointCollection trainingData(features,labels);

	if (options.Verbose) {
		mexPrintf("Training data has: %d features %d classes and %d examples.\n",
              trainingData.Dimensions(), trainingData.CountClasses(), trainingData.Count());
  }

  Random random;

  // The range for each feature
  std::vector<Stats> featureStats;
  featureStats.reserve(trainingData.Dimensions());

  if (!options.FeatureScaling) {

    if (options.Verbose) {
      mexPrintf("No feature scaling is performed: make sure your features are scaled. \n");
    }

  } else {
    for (unsigned int d = 0; d < trainingData.Dimensions(); ++d) {
      featureStats.push_back(trainingData.GetStats(d));

      if (options.Verbose) {
        mexPrintf("Feature: %d mean: %f stdev: %f. \n", d, featureStats[d].mean, featureStats[d].stdev);
      }
    }
  }

  FeatureFactory<F> featureFactory(trainingData.Dimensions(), featureStats);

	ClassificationTrainingContext<F>
		classificationContext(trainingData.CountClasses(), &featureFactory);

  // Without OPENMP no multi threading.
  #if USE_OPENMP == 0
    if (options.MaxThreads > 1) {
      mexPrintf("Compiled without OpenMP flags, falling back to single thread code.\n");
    }

    options.MaxThreads = 1;
  #endif

  std::auto_ptr<Forest<F, S> > forest ;

	// Create forest
  if (options.MaxThreads == 1)
  {
    ProgressStream progressStream(std::cout, Silent);

    mexPrintf("Using 1 thread.\n");

    forest = ForestTrainer<F, S>::TrainForest
    (random, trainingParameters, classificationContext, trainingData, &progressStream );
  }

  // Parallel
  // ParallelForestTrainer.h segfaults using gcc.
  else
  {
    #if USE_OPENMP == 1
      omp_set_num_threads(options.MaxThreads);

      unsigned int current_num_threads = 0;
      if (options.Verbose)
      {
        int current_num_threads;

        #pragma omp parallel
          current_num_threads = omp_get_num_threads();

        mexPrintf("Using OpenMP with %d threads (maximum %d) \n ",current_num_threads,omp_get_max_threads());
      }

      forest = std::auto_ptr<Forest<F,S> >(new Forest<F,S>());

      omp_lock_t writelock;
      omp_init_lock(&writelock);

      #pragma omp parallel for
      for (int t = 0; t < trainingParameters.NumberOfTrees; t++)
      {
        std::auto_ptr<Tree<F,S> > tree = TreeTrainer<F,S>::TrainTree(random,
            classificationContext, trainingParameters, trainingData);

        omp_set_lock(&writelock);
        forest->AddTree(tree);
        omp_unset_lock(&writelock);
      }

      omp_destroy_lock(&writelock);

    #endif
  }

  // Saving the forest
  std::ofstream o(options.ForestName.c_str(), std::ios_base::binary);
	forest->Serialize(o);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray  *prhs[])
{
	MexParams params(1, prhs+2);
	Options options(params);

  if (!options.WeakLearner.compare("axis-aligned-hyperplane") && !options.FeatureScaling)
    sherwood_train<AxisAlignedFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if  (!options.WeakLearner.compare("axis-aligned-hyperplane") && options.FeatureScaling)
    sherwood_train<AxisAlignedFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if (!options.WeakLearner.compare("random-hyperplane") && !options.FeatureScaling)
    sherwood_train<RandomHyperplaneFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if (!options.WeakLearner.compare("random-hyperplane") && options.FeatureScaling)
    sherwood_train<RandomHyperplaneFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else
   mexErrMsgTxt("Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane");
}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_SVX_SDRPAINTWINDOW_HXX
#define INCLUDED_SVX_SDRPAINTWINDOW_HXX

#include <rtl/ref.hxx>
#include <vcl/virdev.hxx>
#include <svx/svxdllapi.h>

class SdrPaintView;

namespace sdr
{
    namespace overlay
    {
        class OverlayManager;
    }
}

#ifdef _MSC_VER // broken msvc template instantiation
#include <svx/sdr/overlay/overlaymanager.hxx>
#endif

/// paint the transparent children of rWin that overlap rPixelRect
/// (for example, transparent form controls like check boxes)
void SVX_DLLPUBLIC
PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect);

class SdrPreRenderDevice
{
    // The original OutputDevice
    OutputDevice&          mrOutputDevice;

    // The VirtualDevice for PreRendering
    VclPtr<VirtualDevice>  mpPreRenderDevice;

public:
    explicit SdrPreRenderDevice(OutputDevice& rOriginal);
    ~SdrPreRenderDevice();

    void PreparePreRenderDevice();
    void OutputPreRenderDevice(const vcl::Region& rExpandedRegion);

    OutputDevice& GetOriginalOutputDevice() const { return mrOutputDevice; }
    OutputDevice& GetPreRenderDevice() { return *mpPreRenderDevice.get(); }
};

class SVX_DLLPUBLIC SdrPaintWindow
{
private:
    // the OutputDevice this window represents
    OutputDevice&                                       mrOutputDevice;

    /// In case mrOutputDevice is a buffer for a vcl::Window, this is the window.
    vcl::Window*                                        mpWindow;

    // the SdrPaintView this window belongs to
    SdrPaintView&                                       mrPaintView;

    // the new OverlayManager for the new OverlayObjects. Test add here, will
    // replace the IAOManager as soon as it works.
    rtl::Reference< sdr::overlay::OverlayManager >    mxOverlayManager;

    // The PreRenderDevice for PreRendering
    SdrPreRenderDevice*                                 mpPreRenderDevice;

    // The RedrawRegion used for rendering
    vcl::Region                                              maRedrawRegion;

    // bitfield
    // #i72889# flag if this is only a temporary target for repaint, default is false
    bool                                                mbTemporaryTarget : 1;

    /** Remember whether the mxOverlayManager supports buffering.  Using
        this flags expensive dynamic_casts on mxOverlayManager in order to
        detect this.
    */
    bool mbUseBuffer;

    // helpers
    void impCreateOverlayManager();

public:
    SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut, vcl::Window* pWindow = 0);
    ~SdrPaintWindow();

    // data read accesses
    SdrPaintView& GetPaintView() const { return mrPaintView; }
    OutputDevice& GetOutputDevice() const { return mrOutputDevice; }
    vcl::Window* GetWindow() const { return mpWindow; }

    // OVERLAYMANAGER
    rtl::Reference< sdr::overlay::OverlayManager > GetOverlayManager() const;

    // #i73602# add flag if buffer shall be used
    void DrawOverlay(const vcl::Region& rRegion);

    // calculate visible area and return
    Rectangle GetVisibleArea() const;

    // Is OutDev a printer?
    bool OutputToPrinter() const { return (OUTDEV_PRINTER == mrOutputDevice.GetOutDevType()); }

    // Is OutDev a window?
    bool OutputToWindow() const { return (OUTDEV_WINDOW == mrOutputDevice.GetOutDevType()); }

    // Is OutDev a VirtualDevice?
    bool OutputToVirtualDevice() const { return (OUTDEV_VIRDEV == mrOutputDevice.GetOutDevType()); }

    // Is OutDev a recording MetaFile?
    bool OutputToRecordingMetaFile() const;

    // prepare PreRendering (evtl.)
    void PreparePreRenderDevice();
    void DestroyPreRenderDevice();
    void OutputPreRenderDevice(const vcl::Region& rExpandedRegion);
    SdrPreRenderDevice* GetPreRenderDevice() const { return mpPreRenderDevice; }

    // RedrawRegion
    const vcl::Region& GetRedrawRegion() const { return maRedrawRegion;}
    void SetRedrawRegion(const vcl::Region& rNew);

    // #i72889# read/write access to TempoparyTarget
    bool getTemporaryTarget() const { return (bool)mbTemporaryTarget; }
    void setTemporaryTarget(bool bNew) { mbTemporaryTarget = bNew; }

    // #i72889# get target output device, take into account output buffering
    OutputDevice& GetTargetOutputDevice() { if(mpPreRenderDevice) return mpPreRenderDevice->GetPreRenderDevice(); else return mrOutputDevice; }
};

// typedefs for a list of SdrPaintWindows
typedef ::std::vector< SdrPaintWindow* > SdrPaintWindowVector;

#endif // INCLUDED_SVX_SDRPAINTWINDOW_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>loplugin:vclwidgets<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_SVX_SDRPAINTWINDOW_HXX
#define INCLUDED_SVX_SDRPAINTWINDOW_HXX

#include <rtl/ref.hxx>
#include <vcl/virdev.hxx>
#include <svx/svxdllapi.h>

class SdrPaintView;

namespace sdr
{
    namespace overlay
    {
        class OverlayManager;
    }
}

#ifdef _MSC_VER // broken msvc template instantiation
#include <svx/sdr/overlay/overlaymanager.hxx>
#endif

/// paint the transparent children of rWin that overlap rPixelRect
/// (for example, transparent form controls like check boxes)
void SVX_DLLPUBLIC
PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect);

class SdrPreRenderDevice
{
    // The original OutputDevice
    OutputDevice&          mrOutputDevice;

    // The VirtualDevice for PreRendering
    VclPtr<VirtualDevice>  mpPreRenderDevice;

public:
    explicit SdrPreRenderDevice(OutputDevice& rOriginal);
    ~SdrPreRenderDevice();

    void PreparePreRenderDevice();
    void OutputPreRenderDevice(const vcl::Region& rExpandedRegion);

    OutputDevice& GetOriginalOutputDevice() const { return mrOutputDevice; }
    OutputDevice& GetPreRenderDevice() { return *mpPreRenderDevice.get(); }
};

class SVX_DLLPUBLIC SdrPaintWindow
{
private:
    // the OutputDevice this window represents
    OutputDevice&                                       mrOutputDevice;

    /// In case mrOutputDevice is a buffer for a vcl::Window, this is the window.
    VclPtr<vcl::Window>                                 mpWindow;

    // the SdrPaintView this window belongs to
    SdrPaintView&                                       mrPaintView;

    // the new OverlayManager for the new OverlayObjects. Test add here, will
    // replace the IAOManager as soon as it works.
    rtl::Reference< sdr::overlay::OverlayManager >    mxOverlayManager;

    // The PreRenderDevice for PreRendering
    SdrPreRenderDevice*                                 mpPreRenderDevice;

    // The RedrawRegion used for rendering
    vcl::Region                                              maRedrawRegion;

    // bitfield
    // #i72889# flag if this is only a temporary target for repaint, default is false
    bool                                                mbTemporaryTarget : 1;

    /** Remember whether the mxOverlayManager supports buffering.  Using
        this flags expensive dynamic_casts on mxOverlayManager in order to
        detect this.
    */
    bool mbUseBuffer;

    // helpers
    void impCreateOverlayManager();

public:
    SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut, vcl::Window* pWindow = 0);
    ~SdrPaintWindow();

    // data read accesses
    SdrPaintView& GetPaintView() const { return mrPaintView; }
    OutputDevice& GetOutputDevice() const { return mrOutputDevice; }
    vcl::Window* GetWindow() const { return mpWindow; }

    // OVERLAYMANAGER
    rtl::Reference< sdr::overlay::OverlayManager > GetOverlayManager() const;

    // #i73602# add flag if buffer shall be used
    void DrawOverlay(const vcl::Region& rRegion);

    // calculate visible area and return
    Rectangle GetVisibleArea() const;

    // Is OutDev a printer?
    bool OutputToPrinter() const { return (OUTDEV_PRINTER == mrOutputDevice.GetOutDevType()); }

    // Is OutDev a window?
    bool OutputToWindow() const { return (OUTDEV_WINDOW == mrOutputDevice.GetOutDevType()); }

    // Is OutDev a VirtualDevice?
    bool OutputToVirtualDevice() const { return (OUTDEV_VIRDEV == mrOutputDevice.GetOutDevType()); }

    // Is OutDev a recording MetaFile?
    bool OutputToRecordingMetaFile() const;

    // prepare PreRendering (evtl.)
    void PreparePreRenderDevice();
    void DestroyPreRenderDevice();
    void OutputPreRenderDevice(const vcl::Region& rExpandedRegion);
    SdrPreRenderDevice* GetPreRenderDevice() const { return mpPreRenderDevice; }

    // RedrawRegion
    const vcl::Region& GetRedrawRegion() const { return maRedrawRegion;}
    void SetRedrawRegion(const vcl::Region& rNew);

    // #i72889# read/write access to TempoparyTarget
    bool getTemporaryTarget() const { return (bool)mbTemporaryTarget; }
    void setTemporaryTarget(bool bNew) { mbTemporaryTarget = bNew; }

    // #i72889# get target output device, take into account output buffering
    OutputDevice& GetTargetOutputDevice() { if(mpPreRenderDevice) return mpPreRenderDevice->GetPreRenderDevice(); else return mrOutputDevice; }
};

// typedefs for a list of SdrPaintWindows
typedef ::std::vector< SdrPaintWindow* > SdrPaintWindowVector;

#endif // INCLUDED_SVX_SDRPAINTWINDOW_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#ifndef TWISTEDCPP_REACTOR_HPP
#define TWISTEDCPP_REACTOR_HPP

#include "exception.hpp"
#include "sockets.hpp"
#include "ssl_options.hpp"

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/system/system_error.hpp>

#include <iostream>
#include <memory>
#include <iterator>

namespace twisted {

class reactor {
public:
    void run() { _io_service.run(); }

    void stop() { _io_service.stop(); }

    template <typename ProtocolFactory>
    void listen_tcp(int port, ProtocolFactory factory) {
        run_impl_tcp(port, std::move(factory));
    }

    template <typename ProtocolFactory>
    void listen_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) {
        run_impl_ssl(port, std::move(factory), std::move(ssl_ops));
    }

private:
    template <typename ProtocolFactory>
    void run_impl_tcp(int port, ProtocolFactory factory) {
        boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) {
            using boost::asio::ip::tcp;
            tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port));
            run_impl_tcp_core(acceptor, factory, yield);
        });
    }

    template <typename ProtocolFactory>
    void run_impl_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) {
        boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) {
            using boost::asio::ip::tcp;
            tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port));
            run_impl_ssl_core(acceptor, factory, yield, ssl_ops);
        });
    }

    template <typename ProtocolFactory>
    void run_impl_tcp_core(boost::asio::ip::tcp::acceptor& acceptor,
                           ProtocolFactory factory,
                           boost::asio::yield_context yield) {

        auto socket_factory = [=]() {
            return std::unique_ptr<detail::tcp_socket>(
                new detail::tcp_socket(_io_service));
        };

        run_loop(acceptor, std::move(factory), yield, socket_factory);
    }

    template <typename ProtocolFactory>
    void run_impl_ssl_core(boost::asio::ip::tcp::acceptor& acceptor,
                           ProtocolFactory factory,
                           boost::asio::yield_context yield,
                           ssl_options ssl_ops) {
        using boost::asio::ip::tcp;

        auto socket_factory = [=] {
            boost::asio::ssl::context _context(boost::asio::ssl::context::sslv23_server);
            _context.set_options(
                boost::asio::ssl::context::default_workarounds |
                boost::asio::ssl::context::no_sslv2 |
                boost::asio::ssl::context::single_dh_use);
            _context.set_password_callback([=](
                std::size_t /* max_length */,
                boost::asio::ssl::context::password_purpose /* purpose */) {
                return ssl_ops.password();
            });
            _context.use_certificate_chain_file(ssl_ops.certificate());
            _context.use_private_key_file(ssl_ops.key(),
                                          boost::asio::ssl::context::pem);

            return std::unique_ptr<detail::ssl_socket>(
                new detail::ssl_socket(_io_service, _context));
        };

        run_loop(acceptor, std::move(factory), yield, socket_factory);
    }

    template <typename ProtocolFactory, typename SocketFactory>
    void run_loop(boost::asio::ip::tcp::acceptor& acceptor,
                  ProtocolFactory factory, boost::asio::yield_context yield,
                  SocketFactory socket_factory) {

        for (;;) {
            boost::system::error_code ec;

            auto socket = socket_factory();

            acceptor.async_accept(socket->lowest_layer(), yield[ec]);

            if (ec) {
                throw boost::system::system_error(ec);
            }

            auto new_client = std::make_shared<decltype(factory())>(factory());
            // lazy init to avoid clutter in protocol constructors
            new_client->set_socket(std::move(socket));
            new_client->run_protocol();
        }
    }

    boost::asio::io_service _io_service;
};

} // namespace twisted

#endif
<commit_msg>switched from error code in excep in reactor<commit_after>#ifndef TWISTEDCPP_REACTOR_HPP
#define TWISTEDCPP_REACTOR_HPP

#include "exception.hpp"
#include "sockets.hpp"
#include "ssl_options.hpp"

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/system/system_error.hpp>

#include <iostream>
#include <memory>
#include <iterator>

namespace twisted {

class reactor {
public:
    void run() { _io_service.run(); }

    void stop() { _io_service.stop(); }

    template <typename ProtocolFactory>
    void listen_tcp(int port, ProtocolFactory factory) {
        run_impl_tcp(port, std::move(factory));
    }

    template <typename ProtocolFactory>
    void listen_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) {
        run_impl_ssl(port, std::move(factory), std::move(ssl_ops));
    }

private:
    template <typename ProtocolFactory>
    void run_impl_tcp(int port, ProtocolFactory factory) {
        boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) {
            using boost::asio::ip::tcp;
            tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port));
            run_impl_tcp_core(acceptor, factory, yield);
        });
    }

    template <typename ProtocolFactory>
    void run_impl_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) {
        boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) {
            using boost::asio::ip::tcp;
            tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port));
            run_impl_ssl_core(acceptor, factory, yield, ssl_ops);
        });
    }

    template <typename ProtocolFactory>
    void run_impl_tcp_core(boost::asio::ip::tcp::acceptor& acceptor,
                           ProtocolFactory factory,
                           boost::asio::yield_context yield) {

        auto socket_factory = [=]() {
            return std::unique_ptr<detail::tcp_socket>(
                new detail::tcp_socket(_io_service));
        };

        run_loop(acceptor, std::move(factory), yield, socket_factory);
    }

    template <typename ProtocolFactory>
    void run_impl_ssl_core(boost::asio::ip::tcp::acceptor& acceptor,
                           ProtocolFactory factory,
                           boost::asio::yield_context yield,
                           ssl_options ssl_ops) {
        using boost::asio::ip::tcp;

        auto socket_factory = [=] {
            boost::asio::ssl::context _context(boost::asio::ssl::context::sslv23_server);
            _context.set_options(
                boost::asio::ssl::context::default_workarounds |
                boost::asio::ssl::context::no_sslv2 |
                boost::asio::ssl::context::single_dh_use);
            _context.set_password_callback([=](
                std::size_t /* max_length */,
                boost::asio::ssl::context::password_purpose /* purpose */) {
                return ssl_ops.password();
            });
            _context.use_certificate_chain_file(ssl_ops.certificate());
            _context.use_private_key_file(ssl_ops.key(),
                                          boost::asio::ssl::context::pem);

            return std::unique_ptr<detail::ssl_socket>(
                new detail::ssl_socket(_io_service, _context));
        };

        run_loop(acceptor, std::move(factory), yield, socket_factory);
    }

    template <typename ProtocolFactory, typename SocketFactory>
    void run_loop(boost::asio::ip::tcp::acceptor& acceptor,
                  ProtocolFactory factory, boost::asio::yield_context yield,
                  SocketFactory socket_factory) {

        for (;;) {
            auto socket = socket_factory();

            acceptor.async_accept(socket->lowest_layer(), yield);

            auto new_client = std::make_shared<decltype(factory())>(factory());
            // lazy init to avoid clutter in protocol constructors
            new_client->set_socket(std::move(socket));
            new_client->run_protocol();
        }
    }

    boost::asio::io_service _io_service;
};

} // namespace twisted

#endif
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
// StdAir
#include <stdair/stdair_demand_types.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// TRADEMGEN
#include <trademgen/TRADEMGEN_Service.hpp>
// Airsched
#include <airsched/AIRSCHED_Service.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/command/Simulator.hpp>

namespace DSIM {

  // ////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                            TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) {

    try {

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation is starting");

      // /////////////////////////////////////////////////////
      // Event queue
      stdair::EventQueue lEventQueue;

      /**
         Initialisation step.

Generate the first event for each demand stream.
      */
      ioTRADEMGEN_Service.generateFirstRequests (lEventQueue);

      /** (Boost) progress display (current number of events, total
          number of events) for every demand stream. */
      stdair::ProgressDisplayMap_T lProgressDisplays;
      lEventQueue.initProgressDisplays (lProgressDisplays);

      /**
         Main loop.

Pop a request and get its associated type/demand stream.

Generate the next request for the same type/demand stream.

      */
      stdair::Count_T eventIdx = 1;
      while (lEventQueue.isQueueDone() == false) {

        // Get the next event from the event queue
        stdair::EventStruct& lEventStruct = lEventQueue.popEvent ();

        // Extract the corresponding demand/booking request
        const stdair::BookingRequestStruct& lPoppedRequest =
          lEventStruct.getBookingRequest ();

        // DEBUG
        STDAIR_LOG_DEBUG ("[" << eventIdx << "] Poped booking request: '"
                          << lPoppedRequest.describe() << "'.");

        // Play booking request
        playBookingRequest (ioSIMCRS_Service, lPoppedRequest);

        // Retrieve the corresponding demand stream
        const stdair::DemandStreamKeyStr_T& lDemandStreamKey =
          lEventStruct.getDemandStreamKey ();

        // Assess whether more events should be generated for that
        // demand stream
        bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.
          stillHavingRequestsToBeGenerated (lDemandStreamKey);

        // Retrieve, from the demand stream, the total number of events
        // to be generated
        const stdair::NbOfRequests_T& lNbOfRequests = ioTRADEMGEN_Service.
          getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey);

        // DEBUG
        STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
                          << "Still generate events for that demand stream? "
                          << stillHavingRequestsToBeGenerated);

        // If there are still events to be generated for that demand
        // stream, generate and add them to the event queue
        if (stillHavingRequestsToBeGenerated) {
          stdair::BookingRequestPtr_T lNextRequest_ptr =
            ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey);
          assert (lNextRequest_ptr != NULL);

          // Sanity check
          const stdair::Duration_T lDuration =
            lNextRequest_ptr->getRequestDateTime()
            - lPoppedRequest.getRequestDateTime();
          if (lDuration.total_milliseconds() < 0) {
            STDAIR_LOG_ERROR ("[" << lDemandStreamKey
                              << "] The date-time of the generated event ("
                              << lNextRequest_ptr->getRequestDateTime()
                              << ") is lower than the date-time "
                              << "of the current event ("
                              << lPoppedRequest.getRequestDateTime() << ")");
            assert (false);
          }

          //
          stdair::EventStruct lNextEventStruct (stdair::EventType::BKG_REQ,
                                                lDemandStreamKey,
                                                lNextRequest_ptr);

          /**
             Note that when adding an event in the event queue, the
             former can be altered. It happends when an event already
             exists in the event queue with exactly the same date-time
             stamp. In that case, the date-time stamp is altered for the
             newly added event, so that the unicity on the date-time
             stamp can be guaranteed.
          */
          lEventQueue.addEvent (lNextEventStruct);

          // DEBUG
          STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
                            << lNextRequest_ptr->describe()
                            << "'. Is queue done? "
                            << lEventQueue.isQueueDone());
        }

        /**
           Remove the last used event, so that, at any given moment, the
           queue keeps only the active events.
        */
        lEventQueue.eraseLastUsedEvent ();

        // Iterate
        ++eventIdx;
      }

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation has ended");

    } catch (const std::exception& lStdError) {
      STDAIR_LOG_ERROR ("Error: " << lStdError.what());
      throw SimulationException();
    }
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                      const stdair::BookingRequestStruct& iBookingRequest) {
    // Retrieve a list of travel solutions corresponding the given
    // booking request.
    const stdair::SegmentPathList_T& lSegmentPathList =
      ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest);
    if (lSegmentPathList.empty() == false) {
      // Get the fare quote for each travel solution.
      stdair::TravelSolutionList_T lTravelSolutionList =
        ioSIMCRS_Service.fareQuote (iBookingRequest, lSegmentPathList);

      // Get the availability for each travel solution.
      ioSIMCRS_Service.calculateAvailability (lTravelSolutionList);

      // Hardcode a travel solution choice.
      stdair::TravelSolutionList_T::const_iterator itTS =
        lTravelSolutionList.begin();
      const stdair::TravelSolutionStruct& lChosenTS = *itTS;

      // DEBUG
      STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS << "\n");

      // Make a sale.
      const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();
      ioSIMCRS_Service.sell (lChosenTS, lPartySize);

    } else {
      // DEBUG
      STDAIR_LOG_DEBUG ("No travel solution has been found/chosen.");
    }
  }

}
<commit_msg>[DSim] Updated the code for the new Discrete Event related StdAir code.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
// StdAir
#include <stdair/stdair_demand_types.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// TRADEMGEN
#include <trademgen/TRADEMGEN_Service.hpp>
// Airsched
#include <airsched/AIRSCHED_Service.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/command/Simulator.hpp>

namespace DSIM {

  // ////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                            TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) {

    try {

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation is starting");

      /**
         Initialisation step.

Generate the first event for each demand stream.
      */
      ioTRADEMGEN_Service.generateFirstRequests();

      /** (Boost) progress display (current number of events, total
          number of events) for every demand stream. */
      stdair::ProgressDisplayMap_T lProgressDisplays;
      ioTRADEMGEN_Service.initProgressDisplays (lProgressDisplays);

      /**
         Main loop.

Pop a request and get its associated type/demand stream.

Generate the next request for the same type/demand stream.

      */
      stdair::Count_T eventIdx = 1;
      while (ioTRADEMGEN_Service.isQueueDone() == false) {

        // Get the next event from the event queue
        const stdair::EventStruct& lEventStruct= ioTRADEMGEN_Service.popEvent();

        // Extract the corresponding demand/booking request
        const stdair::BookingRequestStruct& lPoppedRequest =
          lEventStruct.getBookingRequest ();

        // DEBUG
        STDAIR_LOG_DEBUG ("[" << eventIdx << "] Poped booking request: '"
                          << lPoppedRequest.describe() << "'.");

        // Play booking request
        playBookingRequest (ioSIMCRS_Service, lPoppedRequest);

        // Retrieve the corresponding demand stream
        const stdair::DemandStreamKeyStr_T& lDemandStreamKey =
          lEventStruct.getDemandStreamKey ();

        // Assess whether more events should be generated for that
        // demand stream
        bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.
          stillHavingRequestsToBeGenerated (lDemandStreamKey);

        // Retrieve, from the demand stream, the total number of events
        // to be generated
        const stdair::NbOfRequests_T& lNbOfRequests = ioTRADEMGEN_Service.
          getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey);

        // DEBUG
        STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
                          << "Still generate events for that demand stream? "
                          << stillHavingRequestsToBeGenerated);

        // If there are still events to be generated for that demand
        // stream, generate and add them to the event queue
        if (stillHavingRequestsToBeGenerated) {
          stdair::BookingRequestPtr_T lNextRequest_ptr =
            ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey);
          assert (lNextRequest_ptr != NULL);

          // Sanity check
          const stdair::Duration_T lDuration =
            lNextRequest_ptr->getRequestDateTime()
            - lPoppedRequest.getRequestDateTime();
          if (lDuration.total_milliseconds() < 0) {
            STDAIR_LOG_ERROR ("[" << lDemandStreamKey
                              << "] The date-time of the generated event ("
                              << lNextRequest_ptr->getRequestDateTime()
                              << ") is lower than the date-time "
                              << "of the current event ("
                              << lPoppedRequest.getRequestDateTime() << ")");
            assert (false);
          }

          //
          stdair::EventStruct lNextEventStruct (stdair::EventType::BKG_REQ,
                                                lDemandStreamKey,
                                                lNextRequest_ptr);

          /**
             Note that when adding an event in the event queue, the
             former can be altered. It happends when an event already
             exists in the event queue with exactly the same date-time
             stamp. In that case, the date-time stamp is altered for the
             newly added event, so that the unicity on the date-time
             stamp can be guaranteed.
          */
          ioTRADEMGEN_Service.addEvent (lNextEventStruct);

          // DEBUG
          STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
                            << lNextRequest_ptr->describe()
                            << "'. Is queue done? "
                            << ioTRADEMGEN_Service.isQueueDone());
        }

        // Iterate
        ++eventIdx;
      }

      // DEBUG
      STDAIR_LOG_DEBUG ("The simulation has ended");

    } catch (const std::exception& lStdError) {
      STDAIR_LOG_ERROR ("Error: " << lStdError.what());
      throw SimulationException();
    }
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                      const stdair::BookingRequestStruct& iBookingRequest) {
    // Retrieve a list of travel solutions corresponding the given
    // booking request.
    const stdair::SegmentPathList_T& lSegmentPathList =
      ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest);
    if (lSegmentPathList.empty() == false) {
      // Get the fare quote for each travel solution.
      stdair::TravelSolutionList_T lTravelSolutionList =
        ioSIMCRS_Service.fareQuote (iBookingRequest, lSegmentPathList);

      // Get the availability for each travel solution.
      ioSIMCRS_Service.calculateAvailability (lTravelSolutionList);

      // Hardcode a travel solution choice.
      stdair::TravelSolutionList_T::const_iterator itTS =
        lTravelSolutionList.begin();
      const stdair::TravelSolutionStruct& lChosenTS = *itTS;

      // DEBUG
      STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS << "\n");

      // Make a sale.
      const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();
      ioSIMCRS_Service.sell (lChosenTS, lPartySize);

    } else {
      // DEBUG
      STDAIR_LOG_DEBUG ("No travel solution has been found/chosen.");
    }
  }

}
<|endoftext|>


<commit_before>#ifndef INTEGER_RANGE_HPP
#define INTEGER_RANGE_HPP

#include <boost/assert.hpp>

#include <type_traits>

#include <cstdint>

namespace osrm
{
namespace util
{

template <typename Integer> class range
{
  private:
    const Integer last;
    Integer iter;

  public:
    range(Integer start, Integer end) noexcept : last(end), iter(start)
    {
        BOOST_ASSERT_MSG(start <= end, "backwards counting ranges not suppoted");
        static_assert(std::is_integral<Integer>::value, "range type must be integral");
    }

    // Iterable functions
    const range &begin() const noexcept { return *this; }
    const range &end() const noexcept { return *this; }
    Integer front() const noexcept { return iter; }
    Integer back() const noexcept { return last - 1; }
    std::size_t size() const noexcept { return static_cast<std::size_t>(last - iter); }

    // Iterator functions
    bool operator!=(const range &) const noexcept { return iter < last; }
    void operator++() noexcept { ++iter; }
    Integer operator*() const noexcept { return iter; }
};

// convenience function to construct an integer range with type deduction
template <typename Integer>
range<Integer>
irange(const Integer first,
       const Integer last,
       typename std::enable_if<std::is_integral<Integer>::value>::type * = 0) noexcept
{
    return range<Integer>(first, last);
}
}
}

#endif // INTEGER_RANGE_HPP
<commit_msg>Documents why not to use boost::irange in favor of our hand-written irange<commit_after>#ifndef INTEGER_RANGE_HPP
#define INTEGER_RANGE_HPP

#include <boost/assert.hpp>

#include <type_traits>

#include <cstdint>

namespace osrm
{
namespace util
{

// Warning: do not try to replace this with Boost's irange, as it is broken on Boost 1.55:
//     auto r = boost::irange<unsigned int>(0, 15);
//     std::cout << r.size() << std::endl;
// results in -4294967281. Latest Boost versions fix this, but we still support older ones.

template <typename Integer> class range
{
  private:
    const Integer last;
    Integer iter;

  public:
    range(Integer start, Integer end) noexcept : last(end), iter(start)
    {
        BOOST_ASSERT_MSG(start <= end, "backwards counting ranges not suppoted");
        static_assert(std::is_integral<Integer>::value, "range type must be integral");
    }

    // Iterable functions
    const range &begin() const noexcept { return *this; }
    const range &end() const noexcept { return *this; }
    Integer front() const noexcept { return iter; }
    Integer back() const noexcept { return last - 1; }
    std::size_t size() const noexcept { return static_cast<std::size_t>(last - iter); }

    // Iterator functions
    bool operator!=(const range &) const noexcept { return iter < last; }
    void operator++() noexcept { ++iter; }
    Integer operator*() const noexcept { return iter; }
};

// convenience function to construct an integer range with type deduction
template <typename Integer>
range<Integer>
irange(const Integer first,
       const Integer last,
       typename std::enable_if<std::is_integral<Integer>::value>::type * = 0) noexcept
{
    return range<Integer>(first, last);
}
}
}

#endif // INTEGER_RANGE_HPP
<|endoftext|>


<commit_before>#include "indexer/feature_visibility.hpp"
#include "indexer/classificator.hpp"
#include "indexer/drawing_rules.hpp"
#include "indexer/scales.hpp"

#include "base/assert.hpp"

#include "std/array.hpp"

template <class ToDo> typename ToDo::ResultType
Classificator::ProcessObjects(uint32_t type, ToDo & toDo) const
{
  typedef typename ToDo::ResultType ResultType;
  ResultType res = ResultType(); // default initialization

  ClassifObject const * p = GetObject(type);
  if (p != &m_root)
  {
    ASSERT(p, ());
    toDo(p, res);
  }
  return res;
}

ClassifObject const * Classificator::GetObject(uint32_t type) const
{
  ClassifObject const * p = &m_root;
  uint8_t i = 0;

  // get the final ClassifObject
  uint8_t v;
  while (ftype::GetValue(type, i, v))
  {
    ++i;
    p = p->GetObject(v);
  }

  return p;
}

string Classificator::GetFullObjectName(uint32_t type) const
{
  ClassifObject const * p = &m_root;
  uint8_t i = 0;
  string s;

  // get the final ClassifObject
  uint8_t v;
  while (ftype::GetValue(type, i, v))
  {
    ++i;
    p = p->GetObject(v);
    s = s + p->GetName() + '|';
  }

  return s;
}

namespace feature
{

namespace
{
  class DrawRuleGetter
  {
    int m_scale;
    EGeomType m_ft;
    drule::KeysT & m_keys;

  public:
    DrawRuleGetter(int scale, EGeomType ft, drule::KeysT & keys)
      : m_scale(scale), m_ft(ft), m_keys(keys)
    {
    }

    typedef bool ResultType;

    void operator() (ClassifObject const *)
    {
    }
    bool operator() (ClassifObject const * p, bool & res)
    {
      res = true;
      p->GetSuitable(min(m_scale, scales::GetUpperStyleScale()), m_ft, m_keys);
      return false;
    }
  };
}

pair<int, bool> GetDrawRule(TypesHolder const & types, int level,
                            drule::KeysT & keys)
{
  ASSERT ( keys.empty(), () );
  Classificator const & c = classif();

  DrawRuleGetter doRules(level, types.GetGeoType(), keys);
  for (uint32_t t : types)
    (void)c.ProcessObjects(t, doRules);

  return make_pair(types.GetGeoType(), types.Has(c.GetCoastType()));
}

void GetDrawRule(vector<uint32_t> const & types, int level, int geoType,
                 drule::KeysT & keys)

{
  ASSERT ( keys.empty(), () );
  Classificator const & c = classif();

  DrawRuleGetter doRules(level, EGeomType(geoType), keys);

  for (uint32_t t : types)
    (void)c.ProcessObjects(t, doRules);
}

void FilterRulesByRuntimeSelector(FeatureType const & f, int zoomLevel, drule::KeysT & keys)
{
  keys.erase_if([&f, zoomLevel](drule::Key const & key)->bool
  {
    drule::BaseRule const * const rule = drule::rules().Find(key);
    if (rule == nullptr)
      return true;
    return !rule->TestFeature(f, zoomLevel);
  });
}

namespace
{
  class IsDrawableChecker
  {
    int m_scale;

  public:
    IsDrawableChecker(int scale) : m_scale(scale) {}

    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      if (p->IsDrawable(m_scale))
      {
        res = true;
        return true;
      }
      return false;
    }
  };

  class IsDrawableLikeChecker
  {
    EGeomType m_geomType;
    bool m_emptyName;

  public:
    IsDrawableLikeChecker(EGeomType geomType, bool emptyName = false)
      : m_geomType(geomType), m_emptyName(emptyName)
    {
    }

    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      if (p->IsDrawableLike(m_geomType, m_emptyName))
      {
        res = true;
        return true;
      }
      return false;
    }
  };

  class IsDrawableRulesChecker
  {
    int m_scale;
    EGeomType m_ft;
    bool m_arr[3];

  public:
    IsDrawableRulesChecker(int scale, EGeomType ft, int rules)
      : m_scale(scale), m_ft(ft)
    {
      m_arr[0] = rules & RULE_CAPTION;
      m_arr[1] = rules & RULE_PATH_TEXT;
      m_arr[2] = rules & RULE_SYMBOL;
    }

    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      drule::KeysT keys;
      p->GetSuitable(m_scale, m_ft, keys);

      for (auto const & k : keys)
      {
        if ((m_arr[0] && k.m_type == drule::caption) ||
            (m_arr[1] && k.m_type == drule::pathtext) ||
            (m_arr[2] && k.m_type == drule::symbol))
        {
          res = true;
          return true;
        }
      }

      return false;
    }
  };

  bool HasRoutingExceptionType(uint32_t t)
  {
    static const uint32_t s = classif().GetTypeByPath({ "route", "shuttle_train" });
    return s == t;
  }

  /// Add here all exception classificator types: needed for algorithms,
  /// but don't have drawing rules.
  /// See also ftypes_matcher.cpp, IsInvisibleIndexedChecker.
  bool TypeAlwaysExists(uint32_t type, EGeomType g = GEOM_UNDEFINED)
  {
    if (!classif().IsTypeValid(type))
      return false;

    static const uint32_t roundabout = classif().GetTypeByPath({ "junction", "roundabout" });
    static const uint32_t hwtag = classif().GetTypeByPath({ "hwtag" });
    static const uint32_t psurface = classif().GetTypeByPath({ "psurface" });
    static const uint32_t wheelchair = classif().GetTypeByPath({ "wheelchair" });
    static const uint32_t sponsored = classif().GetTypeByPath({ "sponsored" });
    static const uint32_t event = classif().GetTypeByPath({ "event" });
    static const uint32_t internet = classif().GetTypeByPath({ "internet_access" });

    // Caching type length to exclude generic [wheelchair].
    uint8_t const typeLength = ftype::GetLevel(type);

    if (g == GEOM_LINE || g == GEOM_UNDEFINED)
    {
      if (roundabout == type)
        return true;

      if (HasRoutingExceptionType(type))
        return true;

      ftype::TruncValue(type, 1);
      if (hwtag == type || psurface == type)
        return true;
    }

    // We're okay with the type being already truncated above.
    ftype::TruncValue(type, 1);
    if (wheelchair == type && typeLength == 2)
      return true;

    if (sponsored == type || internet == type || event == type)
      return true;

    return false;
  }
}

bool RequireGeometryInIndex(FeatureBase const & f)
{
  TypesHolder const types(f);

  for (uint32_t t : types)
  {
    if (HasRoutingExceptionType(t))
      return true;
  }
  return false;
}

bool IsDrawableAny(uint32_t type)
{
  return (TypeAlwaysExists(type) || classif().GetObject(type)->IsDrawableAny());
}

bool IsDrawableLike(vector<uint32_t> const & types, EGeomType geomType)
{
  Classificator const & c = classif();

  IsDrawableLikeChecker doCheck(geomType);
  for (uint32_t t : types)
    if (c.ProcessObjects(t, doCheck))
      return true;
  return false;
}

bool IsDrawableForIndex(FeatureBase const & f, int level)
{
  return IsDrawableForIndexGeometryOnly(f, level) && IsDrawableForIndexClassifOnly(f, level);
}

bool IsDrawableForIndexGeometryOnly(FeatureBase const & f, int level)
{
  Classificator const & c = classif();

  static uint32_t const buildingPartType = c.GetTypeByPath({"building:part"});

  TypesHolder const types(f);

  if (types.GetGeoType() == GEOM_AREA
      && !types.Has(c.GetCoastType()) && !types.Has(buildingPartType)
      && !scales::IsGoodForLevel(level, f.GetLimitRect()))
    return false;

  return true;
}

bool IsDrawableForIndexClassifOnly(FeatureBase const & f, int level)
{
  Classificator const & c = classif();

  TypesHolder const types(f);

  IsDrawableChecker doCheck(level);
  for (uint32_t t : types)
    if (c.ProcessObjects(t, doCheck))
      return true;

  return false;
}

bool RemoveNoDrawableTypes(vector<uint32_t> & types, EGeomType geomType, bool emptyName)
{
  Classificator const & c = classif();

  types.erase(remove_if(types.begin(), types.end(), [&] (uint32_t t)
  {
   if (TypeAlwaysExists(t, geomType))
     return false;

   IsDrawableLikeChecker doCheck(geomType, emptyName);
   if (c.ProcessObjects(t, doCheck))
     return false;

   // IsDrawableLikeChecker checks only unique area styles,
   // so we need to take into account point styles too.
   if (geomType == GEOM_AREA)
   {
     IsDrawableLikeChecker doCheck(GEOM_POINT, emptyName);
     if (c.ProcessObjects(t, doCheck))
       return false;
   }

   return true;
  }), types.end());

  return !types.empty();
}

int GetMinDrawableScale(FeatureBase const & f)
{
  int const upBound = scales::GetUpperStyleScale();

  for (int level = 0; level <= upBound; ++level)
    if (IsDrawableForIndex(f, level))
      return level;

  return -1;
}

int GetMinDrawableScaleClassifOnly(FeatureBase const & f)
{
  int const upBound = scales::GetUpperStyleScale();

  for (int level = 0; level <= upBound; ++level)
    if (IsDrawableForIndexClassifOnly(f, level))
      return level;

  return -1;
}

namespace
{
  void AddRange(pair<int, int> & dest, pair<int, int> const & src)
  {
    if (src.first != -1)
    {
      ASSERT_GREATER(src.first, -1, ());
      ASSERT_GREATER(src.second, -1, ());

      dest.first = min(dest.first, src.first);
      dest.second = max(dest.second, src.second);

      ASSERT_GREATER(dest.first, -1, ());
      ASSERT_GREATER(dest.second, -1, ());
    }
  }

  class DoGetScalesRange
  {
    pair<int, int> m_scales;
  public:
    DoGetScalesRange() : m_scales(1000, -1000) {}
    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      res = true;
      AddRange(m_scales, p->GetDrawScaleRange());
      return false;
    }

    pair<int, int> GetScale() const
    {
      return (m_scales.first > m_scales.second ? make_pair(-1, -1) : m_scales);
    }
  };
}

pair<int, int> GetDrawableScaleRange(uint32_t type)
{
  DoGetScalesRange doGet;
  (void)classif().ProcessObjects(type, doGet);
  return doGet.GetScale();
}

pair<int, int> GetDrawableScaleRange(TypesHolder const & types)
{
  pair<int, int> res(1000, -1000);

  for (uint32_t t : types)
    AddRange(res, GetDrawableScaleRange(t));

  return (res.first > res.second ? make_pair(-1, -1) : res);
}

namespace
{
  bool IsDrawableForRules(TypesHolder const & types, int level, int rules)
  {
    Classificator const & c = classif();

    IsDrawableRulesChecker doCheck(level, types.GetGeoType(), rules);
    for (uint32_t t : types)
      if (c.ProcessObjects(t, doCheck))
        return true;

    return false;
  }
}

pair<int, int> GetDrawableScaleRangeForRules(TypesHolder const & types, int rules)
{
  int const upBound = scales::GetUpperStyleScale();
  int lowL = -1;
  for (int level = 0; level <= upBound; ++level)
  {
    if (IsDrawableForRules(types, level, rules))
    {
      lowL = level;
      break;
    }
  }

  if (lowL == -1)
    return make_pair(-1, -1);

  int highL = lowL;
  for (int level = upBound; level > lowL; --level)
  {
    if (IsDrawableForRules(types, level, rules))
    {
      highL = level;
      break;
    }
  }

  return make_pair(lowL, highL);
}

pair<int, int> GetDrawableScaleRangeForRules(FeatureBase const & f, int rules)
{
  return GetDrawableScaleRangeForRules(TypesHolder(f), rules);
}

TypeSetChecker::TypeSetChecker(initializer_list<char const *> const & lst)
{
  m_type = classif().GetTypeByPath(lst);
  m_level = lst.size();
}

bool TypeSetChecker::IsEqual(uint32_t type) const
{
  ftype::TruncValue(type, m_level);
  return (m_type == type);
}

}   // namespace feature
<commit_msg>[generator] Disable fake types for lines<commit_after>#include "indexer/feature_visibility.hpp"
#include "indexer/classificator.hpp"
#include "indexer/drawing_rules.hpp"
#include "indexer/scales.hpp"

#include "base/assert.hpp"

#include "std/array.hpp"

template <class ToDo> typename ToDo::ResultType
Classificator::ProcessObjects(uint32_t type, ToDo & toDo) const
{
  typedef typename ToDo::ResultType ResultType;
  ResultType res = ResultType(); // default initialization

  ClassifObject const * p = GetObject(type);
  if (p != &m_root)
  {
    ASSERT(p, ());
    toDo(p, res);
  }
  return res;
}

ClassifObject const * Classificator::GetObject(uint32_t type) const
{
  ClassifObject const * p = &m_root;
  uint8_t i = 0;

  // get the final ClassifObject
  uint8_t v;
  while (ftype::GetValue(type, i, v))
  {
    ++i;
    p = p->GetObject(v);
  }

  return p;
}

string Classificator::GetFullObjectName(uint32_t type) const
{
  ClassifObject const * p = &m_root;
  uint8_t i = 0;
  string s;

  // get the final ClassifObject
  uint8_t v;
  while (ftype::GetValue(type, i, v))
  {
    ++i;
    p = p->GetObject(v);
    s = s + p->GetName() + '|';
  }

  return s;
}

namespace feature
{

namespace
{
  class DrawRuleGetter
  {
    int m_scale;
    EGeomType m_ft;
    drule::KeysT & m_keys;

  public:
    DrawRuleGetter(int scale, EGeomType ft, drule::KeysT & keys)
      : m_scale(scale), m_ft(ft), m_keys(keys)
    {
    }

    typedef bool ResultType;

    void operator() (ClassifObject const *)
    {
    }
    bool operator() (ClassifObject const * p, bool & res)
    {
      res = true;
      p->GetSuitable(min(m_scale, scales::GetUpperStyleScale()), m_ft, m_keys);
      return false;
    }
  };
}

pair<int, bool> GetDrawRule(TypesHolder const & types, int level,
                            drule::KeysT & keys)
{
  ASSERT ( keys.empty(), () );
  Classificator const & c = classif();

  DrawRuleGetter doRules(level, types.GetGeoType(), keys);
  for (uint32_t t : types)
    (void)c.ProcessObjects(t, doRules);

  return make_pair(types.GetGeoType(), types.Has(c.GetCoastType()));
}

void GetDrawRule(vector<uint32_t> const & types, int level, int geoType,
                 drule::KeysT & keys)

{
  ASSERT ( keys.empty(), () );
  Classificator const & c = classif();

  DrawRuleGetter doRules(level, EGeomType(geoType), keys);

  for (uint32_t t : types)
    (void)c.ProcessObjects(t, doRules);
}

void FilterRulesByRuntimeSelector(FeatureType const & f, int zoomLevel, drule::KeysT & keys)
{
  keys.erase_if([&f, zoomLevel](drule::Key const & key)->bool
  {
    drule::BaseRule const * const rule = drule::rules().Find(key);
    if (rule == nullptr)
      return true;
    return !rule->TestFeature(f, zoomLevel);
  });
}

namespace
{
  class IsDrawableChecker
  {
    int m_scale;

  public:
    IsDrawableChecker(int scale) : m_scale(scale) {}

    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      if (p->IsDrawable(m_scale))
      {
        res = true;
        return true;
      }
      return false;
    }
  };

  class IsDrawableLikeChecker
  {
    EGeomType m_geomType;
    bool m_emptyName;

  public:
    IsDrawableLikeChecker(EGeomType geomType, bool emptyName = false)
      : m_geomType(geomType), m_emptyName(emptyName)
    {
    }

    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      if (p->IsDrawableLike(m_geomType, m_emptyName))
      {
        res = true;
        return true;
      }
      return false;
    }
  };

  class IsDrawableRulesChecker
  {
    int m_scale;
    EGeomType m_ft;
    bool m_arr[3];

  public:
    IsDrawableRulesChecker(int scale, EGeomType ft, int rules)
      : m_scale(scale), m_ft(ft)
    {
      m_arr[0] = rules & RULE_CAPTION;
      m_arr[1] = rules & RULE_PATH_TEXT;
      m_arr[2] = rules & RULE_SYMBOL;
    }

    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      drule::KeysT keys;
      p->GetSuitable(m_scale, m_ft, keys);

      for (auto const & k : keys)
      {
        if ((m_arr[0] && k.m_type == drule::caption) ||
            (m_arr[1] && k.m_type == drule::pathtext) ||
            (m_arr[2] && k.m_type == drule::symbol))
        {
          res = true;
          return true;
        }
      }

      return false;
    }
  };

  bool HasRoutingExceptionType(uint32_t t)
  {
    static const uint32_t s = classif().GetTypeByPath({ "route", "shuttle_train" });
    return s == t;
  }

  /// Add here all exception classificator types: needed for algorithms,
  /// but don't have drawing rules.
  /// See also ftypes_matcher.cpp, IsInvisibleIndexedChecker.
  bool TypeAlwaysExists(uint32_t type, EGeomType g = GEOM_UNDEFINED)
  {
    if (!classif().IsTypeValid(type))
      return false;

    static const uint32_t roundabout = classif().GetTypeByPath({ "junction", "roundabout" });
    static const uint32_t hwtag = classif().GetTypeByPath({ "hwtag" });
    static const uint32_t psurface = classif().GetTypeByPath({ "psurface" });
    static const uint32_t wheelchair = classif().GetTypeByPath({ "wheelchair" });
    static const uint32_t sponsored = classif().GetTypeByPath({ "sponsored" });
    static const uint32_t event = classif().GetTypeByPath({ "event" });
    static const uint32_t internet = classif().GetTypeByPath({ "internet_access" });

    // Caching type length to exclude generic [wheelchair].
    uint8_t const typeLength = ftype::GetLevel(type);

    if (g == GEOM_LINE || g == GEOM_UNDEFINED)
    {
      if (roundabout == type)
        return true;

      if (HasRoutingExceptionType(type))
        return true;

      ftype::TruncValue(type, 1);
      if (hwtag == type || psurface == type)
        return true;
    }

    // We're okay with the type being already truncated above.
    ftype::TruncValue(type, 1);
    if (wheelchair == type && typeLength == 2)
      return true;

    if (g != GEOM_LINE)
    {
      if (sponsored == type || internet == type || event == type)
        return true;
    }

    return false;
  }
}

bool RequireGeometryInIndex(FeatureBase const & f)
{
  TypesHolder const types(f);

  for (uint32_t t : types)
  {
    if (HasRoutingExceptionType(t))
      return true;
  }
  return false;
}

bool IsDrawableAny(uint32_t type)
{
  return (TypeAlwaysExists(type) || classif().GetObject(type)->IsDrawableAny());
}

bool IsDrawableLike(vector<uint32_t> const & types, EGeomType geomType)
{
  Classificator const & c = classif();

  IsDrawableLikeChecker doCheck(geomType);
  for (uint32_t t : types)
    if (c.ProcessObjects(t, doCheck))
      return true;
  return false;
}

bool IsDrawableForIndex(FeatureBase const & f, int level)
{
  return IsDrawableForIndexGeometryOnly(f, level) && IsDrawableForIndexClassifOnly(f, level);
}

bool IsDrawableForIndexGeometryOnly(FeatureBase const & f, int level)
{
  Classificator const & c = classif();

  static uint32_t const buildingPartType = c.GetTypeByPath({"building:part"});

  TypesHolder const types(f);

  if (types.GetGeoType() == GEOM_AREA
      && !types.Has(c.GetCoastType()) && !types.Has(buildingPartType)
      && !scales::IsGoodForLevel(level, f.GetLimitRect()))
    return false;

  return true;
}

bool IsDrawableForIndexClassifOnly(FeatureBase const & f, int level)
{
  Classificator const & c = classif();

  TypesHolder const types(f);

  IsDrawableChecker doCheck(level);
  for (uint32_t t : types)
    if (c.ProcessObjects(t, doCheck))
      return true;

  return false;
}

bool RemoveNoDrawableTypes(vector<uint32_t> & types, EGeomType geomType, bool emptyName)
{
  Classificator const & c = classif();

  types.erase(remove_if(types.begin(), types.end(), [&] (uint32_t t)
  {
   if (TypeAlwaysExists(t, geomType))
     return false;

   IsDrawableLikeChecker doCheck(geomType, emptyName);
   if (c.ProcessObjects(t, doCheck))
     return false;

   // IsDrawableLikeChecker checks only unique area styles,
   // so we need to take into account point styles too.
   if (geomType == GEOM_AREA)
   {
     IsDrawableLikeChecker doCheck(GEOM_POINT, emptyName);
     if (c.ProcessObjects(t, doCheck))
       return false;
   }

   return true;
  }), types.end());

  return !types.empty();
}

int GetMinDrawableScale(FeatureBase const & f)
{
  int const upBound = scales::GetUpperStyleScale();

  for (int level = 0; level <= upBound; ++level)
    if (IsDrawableForIndex(f, level))
      return level;

  return -1;
}

int GetMinDrawableScaleClassifOnly(FeatureBase const & f)
{
  int const upBound = scales::GetUpperStyleScale();

  for (int level = 0; level <= upBound; ++level)
    if (IsDrawableForIndexClassifOnly(f, level))
      return level;

  return -1;
}

namespace
{
  void AddRange(pair<int, int> & dest, pair<int, int> const & src)
  {
    if (src.first != -1)
    {
      ASSERT_GREATER(src.first, -1, ());
      ASSERT_GREATER(src.second, -1, ());

      dest.first = min(dest.first, src.first);
      dest.second = max(dest.second, src.second);

      ASSERT_GREATER(dest.first, -1, ());
      ASSERT_GREATER(dest.second, -1, ());
    }
  }

  class DoGetScalesRange
  {
    pair<int, int> m_scales;
  public:
    DoGetScalesRange() : m_scales(1000, -1000) {}
    typedef bool ResultType;

    void operator() (ClassifObject const *) {}
    bool operator() (ClassifObject const * p, bool & res)
    {
      res = true;
      AddRange(m_scales, p->GetDrawScaleRange());
      return false;
    }

    pair<int, int> GetScale() const
    {
      return (m_scales.first > m_scales.second ? make_pair(-1, -1) : m_scales);
    }
  };
}

pair<int, int> GetDrawableScaleRange(uint32_t type)
{
  DoGetScalesRange doGet;
  (void)classif().ProcessObjects(type, doGet);
  return doGet.GetScale();
}

pair<int, int> GetDrawableScaleRange(TypesHolder const & types)
{
  pair<int, int> res(1000, -1000);

  for (uint32_t t : types)
    AddRange(res, GetDrawableScaleRange(t));

  return (res.first > res.second ? make_pair(-1, -1) : res);
}

namespace
{
  bool IsDrawableForRules(TypesHolder const & types, int level, int rules)
  {
    Classificator const & c = classif();

    IsDrawableRulesChecker doCheck(level, types.GetGeoType(), rules);
    for (uint32_t t : types)
      if (c.ProcessObjects(t, doCheck))
        return true;

    return false;
  }
}

pair<int, int> GetDrawableScaleRangeForRules(TypesHolder const & types, int rules)
{
  int const upBound = scales::GetUpperStyleScale();
  int lowL = -1;
  for (int level = 0; level <= upBound; ++level)
  {
    if (IsDrawableForRules(types, level, rules))
    {
      lowL = level;
      break;
    }
  }

  if (lowL == -1)
    return make_pair(-1, -1);

  int highL = lowL;
  for (int level = upBound; level > lowL; --level)
  {
    if (IsDrawableForRules(types, level, rules))
    {
      highL = level;
      break;
    }
  }

  return make_pair(lowL, highL);
}

pair<int, int> GetDrawableScaleRangeForRules(FeatureBase const & f, int rules)
{
  return GetDrawableScaleRangeForRules(TypesHolder(f), rules);
}

TypeSetChecker::TypeSetChecker(initializer_list<char const *> const & lst)
{
  m_type = classif().GetTypeByPath(lst);
  m_level = lst.size();
}

bool TypeSetChecker::IsEqual(uint32_t type) const
{
  ftype::TruncValue(type, m_level);
  return (m_type == type);
}

}   // namespace feature
<|endoftext|>


<commit_before>#include "SQLiteQuery.h"

/**
 * The function to call when running the 'index' command.
 */
SQLiteQuery::SQLiteQuery(char * indexdir, EMatrix * ematrix) :
  IndexQuery(indexdir, ematrix) {

}
/**
 * Destructor
 */
SQLiteQuery::~SQLiteQuery() {

}

/**
 * Performs the indexing.
 */
void SQLiteQuery::run(int x_coord, int y_coord, float score) {
  int i;
  char q[2048];
  sqlite3_stmt *cluster_select_stmt;
  int rc;
  int j, k, cluster_num, num_clusters, num_missing, num_samples;
  char * samples;
  float cv;

  // Iterate through the directories.
  for (i = 100; i >= 0; i--) {

    // If a threshold is set then don't examine indexes below the requested value.
    if (i / 100.0 <= score) {
      continue;
    }

    char dirname[1024];
    char dbname[1024];
    if (i > 0) {
      sprintf(dirname, "./%s/%03d", indexdir, i);
      sprintf(dbname, "%s/%03d.db", dirname, i);
    }
    else {
      sprintf(dirname, "./%s/nan", indexdir);
      sprintf(dbname, "%s/nan.db", dirname);
    }

    // Open the output directory.
    DIR * dir;
    dir = opendir(dirname);
    if (!dir) {
      fprintf(stderr, "WARNING: The output directory, %s, is missing. skipping.\n", dirname);
      continue;
    }

    // Each directory has it's own SQLite database.
    sqlite3 * db;
    if (sqlite3_open(dbname, &db)){
      fprintf(stderr, "ERROR: Can't open SQLite database: %s\n", sqlite3_errmsg(db));
      exit(-1);
    }

    // Build the SQL query for filtering.
    sprintf(q, "%s", "\
      SELECT gene1, gene2, num_clusters, cluster_num, num_missing, \
        num_samples, score, samples  \
        FROM clusters C WHERE (1=1) ");
    if (x_coord) {
      sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, x_coord, x_coord);
    }
    if (y_coord) {
      sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, y_coord, y_coord);
    }
    if (score) {
      sprintf(q, "%s AND (score >= %f OR score <= -%f) ", q, score, score);
    }
    // sprintf(q, "%s ORDER BY score DESC;", q);
    sprintf(q, "%s;", q);
 // printf("%s\n", q);

    // Prepare the query for execution.
    rc = sqlite3_prepare_v2(db, q, 2048, &cluster_select_stmt, NULL);
    if (rc != SQLITE_OK) {
      fprintf(stderr, "Failed to prepare cluster select statement: %s\n", sqlite3_errmsg(db));
      exit(-1);
    }

    // Iterate through the results of the query
    rc = sqlite3_step(cluster_select_stmt);
    while (rc == SQLITE_ROW) {

      // Get the values for this row in the result set.
      j  = sqlite3_column_int(cluster_select_stmt, 0);
      k  = sqlite3_column_int(cluster_select_stmt, 1);
      num_clusters  = sqlite3_column_int(cluster_select_stmt, 2);
      cluster_num  = sqlite3_column_int(cluster_select_stmt, 3);
      num_missing  = sqlite3_column_int(cluster_select_stmt, 4);
      num_samples  = sqlite3_column_int(cluster_select_stmt, 5);
      cv  = sqlite3_column_double(cluster_select_stmt, 6);
      samples  = (char *) sqlite3_column_text(cluster_select_stmt, 7);

      // Write the line to output.
      printf("%s\t%s\t%0.8f\tco\t%d\t%d\t%d\t%d\t%s\n", ematrix->getGene(j), ematrix->getGene(k), cv,
          cluster_num, num_clusters, num_samples, num_missing, samples);

      // Get the next row.
      rc = sqlite3_step(cluster_select_stmt);
    }
    // Finalize the statement.
    sqlite3_finalize(cluster_select_stmt);

    // Close the database.
    sqlite3_close(db);
  }
}
<commit_msg>Change to error messaging<commit_after>#include "SQLiteQuery.h"

/**
 * The function to call when running the 'index' command.
 */
SQLiteQuery::SQLiteQuery(char * indexdir, EMatrix * ematrix) :
  IndexQuery(indexdir, ematrix) {

}
/**
 * Destructor
 */
SQLiteQuery::~SQLiteQuery() {

}

/**
 * Performs the indexing.
 */
void SQLiteQuery::run(int x_coord, int y_coord, float score) {
  int i;
  char q[2048];
  sqlite3_stmt *cluster_select_stmt;
  int rc;
  int j, k, cluster_num, num_clusters, num_missing, num_samples;
  char * samples;
  float cv;

  // Iterate through the directories.
  for (i = 100; i >= 0; i--) {

    // If a threshold is set then don't examine indexes below the requested value.
    if (i / 100.0 <= score) {
      continue;
    }

    char dirname[1024];
    char dbname[1024];
    if (i > 0) {
      sprintf(dirname, "./%s/%03d", indexdir, i);
      sprintf(dbname, "%s/%03d.db", dirname, i);
    }
    else {
      sprintf(dirname, "./%s/nan", indexdir);
      sprintf(dbname, "%s/nan.db", dirname);
    }

    // Open the output directory.
    DIR * dir;
    dir = opendir(dirname);
    if (!dir) {
      fprintf(stderr, "WARNING: The output directory, %s, is missing. skipping.\n", dirname);
      continue;
    }

    // Each directory has it's own SQLite database.
    sqlite3 * db;
    if (sqlite3_open(dbname, &db)){
      fprintf(stderr, "ERROR: Can't open SQLite database: %s\n", sqlite3_errmsg(db));
      exit(-1);
    }

    // Build the SQL query for filtering.
    sprintf(q, "%s", "\
      SELECT gene1, gene2, num_clusters, cluster_num, num_missing, \
        num_samples, score, samples  \
        FROM clusters C WHERE (1=1) ");
    if (x_coord) {
      sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, x_coord, x_coord);
    }
    if (y_coord) {
      sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, y_coord, y_coord);
    }
    if (score) {
      sprintf(q, "%s AND (score >= %f OR score <= -%f) ", q, score, score);
    }
    // sprintf(q, "%s ORDER BY score DESC;", q);
    sprintf(q, "%s;", q);
 // printf("%s\n", q);

    // Prepare the query for execution.
    rc = sqlite3_prepare_v2(db, q, 2048, &cluster_select_stmt, NULL);
    if (rc != SQLITE_OK) {
      fprintf(stderr, "Failed to prepare cluster select statement for index %s: %s\n", dirname, sqlite3_errmsg(db));
      exit(-1);
    }

    // Iterate through the results of the query
    rc = sqlite3_step(cluster_select_stmt);
    while (rc == SQLITE_ROW) {

      // Get the values for this row in the result set.
      j  = sqlite3_column_int(cluster_select_stmt, 0);
      k  = sqlite3_column_int(cluster_select_stmt, 1);
      num_clusters  = sqlite3_column_int(cluster_select_stmt, 2);
      cluster_num  = sqlite3_column_int(cluster_select_stmt, 3);
      num_missing  = sqlite3_column_int(cluster_select_stmt, 4);
      num_samples  = sqlite3_column_int(cluster_select_stmt, 5);
      cv  = sqlite3_column_double(cluster_select_stmt, 6);
      samples  = (char *) sqlite3_column_text(cluster_select_stmt, 7);

      // Write the line to output.
      printf("%s\t%s\t%0.8f\tco\t%d\t%d\t%d\t%d\t%s\n", ematrix->getGene(j), ematrix->getGene(k), cv,
          cluster_num, num_clusters, num_samples, num_missing, samples);

      // Get the next row.
      rc = sqlite3_step(cluster_select_stmt);
    }
    // Finalize the statement.
    sqlite3_finalize(cluster_select_stmt);

    // Close the database.
    sqlite3_close(db);
  }
}
<|endoftext|>


<commit_before>/**
 * @file llfloatermap.cpp
 * @brief The "mini-map" or radar in the upper right part of the screen.
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * 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;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

// self include
#include "llfloatermap.h"

// Library includes
#include "llfloaterreg.h"
#include "llfontgl.h"
#include "llglheaders.h"

// Viewer includes
#include "llagentcamera.h"
#include "llviewercontrol.h"
#include "llnetmap.h"
#include "lltracker.h"
#include "llviewercamera.h"
#include "lldraghandle.h"
#include "lltextbox.h"
#include "llviewermenu.h"

//
// Constants
//

// The minor cardinal direction labels are hidden if their height is more
// than this proportion of the map.
const F32 MAP_MINOR_DIR_THRESHOLD = 0.07f;
const S32 MAP_PADDING_LEFT = 0;
const S32 MAP_PADDING_TOP = 2;
const S32 MAP_PADDING_RIGHT = 2;
const S32 MAP_PADDING_BOTTOM = 0;
//
// Member functions
//

LLFloaterMap::LLFloaterMap(const LLSD& key)
	: LLFloater(key),
	  mPopupMenu(NULL),
	  mTextBoxEast(NULL),
	  mTextBoxNorth(NULL),
	  mTextBoxWest(NULL),
	  mTextBoxSouth(NULL),
	  mTextBoxSouthEast(NULL),
	  mTextBoxNorthEast(NULL),
	  mTextBoxNorthWest(NULL),
	  mTextBoxSouthWest(NULL),
	  mMap(NULL)
{
	//Called from floater reg: LLUICtrlFactory::getInstance()->buildFloater(this, "floater_map.xml", FALSE);
}

LLFloaterMap::~LLFloaterMap()
{
}

BOOL LLFloaterMap::postBuild()
{
	mMap = getChild<LLNetMap>("Net Map");
	mMap->setScale(gSavedSettings.getF32("MiniMapScale"));
	mMap->setToolTipMsg(getString("ToolTipMsg"));
	sendChildToBack(mMap);

	mTextBoxNorth = getChild<LLTextBox> ("floater_map_north");
	mTextBoxEast = getChild<LLTextBox> ("floater_map_east");
	mTextBoxWest = getChild<LLTextBox> ("floater_map_west");
	mTextBoxSouth = getChild<LLTextBox> ("floater_map_south");
	mTextBoxSouthEast = getChild<LLTextBox> ("floater_map_southeast");
	mTextBoxNorthEast = getChild<LLTextBox> ("floater_map_northeast");
	mTextBoxSouthWest = getChild<LLTextBox> ("floater_map_southwest");
	mTextBoxNorthWest = getChild<LLTextBox> ("floater_map_northwest");

	LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;

	registrar.add("Minimap.Zoom", boost::bind(&LLFloaterMap::handleZoom, this, _2));
	registrar.add("Minimap.Tracker", boost::bind(&LLFloaterMap::handleStopTracking, this, _2));

	mPopupMenu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_mini_map.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
	if (mPopupMenu && !LLTracker::isTracking(0))
	{
		mPopupMenu->setItemEnabled ("Stop Tracking", false);
	}

	stretchMiniMap(getRect().getWidth() - MAP_PADDING_LEFT - MAP_PADDING_RIGHT
		,getRect().getHeight() - MAP_PADDING_TOP - MAP_PADDING_BOTTOM);

	updateMinorDirections();

	// Get the drag handle all the way in back
	sendChildToBack(getDragHandle());

	setIsChrome(TRUE);
	getDragHandle()->setTitleVisible(TRUE);

	// keep onscreen
	gFloaterView->adjustToFitScreen(this, FALSE);

	return TRUE;
}

BOOL LLFloaterMap::handleDoubleClick( S32 x, S32 y, MASK mask )
{
	LLFloaterReg::showInstance("world_map");
	return TRUE;
}

BOOL LLFloaterMap::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
	if (mPopupMenu)
	{
		mPopupMenu->buildDrawLabels();
		mPopupMenu->updateParent(LLMenuGL::sMenuContainer);
		LLMenuGL::showPopup(this, mPopupMenu, x, y);
	}
	return TRUE;
}

void LLFloaterMap::setDirectionPos( LLTextBox* text_box, F32 rotation )
{
	// Rotation is in radians.
	// Rotation of 0 means x = 1, y = 0 on the unit circle.

	F32 map_half_height = (F32)(getRect().getHeight() / 2) - getHeaderHeight()/2;
	F32 map_half_width = (F32)(getRect().getWidth() / 2) ;
	F32 text_half_height = (F32)(text_box->getRect().getHeight() / 2);
	F32 text_half_width = (F32)(text_box->getRect().getWidth() / 2);
	F32 radius = llmin( map_half_height - text_half_height, map_half_width - text_half_width );

	// Inset by a little to account for position display.
	radius -= 8.f;

	text_box->setOrigin(
		llround(map_half_width - text_half_width + radius * cos( rotation )),
		llround(map_half_height - text_half_height + radius * sin( rotation )) );
}

void LLFloaterMap::updateMinorDirections()
{
	if (mTextBoxNorthEast == NULL)
	{
		return;
	}

	// Hide minor directions if they cover too much of the map
	bool show_minors = mTextBoxNorthEast->getRect().getHeight() < MAP_MINOR_DIR_THRESHOLD *
		llmin(getRect().getWidth(), getRect().getHeight());

	mTextBoxNorthEast->setVisible(show_minors);
	mTextBoxNorthWest->setVisible(show_minors);
	mTextBoxSouthWest->setVisible(show_minors);
	mTextBoxSouthEast->setVisible(show_minors);
}

// virtual
void LLFloaterMap::draw()
{
	F32 rotation = 0;

	static LLUICachedControl<bool> rotate_map("MiniMapRotate", true);
	if( rotate_map )
	{
		// rotate subsequent draws to agent rotation
		rotation = atan2( LLViewerCamera::getInstance()->getAtAxis().mV[VX], LLViewerCamera::getInstance()->getAtAxis().mV[VY] );
	}

	setDirectionPos( mTextBoxEast,  rotation );
	setDirectionPos( mTextBoxNorth, rotation + F_PI_BY_TWO );
	setDirectionPos( mTextBoxWest,  rotation + F_PI );
	setDirectionPos( mTextBoxSouth, rotation + F_PI + F_PI_BY_TWO );

	setDirectionPos( mTextBoxNorthEast, rotation +						F_PI_BY_TWO / 2);
	setDirectionPos( mTextBoxNorthWest, rotation + F_PI_BY_TWO +		F_PI_BY_TWO / 2);
	setDirectionPos( mTextBoxSouthWest, rotation + F_PI +				F_PI_BY_TWO / 2);
	setDirectionPos( mTextBoxSouthEast, rotation + F_PI + F_PI_BY_TWO + F_PI_BY_TWO / 2);

	// Note: we can't just gAgent.check cameraMouselook() because the transition states are wrong.
	if(gAgentCamera.cameraMouselook())
	{
		setMouseOpaque(FALSE);
		getDragHandle()->setMouseOpaque(FALSE);
	}
	else
	{
		setMouseOpaque(TRUE);
		getDragHandle()->setMouseOpaque(TRUE);
	}

	if (LLTracker::isTracking(0))
	{
		mPopupMenu->setItemEnabled ("Stop Tracking", true);
	}

	LLFloater::draw();
}

// virtual
void LLFloaterMap::onFocusReceived()
{
	setBackgroundOpaque(true);
	LLPanel::onFocusReceived();
}

// virtual
void LLFloaterMap::onFocusLost()
{
	setBackgroundOpaque(false);
	LLPanel::onFocusLost();
}

void LLFloaterMap::stretchMiniMap(S32 width,S32 height)
{
	//fix for ext-7112
	//by default ctrl can't overlap caption area
	if(mMap)
	{
		LLRect map_rect;
		map_rect.setLeftTopAndSize( MAP_PADDING_LEFT, getRect().getHeight() - MAP_PADDING_TOP, width, height);
		mMap->reshape( width, height, 1);
		mMap->setRect(map_rect);
	}
}

void LLFloaterMap::reshape(S32 width, S32 height, BOOL called_from_parent)
{
	LLFloater::reshape(width, height, called_from_parent);

	stretchMiniMap(width - MAP_PADDING_LEFT - MAP_PADDING_RIGHT
		,height - MAP_PADDING_TOP - MAP_PADDING_BOTTOM);

	updateMinorDirections();
}

void LLFloaterMap::handleZoom(const LLSD& userdata)
{
	std::string level = userdata.asString();

	F32 scale = 0.0f;
	if (level == std::string("close"))
		scale = LLNetMap::MAP_SCALE_MAX;
	else if (level == std::string("medium"))
		scale = LLNetMap::MAP_SCALE_MID;
	else if (level == std::string("far"))
		scale = LLNetMap::MAP_SCALE_MIN;
	if (scale != 0.0f)
	{
		gSavedSettings.setF32("MiniMapScale", scale );
		mMap->setScale(scale);
	}
}

void LLFloaterMap::handleStopTracking (const LLSD& userdata)
{
	if (mPopupMenu)
	{
		mPopupMenu->setItemEnabled ("Stop Tracking", false);
		LLTracker::stopTracking ((void*)LLTracker::isTracking(NULL));
	}
}
void	LLFloaterMap::setMinimized(BOOL b)
{
	LLFloater::setMinimized(b);
	if(b)
	{
		setTitle(getString("mini_map_caption"));
	}
	else
	{
		setTitle("");
	}
}
<commit_msg>STORM-299 FIXED World map floater opening instead Mini-map if double-click on minimized Mini-map.<commit_after>/**
 * @file llfloatermap.cpp
 * @brief The "mini-map" or radar in the upper right part of the screen.
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * 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;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

// self include
#include "llfloatermap.h"

// Library includes
#include "llfloaterreg.h"
#include "llfontgl.h"
#include "llglheaders.h"

// Viewer includes
#include "llagentcamera.h"
#include "llviewercontrol.h"
#include "llnetmap.h"
#include "lltracker.h"
#include "llviewercamera.h"
#include "lldraghandle.h"
#include "lltextbox.h"
#include "llviewermenu.h"

//
// Constants
//

// The minor cardinal direction labels are hidden if their height is more
// than this proportion of the map.
const F32 MAP_MINOR_DIR_THRESHOLD = 0.07f;
const S32 MAP_PADDING_LEFT = 0;
const S32 MAP_PADDING_TOP = 2;
const S32 MAP_PADDING_RIGHT = 2;
const S32 MAP_PADDING_BOTTOM = 0;
//
// Member functions
//

LLFloaterMap::LLFloaterMap(const LLSD& key)
	: LLFloater(key),
	  mPopupMenu(NULL),
	  mTextBoxEast(NULL),
	  mTextBoxNorth(NULL),
	  mTextBoxWest(NULL),
	  mTextBoxSouth(NULL),
	  mTextBoxSouthEast(NULL),
	  mTextBoxNorthEast(NULL),
	  mTextBoxNorthWest(NULL),
	  mTextBoxSouthWest(NULL),
	  mMap(NULL)
{
	//Called from floater reg: LLUICtrlFactory::getInstance()->buildFloater(this, "floater_map.xml", FALSE);
}

LLFloaterMap::~LLFloaterMap()
{
}

BOOL LLFloaterMap::postBuild()
{
	mMap = getChild<LLNetMap>("Net Map");
	mMap->setScale(gSavedSettings.getF32("MiniMapScale"));
	mMap->setToolTipMsg(getString("ToolTipMsg"));
	sendChildToBack(mMap);

	mTextBoxNorth = getChild<LLTextBox> ("floater_map_north");
	mTextBoxEast = getChild<LLTextBox> ("floater_map_east");
	mTextBoxWest = getChild<LLTextBox> ("floater_map_west");
	mTextBoxSouth = getChild<LLTextBox> ("floater_map_south");
	mTextBoxSouthEast = getChild<LLTextBox> ("floater_map_southeast");
	mTextBoxNorthEast = getChild<LLTextBox> ("floater_map_northeast");
	mTextBoxSouthWest = getChild<LLTextBox> ("floater_map_southwest");
	mTextBoxNorthWest = getChild<LLTextBox> ("floater_map_northwest");

	LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;

	registrar.add("Minimap.Zoom", boost::bind(&LLFloaterMap::handleZoom, this, _2));
	registrar.add("Minimap.Tracker", boost::bind(&LLFloaterMap::handleStopTracking, this, _2));

	mPopupMenu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_mini_map.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
	if (mPopupMenu && !LLTracker::isTracking(0))
	{
		mPopupMenu->setItemEnabled ("Stop Tracking", false);
	}

	stretchMiniMap(getRect().getWidth() - MAP_PADDING_LEFT - MAP_PADDING_RIGHT
		,getRect().getHeight() - MAP_PADDING_TOP - MAP_PADDING_BOTTOM);

	updateMinorDirections();

	// Get the drag handle all the way in back
	sendChildToBack(getDragHandle());

	setIsChrome(TRUE);
	getDragHandle()->setTitleVisible(TRUE);

	// keep onscreen
	gFloaterView->adjustToFitScreen(this, FALSE);

	return TRUE;
}

BOOL LLFloaterMap::handleDoubleClick( S32 x, S32 y, MASK mask )
{
	// If floater is minimized, minimap should be shown on doubleclick (STORM-299)
	std::string floater_to_show = this->isMinimized() ? "mini_map" : "world_map";
	LLFloaterReg::showInstance(floater_to_show);
	return TRUE;
}

BOOL LLFloaterMap::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
	if (mPopupMenu)
	{
		mPopupMenu->buildDrawLabels();
		mPopupMenu->updateParent(LLMenuGL::sMenuContainer);
		LLMenuGL::showPopup(this, mPopupMenu, x, y);
	}
	return TRUE;
}

void LLFloaterMap::setDirectionPos( LLTextBox* text_box, F32 rotation )
{
	// Rotation is in radians.
	// Rotation of 0 means x = 1, y = 0 on the unit circle.

	F32 map_half_height = (F32)(getRect().getHeight() / 2) - getHeaderHeight()/2;
	F32 map_half_width = (F32)(getRect().getWidth() / 2) ;
	F32 text_half_height = (F32)(text_box->getRect().getHeight() / 2);
	F32 text_half_width = (F32)(text_box->getRect().getWidth() / 2);
	F32 radius = llmin( map_half_height - text_half_height, map_half_width - text_half_width );

	// Inset by a little to account for position display.
	radius -= 8.f;

	text_box->setOrigin(
		llround(map_half_width - text_half_width + radius * cos( rotation )),
		llround(map_half_height - text_half_height + radius * sin( rotation )) );
}

void LLFloaterMap::updateMinorDirections()
{
	if (mTextBoxNorthEast == NULL)
	{
		return;
	}

	// Hide minor directions if they cover too much of the map
	bool show_minors = mTextBoxNorthEast->getRect().getHeight() < MAP_MINOR_DIR_THRESHOLD *
		llmin(getRect().getWidth(), getRect().getHeight());

	mTextBoxNorthEast->setVisible(show_minors);
	mTextBoxNorthWest->setVisible(show_minors);
	mTextBoxSouthWest->setVisible(show_minors);
	mTextBoxSouthEast->setVisible(show_minors);
}

// virtual
void LLFloaterMap::draw()
{
	F32 rotation = 0;

	static LLUICachedControl<bool> rotate_map("MiniMapRotate", true);
	if( rotate_map )
	{
		// rotate subsequent draws to agent rotation
		rotation = atan2( LLViewerCamera::getInstance()->getAtAxis().mV[VX], LLViewerCamera::getInstance()->getAtAxis().mV[VY] );
	}

	setDirectionPos( mTextBoxEast,  rotation );
	setDirectionPos( mTextBoxNorth, rotation + F_PI_BY_TWO );
	setDirectionPos( mTextBoxWest,  rotation + F_PI );
	setDirectionPos( mTextBoxSouth, rotation + F_PI + F_PI_BY_TWO );

	setDirectionPos( mTextBoxNorthEast, rotation +						F_PI_BY_TWO / 2);
	setDirectionPos( mTextBoxNorthWest, rotation + F_PI_BY_TWO +		F_PI_BY_TWO / 2);
	setDirectionPos( mTextBoxSouthWest, rotation + F_PI +				F_PI_BY_TWO / 2);
	setDirectionPos( mTextBoxSouthEast, rotation + F_PI + F_PI_BY_TWO + F_PI_BY_TWO / 2);

	// Note: we can't just gAgent.check cameraMouselook() because the transition states are wrong.
	if(gAgentCamera.cameraMouselook())
	{
		setMouseOpaque(FALSE);
		getDragHandle()->setMouseOpaque(FALSE);
	}
	else
	{
		setMouseOpaque(TRUE);
		getDragHandle()->setMouseOpaque(TRUE);
	}

	if (LLTracker::isTracking(0))
	{
		mPopupMenu->setItemEnabled ("Stop Tracking", true);
	}

	LLFloater::draw();
}

// virtual
void LLFloaterMap::onFocusReceived()
{
	setBackgroundOpaque(true);
	LLPanel::onFocusReceived();
}

// virtual
void LLFloaterMap::onFocusLost()
{
	setBackgroundOpaque(false);
	LLPanel::onFocusLost();
}

void LLFloaterMap::stretchMiniMap(S32 width,S32 height)
{
	//fix for ext-7112
	//by default ctrl can't overlap caption area
	if(mMap)
	{
		LLRect map_rect;
		map_rect.setLeftTopAndSize( MAP_PADDING_LEFT, getRect().getHeight() - MAP_PADDING_TOP, width, height);
		mMap->reshape( width, height, 1);
		mMap->setRect(map_rect);
	}
}

void LLFloaterMap::reshape(S32 width, S32 height, BOOL called_from_parent)
{
	LLFloater::reshape(width, height, called_from_parent);

	stretchMiniMap(width - MAP_PADDING_LEFT - MAP_PADDING_RIGHT
		,height - MAP_PADDING_TOP - MAP_PADDING_BOTTOM);

	updateMinorDirections();
}

void LLFloaterMap::handleZoom(const LLSD& userdata)
{
	std::string level = userdata.asString();

	F32 scale = 0.0f;
	if (level == std::string("close"))
		scale = LLNetMap::MAP_SCALE_MAX;
	else if (level == std::string("medium"))
		scale = LLNetMap::MAP_SCALE_MID;
	else if (level == std::string("far"))
		scale = LLNetMap::MAP_SCALE_MIN;
	if (scale != 0.0f)
	{
		gSavedSettings.setF32("MiniMapScale", scale );
		mMap->setScale(scale);
	}
}

void LLFloaterMap::handleStopTracking (const LLSD& userdata)
{
	if (mPopupMenu)
	{
		mPopupMenu->setItemEnabled ("Stop Tracking", false);
		LLTracker::stopTracking ((void*)LLTracker::isTracking(NULL));
	}
}
void	LLFloaterMap::setMinimized(BOOL b)
{
	LLFloater::setMinimized(b);
	if(b)
	{
		setTitle(getString("mini_map_caption"));
	}
	else
	{
		setTitle("");
	}
}
<|endoftext|>