<commit_before>#include <iostream>
#include <string>
/*add the header if you need*/
using namespace std;

//Abstract base class for Dessert Item hierarchy
class DessertItem
{
private:
//Name of the DessertItem object
    string name;

public:
    DessertItem(){}
    DessertItem(string name):name(name){}
//Empty virtual destructor for DessertItem class
    virtual ~DessertItem(){}
//returns Name of DessertItem
    string getName(){ return name;}
    virtual string getDetails() = 0;
    virtual double getCost() = 0;
};

class IceCream : public DessertItem
{

    /* Write about IceCream Constructor
       IceCream(string name, double cost):DessertItem(name),cost(cost)
    */

    /* Write about IceCream other member functions*/
private:
    double cost;
};

class Topping : public IceCream
{

    /* Write about Topping Constructor
       Topping(string iceCreamName, double iceCreamCost,
	string toppingName, double toppingCost)
    */

    /* Write about Topping other member functions*/
private:
    string toppingName;
    double toppingCost;
};

class Cookie : public DessertItem
{
    /* Write about Cookie Constructor
       Cookie(string name, int number, double pricePerDozen)
    */

    /* Write about Cookie other member functions*/

private:
//Number of dozens of Cookie
    int number;
    double pricePerDozen;
};

class Candy : public DessertItem
{
public:
    /* Write here about Candy Constructor
       Candy(string name, double weight, double pricePerGram)
    */
    /* Write about Candy other member functions*/
private:
//Weight of Candy
    double weight;
    double pricePerGram;
};

class Checkout {

    friend ostream &operator<<(std::ostream &, Checkout &);

    /* Write about Checkout member functions
    1. "enterItem" function to add the element into the list
    2. "removeItem" function to remove the elemtent from the list
    3. calculate the total cost and tax in the list
    4. "numberOfItems" for number of Item in the list
    5. "clear" clear all Items from list
    */
private:
    list<DessertItem*> itemList;
};

ostream &operator<<(ostream &output, Checkout &checkout){

/*Overloaded operator that output a receipt for the current list of items*/

}
<commit_msg>HW5/p1.hpp<commit_after>#include <iostream>
#include <string>
/*add the header if you need*/
#include <list>
#include <iomanip>
#include <sstream>
using namespace std;

//Abstract base class for Dessert Item hierarchy
class DessertItem
{
private:
//Name of the DessertItem object
    string name;

public:
    DessertItem(){}
    DessertItem(string name):name(name){}
//Empty virtual destructor for DessertItem class
    virtual ~DessertItem(){}
//returns Name of DessertItem
    string getName(){ return name;}
    virtual string getDetails() = 0;
    virtual double getCost() = 0;
};

class IceCream : public DessertItem
{
public:
    /* Write about IceCream Constructor
       IceCream(string name, double cost):DessertItem(name),cost(cost)
    */
    IceCream(string name, double cost):DessertItem(name), cost(cost)
    {

    }
    /* Write about IceCream other member functions*/
    string getDetails()
    {
        return "";
    }

    double getCost()
    {
        return cost;
    }
private:
    double cost;
};

class Topping : public IceCream
{
public:
    /* Write about Topping Constructor
       Topping(string iceCreamName, double iceCreamCost,
	string toppingName, double toppingCost)
    */
    Topping(string iceCreamName, double iceCreamCost, string toppingName, double toppingCost)
    :IceCream(toppingName + " Sundae with " + iceCreamName, iceCreamCost), toppingName(toppingName), toppingCost(toppingCost)
    {

    }
    /* Write about Topping other member functions*/
    string getDetails()
    {
        return "";
    }

    double getCost()
    {
        return toppingCost + IceCream::getCost();
    }
private:
    string toppingName;
    double toppingCost;
};

class Cookie : public DessertItem
{
public:
    /* Write about Cookie Constructor
       Cookie(string name, int number, double pricePerDozen)
    */
    Cookie(string name, int number, double pricePerDozen)
    :DessertItem(name), number(number), pricePerDozen(pricePerDozen)
    {

    }
    /* Write about Cookie other member functions*/
    string getDetails()
    {
        return "(" + to_string(number) + " dozen(s) * " + (stringstream() << pricePerDozen).str() + "/dozen)\n";
    }

    double getCost()
    {
        return number * pricePerDozen;
    }
private:
//Number of dozens of Cookie
    int number;
    double pricePerDozen;
};

class Candy : public DessertItem
{
public:
    /* Write here about Candy Constructor
       Candy(string name, double weight, double pricePerGram)
    */
    Candy(string name, double weight, double pricePerGram)
    :DessertItem(name), weight(weight), pricePerGram(pricePerGram)
    {

    }
    /* Write about Candy other member functions*/
    string getDetails()
    {
        return "(" + (stringstream() << weight).str() + " gram(s) * " + (stringstream() << pricePerGram).str() + "/gram)\n";
    }

    double getCost()
    {
        return weight * pricePerGram;
    }
private:
//Weight of Candy
    double weight;
    double pricePerGram;
};

class Checkout {

    friend ostream &operator<<(std::ostream &, Checkout &);

    /* Write about Checkout member functions
    1. "enterItem" function to add the element into the list
    2. "removeItem" function to remove the elemtent from the list
    3. calculate the total cost and tax in the list
    4. "numberOfItems" for number of Item in the list
    5. "clear" clear all Items from list
    */
public:
    void enterItem(DessertItem *ptr)
    {
        itemList.push_back(ptr);
    }

    void removeItem(int idx)
    {
        auto it = itemList.begin();
        while(idx--){
            it++;
        }
        itemList.erase(it);
    }

    int numberOfItems() const
    {
        return itemList.size();
    }

    void clear()
    {
        itemList.clear();
    }
private:
    list<DessertItem*> itemList;
};

ostream &operator<<(ostream &output, Checkout &checkout){

/*Overloaded operator that output a receipt for the current list of items*/
    output.setf(ios::fixed, ios::floatfield);
    output << setprecision(0);
    output << "Welcome to OOP's shop" << endl;
    output << "------------------------------" << endl;
    output << endl;
    output << "Number of items: " << checkout.numberOfItems() << endl;
    output << endl;
    double cost = 0;
    for(auto dessert:checkout.itemList){
        cost += dessert->getCost();
        cout << setw(50) << left << dessert->getName() << right << dessert->getCost() << endl;
        cout << dessert->getDetails();
    }
    output << endl;
    output << "------------------------------" << endl;
    output << setw(50) << left << "Cost" << right << cost << endl;
    output << setw(50) << left << "Tax" << right << cost / 20 << endl;
    output << endl;
    output << setw(50) << left << "Total cost" << right << cost * (1.05);
    return output;
}
<|endoftext|>


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

#include "chrome/renderer/media/cast_rtp_stream.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "chrome/renderer/media/cast_session.h"
#include "chrome/renderer/media/cast_udp_transport.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "content/public/renderer/media_stream_video_sink.h"
#include "media/audio/audio_parameters.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_fifo.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/multi_channel_resampler.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_defines.h"
#include "media/cast/cast_sender.h"
#include "media/cast/transport/cast_transport_config.h"
#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"

using media::cast::AudioSenderConfig;
using media::cast::VideoSenderConfig;

namespace {

const char kCodecNameOpus[] = "OPUS";
const char kCodecNameVp8[] = "VP8";

// This constant defines the number of sets of audio data to buffer
// in the FIFO. If input audio and output data have different resampling
// rates then buffer is necessary to avoid audio glitches.
// See CastAudioSink::ResampleData() and CastAudioSink::OnSetFormat()
// for more defaults.
const int kBufferAudioData = 2;

CastRtpPayloadParams DefaultOpusPayload() {
  CastRtpPayloadParams payload;
  payload.ssrc = 1;
  payload.feedback_ssrc = 1;
  payload.payload_type = 127;
  payload.codec_name = kCodecNameOpus;
  payload.clock_rate = 48000;
  payload.channels = 2;
  payload.min_bitrate = payload.max_bitrate =
      media::cast::kDefaultAudioEncoderBitrate;
  return payload;
}

CastRtpPayloadParams DefaultVp8Payload() {
  CastRtpPayloadParams payload;
  payload.ssrc = 11;
  payload.feedback_ssrc = 12;
  payload.payload_type = 96;
  payload.codec_name = kCodecNameVp8;
  payload.clock_rate = 90000;
  payload.width = 1280;
  payload.height = 720;
  payload.min_bitrate = 50 * 1000;
  payload.max_bitrate = 2000 * 1000;
  return payload;
}

std::vector<CastRtpParams> SupportedAudioParams() {
  // TODO(hclam): Fill in more codecs here.
  std::vector<CastRtpParams> supported_params;
  supported_params.push_back(CastRtpParams(DefaultOpusPayload()));
  return supported_params;
}

std::vector<CastRtpParams> SupportedVideoParams() {
  // TODO(hclam): Fill in H264 here.
  std::vector<CastRtpParams> supported_params;
  supported_params.push_back(CastRtpParams(DefaultVp8Payload()));
  return supported_params;
}

bool ToAudioSenderConfig(const CastRtpParams& params,
                         AudioSenderConfig* config) {
  config->sender_ssrc = params.payload.ssrc;
  config->incoming_feedback_ssrc = params.payload.feedback_ssrc;
  config->rtp_config.payload_type = params.payload.payload_type;
  config->use_external_encoder = false;
  config->frequency = params.payload.clock_rate;
  config->channels = params.payload.channels;
  config->bitrate = params.payload.max_bitrate;
  config->codec = media::cast::transport::kPcm16;
  if (params.payload.codec_name == kCodecNameOpus)
    config->codec = media::cast::transport::kOpus;
  else
    return false;
  return true;
}

bool ToVideoSenderConfig(const CastRtpParams& params,
                         VideoSenderConfig* config) {
  config->sender_ssrc = params.payload.ssrc;
  config->incoming_feedback_ssrc = params.payload.feedback_ssrc;
  config->rtp_config.payload_type = params.payload.payload_type;
  config->use_external_encoder = false;
  config->width = params.payload.width;
  config->height = params.payload.height;
  config->min_bitrate = config->start_bitrate = params.payload.min_bitrate;
  config->max_bitrate = params.payload.max_bitrate;
  if (params.payload.codec_name == kCodecNameVp8)
    config->codec = media::cast::transport::kVp8;
  else
    return false;
  return true;
}

}  // namespace

// This class receives MediaStreamTrack events and video frames from a
// MediaStreamTrack. Video frames are submitted to media::cast::FrameInput.
//
// Threading: Video frames are received on the render thread.
class CastVideoSink : public base::SupportsWeakPtr<CastVideoSink>,
                      public content::MediaStreamVideoSink {
 public:
  // |track| provides data for this sink.
  // |error_callback| is called if video formats don't match.
  CastVideoSink(const blink::WebMediaStreamTrack& track,
                const CastRtpStream::ErrorCallback& error_callback)
      : track_(track),
        sink_added_(false),
        error_callback_(error_callback) {}

  virtual ~CastVideoSink() {
    if (sink_added_)
      RemoveFromVideoTrack(this, track_);
  }

  // content::MediaStreamVideoSink implementation.
  virtual void OnVideoFrame(const scoped_refptr<media::VideoFrame>& frame)
      OVERRIDE {
    DCHECK(frame_input_);
    // TODO(hclam): Pass in the accurate capture time to have good
    // audio/video sync.
    frame_input_->InsertRawVideoFrame(frame, base::TimeTicks::Now());
  }

  // Attach this sink to a video track represented by |track_|.
  // Data received from the track will be submitted to |frame_input|.
  void AddToTrack(
      const scoped_refptr<media::cast::VideoFrameInput>& frame_input) {
    DCHECK(!sink_added_);
    sink_added_ = true;

    frame_input_ = frame_input;
    AddToVideoTrack(this, track_);
  }

 private:
  blink::WebMediaStreamTrack track_;
  scoped_refptr<media::cast::VideoFrameInput> frame_input_;
  bool sink_added_;
  CastRtpStream::ErrorCallback error_callback_;

  DISALLOW_COPY_AND_ASSIGN(CastVideoSink);
};

// Receives audio data from a MediaStreamTrack. Data is submitted to
// media::cast::FrameInput.
//
// Threading: Audio frames are received on the real-time audio thread.
class CastAudioSink : public base::SupportsWeakPtr<CastAudioSink>,
                      public content::MediaStreamAudioSink {
 public:
  // |track| provides data for this sink.
  // |error_callback| is called if audio formats don't match.
  CastAudioSink(const blink::WebMediaStreamTrack& track,
                const CastRtpStream::ErrorCallback& error_callback,
                int output_channels,
                int output_sample_rate)
      : track_(track),
        sink_added_(false),
        error_callback_(error_callback),
        weak_factory_(this),
        input_preroll_(0),
        output_channels_(output_channels),
        output_sample_rate_(output_sample_rate) {}

  virtual ~CastAudioSink() {
    if (sink_added_)
      RemoveFromAudioTrack(this, track_);
  }

  // Called on real-time audio thread.
  // content::MediaStreamAudioSink implementation.
  virtual void OnData(const int16* audio_data,
                      int sample_rate,
                      int number_of_channels,
                      int number_of_frames) OVERRIDE {
    scoped_ptr<media::AudioBus> input_bus;
    if (resampler_) {
      input_bus = ResampleData(
          audio_data, sample_rate, number_of_channels, number_of_frames);
      if (!input_bus)
        return;
    } else {
      input_bus = media::AudioBus::Create(
          number_of_channels, number_of_frames);
      input_bus->FromInterleaved(
          audio_data, number_of_frames, number_of_channels);
    }

    // TODO(hclam): Pass in the accurate capture time to have good
    // audio / video sync.
    frame_input_->InsertAudio(input_bus.Pass(), base::TimeTicks::Now());
  }

  // Return a resampled audio data from input. This is called when the
  // input sample rate doesn't match the output.
  // The flow of data is as follows:
  // |audio_data| ->
  //     AudioFifo |fifo_| ->
  //         MultiChannelResampler |resampler|.
  //
  // The resampler pulls data out of the FIFO and resample the data in
  // frequency domain. It might call |fifo_| for more than once. But no more
  // than |kBufferAudioData| times. We preroll audio data into the FIFO to
  // make sure there's enough data for resampling.
  scoped_ptr<media::AudioBus> ResampleData(
      const int16* audio_data,
      int sample_rate,
      int number_of_channels,
      int number_of_frames) {
    DCHECK_EQ(number_of_channels, output_channels_);
    fifo_input_bus_->FromInterleaved(
        audio_data, number_of_frames, number_of_channels);
    fifo_->Push(fifo_input_bus_.get());

    if (input_preroll_ < kBufferAudioData - 1) {
      ++input_preroll_;
      return scoped_ptr<media::AudioBus>();
    }

    scoped_ptr<media::AudioBus> output_bus(
        media::AudioBus::Create(
            output_channels_,
            output_sample_rate_ * fifo_input_bus_->frames() / sample_rate));

    // Resampler will then call ProvideData() below to fetch data from
    // |input_data_|.
    resampler_->Resample(output_bus->frames(), output_bus.get());
    return output_bus.Pass();
  }

  // Called on real-time audio thread.
  virtual void OnSetFormat(const media::AudioParameters& params) OVERRIDE {
    if (params.sample_rate() == output_sample_rate_)
      return;
    fifo_.reset(new media::AudioFifo(
        output_channels_,
        kBufferAudioData * params.frames_per_buffer()));
    fifo_input_bus_ = media::AudioBus::Create(
        params.channels(), params.frames_per_buffer());
    resampler_.reset(new media::MultiChannelResampler(
        output_channels_,
        static_cast<double>(params.sample_rate()) / output_sample_rate_,
        params.frames_per_buffer(),
        base::Bind(&CastAudioSink::ProvideData, base::Unretained(this))));
  }

  // Add this sink to the track. Data received from the track will be
  // submitted to |frame_input|.
  void AddToTrack(
      const scoped_refptr<media::cast::AudioFrameInput>& frame_input) {
    DCHECK(!sink_added_);
    sink_added_ = true;

    // This member is written here and then accessed on the IO thread
    // We will not get data until AddToAudioTrack is called so it is
    // safe to access this member now.
    frame_input_ = frame_input;
    AddToAudioTrack(this, track_);
  }

  void ProvideData(int frame_delay, media::AudioBus* output_bus) {
    fifo_->Consume(output_bus, 0, output_bus->frames());
  }

 private:
  blink::WebMediaStreamTrack track_;
  bool sink_added_;
  CastRtpStream::ErrorCallback error_callback_;
  base::WeakPtrFactory<CastAudioSink> weak_factory_;

  scoped_ptr<media::MultiChannelResampler> resampler_;
  scoped_ptr<media::AudioFifo> fifo_;
  scoped_ptr<media::AudioBus> fifo_input_bus_;
  int input_preroll_;
  const int output_channels_;
  const int output_sample_rate_;

  // This member is accessed on the real-time audio time.
  scoped_refptr<media::cast::AudioFrameInput> frame_input_;

  DISALLOW_COPY_AND_ASSIGN(CastAudioSink);
};

CastRtpParams::CastRtpParams(const CastRtpPayloadParams& payload_params)
    : payload(payload_params) {}

CastCodecSpecificParams::CastCodecSpecificParams() {}

CastCodecSpecificParams::~CastCodecSpecificParams() {}

CastRtpPayloadParams::CastRtpPayloadParams()
    : payload_type(0),
      ssrc(0),
      feedback_ssrc(0),
      clock_rate(0),
      max_bitrate(0),
      min_bitrate(0),
      channels(0),
      width(0),
      height(0) {}

CastRtpPayloadParams::~CastRtpPayloadParams() {}

CastRtpParams::CastRtpParams() {}

CastRtpParams::~CastRtpParams() {}

CastRtpStream::CastRtpStream(const blink::WebMediaStreamTrack& track,
                             const scoped_refptr<CastSession>& session)
    : track_(track), cast_session_(session), weak_factory_(this) {}

CastRtpStream::~CastRtpStream() {}

std::vector<CastRtpParams> CastRtpStream::GetSupportedParams() {
  if (IsAudio())
    return SupportedAudioParams();
  else
    return SupportedVideoParams();
}

CastRtpParams CastRtpStream::GetParams() { return params_; }

void CastRtpStream::Start(const CastRtpParams& params,
                          const base::Closure& start_callback,
                          const base::Closure& stop_callback,
                          const ErrorCallback& error_callback) {
  stop_callback_ = stop_callback;
  error_callback_ = error_callback;

  if (IsAudio()) {
    AudioSenderConfig config;
    if (!ToAudioSenderConfig(params, &config)) {
      DidEncounterError("Invalid parameters for audio.");
      return;
    }

    // In case of error we have to go through DidEncounterError() to stop
    // the streaming after reporting the error.
    audio_sink_.reset(new CastAudioSink(
        track_,
        media::BindToCurrentLoop(base::Bind(&CastRtpStream::DidEncounterError,
                                            weak_factory_.GetWeakPtr())),
        params.payload.channels,
        params.payload.clock_rate));
    cast_session_->StartAudio(
        config,
        base::Bind(&CastAudioSink::AddToTrack, audio_sink_->AsWeakPtr()));
    start_callback.Run();
  } else {
    VideoSenderConfig config;
    if (!ToVideoSenderConfig(params, &config)) {
      DidEncounterError("Invalid parameters for video.");
      return;
    }
    // See the code for audio above for explanation of callbacks.
    video_sink_.reset(new CastVideoSink(
        track_,
        media::BindToCurrentLoop(base::Bind(&CastRtpStream::DidEncounterError,
                                            weak_factory_.GetWeakPtr()))));
    cast_session_->StartVideo(
        config,
        base::Bind(&CastVideoSink::AddToTrack, video_sink_->AsWeakPtr()));
    start_callback.Run();
  }
}

void CastRtpStream::Stop() {
  audio_sink_.reset();
  video_sink_.reset();
  stop_callback_.Run();
}

void CastRtpStream::ToggleLogging(bool enable) {
  cast_session_->ToggleLogging(IsAudio(), enable);
}

void CastRtpStream::GetRawEvents(
    const base::Callback<void(scoped_ptr<base::BinaryValue>)>& callback) {
  cast_session_->GetEventLogsAndReset(IsAudio(), callback);
}

void CastRtpStream::GetStats(
    const base::Callback<void(scoped_ptr<base::DictionaryValue>)>& callback) {
  cast_session_->GetStatsAndReset(IsAudio(), callback);
}

bool CastRtpStream::IsAudio() const {
  return track_.source().type() == blink::WebMediaStreamSource::TypeAudio;
}

void CastRtpStream::DidEncounterError(const std::string& message) {
  error_callback_.Run(message);
  Stop();
}
<commit_msg>Cast: Use VideoFrame::GetTimestamp() to calculate the timestamp<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/media/cast_rtp_stream.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "chrome/renderer/media/cast_session.h"
#include "chrome/renderer/media/cast_udp_transport.h"
#include "content/public/renderer/media_stream_audio_sink.h"
#include "content/public/renderer/media_stream_video_sink.h"
#include "media/audio/audio_parameters.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_fifo.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/multi_channel_resampler.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_defines.h"
#include "media/cast/cast_sender.h"
#include "media/cast/transport/cast_transport_config.h"
#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"

using media::cast::AudioSenderConfig;
using media::cast::VideoSenderConfig;

namespace {

const char kCodecNameOpus[] = "OPUS";
const char kCodecNameVp8[] = "VP8";

// This constant defines the number of sets of audio data to buffer
// in the FIFO. If input audio and output data have different resampling
// rates then buffer is necessary to avoid audio glitches.
// See CastAudioSink::ResampleData() and CastAudioSink::OnSetFormat()
// for more defaults.
const int kBufferAudioData = 2;

CastRtpPayloadParams DefaultOpusPayload() {
  CastRtpPayloadParams payload;
  payload.ssrc = 1;
  payload.feedback_ssrc = 1;
  payload.payload_type = 127;
  payload.codec_name = kCodecNameOpus;
  payload.clock_rate = 48000;
  payload.channels = 2;
  payload.min_bitrate = payload.max_bitrate =
      media::cast::kDefaultAudioEncoderBitrate;
  return payload;
}

CastRtpPayloadParams DefaultVp8Payload() {
  CastRtpPayloadParams payload;
  payload.ssrc = 11;
  payload.feedback_ssrc = 12;
  payload.payload_type = 96;
  payload.codec_name = kCodecNameVp8;
  payload.clock_rate = 90000;
  payload.width = 1280;
  payload.height = 720;
  payload.min_bitrate = 50 * 1000;
  payload.max_bitrate = 2000 * 1000;
  return payload;
}

std::vector<CastRtpParams> SupportedAudioParams() {
  // TODO(hclam): Fill in more codecs here.
  std::vector<CastRtpParams> supported_params;
  supported_params.push_back(CastRtpParams(DefaultOpusPayload()));
  return supported_params;
}

std::vector<CastRtpParams> SupportedVideoParams() {
  // TODO(hclam): Fill in H264 here.
  std::vector<CastRtpParams> supported_params;
  supported_params.push_back(CastRtpParams(DefaultVp8Payload()));
  return supported_params;
}

bool ToAudioSenderConfig(const CastRtpParams& params,
                         AudioSenderConfig* config) {
  config->sender_ssrc = params.payload.ssrc;
  config->incoming_feedback_ssrc = params.payload.feedback_ssrc;
  config->rtp_config.payload_type = params.payload.payload_type;
  config->use_external_encoder = false;
  config->frequency = params.payload.clock_rate;
  config->channels = params.payload.channels;
  config->bitrate = params.payload.max_bitrate;
  config->codec = media::cast::transport::kPcm16;
  if (params.payload.codec_name == kCodecNameOpus)
    config->codec = media::cast::transport::kOpus;
  else
    return false;
  return true;
}

bool ToVideoSenderConfig(const CastRtpParams& params,
                         VideoSenderConfig* config) {
  config->sender_ssrc = params.payload.ssrc;
  config->incoming_feedback_ssrc = params.payload.feedback_ssrc;
  config->rtp_config.payload_type = params.payload.payload_type;
  config->use_external_encoder = false;
  config->width = params.payload.width;
  config->height = params.payload.height;
  config->min_bitrate = config->start_bitrate = params.payload.min_bitrate;
  config->max_bitrate = params.payload.max_bitrate;
  if (params.payload.codec_name == kCodecNameVp8)
    config->codec = media::cast::transport::kVp8;
  else
    return false;
  return true;
}

}  // namespace

// This class receives MediaStreamTrack events and video frames from a
// MediaStreamTrack. Video frames are submitted to media::cast::FrameInput.
//
// Threading: Video frames are received on the render thread.
class CastVideoSink : public base::SupportsWeakPtr<CastVideoSink>,
                      public content::MediaStreamVideoSink {
 public:
  // |track| provides data for this sink.
  // |error_callback| is called if video formats don't match.
  CastVideoSink(const blink::WebMediaStreamTrack& track,
                const CastRtpStream::ErrorCallback& error_callback)
      : track_(track),
        sink_added_(false),
        error_callback_(error_callback) {}

  virtual ~CastVideoSink() {
    if (sink_added_)
      RemoveFromVideoTrack(this, track_);
  }

  // content::MediaStreamVideoSink implementation.
  virtual void OnVideoFrame(const scoped_refptr<media::VideoFrame>& frame)
      OVERRIDE {
    DCHECK(frame_input_);

    // Capture time is calculated using the time when the first frame
    // is delivered. Doing so has less jitter because each frame has
    // a TimeDelta from the first frame. However there is a delay between
    // capture and delivery here for the first frame. We do not account
    // for this delay.
    if (first_frame_timestamp_.is_null())
      first_frame_timestamp_ = base::TimeTicks::Now();
    frame_input_->InsertRawVideoFrame(
        frame, first_frame_timestamp_ + frame->GetTimestamp());
  }

  // Attach this sink to a video track represented by |track_|.
  // Data received from the track will be submitted to |frame_input|.
  void AddToTrack(
      const scoped_refptr<media::cast::VideoFrameInput>& frame_input) {
    DCHECK(!sink_added_);
    sink_added_ = true;

    frame_input_ = frame_input;
    AddToVideoTrack(this, track_);
  }

 private:
  blink::WebMediaStreamTrack track_;
  scoped_refptr<media::cast::VideoFrameInput> frame_input_;
  bool sink_added_;
  CastRtpStream::ErrorCallback error_callback_;
  base::TimeTicks first_frame_timestamp_;

  DISALLOW_COPY_AND_ASSIGN(CastVideoSink);
};

// Receives audio data from a MediaStreamTrack. Data is submitted to
// media::cast::FrameInput.
//
// Threading: Audio frames are received on the real-time audio thread.
class CastAudioSink : public base::SupportsWeakPtr<CastAudioSink>,
                      public content::MediaStreamAudioSink {
 public:
  // |track| provides data for this sink.
  // |error_callback| is called if audio formats don't match.
  CastAudioSink(const blink::WebMediaStreamTrack& track,
                const CastRtpStream::ErrorCallback& error_callback,
                int output_channels,
                int output_sample_rate)
      : track_(track),
        sink_added_(false),
        error_callback_(error_callback),
        weak_factory_(this),
        input_preroll_(0),
        output_channels_(output_channels),
        output_sample_rate_(output_sample_rate) {}

  virtual ~CastAudioSink() {
    if (sink_added_)
      RemoveFromAudioTrack(this, track_);
  }

  // Called on real-time audio thread.
  // content::MediaStreamAudioSink implementation.
  virtual void OnData(const int16* audio_data,
                      int sample_rate,
                      int number_of_channels,
                      int number_of_frames) OVERRIDE {
    scoped_ptr<media::AudioBus> input_bus;
    if (resampler_) {
      input_bus = ResampleData(
          audio_data, sample_rate, number_of_channels, number_of_frames);
      if (!input_bus)
        return;
    } else {
      input_bus = media::AudioBus::Create(
          number_of_channels, number_of_frames);
      input_bus->FromInterleaved(
          audio_data, number_of_frames, number_of_channels);
    }

    // TODO(hclam): Pass in the accurate capture time to have good
    // audio / video sync.
    frame_input_->InsertAudio(input_bus.Pass(), base::TimeTicks::Now());
  }

  // Return a resampled audio data from input. This is called when the
  // input sample rate doesn't match the output.
  // The flow of data is as follows:
  // |audio_data| ->
  //     AudioFifo |fifo_| ->
  //         MultiChannelResampler |resampler|.
  //
  // The resampler pulls data out of the FIFO and resample the data in
  // frequency domain. It might call |fifo_| for more than once. But no more
  // than |kBufferAudioData| times. We preroll audio data into the FIFO to
  // make sure there's enough data for resampling.
  scoped_ptr<media::AudioBus> ResampleData(
      const int16* audio_data,
      int sample_rate,
      int number_of_channels,
      int number_of_frames) {
    DCHECK_EQ(number_of_channels, output_channels_);
    fifo_input_bus_->FromInterleaved(
        audio_data, number_of_frames, number_of_channels);
    fifo_->Push(fifo_input_bus_.get());

    if (input_preroll_ < kBufferAudioData - 1) {
      ++input_preroll_;
      return scoped_ptr<media::AudioBus>();
    }

    scoped_ptr<media::AudioBus> output_bus(
        media::AudioBus::Create(
            output_channels_,
            output_sample_rate_ * fifo_input_bus_->frames() / sample_rate));

    // Resampler will then call ProvideData() below to fetch data from
    // |input_data_|.
    resampler_->Resample(output_bus->frames(), output_bus.get());
    return output_bus.Pass();
  }

  // Called on real-time audio thread.
  virtual void OnSetFormat(const media::AudioParameters& params) OVERRIDE {
    if (params.sample_rate() == output_sample_rate_)
      return;
    fifo_.reset(new media::AudioFifo(
        output_channels_,
        kBufferAudioData * params.frames_per_buffer()));
    fifo_input_bus_ = media::AudioBus::Create(
        params.channels(), params.frames_per_buffer());
    resampler_.reset(new media::MultiChannelResampler(
        output_channels_,
        static_cast<double>(params.sample_rate()) / output_sample_rate_,
        params.frames_per_buffer(),
        base::Bind(&CastAudioSink::ProvideData, base::Unretained(this))));
  }

  // Add this sink to the track. Data received from the track will be
  // submitted to |frame_input|.
  void AddToTrack(
      const scoped_refptr<media::cast::AudioFrameInput>& frame_input) {
    DCHECK(!sink_added_);
    sink_added_ = true;

    // This member is written here and then accessed on the IO thread
    // We will not get data until AddToAudioTrack is called so it is
    // safe to access this member now.
    frame_input_ = frame_input;
    AddToAudioTrack(this, track_);
  }

  void ProvideData(int frame_delay, media::AudioBus* output_bus) {
    fifo_->Consume(output_bus, 0, output_bus->frames());
  }

 private:
  blink::WebMediaStreamTrack track_;
  bool sink_added_;
  CastRtpStream::ErrorCallback error_callback_;
  base::WeakPtrFactory<CastAudioSink> weak_factory_;

  scoped_ptr<media::MultiChannelResampler> resampler_;
  scoped_ptr<media::AudioFifo> fifo_;
  scoped_ptr<media::AudioBus> fifo_input_bus_;
  int input_preroll_;
  const int output_channels_;
  const int output_sample_rate_;

  // This member is accessed on the real-time audio time.
  scoped_refptr<media::cast::AudioFrameInput> frame_input_;

  DISALLOW_COPY_AND_ASSIGN(CastAudioSink);
};

CastRtpParams::CastRtpParams(const CastRtpPayloadParams& payload_params)
    : payload(payload_params) {}

CastCodecSpecificParams::CastCodecSpecificParams() {}

CastCodecSpecificParams::~CastCodecSpecificParams() {}

CastRtpPayloadParams::CastRtpPayloadParams()
    : payload_type(0),
      ssrc(0),
      feedback_ssrc(0),
      clock_rate(0),
      max_bitrate(0),
      min_bitrate(0),
      channels(0),
      width(0),
      height(0) {}

CastRtpPayloadParams::~CastRtpPayloadParams() {}

CastRtpParams::CastRtpParams() {}

CastRtpParams::~CastRtpParams() {}

CastRtpStream::CastRtpStream(const blink::WebMediaStreamTrack& track,
                             const scoped_refptr<CastSession>& session)
    : track_(track), cast_session_(session), weak_factory_(this) {}

CastRtpStream::~CastRtpStream() {}

std::vector<CastRtpParams> CastRtpStream::GetSupportedParams() {
  if (IsAudio())
    return SupportedAudioParams();
  else
    return SupportedVideoParams();
}

CastRtpParams CastRtpStream::GetParams() { return params_; }

void CastRtpStream::Start(const CastRtpParams& params,
                          const base::Closure& start_callback,
                          const base::Closure& stop_callback,
                          const ErrorCallback& error_callback) {
  stop_callback_ = stop_callback;
  error_callback_ = error_callback;

  if (IsAudio()) {
    AudioSenderConfig config;
    if (!ToAudioSenderConfig(params, &config)) {
      DidEncounterError("Invalid parameters for audio.");
      return;
    }

    // In case of error we have to go through DidEncounterError() to stop
    // the streaming after reporting the error.
    audio_sink_.reset(new CastAudioSink(
        track_,
        media::BindToCurrentLoop(base::Bind(&CastRtpStream::DidEncounterError,
                                            weak_factory_.GetWeakPtr())),
        params.payload.channels,
        params.payload.clock_rate));
    cast_session_->StartAudio(
        config,
        base::Bind(&CastAudioSink::AddToTrack, audio_sink_->AsWeakPtr()));
    start_callback.Run();
  } else {
    VideoSenderConfig config;
    if (!ToVideoSenderConfig(params, &config)) {
      DidEncounterError("Invalid parameters for video.");
      return;
    }
    // See the code for audio above for explanation of callbacks.
    video_sink_.reset(new CastVideoSink(
        track_,
        media::BindToCurrentLoop(base::Bind(&CastRtpStream::DidEncounterError,
                                            weak_factory_.GetWeakPtr()))));
    cast_session_->StartVideo(
        config,
        base::Bind(&CastVideoSink::AddToTrack, video_sink_->AsWeakPtr()));
    start_callback.Run();
  }
}

void CastRtpStream::Stop() {
  audio_sink_.reset();
  video_sink_.reset();
  stop_callback_.Run();
}

void CastRtpStream::ToggleLogging(bool enable) {
  cast_session_->ToggleLogging(IsAudio(), enable);
}

void CastRtpStream::GetRawEvents(
    const base::Callback<void(scoped_ptr<base::BinaryValue>)>& callback) {
  cast_session_->GetEventLogsAndReset(IsAudio(), callback);
}

void CastRtpStream::GetStats(
    const base::Callback<void(scoped_ptr<base::DictionaryValue>)>& callback) {
  cast_session_->GetStatsAndReset(IsAudio(), callback);
}

bool CastRtpStream::IsAudio() const {
  return track_.source().type() == blink::WebMediaStreamSource::TypeAudio;
}

void CastRtpStream::DidEncounterError(const std::string& message) {
  error_callback_.Run(message);
  Stop();
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include <QtSql>

#include "../dbmanager.h"
#include "querytextedit.h"

#include "../config.h"

QueryTextEdit::QueryTextEdit(QWidget *parent)
    : QTextEdit(parent)
{
  syntax = new SqlHighlighter(this);

  setupCompleter();

  setFont(Config::editorFont);
  setFontPointSize(Config::editorFont.pointSize());
//  setOpenExternalLinks(true);
//  setOpenLinks(true);
//  setReadOnly(false);
}

void QueryTextEdit::cleanTables()
{

}

void QueryTextEdit::focusInEvent(QFocusEvent *e)
{
  completer->setWidget(this);
  QTextEdit::focusInEvent(e);
}

void QueryTextEdit::keyPressEvent(QKeyEvent *event)
{
  if(Config::compCharCount == -1)
    return;

  // If the completer is actually shown, it handles some keys
  if(completer->popup()->isVisible())
  {
    switch(event->key())
    {
    case Qt::Key_Enter:
    case Qt::Key_Return:
    case Qt::Key_Escape:
    case Qt::Key_Tab:
    case Qt::Key_Backtab:
      event->ignore();
      return;
    default:
      break;
    }
  }

//  if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Control)
//  {
//    scanTables();
//    return;
//  }

  // the shortcut to pop up the completer
  bool isShortcut = ((event->modifiers() & Qt::ControlModifier)
                     && event->key() == Qt::Key_Space);
  if(!isShortcut)
  {
//    QString prevLine = "";
//    if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
//    {
//      QTextCursor cursor = textCursor();
//      if(cursor.movePosition(QTextCursor::Up))
//      {
//        cursor.select(QTextCursor::LineUnderCursor);
//        prevLine = textCursor().selectedText();
//      }
//    }

    QTextEdit::keyPressEvent(event);
//    if(!prevLine.isEmpty())
//      for(int i=0; prevLine.at(i) == QChar(' '); i++)
//        insertPlainText(" ");
  }

  QString completionPrefix = textUnderCursor();
  if(event->key() == Qt::Key_Backspace && !completionPrefix.isEmpty()
    && !completionPrefix.right(1).at(0).isLetterOrNumber())
  {
    completer->popup()->hide();
    event->accept();
    return;
  }

  bool ctrlOrShift = event->modifiers() &
                     (Qt::ControlModifier | Qt::ShiftModifier);

  // if the user just pressed Control or Shift (nothing else)
  if(ctrlOrShift && event->text().isEmpty())
    return;

  bool hasModifier = (event->modifiers() != Qt::NoModifier) && !ctrlOrShift;

  // if lastChar is not a letter, the popup will not be shown
  QChar lastChar;
  if(!completionPrefix.isEmpty())
    lastChar = completionPrefix.right(1).at(0);

  bool followsTable = false;
  if(lastChar == '.')
  {
    QString table = completionPrefix.left(completionPrefix.length()-1);
    followsTable = tables.contains(table);
  }

  if(!isShortcut && ((!lastChar.isLetterOrNumber() && !followsTable) ||
                     hasModifier ||
                     event->text().isEmpty() ||
                     completionPrefix.length() < Config::compCharCount))
  {
    completer->popup()->hide();
    return;
  }

  if(completionPrefix != completer->completionPrefix())
  {
    completer->setCompletionPrefix(completionPrefix);
    completer->popup()->setCurrentIndex(
        completer->completionModel()->index(0,0));
  }

  QRect cr = cursorRect();
  cr.setWidth(completer->popup()->sizeHintForColumn(0) +
              completer->popup()->verticalScrollBar()->width());

  completer->complete(cr);
}

void QueryTextEdit::insertCompletion(QString text)
{
  if(completer->widget() != this)
    return;

  QTextCursor tc = textCursor();
  tc.select(QTextCursor::WordUnderCursor);
  tc.removeSelectedText();
  tc.insertHtml(text);
}

void QueryTextEdit::insertFromMimeData(const QMimeData *source) {
  QTextEdit::insertPlainText(source->text());
}

void QueryTextEdit::reloadCompleter()
{
  SqlHighlighter::reloadKeywords();
}

void QueryTextEdit::reloadContext(QStringList tables,
                                  QMultiMap<QString, QString> fields)
{
  if(!Config::editorSemantic)
    return;

  this->tables = tables;

  // The syntax highlighting must reload the context too
  syntax->reloadContext(tables, fields);

  // collects all items to show
  QStringList items = tables;
  items << fields.values();

  items << SqlHighlighter::sqlFunctionList();
  items << SqlHighlighter::sqlKeywordList();
  items << SqlHighlighter::sqlTypeList();

  // cleaning and sorting
#if QT_VERSION >= 0x040500
  items.removeDuplicates();
#endif

  QMap<QString, QString> m;
  foreach(QString i, items)
    m.insert(i.toLower(), i);

  items = m.values();
  completerContextModel->setStringList(items);
  completer->setModel(completerContextModel);
}

/**
 * Replaces all tables by links
 */
void QueryTextEdit::scanTables()
{
  QString newstr;
  int pos = 0;
  QString text = toHtml();
  QTextCursor tc;
  foreach(QString table, tables)
  {
    pos = text.indexOf(table);
    while(pos != -1)
    {
      tc = textCursor();
      tc.setPosition(pos+1);
      tc.select(QTextCursor::WordUnderCursor);
      newstr = QString("%1").arg(table);
      tc.removeSelectedText();
      tc.insertHtml(newstr);
      text = toPlainText();
      pos += newstr.size();
    }
  }
}

void QueryTextEdit::setupCompleter()
{
  completer = new QCompleter(this);
  completer->setCaseSensitivity(Qt::CaseInsensitive);
  completer->setWrapAround(false);
  completer->setWidget(this);
  completer->setCompletionMode(QCompleter::PopupCompletion);

  connect(completer, SIGNAL(activated(QString)),
          this, SLOT(insertCompletion(QString)));

  QStringList items;
  items << SqlHighlighter::sqlKeywordList()
      << SqlHighlighter::sqlFunctionList()
      << SqlHighlighter::sqlTypeList();
  completerContextModel = new QStringListModel(items, this);
  completer->setModel(completerContextModel);

  reloadContext(QStringList(), QMultiMap<QString, QString>());
}

QString QueryTextEdit::textUnderCursor() const
{
  QTextCursor tc = textCursor();
  tc.select( QTextCursor::WordUnderCursor );
  return tc.selectedText();
}
<commit_msg>Fiabilisation auto-complément<commit_after>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include <QtSql>

#include "../dbmanager.h"
#include "querytextedit.h"

#include "../config.h"

QueryTextEdit::QueryTextEdit(QWidget *parent)
    : QTextEdit(parent)
{
  syntax = new SqlHighlighter(this);

  setupCompleter();

  setFont(Config::editorFont);
  setFontPointSize(Config::editorFont.pointSize());
//  setOpenExternalLinks(true);
//  setOpenLinks(true);
//  setReadOnly(false);
}

void QueryTextEdit::cleanTables()
{

}

void QueryTextEdit::focusInEvent(QFocusEvent *e)
{
  completer->setWidget(this);
  QTextEdit::focusInEvent(e);
}

void QueryTextEdit::keyPressEvent(QKeyEvent *event)
{
  if(Config::compCharCount == -1)
    return;

  // If the completer is actually shown, it handles some keys
  if(completer->popup()->isVisible())
  {
    switch(event->key())
    {
    case Qt::Key_Enter:
    case Qt::Key_Return:
    case Qt::Key_Escape:
    case Qt::Key_Tab:
    case Qt::Key_Backtab:
      event->ignore();
      return;
    default:
      break;
    }
  }

//  if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Control)
//  {
//    scanTables();
//    return;
//  }

  // the shortcut to pop up the completer
  bool isShortcut = ((event->modifiers() & Qt::ControlModifier)
                     && event->key() == Qt::Key_Space);
  if(!isShortcut)
  {
//    QString prevLine = "";
//    if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
//    {
//      QTextCursor cursor = textCursor();
//      if(cursor.movePosition(QTextCursor::Up))
//      {
//        cursor.select(QTextCursor::LineUnderCursor);
//        prevLine = textCursor().selectedText();
//      }
//    }

    QTextEdit::keyPressEvent(event);
//    if(!prevLine.isEmpty())
//      for(int i=0; prevLine.at(i) == QChar(' '); i++)
//        insertPlainText(" ");
  }

  QString completionPrefix = textUnderCursor();
  if (event->key() == Qt::Key_Backspace && completer->popup()->isHidden()) {
    completer->popup()->hide();
    event->accept();
    return;
  }

  bool ctrlOrShift = event->modifiers() &
                     (Qt::ControlModifier | Qt::ShiftModifier);

  // if the user just pressed Control or Shift (nothing else)
  if(ctrlOrShift && event->text().isEmpty())
    return;

  bool hasModifier = (event->modifiers() != Qt::NoModifier) && !ctrlOrShift;

  // if lastChar is not a letter, the popup will not be shown
  QChar lastChar;
  if(!completionPrefix.isEmpty())
    lastChar = completionPrefix.right(1).at(0);

  bool followsTable = false;
  if(lastChar == '.')
  {
    QString table = completionPrefix.left(completionPrefix.length()-1);
    followsTable = tables.contains(table);
  }

  if(!isShortcut && ((!lastChar.isLetterOrNumber() && !followsTable) ||
                     hasModifier ||
                     event->text().isEmpty() ||
                     completionPrefix.length() < Config::compCharCount))
  {
    completer->popup()->hide();
    return;
  }

  if(completionPrefix != completer->completionPrefix())
  {
    completer->setCompletionPrefix(completionPrefix);
    completer->popup()->setCurrentIndex(
        completer->completionModel()->index(0,0));
  }

  QRect cr = cursorRect();
  cr.setWidth(completer->popup()->sizeHintForColumn(0) +
              completer->popup()->verticalScrollBar()->width());

  completer->complete(cr);
}

void QueryTextEdit::insertCompletion(QString text)
{
  if(completer->widget() != this)
    return;

  QTextCursor tc = textCursor();
  tc.select(QTextCursor::WordUnderCursor);
  tc.removeSelectedText();
  tc.insertHtml(text);
}

void QueryTextEdit::insertFromMimeData(const QMimeData *source) {
  QTextEdit::insertPlainText(source->text());
}

void QueryTextEdit::reloadCompleter()
{
  SqlHighlighter::reloadKeywords();
}

void QueryTextEdit::reloadContext(QStringList tables,
                                  QMultiMap<QString, QString> fields)
{
  if(!Config::editorSemantic)
    return;

  this->tables = tables;

  // The syntax highlighting must reload the context too
  syntax->reloadContext(tables, fields);

  // collects all items to show
  QStringList items = tables;
  items << fields.values();

  items << SqlHighlighter::sqlFunctionList();
  items << SqlHighlighter::sqlKeywordList();
  items << SqlHighlighter::sqlTypeList();

  // cleaning and sorting
#if QT_VERSION >= 0x040500
  items.removeDuplicates();
#endif

  QMap<QString, QString> m;
  foreach(QString i, items)
    m.insert(i.toLower(), i);

  items = m.values();
  completerContextModel->setStringList(items);
  completer->setModel(completerContextModel);
}

/**
 * Replaces all tables by links
 */
void QueryTextEdit::scanTables()
{
  QString newstr;
  int pos = 0;
  QString text = toHtml();
  QTextCursor tc;
  foreach(QString table, tables)
  {
    pos = text.indexOf(table);
    while(pos != -1)
    {
      tc = textCursor();
      tc.setPosition(pos+1);
      tc.select(QTextCursor::WordUnderCursor);
      newstr = QString("%1").arg(table);
      tc.removeSelectedText();
      tc.insertHtml(newstr);
      text = toPlainText();
      pos += newstr.size();
    }
  }
}

void QueryTextEdit::setupCompleter()
{
  completer = new QCompleter(this);
  completer->setCaseSensitivity(Qt::CaseInsensitive);
  completer->setWrapAround(false);
  completer->setWidget(this);
  completer->setCompletionMode(QCompleter::PopupCompletion);

  connect(completer, SIGNAL(activated(QString)),
          this, SLOT(insertCompletion(QString)));

  QStringList items;
  items << SqlHighlighter::sqlKeywordList()
      << SqlHighlighter::sqlFunctionList()
      << SqlHighlighter::sqlTypeList();
  completerContextModel = new QStringListModel(items, this);
  completer->setModel(completerContextModel);

  reloadContext(QStringList(), QMultiMap<QString, QString>());
}

QString QueryTextEdit::textUnderCursor() const
{
  QTextCursor tc = textCursor();
  tc.select( QTextCursor::WordUnderCursor );
  return tc.selectedText();
}
<|endoftext|>


<commit_before>#include "writer/verilog/ticker.h"

#include "iroha/i_design.h"
#include "writer/module_template.h"
#include "writer/verilog/state.h"
#include "writer/verilog/table.h"
#include "writer/verilog/module.h"

namespace iroha {
namespace writer {
namespace verilog {

Ticker::Ticker(const IResource &res, const Table &table)
  : Resource(res, table) {
}

void Ticker::BuildResource() {
  string n = TickerName();
  ostream &rs = tab_.ResourceSectionStream();
  rs << "  reg [31:0] " << n << ";\n";
  ostream &is = tab_.InitialValueSectionStream();
  is << "      " << n << " <= 0;\n";
  ostream &ss = tab_.StateOutputSectionStream();
  ss << "      " << n << " <= " << n << " + 1;\n";
}

void Ticker::BuildInsn(IInsn *insn, State *st) {
  ostream &os = st->StateBodySectionStream();
  string n = TickerName();
  os << "          $display(\"ticker:%d\", " << n << ");\n";
}

string Ticker::TickerName() {
  return "ticker_" + Util::Itoa(res_.GetTable()->GetId()) + "_" +
    Util::Itoa(res_.GetId());
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha
<commit_msg>ticker to generate an output value.<commit_after>#include "writer/verilog/ticker.h"

#include "iroha/i_design.h"
#include "writer/module_template.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/state.h"
#include "writer/verilog/table.h"
#include "writer/verilog/module.h"

namespace iroha {
namespace writer {
namespace verilog {

Ticker::Ticker(const IResource &res, const Table &table)
  : Resource(res, table) {
}

void Ticker::BuildResource() {
  string n = TickerName();
  ostream &rs = tab_.ResourceSectionStream();
  rs << "  reg [31:0] " << n << ";\n";
  ostream &is = tab_.InitialValueSectionStream();
  is << "      " << n << " <= 0;\n";
  ostream &ss = tab_.StateOutputSectionStream();
  ss << "      " << n << " <= " << n << " + 1;\n";
}

void Ticker::BuildInsn(IInsn *insn, State *st) {
  string n = TickerName();
  if (insn->outputs_.size() > 0) {
    ostream &ws = tab_.InsnWireValueSectionStream();
    ws << "  assign " << InsnWriter::InsnOutputWireName(*insn, 0)
       << " = " << n << ";\n";
  } else {
    ostream &os = st->StateBodySectionStream();
    os << "          $display(\"ticker:%d\", " << n << ");\n";
  }
}

string Ticker::TickerName() {
  return "ticker_" + Util::Itoa(res_.GetTable()->GetId()) + "_" +
    Util::Itoa(res_.GetId());
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha
<|endoftext|>


<commit_before>#include <GL/glut.h>

void init()
{
  glClearColor(0.0, 0.0, 0.0, 1.0);
  glColor3f(1.0, 1.0, 1.0);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}

void myDisplay()
{
  glClear(GL_COLOR_BUFFER_BIT);
  glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(-0.5, -0.5);

    glColor3f(0.0, 1.0, 0.0);
    glVertex2f(-0.5, 0.5);

    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(0.5, 0.5);

    glColor3f(1.0, 1.0, 0.0);
    glVertex2f(0.5, -0.5);
  glEnd();
  glFlush();
}

int main(int argc, char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(0,0);
  glutCreateWindow("Homework 1");

  glutDisplayFunc(myDisplay);

  init();

  glutMainLoop();
}
<commit_msg>Added 4 squares in corners with colors specified in homework.<commit_after>#include <GL/glut.h>

void init()
{
  glClearColor(0.0, 0.0, 0.0, 1.0);
  glColor3f(1.0, 1.0, 1.0);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}

//rainbow square
void bottomLeftPolygon()
{
  glViewport(0, 0, 250, 250);

  glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(-0.5, -0.5);

    glColor3f(0.0, 1.0, 0.0);
    glVertex2f(-0.5, 0.5);

    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(0.5, 0.5);

    glColor3f(1.0, 1.0, 0.0);
    glVertex2f(0.5, -0.5);
  glEnd();
}

//blue square
void bottomRightPolygon()
{
  glViewport(250, 0, 250, 250);

  glBegin(GL_POLYGON);
    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(-0.5, -0.5);

    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(-0.5, 0.5);

    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(0.5, 0.5);

    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(0.5, -0.5);
  glEnd();
}

//green square
void topLeftPolygon()
{
  glViewport(0, 250, 250, 250);

  glBegin(GL_POLYGON);
    glColor3f(0.0, 1.0, 0.0);
    glVertex2f(-0.5, -0.5);

    glColor3f(0.0, 1.0, 0.0);
    glVertex2f(-0.5, 0.5);

    glColor3f(0.0, 1.0, 0.0);
    glVertex2f(0.5, 0.5);

    glColor3f(0.0, 1.0, 0.0);
    glVertex2f(0.5, -0.5);
  glEnd();
}

//red square
void topRightPolygon()
{
  glViewport(250, 250, 250, 250);

  glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(-0.5, -0.5);

    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(-0.5, 0.5);

    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(0.5, 0.5);

    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(0.5, -0.5);
  glEnd();
}

void myDisplay()
{
  glClear(GL_COLOR_BUFFER_BIT);

  bottomLeftPolygon();
  bottomRightPolygon();
  topLeftPolygon();
  topRightPolygon();

  glFlush();
}

int main(int argc, char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(0,0);
  glutCreateWindow("Homework 1");

  glutDisplayFunc(myDisplay);

  init();

  glutMainLoop();
}
<|endoftext|>


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

#include "base/at_exit.h"
#include "base/command_line.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_surface.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/surface_factory_ozone.h"

int main(int argc, char** argv) {
  CommandLine::Init(argc, argv);
  base::AtExitManager exit_manager;

  ui::OzonePlatform::InitializeForUI();
  if (!gfx::GLSurface::InitializeOneOff())
    LOG(FATAL) << "Failed to initialize GL";

  gfx::AcceleratedWidget widget =
      ui::SurfaceFactoryOzone::GetInstance()->GetAcceleratedWidget();
  scoped_refptr<gfx::GLSurface> surface =
      gfx::GLSurface::CreateViewGLSurface(widget);
  if (!surface)
    LOG(FATAL) << "Failed to create GL surface";

  scoped_refptr<gfx::GLContext> context = gfx::GLContext::CreateGLContext(
      NULL, surface.get(), gfx::PreferIntegratedGpu);
  if (!context)
    LOG(FATAL) << "Failed to create GL context";

  const gfx::Size window_size(800, 600);
  int iterations = 120;

  surface->Resize(window_size);
  if (!context->MakeCurrent(surface.get()))
    LOG(FATAL) << "Failed to make current on GL context";

  for (int i = 0; i < iterations; ++i) {
    glViewport(0, 0, window_size.width(), window_size.height());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    float fraction = static_cast<float>(i) / iterations;
    glClearColor(1 - fraction, fraction, 0.0, 1.0);

    if (!surface->SwapBuffers())
      LOG(FATAL) << "Failed to swap buffers";
  }

  return 0;
}
<commit_msg>ozone: Port egl_demo on top of PlatformWindow<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_surface.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/surface_factory_ozone.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/platform_window_delegate.h"

const int kTestWindowWidth = 800;
const int kTestWindowHeight = 600;

class DemoWindow : public ui::PlatformWindowDelegate {
 public:
  DemoWindow() : widget_(gfx::kNullAcceleratedWidget) {
    platform_window_ = ui::OzonePlatform::GetInstance()->CreatePlatformWindow(
        this, gfx::Rect(kTestWindowWidth, kTestWindowHeight));
  }
  virtual ~DemoWindow() {}

  gfx::AcceleratedWidget GetAcceleratedWidget() {
    // TODO(spang): We should start rendering asynchronously.
    CHECK_NE(widget_, gfx::kNullAcceleratedWidget)
        << "widget not available synchronously";
    return widget_;
  }

  gfx::Size GetSize() { return platform_window_->GetBounds().size(); }

  // PlatformWindowDelegate:
  virtual void OnBoundsChanged(const gfx::Rect& new_bounds) OVERRIDE {}
  virtual void OnDamageRect(const gfx::Rect& damaged_region) OVERRIDE {}
  virtual void DispatchEvent(ui::Event* event) OVERRIDE {}
  virtual void OnCloseRequest() OVERRIDE {}
  virtual void OnClosed() OVERRIDE {}
  virtual void OnWindowStateChanged(
      ui::PlatformWindowState new_state) OVERRIDE {}
  virtual void OnLostCapture() OVERRIDE {}
  virtual void OnAcceleratedWidgetAvailable(
      gfx::AcceleratedWidget widget) OVERRIDE {
    CHECK_NE(widget, gfx::kNullAcceleratedWidget);
    widget_ = widget;
  }

 private:
  scoped_ptr<ui::PlatformWindow> platform_window_;
  gfx::AcceleratedWidget widget_;

  DISALLOW_COPY_AND_ASSIGN(DemoWindow);
};

int main(int argc, char** argv) {
  CommandLine::Init(argc, argv);
  base::AtExitManager exit_manager;

  base::MessageLoopForUI message_loop;

  ui::OzonePlatform::InitializeForUI();
  if (!gfx::GLSurface::InitializeOneOff())
    LOG(FATAL) << "Failed to initialize GL";

  DemoWindow window;

  scoped_refptr<gfx::GLSurface> surface =
      gfx::GLSurface::CreateViewGLSurface(window.GetAcceleratedWidget());
  if (!surface)
    LOG(FATAL) << "Failed to create GL surface";

  scoped_refptr<gfx::GLContext> context = gfx::GLContext::CreateGLContext(
      NULL, surface.get(), gfx::PreferIntegratedGpu);
  if (!context)
    LOG(FATAL) << "Failed to create GL context";

  gfx::Size window_size = window.GetSize();

  int iterations = 120;

  surface->Resize(window_size);
  if (!context->MakeCurrent(surface.get()))
    LOG(FATAL) << "Failed to make current on GL context";

  for (int i = 0; i < iterations; ++i) {
    glViewport(0, 0, window_size.width(), window_size.height());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    float fraction = static_cast<float>(i) / iterations;
    glClearColor(1 - fraction, fraction, 0.0, 1.0);

    if (!surface->SwapBuffers())
      LOG(FATAL) << "Failed to swap buffers";
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "SimpleExample.h"
#include "Utils.h"
#include <cmath>
#include <limits>

using namespace std;

SimpleExample::SimpleExample()
:params(100)
,scalars(2)
{

}

void SimpleExample::from_prior(RNG& rng)
{
	for(double& x:params)
		x = rng.rand();
	compute_scalars();
}

double SimpleExample::perturb(RNG& rng)
{
	int which = rng.rand_int(params.size());
	params[which] += rng.randh();
	wrap(params[which], 0., 1.);
	compute_scalars();
	return 0.;
}

void SimpleExample::compute_scalars()
{
	scalars[0] = 0.;
	scalars[1] = 0.;
	for(const double& x: params)
	{
		scalars[0] += -pow(x - 0.5, 2);
		scalars[1] += -pow(sin(4.*M_PI*x), 2);
	}
}

void SimpleExample::write_text(std::ostream& out) const
{
	for(size_t i=0; i<params.size(); i++)
		out<<params[i]<<' ';
}

<commit_msg>Bolder proposal<commit_after>#include "SimpleExample.h"
#include "Utils.h"
#include <cmath>
#include <limits>

using namespace std;

SimpleExample::SimpleExample()
:params(100)
,scalars(2)
{

}

void SimpleExample::from_prior(RNG& rng)
{
	for(double& x:params)
		x = rng.rand();
	compute_scalars();
}

double SimpleExample::perturb(RNG& rng)
{
	int which, count;
	if(rng.rand() <= 0.5)
		count = 0;
	else
		count = static_cast<int>(pow(10., 2.*rng.rand()));

	for(int i=0; i<count; i++)
	{
		which = rng.rand_int(params.size());
		params[which] += rng.randh();
		wrap(params[which], 0., 1.);
	}

	compute_scalars();
	return 0.;
}

void SimpleExample::compute_scalars()
{
	scalars[0] = 0.;
	scalars[1] = 0.;
	for(const double& x: params)
	{
		scalars[0] += -pow(x - 0.5, 2);
		scalars[1] += -pow(sin(4.*M_PI*x), 2);
	}
}

void SimpleExample::write_text(std::ostream& out) const
{
	for(size_t i=0; i<params.size(); i++)
		out<<params[i]<<' ';
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003-2006 Funambol
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdio.h>
#include "base/Log.h"
#include "base/util/utils.h"

long utf8len(const wchar_t* s) {
    if ((s == NULL) || (wcslen(s) == 0)) {
        return 0;
    }

    long k = 0;

    // If the function succeeds (WideCharToMultiByte)
    // the return value is the required size, in bytes,
    // for a buffer that can receive the translated string.

    k = WideCharToMultiByte (CP_UTF8, 0, s, wcslen(s), NULL, 0, NULL, NULL);

    return (k != 0) ? (long)k : -1;
}

char* wc2utf8(const wchar_t* s, char* d, unsigned long dsize) {

    //
    // First of all, if s is NULL, just return NULL.
    // Then, if d is NULL, let's allocate the required memory to contain the
    // utf8 string.
    //
    if (s == NULL) {
        return NULL;
    }

    if (d == NULL) {
        dsize = utf8len(s);
        d = new char[dsize+1];
    }

    unsigned long k = 0;

    k = WideCharToMultiByte (CP_UTF8, 0, s, wcslen(s), d, dsize, 0, 0);

	d[dsize] = 0;

    return (k != 0) ? d : NULL;
}

wchar_t* utf82wc(const char* s, wchar_t* d, unsigned long dsize) {

    //
    // First of all, if s is NULL, just return NULL.
    // Then, if d is NULL, let's allocate the required memory to contain the
    // wchar_t string.
    //
    if (s == NULL) {
        return NULL;
    }

    if (d == NULL) {
        dsize = strlen(s);
        d = new wchar_t[dsize+1];
    }

    wmemset(d, 0, dsize + 1);

    int k = MultiByteToWideChar(CP_UTF8, 0, s, strlen(s), d, dsize + 1);

    return (k != 0) ? d : NULL;

}

/*
 * Return a filename composed by the system temp dir and the name given
 * in input. If the file exists, try to add a digit 0-9.
 * If this fails too, return NULL (there's must be something wrong in
 * the calling program)
 *
 * @param name - a file name, without path
 * @return - a full pathname, allocated with new[], or NULL on error
 */
wchar_t *mkTempFileName(const wchar_t *name)
{
    wchar_t tmpPath[64];
    wchar_t* tmpFileName = new wchar_t[MAX_PATH];  // System constants for the path

    GetTempPath(64, tmpPath);
    int ret = GetTempFileName(tmpPath, TEXT("fun"), 0, tmpFileName);

    if (ret == 0) { // function GetTempFileName fails
        delete [] tmpFileName;
        tmpFileName = NULL;
    }

    return tmpFileName;

    /*
	wchar_t *ret = new wchar_t[wcslen(TEMPROOT)+wcslen(name)+3] ;
	wsprintf(ret, TEXT("%s\\%s"), TEMPROOT, name);
	FILE *f;
    int i;

	for (i=0; i<10 && (f=_wfopen(ret, TEXT("r")))!=NULL; i++ ) {
		fclose(f);
		wsprintf(ret, TEXT("%s\\%d%s"), TEMPROOT, i, name);
	}

	if(i==10) {
		// Can't find a free temp file name !
		delete [] ret;
		return NULL;
	}

	return ret;*/
}

bool saveFile(const char *filename, const char *buffer, size_t len, bool binary)
{
	const char *mode = binary ? "wb" : "w" ;

    FILE *f = fopen(filename, mode);

    if(!f)
        return false;

    if (fwrite(buffer, sizeof(char), len, f) != len) {
        fclose(f);
        return false;
    }
    fclose(f);

    return true;
}

size_t fgetsize(FILE *f)
{
    size_t size;

    fseek(f, 0, SEEK_END);
    size=ftell(f);
    fseek(f, 0, SEEK_SET);
    return size;
}

bool readFile(const char* path, char **message, size_t *len, bool binary)
{
    FILE *f;
    size_t msglen=0;
    char *msg=0;
    const char *mode = binary ? "rb" : "r" ;

    f = fopen(path, mode);
    if ( !f ) {
        return false;
    }
    msglen = fgetsize(f);
    msg = new char[msglen+1];

    fread(msg, msglen, sizeof(char), f);

    if(ferror(f)){
        delete [] msg;
        return false;
    }
    fclose(f);
    // Terminate the string, so that if it's a text file, the result is
    // a NULL terminated string
    msg[msglen]=0;
    *message= msg ;
    *len=msglen;

    return true;
}

long int getLenEncoding(const wchar_t* s, const wchar_t* encoding) {

	if ((s == NULL) || (wcslen(s) == 0)) {
        return 0;
    }

	int i = 0;
	long k = 0;

	while(encodings[i].name) {
		if(wcscmpIgnoreCase(encodings[i].name, encoding)) {
			k = WideCharToMultiByte (encodings[i].codepage_id, 0, s, wcslen(s), NULL, 0, NULL, NULL);
			break;
		}
		i++;
	}

    return (k != 0) ? (long)k : -1;

}

char* toMultibyte(const wchar_t *wc, const wchar_t *encoding) {
	if (wc == NULL) {
        return NULL;
    }

    unsigned long dsize = getLenEncoding(wc, encoding);
	if(dsize <= 0)
		return NULL;

    char* ret = new char[dsize+1];

    unsigned long k = 0;
    int i = 0;

	while(encodings[i].name) {
		if(wcscmpIgnoreCase(encodings[i].name, encoding)) {
			k = WideCharToMultiByte (encodings[i].codepage_id, 0, wc, wcslen(wc), ret, dsize, 0, 0);
			break;
		}
		i++;
	}

	ret[dsize] = 0;

	if(k == 0) {
		delete [] ret; ret = NULL;
	}
    return ret;
}

wchar_t* toWideChar(const char *mb, const wchar_t *encoding) {

	if (mb == NULL) {
        return NULL;
    }

    unsigned long dsize = strlen(mb);
	wchar_t* ret = new wchar_t[dsize+1];

    wmemset(ret, 0, dsize + 1);

	unsigned long k = 0;
    int i = 0;

	while(encodings[i].name) {
		if(wcscmpIgnoreCase(encodings[i].name, encoding)) {
			k = MultiByteToWideChar(encodings[i].codepage_id, 0, mb, strlen(mb), ret, dsize + 1);
			break;
		}
		i++;
	}

    if(k == 0) {
		delete [] ret; ret = NULL;
	}
    return ret;
}

#ifdef __DEBUG__

    //
    // This is required since in debug mode, new is rewritten
    // as new(__FILE__, __LINE__). See utils.h for details
    //
    #undef new
    #undef delete

    #include <stddef.h>

    void *operator new(size_t s, char* file, int line) {
        wchar_t m[256];

        void* p = malloc(s);

        // /** WARNING: this sloooooowwwwssss doooowwwwnnnn things
        wcsprintf(m, L"%S:%d new - s:%ld, p:%lx\n", file, line, s, p);
        LOG.error(m);
        // **/

        return p;
    }

    void *operator new(size_t s) {
        return ::operator new(s, "", 0);
    }

    void *operator new[](size_t s) {
        return ::operator new(s, "", 0);
    }

    void *operator new[](size_t s, char* file, int line) {
        return ::operator new(s, file, line);
    }

    void operator delete(void* p) {
        wchar_t m[216];

        // /** WARNING: this sloooooowwwwssss doooowwwwnnnn things
        wcsprintf(m, L"delete - p:%lx\n", (long)p);
        LOG.error(m);
        // **/

        if (p) {
            free(p);
        }
    }

    void operator delete[] (void* p) {
        ::operator delete(p);
    }

#endif

<commit_msg>Thi file is not used anymore. See winmobileadapter.cpp<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2022 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStatisticsXMLFileWriter.h"
#include "otbStreamingStatisticsVectorImageFilter.h"
#include <sstream>

namespace otb
{
namespace Wrapper
{

class ComputeImagesStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ComputeImagesStatistics       Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(ComputeImagesStatistics, otb::Application);

private:
  void DoInit() override
  {
    SetName("ComputeImagesStatistics");
    SetDescription(
        "Computes global mean and standard deviation for each band "
        "from a set of images and optionally saves the results in an XML file.");
    SetDocLongDescription(
        "This application computes a global mean and standard deviation "
        "for each band of a set of images and optionally saves the results in an XML file."
        " The output XML is intended to be used as an input "
        "for the TrainImagesClassifier application to normalize samples before learning. "
        "You can also normalize the image with the XML file in the ImageClassifier application.");

    SetDocLimitations(
        "Each image of the set must contain the same bands as the others"
        " (i.e. same types, in the same order).");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso("Documentation of the TrainImagesClassifier and ImageClassifier application.");

    AddDocTag(Tags::Learning);
    AddDocTag(Tags::Analysis);

    AddParameter(ParameterType_InputImageList, "il", "Input images");
    SetParameterDescription("il", "List of input image filenames.");

    AddParameter(ParameterType_Float, "bv", "Background Value");
    SetParameterDescription("bv", "Background value to ignore in computation of statistics.");
    MandatoryOff("bv");

    AddParameter(ParameterType_OutputFilename, "out", "Output XML file");
    SetParameterDescription("out", "XML filename where the statistics are saved for future reuse.");
    MandatoryOff("out");

    AddParameter(ParameterType_String, "mean", "Mean pixel Value");
    SetParameterDescription("mean", "Mean pixel value");
    SetParameterRole("mean", Role_Output);

    AddParameter(ParameterType_String, "min", "Min pixel Value");
    SetParameterDescription("min", "Minimum pixel value");
    SetParameterRole("min", Role_Output);

    AddParameter(ParameterType_String, "max", "Max pixel Value");
    SetParameterDescription("max", "Maximum pixel value");
    SetParameterRole("max", Role_Output);

    AddParameter(ParameterType_String, "std", "Standard deviation of pixel Value");
    SetParameterDescription("std", "Standard deviation of pixel value");
    SetParameterRole("std", Role_Output);

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("il", "QB_1_ortho.tif");
    SetDocExampleParameterValue("out", "EstimateImageStatisticsQB1.xml");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() override
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute() override
  {
    // Statistics estimator
    typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVImageFilterType;

    // Samples
    typedef double                               ValueType;
    typedef itk::VariableLengthVector<ValueType> MeasurementType;
    typedef itk::VariableSizeMatrix<ValueType>   MatrixValueType;

    unsigned int nbBands = 0;

    FloatVectorImageListType*                           imageList = GetParameterImageList("il");
    FloatVectorImageListType::InternalContainerSizeType nbImages  = imageList->Size();

    // Initialization, all image have same size and number of band/component
    FloatVectorImageType* firstImage = imageList->GetNthElement(0);
    nbBands                          = firstImage->GetNumberOfComponentsPerPixel();

    // Build a Measurement Vector of mean
    MatrixValueType mean(nbBands, static_cast<unsigned int>(nbImages));
    mean.Fill(itk::NumericTraits<MatrixValueType::ValueType>::Zero);

    // Build a Measurement Vector of min
    MatrixValueType min(nbBands, static_cast<unsigned int>(nbImages));
    mean.Fill(itk::NumericTraits<MatrixValueType::ValueType>::max());

    // Build a Measurement Vector of max
    MatrixValueType max(nbBands, static_cast<unsigned int>(nbImages));
    max.Fill(itk::NumericTraits<MatrixValueType::ValueType>::min());

    // Build a Measurement Matrix of variance
    MatrixValueType variance(nbBands, static_cast<unsigned int>(nbImages));
    variance.Fill(itk::NumericTraits<MatrixValueType::ValueType>::Zero);

    // Build a Measurement Matrix of nbSamples
    MatrixValueType nbSamples(nbBands, static_cast<unsigned int>(nbImages));
    nbSamples.Fill(itk::NumericTraits<MatrixValueType::ValueType>::Zero);

    // Iterate over all input images
    for (unsigned int imageId = 0; imageId < nbImages; ++imageId)
    {
      FloatVectorImageType* image = imageList->GetNthElement(imageId);
      if (nbBands != image->GetNumberOfComponentsPerPixel())
      {
        itkExceptionMacro(<< "The image #" << imageId + 1 << " has " << image->GetNumberOfComponentsPerPixel() << " bands, while the image #1 has " << nbBands);
      }

      // Compute Statistics of each VectorImage
      StreamingStatisticsVImageFilterType::Pointer statsEstimator = StreamingStatisticsVImageFilterType::New();
      std::ostringstream                           processName;
      processName << "Processing Image (" << imageId + 1 << "/" << imageList->Size() << ")";
      AddProcess(statsEstimator->GetStreamer(), processName.str());
      statsEstimator->SetInput(image);
      statsEstimator->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));

      if (HasValue("bv"))
      {
        statsEstimator->SetIgnoreUserDefinedValue(true);
        statsEstimator->SetUserIgnoredValue(GetParameterFloat("bv"));
      }
      statsEstimator->Update();

      MeasurementType nbRelevantPixels = statsEstimator->GetNbRelevantPixels();
      MeasurementType meanPerBand      = statsEstimator->GetMean();
      MeasurementType minPerBand       = statsEstimator->GetMinimum();
      MeasurementType maxPerBand       = statsEstimator->GetMaximum();

      for (unsigned int itBand = 0; itBand < nbBands; itBand++)
      {
        mean(itBand, imageId)      = meanPerBand[itBand];
        min(itBand, imageId)       = minPerBand[itBand];
        max(itBand, imageId)       = maxPerBand[itBand];
        variance(itBand, imageId)  = (statsEstimator->GetCovariance())(itBand, itBand);
        nbSamples(itBand, imageId) = nbRelevantPixels[itBand];
      }
    }

    // Compute total mean and pooled variation for each band of the image list
    MeasurementType totalSamplesPerBand;
    totalSamplesPerBand.SetSize(nbBands);
    totalSamplesPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);

    MeasurementType totalMeanPerBand;
    totalMeanPerBand.SetSize(nbBands);
    totalMeanPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);

    MeasurementType totalMinPerBand;
    totalMinPerBand.SetSize(nbBands);
    totalMinPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::max());

    MeasurementType totalMaxPerBand;
    totalMaxPerBand.SetSize(nbBands);
    totalMaxPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::min());

    MeasurementType totalVariancePerBand;
    totalVariancePerBand.SetSize(nbBands);
    totalVariancePerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);

    for (unsigned int imageId = 0; imageId < nbImages; ++imageId)
    {
      for (unsigned int itBand = 0; itBand < nbBands; itBand++)
      {
        MeasurementType::ValueType nbSample = nbSamples(itBand, imageId);
        totalSamplesPerBand[itBand] += nbSample;
        totalMeanPerBand[itBand] += mean(itBand, imageId) * nbSample;
        totalMinPerBand[itBand] = std::min(totalMinPerBand[itBand], min(itBand, imageId));
        totalMaxPerBand[itBand] = std::max(totalMaxPerBand[itBand], max(itBand, imageId));
        totalVariancePerBand[itBand] += variance(itBand, imageId) * (nbSample - 1);
      }
    }

    // Check 0 division
    for (unsigned int itBand = 0; itBand < nbBands; itBand++)
    {
      MeasurementType::ValueType nbSample = totalSamplesPerBand[itBand];

      if (nbSample > nbImages)
      {
        totalVariancePerBand[itBand] /= (nbSample - nbImages);
      }
      else
      {
        totalVariancePerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
      }

      if (nbSample != 0)
      {
        totalMeanPerBand[itBand] /= nbSample;
      }
      else
      {
        totalMeanPerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
        totalMinPerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
        totalMaxPerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
      }
    }

    MeasurementType stddev;
    stddev.SetSize(nbBands);
    stddev.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);
    for (unsigned int i = 0; i < totalVariancePerBand.GetSize(); ++i)
    {
      stddev[i] = std::sqrt(totalVariancePerBand[i]);
    }

    // Display the pixel value
    oss_mean << totalMeanPerBand;
    oss_min << totalMinPerBand;
    oss_max << totalMaxPerBand;
    oss_std << stddev;

//    // If the above doesn't work, we can do something like
//    const std::string separator = ",";
//    std::ostringstream oss_mean, oss_min, oss_max, oss_std;
//    oss_mean << "(";
//    oss_min << "(";
//    oss_max << "(";
//    oss_std << "(";
//    for (unsigned int itBand = 0; itBand < nbBands; itBand++)
//    {
//      oss_mean << totalMeanPerBand[itBand] << separator;
//      oss_min << totalMinPerBand[itBand] << separator;
//      oss_max << totalMaxPerBand[itBand] << separator;
//      oss_std << stddev[itBand] << separator;
//    }
//    oss_mean.seekp(-1, oss_mean.cur);
//    oss_min.seekp(-1, oss_min.cur);
//    oss_max.seekp(-1, oss_max.cur);
//    oss_std.seekp(-1, oss_std.cur);
//    oss_mean << ")";
//    oss_min << ")";
//    oss_max << ")";
//    oss_std << ")";

    SetParameterString("mean", oss_mean.str());
    SetParameterString("min", oss_min.str());
    SetParameterString("max", oss_max.str());
    SetParameterString("std", oss_std.str());

    // Display image information in the dedicated logger
    otbAppLogINFO(<< oss.str());

    if (HasValue("out"))
    {
      // Write the Statistics via the statistic writer
      typedef otb::StatisticsXMLFileWriter<MeasurementType> StatisticsWriter;
      StatisticsWriter::Pointer                             writer = StatisticsWriter::New();
      writer->SetFileName(GetParameterString("out"));
      writer->AddInput("mean", totalMeanPerBand);
      writer->AddInput("stddev", stddev);
      writer->Update();
    }
    else
    {
      otbAppLogINFO("Mean: " << mean << std::endl);
      otbAppLogINFO("Standard Deviation: " << stddev << std::endl);
    }
  }

  itk::LightObject::Pointer m_FilterRef;
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::ComputeImagesStatistics)
<commit_msg>ADD: role output for mean, min, max, std<commit_after>/*
 * Copyright (C) 2005-2022 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStatisticsXMLFileWriter.h"
#include "otbStreamingStatisticsVectorImageFilter.h"
#include <sstream>

namespace otb
{
namespace Wrapper
{

class ComputeImagesStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ComputeImagesStatistics       Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(ComputeImagesStatistics, otb::Application);

private:
  void DoInit() override
  {
    SetName("ComputeImagesStatistics");
    SetDescription(
        "Computes global mean and standard deviation for each band "
        "from a set of images and optionally saves the results in an XML file.");
    SetDocLongDescription(
        "This application computes a global mean and standard deviation "
        "for each band of a set of images and optionally saves the results in an XML file."
        " The output XML is intended to be used as an input "
        "for the TrainImagesClassifier application to normalize samples before learning. "
        "You can also normalize the image with the XML file in the ImageClassifier application.");

    SetDocLimitations(
        "Each image of the set must contain the same bands as the others"
        " (i.e. same types, in the same order).");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso("Documentation of the TrainImagesClassifier and ImageClassifier application.");

    AddDocTag(Tags::Learning);
    AddDocTag(Tags::Analysis);

    AddParameter(ParameterType_InputImageList, "il", "Input images");
    SetParameterDescription("il", "List of input image filenames.");

    AddParameter(ParameterType_Float, "bv", "Background Value");
    SetParameterDescription("bv", "Background value to ignore in computation of statistics.");
    MandatoryOff("bv");

    AddParameter(ParameterType_OutputFilename, "out", "Output XML file");
    SetParameterDescription("out", "XML filename where the statistics are saved for future reuse.");
    MandatoryOff("out");

    AddParameter(ParameterType_String, "mean", "Mean pixel Value");
    SetParameterDescription("mean", "Mean pixel value");
    SetParameterRole("mean", Role_Output);

    AddParameter(ParameterType_String, "min", "Min pixel Value");
    SetParameterDescription("min", "Minimum pixel value");
    SetParameterRole("min", Role_Output);

    AddParameter(ParameterType_String, "max", "Max pixel Value");
    SetParameterDescription("max", "Maximum pixel value");
    SetParameterRole("max", Role_Output);

    AddParameter(ParameterType_String, "std", "Standard deviation of pixel Value");
    SetParameterDescription("std", "Standard deviation of pixel value");
    SetParameterRole("std", Role_Output);

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("il", "QB_1_ortho.tif");
    SetDocExampleParameterValue("out", "EstimateImageStatisticsQB1.xml");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() override
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute() override
  {
    // Statistics estimator
    typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVImageFilterType;

    // Samples
    typedef double                               ValueType;
    typedef itk::VariableLengthVector<ValueType> MeasurementType;
    typedef itk::VariableSizeMatrix<ValueType>   MatrixValueType;

    unsigned int nbBands = 0;

    FloatVectorImageListType*                           imageList = GetParameterImageList("il");
    FloatVectorImageListType::InternalContainerSizeType nbImages  = imageList->Size();

    // Initialization, all image have same size and number of band/component
    FloatVectorImageType* firstImage = imageList->GetNthElement(0);
    nbBands                          = firstImage->GetNumberOfComponentsPerPixel();

    // Build a Measurement Vector of mean
    MatrixValueType mean(nbBands, static_cast<unsigned int>(nbImages));
    mean.Fill(itk::NumericTraits<MatrixValueType::ValueType>::Zero);

    // Build a Measurement Vector of min
    MatrixValueType min(nbBands, static_cast<unsigned int>(nbImages));
    mean.Fill(itk::NumericTraits<MatrixValueType::ValueType>::max());

    // Build a Measurement Vector of max
    MatrixValueType max(nbBands, static_cast<unsigned int>(nbImages));
    max.Fill(itk::NumericTraits<MatrixValueType::ValueType>::min());

    // Build a Measurement Matrix of variance
    MatrixValueType variance(nbBands, static_cast<unsigned int>(nbImages));
    variance.Fill(itk::NumericTraits<MatrixValueType::ValueType>::Zero);

    // Build a Measurement Matrix of nbSamples
    MatrixValueType nbSamples(nbBands, static_cast<unsigned int>(nbImages));
    nbSamples.Fill(itk::NumericTraits<MatrixValueType::ValueType>::Zero);

    // Iterate over all input images
    for (unsigned int imageId = 0; imageId < nbImages; ++imageId)
    {
      FloatVectorImageType* image = imageList->GetNthElement(imageId);
      if (nbBands != image->GetNumberOfComponentsPerPixel())
      {
        itkExceptionMacro(<< "The image #" << imageId + 1 << " has " << image->GetNumberOfComponentsPerPixel() << " bands, while the image #1 has " << nbBands);
      }

      // Compute Statistics of each VectorImage
      StreamingStatisticsVImageFilterType::Pointer statsEstimator = StreamingStatisticsVImageFilterType::New();
      std::ostringstream                           processName;
      processName << "Processing Image (" << imageId + 1 << "/" << imageList->Size() << ")";
      AddProcess(statsEstimator->GetStreamer(), processName.str());
      statsEstimator->SetInput(image);
      statsEstimator->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));

      if (HasValue("bv"))
      {
        statsEstimator->SetIgnoreUserDefinedValue(true);
        statsEstimator->SetUserIgnoredValue(GetParameterFloat("bv"));
      }
      statsEstimator->Update();

      MeasurementType nbRelevantPixels = statsEstimator->GetNbRelevantPixels();
      MeasurementType meanPerBand      = statsEstimator->GetMean();
      MeasurementType minPerBand       = statsEstimator->GetMinimum();
      MeasurementType maxPerBand       = statsEstimator->GetMaximum();

      for (unsigned int itBand = 0; itBand < nbBands; itBand++)
      {
        mean(itBand, imageId)      = meanPerBand[itBand];
        min(itBand, imageId)       = minPerBand[itBand];
        max(itBand, imageId)       = maxPerBand[itBand];
        variance(itBand, imageId)  = (statsEstimator->GetCovariance())(itBand, itBand);
        nbSamples(itBand, imageId) = nbRelevantPixels[itBand];
      }
    }

    // Compute total mean and pooled variation for each band of the image list
    MeasurementType totalSamplesPerBand;
    totalSamplesPerBand.SetSize(nbBands);
    totalSamplesPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);

    MeasurementType totalMeanPerBand;
    totalMeanPerBand.SetSize(nbBands);
    totalMeanPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);

    MeasurementType totalMinPerBand;
    totalMinPerBand.SetSize(nbBands);
    totalMinPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::max());

    MeasurementType totalMaxPerBand;
    totalMaxPerBand.SetSize(nbBands);
    totalMaxPerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::min());

    MeasurementType totalVariancePerBand;
    totalVariancePerBand.SetSize(nbBands);
    totalVariancePerBand.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);

    for (unsigned int imageId = 0; imageId < nbImages; ++imageId)
    {
      for (unsigned int itBand = 0; itBand < nbBands; itBand++)
      {
        MeasurementType::ValueType nbSample = nbSamples(itBand, imageId);
        totalSamplesPerBand[itBand] += nbSample;
        totalMeanPerBand[itBand] += mean(itBand, imageId) * nbSample;
        totalMinPerBand[itBand] = std::min(totalMinPerBand[itBand], min(itBand, imageId));
        totalMaxPerBand[itBand] = std::max(totalMaxPerBand[itBand], max(itBand, imageId));
        totalVariancePerBand[itBand] += variance(itBand, imageId) * (nbSample - 1);
      }
    }

    // Check 0 division
    for (unsigned int itBand = 0; itBand < nbBands; itBand++)
    {
      MeasurementType::ValueType nbSample = totalSamplesPerBand[itBand];

      if (nbSample > nbImages)
      {
        totalVariancePerBand[itBand] /= (nbSample - nbImages);
      }
      else
      {
        totalVariancePerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
      }

      if (nbSample != 0)
      {
        totalMeanPerBand[itBand] /= nbSample;
      }
      else
      {
        totalMeanPerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
        totalMinPerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
        totalMaxPerBand[itBand] = itk::NumericTraits<ValueType>::Zero;
      }
    }

    MeasurementType stddev;
    stddev.SetSize(nbBands);
    stddev.Fill(itk::NumericTraits<MeasurementType::ValueType>::Zero);
    for (unsigned int i = 0; i < totalVariancePerBand.GetSize(); ++i)
    {
      stddev[i] = std::sqrt(totalVariancePerBand[i]);
    }

    // Display the pixel value
    std::ostringstream oss_mean, oss_min, oss_max, oss_std;
    oss_mean << totalMeanPerBand;
    oss_min << totalMinPerBand;
    oss_max << totalMaxPerBand;
    oss_std << stddev;

//    // If the above doesn't work, we can do something like
//    const std::string separator = ",";
//    std::ostringstream oss_mean, oss_min, oss_max, oss_std;
//    oss_mean << "(";
//    oss_min << "(";
//    oss_max << "(";
//    oss_std << "(";
//    for (unsigned int itBand = 0; itBand < nbBands; itBand++)
//    {
//      oss_mean << totalMeanPerBand[itBand] << separator;
//      oss_min << totalMinPerBand[itBand] << separator;
//      oss_max << totalMaxPerBand[itBand] << separator;
//      oss_std << stddev[itBand] << separator;
//    }
//    oss_mean.seekp(-1, oss_mean.cur);
//    oss_min.seekp(-1, oss_min.cur);
//    oss_max.seekp(-1, oss_max.cur);
//    oss_std.seekp(-1, oss_std.cur);
//    oss_mean << ")";
//    oss_min << ")";
//    oss_max << ")";
//    oss_std << ")";

    SetParameterString("mean", oss_mean.str());
    SetParameterString("min", oss_min.str());
    SetParameterString("max", oss_max.str());
    SetParameterString("std", oss_std.str());

    if (HasValue("out"))
    {
      // Write the Statistics via the statistic writer
      typedef otb::StatisticsXMLFileWriter<MeasurementType> StatisticsWriter;
      StatisticsWriter::Pointer                             writer = StatisticsWriter::New();
      writer->SetFileName(GetParameterString("out"));
      writer->AddInput("mean", totalMeanPerBand);
      writer->AddInput("stddev", stddev);
      writer->Update();
    }
    else
    {
      otbAppLogINFO("Mean: " << mean << std::endl);
      otbAppLogINFO("Standard Deviation: " << stddev << std::endl);
    }
  }

  itk::LightObject::Pointer m_FilterRef;
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::ComputeImagesStatistics)
<|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_SOURCE_DIALOG_IMAPIMP_HXX
#define INCLUDED_SVX_SOURCE_DIALOG_IMAPIMP_HXX

// ---------------
// - IMapOwnData -
// ---------------

class IMapOwnData
{
public:

    Timer           aTimer;
    Timer           aTbxTimer;
    Graphic         aUpdateGraphic;
    ImageMap        aUpdateImageMap;
    TargetList      aUpdateTargetList;
    void*           pUpdateEditingObject;
    sal_Bool            bExecState;

                    IMapOwnData() : pUpdateEditingObject( NULL )  {}
};

#endif // _IMAPIMP_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738872 Uninitialized scalar field<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_SOURCE_DIALOG_IMAPIMP_HXX
#define INCLUDED_SVX_SOURCE_DIALOG_IMAPIMP_HXX

// ---------------
// - IMapOwnData -
// ---------------

class IMapOwnData
{
public:

    Timer           aTimer;
    Timer           aTbxTimer;
    Graphic         aUpdateGraphic;
    ImageMap        aUpdateImageMap;
    TargetList      aUpdateTargetList;
    void*           pUpdateEditingObject;
    sal_Bool        bExecState;

    IMapOwnData()
        : pUpdateEditingObject(NULL)
        , bExecState(false)
    {
    }
};

#endif // _IMAPIMP_HXX

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