<commit_before>/*
 * Copyright (C) 2017-2018 Daniel Nicoletti <dantti12@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#include "enginerequest.h"

#include "common.h"

#include <Cutelyst/response_p.h>
#include <Cutelyst/Context>

#include <QLoggingCategory>
Q_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, "cutelyst.engine_request", QtWarningMsg)

using namespace Cutelyst;

EngineRequest::EngineRequest()
{

}

EngineRequest::~EngineRequest()
{
    delete context;
}

void EngineRequest::finalizeBody()
{
    if (!(status & EngineRequest::Chunked)) {
        Response *response = context->response();
        QIODevice *body = response->bodyDevice();

        if (body) {
            body->seek(0);
            char block[64 * 1024];
            while (!body->atEnd()) {
                qint64 in = body->read(block, sizeof(block));
                if (in <= 0) {
                    break;
                }

                if (write(block, in) != in) {
                    qCWarning(CUTELYST_ENGINEREQUEST) << "Failed to write body";
                    break;
                }
            }
        } else {
            const QByteArray bodyByteArray = response->body();
            write(bodyByteArray.constData(), bodyByteArray.size());
        }
    } else if (!(status & EngineRequest::ChunkedDone)) {
        // Write the final '0' chunk
        doWrite("0\r\n\r\n", 5);
    }
}

void EngineRequest::finalizeError()
{
    Response *res = context->response();

    res->setContentType(QStringLiteral("text/html; charset=utf-8"));

    QByteArray body;

    // Trick IE. Old versions of IE would display their own error page instead
    // of ours if we'd give it less than 512 bytes.
    body.reserve(512);

    body.append(context->errors().join(QLatin1Char('\n')).toUtf8());

    res->setBody(body);

    // Return 500
    res->setStatus(Response::InternalServerError);
}

void EngineRequest::finalize()
{
    if (context->error()) {
        finalizeError();
    }

    if ((status & EngineRequest::FinalizedHeaders) || finalizeHeaders()) {
        finalizeBody();
    }

    processingFinished();
}

void EngineRequest::finalizeCookies()
{
    Response *res = context->response();
    Headers &headers = res->headers();
    const auto cookies = res->cookies();
    for (const QNetworkCookie &cookie : cookies) {
        headers.pushHeader(QStringLiteral("SET_COOKIE"), QString::fromLatin1(cookie.toRawForm()));
    }
}

bool EngineRequest::finalizeHeaders()
{
    Response *response = context->response();
    Headers &headers = response->headers();

    // Fix missing content length
    if (headers.contentLength() < 0) {
        qint64 size = response->size();
        if (size >= 0) {
            headers.setContentLength(size);
        }
    }

    finalizeCookies();

    // Done
    status |= EngineRequest::FinalizedHeaders;
    return writeHeaders(response->status(), headers);
}

qint64 EngineRequest::write(const char *data, qint64 len)
{
    if (!(status & EngineRequest::Chunked)) {
        return doWrite(data, len);
    } else if (!(status & EngineRequest::ChunkedDone)) {
        const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();
        QByteArray chunk;
        chunk.reserve(int(len + chunkSize.size() + 4));
        chunk.append(chunkSize).append("\r\n", 2)
                .append(data, int(len)).append("\r\n", 2);

        qint64 retWrite = doWrite(chunk.data(), chunk.size());

        // Flag if we wrote an empty chunk
        if (!len) {
            status |= EngineRequest::ChunkedDone;
        }

        return retWrite == chunk.size() ? len : -1;
    }
    return -1;
}

bool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)
{
    if (status & EngineRequest::FinalizedHeaders) {
        return false;
    }

    if (webSocketHandshakeDo(key, origin, protocol)) {
        status |= EngineRequest::FinalizedHeaders | EngineRequest::Async;
        return true;
    }

    return false;
}

bool EngineRequest::webSocketSendTextMessage(const QString &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendPing(const QByteArray &payload)
{
    Q_UNUSED(payload)
    return false;
}

bool EngineRequest::webSocketClose(quint16 code, const QString &reason)
{
    Q_UNUSED(code)
    Q_UNUSED(reason)
    return false;
}

void EngineRequest::processingFinished()
{
}

bool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol)
{
    Q_UNUSED(key)
    Q_UNUSED(origin)
    Q_UNUSED(protocol)
    return false;
}

void EngineRequest::setPath(char *rawPath, const int len)
{
    if (len == 0) {
        path = QString();
        return;
    }

    char *data = rawPath;
    const char *inputPtr = data;

    bool skipUtf8 = true;
    int outlen = 0;
    for (int i = 0; i < len; ++i, ++outlen) {
        const char c = inputPtr[i];
        if (c == '%' && i + 2 < len) {
            int a = inputPtr[++i];
            int b = inputPtr[++i];

            if (a >= '0' && a <= '9') a -= '0';
            else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
            else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;

            if (b >= '0' && b <= '9') b -= '0';
            else if (b >= 'a' && b <= 'f') b  = b - 'a' + 10;
            else if (b >= 'A' && b <= 'F') b  = b - 'A' + 10;

            *data++ = char((a << 4) | b);
            skipUtf8 = false;
        } else if (c == '+') {
            *data++ = ' ';
        } else {
            *data++ = c;
        }
    }

    if (skipUtf8) {
        path = QString::fromLatin1(rawPath, outlen);
    } else {
        path = QString::fromUtf8(rawPath, outlen);
    }
}

#include "moc_enginerequest.cpp"
<commit_msg>core: Do not seek(0) on sequential devices<commit_after>/*
 * Copyright (C) 2017-2018 Daniel Nicoletti <dantti12@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#include "enginerequest.h"

#include "common.h"

#include <Cutelyst/response_p.h>
#include <Cutelyst/Context>

#include <QLoggingCategory>
Q_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, "cutelyst.engine_request", QtWarningMsg)

using namespace Cutelyst;

EngineRequest::EngineRequest()
{

}

EngineRequest::~EngineRequest()
{
    delete context;
}

void EngineRequest::finalizeBody()
{
    if (!(status & EngineRequest::Chunked)) {
        Response *response = context->response();
        QIODevice *body = response->bodyDevice();

        if (body) {
            if (!body->isSequential()) {
                body->seek(0);
            }

            char block[64 * 1024];
            while (!body->atEnd()) {
                qint64 in = body->read(block, sizeof(block));
                if (in <= 0) {
                    break;
                }

                if (write(block, in) != in) {
                    qCWarning(CUTELYST_ENGINEREQUEST) << "Failed to write body";
                    break;
                }
            }
        } else {
            const QByteArray bodyByteArray = response->body();
            write(bodyByteArray.constData(), bodyByteArray.size());
        }
    } else if (!(status & EngineRequest::ChunkedDone)) {
        // Write the final '0' chunk
        doWrite("0\r\n\r\n", 5);
    }
}

void EngineRequest::finalizeError()
{
    Response *res = context->response();

    res->setContentType(QStringLiteral("text/html; charset=utf-8"));

    QByteArray body;

    // Trick IE. Old versions of IE would display their own error page instead
    // of ours if we'd give it less than 512 bytes.
    body.reserve(512);

    body.append(context->errors().join(QLatin1Char('\n')).toUtf8());

    res->setBody(body);

    // Return 500
    res->setStatus(Response::InternalServerError);
}

void EngineRequest::finalize()
{
    if (context->error()) {
        finalizeError();
    }

    if ((status & EngineRequest::FinalizedHeaders) || finalizeHeaders()) {
        finalizeBody();
    }

    processingFinished();
}

void EngineRequest::finalizeCookies()
{
    Response *res = context->response();
    Headers &headers = res->headers();
    const auto cookies = res->cookies();
    for (const QNetworkCookie &cookie : cookies) {
        headers.pushHeader(QStringLiteral("SET_COOKIE"), QString::fromLatin1(cookie.toRawForm()));
    }
}

bool EngineRequest::finalizeHeaders()
{
    Response *response = context->response();
    Headers &headers = response->headers();

    // Fix missing content length
    if (headers.contentLength() < 0) {
        qint64 size = response->size();
        if (size >= 0) {
            headers.setContentLength(size);
        }
    }

    finalizeCookies();

    // Done
    status |= EngineRequest::FinalizedHeaders;
    return writeHeaders(response->status(), headers);
}

qint64 EngineRequest::write(const char *data, qint64 len)
{
    if (!(status & EngineRequest::Chunked)) {
        return doWrite(data, len);
    } else if (!(status & EngineRequest::ChunkedDone)) {
        const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();
        QByteArray chunk;
        chunk.reserve(int(len + chunkSize.size() + 4));
        chunk.append(chunkSize).append("\r\n", 2)
                .append(data, int(len)).append("\r\n", 2);

        qint64 retWrite = doWrite(chunk.data(), chunk.size());

        // Flag if we wrote an empty chunk
        if (!len) {
            status |= EngineRequest::ChunkedDone;
        }

        return retWrite == chunk.size() ? len : -1;
    }
    return -1;
}

bool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)
{
    if (status & EngineRequest::FinalizedHeaders) {
        return false;
    }

    if (webSocketHandshakeDo(key, origin, protocol)) {
        status |= EngineRequest::FinalizedHeaders | EngineRequest::Async;
        return true;
    }

    return false;
}

bool EngineRequest::webSocketSendTextMessage(const QString &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message)
{
    Q_UNUSED(message)
    return false;
}

bool EngineRequest::webSocketSendPing(const QByteArray &payload)
{
    Q_UNUSED(payload)
    return false;
}

bool EngineRequest::webSocketClose(quint16 code, const QString &reason)
{
    Q_UNUSED(code)
    Q_UNUSED(reason)
    return false;
}

void EngineRequest::processingFinished()
{
}

bool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol)
{
    Q_UNUSED(key)
    Q_UNUSED(origin)
    Q_UNUSED(protocol)
    return false;
}

void EngineRequest::setPath(char *rawPath, const int len)
{
    if (len == 0) {
        path = QString();
        return;
    }

    char *data = rawPath;
    const char *inputPtr = data;

    bool skipUtf8 = true;
    int outlen = 0;
    for (int i = 0; i < len; ++i, ++outlen) {
        const char c = inputPtr[i];
        if (c == '%' && i + 2 < len) {
            int a = inputPtr[++i];
            int b = inputPtr[++i];

            if (a >= '0' && a <= '9') a -= '0';
            else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
            else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;

            if (b >= '0' && b <= '9') b -= '0';
            else if (b >= 'a' && b <= 'f') b  = b - 'a' + 10;
            else if (b >= 'A' && b <= 'F') b  = b - 'A' + 10;

            *data++ = char((a << 4) | b);
            skipUtf8 = false;
        } else if (c == '+') {
            *data++ = ' ';
        } else {
            *data++ = c;
        }
    }

    if (skipUtf8) {
        path = QString::fromLatin1(rawPath, outlen);
    } else {
        path = QString::fromUtf8(rawPath, outlen);
    }
}

#include "moc_enginerequest.cpp"
<|endoftext|>


<commit_before>#include "Math/Cartesian3D.h"

#include "Math/Types.h"

#include "RandomNumberEngine.h"

#include "benchmark/benchmark.h"

#include <random>

static bool is_aligned(const void *__restrict__ ptr, size_t align)
{
   return (uintptr_t)ptr % align == 0;
}

template class ROOT::Math::Cartesian3D<double>;

static void BM_Cartesian3D_Sanity(benchmark::State &state)
{
  // Report if we forgot to turn on the explicit vectorisation in ROOT.
  if (sizeof(double) == sizeof(ROOT::Double_v) || sizeof(float) == sizeof(ROOT::Float_v))
    state.SkipWithError("Explicit vectorisation is disabled!");
}
BENCHMARK(BM_Cartesian3D_Sanity);

static void BM_Cartesian3D_CreateEmpty(benchmark::State &state)
{
   while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c;
}
BENCHMARK(BM_Cartesian3D_CreateEmpty);

// template <typename T> class Cartesian3D { T x; T y; T z; /*...*/ };
// // ROOT::Double_v -> double[2]
// template <> class Cartesian3D<double[2]> { double[2] x; double[2] y; double[2] z; /*...*/ };

// template <> class Cartesian3D<double[2]> { double[2] x = 1.; double[2] y = 2.; double[2] z = 3.; /*...*/ };

static void ComputeProcessedEntities(benchmark::State &state, size_t VecSize)
{
   const size_t items_processed = state.iterations() * state.range(0);
   state.SetItemsProcessed(items_processed);
   // FIXME: This is not an accurate byte computation. We need to get the sizeof
   // the underlying type of T.
   state.SetBytesProcessed(items_processed * VecSize);
}

template <typename T>
static void BM_Cartesian3D_Theta(benchmark::State &state)
{
   using namespace ROOT::Benchmark;
   // Allocate N points
   typename Data<T>::Vector Points(state.range(0));
   constexpr size_t VecSize = TypeSize<T>::Get();
   ROOT::Math::Cartesian3D<T> c;
   while (state.KeepRunning())
      for (size_t i = 0, e = Points.size(); i < e; i += VecSize) {
         c.SetCoordinates(Points[i].X, Points[i].Y, Points[i].Z);
         c.Theta();
      }
   ComputeProcessedEntities(state, VecSize);
}
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(1 << 0, 1 << 10);

template <typename T>
static void BM_Cartesian3D_Phi(benchmark::State &state)
{
   using namespace ROOT::Benchmark;
   // Allocate N points
   typename Data<T>::Vector Points(state.range(0));
   constexpr size_t VecSize = TypeSize<T>::Get();
   ROOT::Math::Cartesian3D<T> c;
   while (state.KeepRunning())
      for (size_t i = 0, e = Points.size(); i < e; i += VecSize) {
         c.SetCoordinates(Points[i].X, Points[i].Y, Points[i].Z);
         c.Phi();
      }
   ComputeProcessedEntities(state, VecSize);
}
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(1 << 0, 1 << 10);

template <typename T>
static void BM_Cartesian3D_Mag2(benchmark::State &state)
{
   using namespace ROOT::Benchmark;
   // Allocate N points
   typename Data<T>::Vector Points(state.range(0));
   constexpr size_t VecSize = TypeSize<T>::Get();
   ROOT::Math::Cartesian3D<T> c;
   while (state.KeepRunning())
      for (size_t i = 0, e = Points.size(); i < e; i += VecSize) {
         c.SetCoordinates(Points[i].X, Points[i].Y, Points[i].Z);
         c.Mag2();
      }
   ComputeProcessedEntities(state, VecSize);
}
BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(1 << 0, 1 << 10);

// Define our main.
BENCHMARK_MAIN();
<commit_msg>Compute correctly the amount of processed bytes.<commit_after>#include "Math/Cartesian3D.h"

#include "Math/Types.h"

#include "RandomNumberEngine.h"

#include "benchmark/benchmark.h"

#include <random>

static bool is_aligned(const void *__restrict__ ptr, size_t align)
{
   return (uintptr_t)ptr % align == 0;
}

template class ROOT::Math::Cartesian3D<double>;

static void BM_Cartesian3D_Sanity(benchmark::State &state)
{
  // Report if we forgot to turn on the explicit vectorisation in ROOT.
  if (sizeof(double) == sizeof(ROOT::Double_v) || sizeof(float) == sizeof(ROOT::Float_v))
    state.SkipWithError("Explicit vectorisation is disabled!");
}
BENCHMARK(BM_Cartesian3D_Sanity);

static void BM_Cartesian3D_CreateEmpty(benchmark::State &state)
{
   while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c;
}
BENCHMARK(BM_Cartesian3D_CreateEmpty);

// template <typename T> class Cartesian3D { T x; T y; T z; /*...*/ };
// // ROOT::Double_v -> double[2]
// template <> class Cartesian3D<double[2]> { double[2] x; double[2] y; double[2] z; /*...*/ };

// template <> class Cartesian3D<double[2]> { double[2] x = 1.; double[2] y = 2.; double[2] z = 3.; /*...*/ };

static void ComputeProcessedEntities(benchmark::State &state, size_t Size)
{
   const size_t items_processed = state.iterations() * state.range(0);
   state.SetItemsProcessed(items_processed);
   state.SetBytesProcessed(items_processed * Size);
}

template <typename T>
static void BM_Cartesian3D_Theta(benchmark::State &state)
{
   using namespace ROOT::Benchmark;
   // Allocate N points
   typename Data<T>::Vector Points(state.range(0));
   constexpr size_t VecSize = TypeSize<T>::Get();
   ROOT::Math::Cartesian3D<T> c;
   while (state.KeepRunning())
      for (size_t i = 0, e = Points.size(); i < e; i += VecSize) {
         c.SetCoordinates(Points[i].X, Points[i].Y, Points[i].Z);
         c.Theta();
      }
   ComputeProcessedEntities(state, sizeof(T));
}
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(1 << 0, 1 << 10);

template <typename T>
static void BM_Cartesian3D_Phi(benchmark::State &state)
{
   using namespace ROOT::Benchmark;
   // Allocate N points
   typename Data<T>::Vector Points(state.range(0));
   constexpr size_t VecSize = TypeSize<T>::Get();
   ROOT::Math::Cartesian3D<T> c;
   while (state.KeepRunning())
      for (size_t i = 0, e = Points.size(); i < e; i += VecSize) {
         c.SetCoordinates(Points[i].X, Points[i].Y, Points[i].Z);
         c.Phi();
      }
   ComputeProcessedEntities(state, sizeof(T));
}
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(1 << 0, 1 << 10);

template <typename T>
static void BM_Cartesian3D_Mag2(benchmark::State &state)
{
   using namespace ROOT::Benchmark;
   // Allocate N points
   typename Data<T>::Vector Points(state.range(0));
   constexpr size_t VecSize = TypeSize<T>::Get();
   ROOT::Math::Cartesian3D<T> c;
   while (state.KeepRunning())
      for (size_t i = 0, e = Points.size(); i < e; i += VecSize) {
         c.SetCoordinates(Points[i].X, Points[i].Y, Points[i].Z);
         c.Mag2();
      }
   ComputeProcessedEntities(state, sizeof(T));
}
BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(1 << 0, 1 << 10);

// Define our main.
BENCHMARK_MAIN();
<|endoftext|>


<commit_before>#include "RooWorkspace.h"
#include "RooAddPdf.h"
#include "RooRealVar.h"
#include "RooMinimizer.h"
#include "TFile.h"
#include "TH1.h"
#include "TRandom.h"
#include "TError.h"
#include "RooStats/HistFactory/Measurement.h"
#include "RooStats/HistFactory/HistoToWorkspaceFactoryFast.h"
#include "RooStats/ModelConfig.h"
#include "RooLinkedListIter.h"
#include "RooRealSumPdf.h"

#include "benchmark/benchmark.h"

using namespace RooFit;
using namespace RooStats;
using namespace HistFactory;

void buildBinnedTest()
{
   Measurement meas("meas", "meas");
   meas.SetPOI("SignalStrength");
   meas.SetLumi(1.0);
   meas.SetLumiRelErr(0.10);
   meas.AddConstantParam("Lumi");
   Channel chan("Region0");
   auto Signal_Hist = new TH1F("Signal", "Signal", 100, 0, 100);
   auto Background_Hist = new TH1F("Background", "Background", 100, 0, 100);
   auto Data_Hist = new TH1F("Data", "Data", 100, 0, 100);
   int nbins = Signal_Hist->GetXaxis()->GetNbins();
   for (int bin = 1; bin <= nbins; ++bin) {
      for (int i = 0; i <= bin; ++i) {
         Signal_Hist->Fill(bin + 0.5);
         Data_Hist->Fill(bin + 0.5);
      }
      for (int i = 0; i <= 100; ++i) {
         Background_Hist->Fill(bin + 0.5);
         Data_Hist->Fill(bin + 0.5);
      }
   }
   chan.SetData(Data_Hist);
   Sample background("background");
   background.SetNormalizeByTheory(false);
   background.SetHisto(Background_Hist);
   Sample signal("signal");
   signal.SetNormalizeByTheory(false);
   signal.SetHisto(Signal_Hist);
   signal.AddNormFactor("SignalStrength", 1, 0, 3);
   chan.AddSample(background);
   chan.AddSample(signal);
   meas.AddChannel(chan);
   HistoToWorkspaceFactoryFast hist2workspace(meas);
   RooWorkspace *ws = hist2workspace.MakeSingleChannelModel(meas, chan);
   auto iter = ws->components().fwdIterator();
   RooAbsArg *arg;
   while ((arg = iter.next())) {
      if (arg->IsA() == RooRealSumPdf::Class()) {
         arg->setAttribute("BinnedLikelihood");
         std::cout << "component " << arg->GetName() << " is a binned likelihood" << std::endl;
      }
   }
   ws->SetName("BinnedWorkspace");
   ws->writeToFile("workspace.root");
}

Sample addVariations(Sample asample, int nnps, bool channel_crosstalk, int channel)
{
   for (int nuis = 0; nuis < nnps; ++nuis) {
      TRandom *R = new TRandom(channel * nuis / nnps);
      Double_t random = R->Rndm();
      double uncertainty_up = (1 + random) / sqrt(100);
      double uncertainty_down = (1 - random) / sqrt(100);
      std::cout << "in channel " << channel << "nuisance +/- [" << uncertainty_up << "," << uncertainty_down << "]"
                << std::endl;
      std::string nuis_name = "norm_uncertainty_" + std::to_string(nuis);
      if (!channel_crosstalk) {
         nuis_name = nuis_name + "_channel_" + std::to_string(channel);
      }
      asample.AddOverallSys(nuis_name, uncertainty_up, uncertainty_down);
   }
   return asample;
}

Channel makeChannel(int channel, int nnps, bool channel_crosstalk)
{
   std::string channel_name = "Region" + std::to_string(channel);
   Channel chan(channel_name);
   auto Signal_Hist = new TH1F("Signal", "Signal", 100, 0, 100);
   auto Background_Hist = new TH1F("Background", "Background", 100, 0, 100);
   auto Data_Hist = new TH1F("Data", "Data", 100, 0, 100);
   int nbins = Signal_Hist->GetXaxis()->GetNbins();
   for (Int_t bin = 1; bin <= nbins; ++bin) {
      for (Int_t i = 0; i <= bin; ++i) {
         Signal_Hist->Fill(bin + 0.5);
         Data_Hist->Fill(bin + 0.5);
      }
      for (Int_t i = 0; i <= 100; ++i) {
         Background_Hist->Fill(bin + 0.5);
         Data_Hist->Fill(bin + 0.5);
      }
   }
   chan.SetData(Data_Hist);
   Sample background("background");
   background.SetNormalizeByTheory(false);
   background.SetHisto(Background_Hist);
   background.ActivateStatError();
   Sample signal("signal");
   signal.SetNormalizeByTheory(false);
   signal.SetHisto(Signal_Hist);
   signal.ActivateStatError();
   signal.AddNormFactor("SignalStrength", 1, 0, 3);
   if (nnps > 0) {
      signal = addVariations(signal, nnps, true, channel);
      background = addVariations(background, nnps, false, channel);
   }
   chan.AddSample(background);
   chan.AddSample(signal);
   return chan;
}

void buildBinnedTest_nchannels(int n_channels = 1, int nnps = 1, const char *name_rootfile = "")
{
   bool channel_crosstalk = true;
   Measurement meas("meas", "meas");
   meas.SetPOI("SignalStrength");
   meas.SetLumi(1.0);
   meas.SetLumiRelErr(0.10);
   meas.AddConstantParam("Lumi");
   Channel chan;
   for (int channel = 0; channel < n_channels; ++channel) {
      chan = makeChannel(channel, nnps, channel_crosstalk);
      meas.AddChannel(chan);
   }
   HistoToWorkspaceFactoryFast hist2workspace(meas);
   RooWorkspace *ws;
   if (n_channels < 2) {
      ws = hist2workspace.MakeSingleChannelModel(meas, chan);
   } else {
      ws = hist2workspace.MakeCombinedModel(meas);
   }
   RooFIter iter = ws->components().fwdIterator();
   RooAbsArg *arg;
   while ((arg = iter.next())) {
      if (arg->IsA() == RooRealSumPdf::Class()) {
         arg->setAttribute("BinnedLikelihood");
         std::cout << "component " << arg->GetName() << " is a binned likelihood" << std::endl;
      }
   }
   ws->SetName("BinnedWorkspace");
   ws->writeToFile(name_rootfile);
}

static void CustomArguments(benchmark::internal::Benchmark* b) {
  for (int i = 1; i <= 3; ++i)
    for (int j = 1; j <= 2; ++j)
      b->Args({i, j});
}

static void BM_RooFit_BinnedTestMigrad(benchmark::State &state)
{
   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int cpu = state.range(0);
   TFile *infile = new TFile("workspace.root");
   if (infile->IsZombie()) {
      buildBinnedTest();
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile = TFile::Open("workspace.root");
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchmigradlog");
   for (auto _ : state) {
      m.migrad();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;
}
BENCHMARK(BM_RooFit_BinnedTestMigrad)->DenseRange(1, 4)->UseRealTime()->Unit(benchmark::kMicrosecond);

static void BM_RooFit_BinnedTestMigrad_NChannel(benchmark::State &state)
{
   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int chan = state.range(0);
   int cpu = state.range(1);
   std::string workspace_file = "worspace" + std::to_string(chan) + std::to_string(cpu) + ".root";
   TFile *infile = new TFile(workspace_file.c_str());
   if (infile->IsZombie()) {
      buildBinnedTest_nchannels(chan, 1, workspace_file.c_str());
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile = TFile::Open(workspace_file.c_str());
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchmigradnchanellog");
   for (auto _ : state) {
      m.migrad();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;
}

//FIXME: suppress output from generating workspaces
//BENCHMARK(BM_RooFit_BinnedTestMigrad_NChannel)->Apply(CustomArguments)->UseRealTime()->Unit(benchmark::kMicrosecond);

static void BM_RooFit_BinnedTestHesse(benchmark::State &state)
{
   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int cpu = state.range(0);
   TFile *infile = new TFile("workspace.root");
   if (infile->IsZombie()) {
      buildBinnedTest();
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile->TFile::Open("workspace.root");
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchhesselog");
   m.migrad();
   for (auto _ : state) {
      m.hesse();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;
}
BENCHMARK(BM_RooFit_BinnedTestHesse)->DenseRange(1, 4)->UseRealTime()->Unit(benchmark::kMicrosecond);

static void BM_RooFit_BinnedTestMinos(benchmark::State &state)
{
   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int cpu = state.range(0);
   TFile *infile = new TFile("workspace.root");
   if (infile->IsZombie()) {
      buildBinnedTest();
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile->TFile::Open("workspace.root");
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchminoslog");
   m.migrad();
   for (auto _ : state) {
      m.minos();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;
}
BENCHMARK(BM_RooFit_BinnedTestMinos)->DenseRange(1, 4)->UseRealTime()->Unit(benchmark::kMicrosecond);

BENCHMARK_MAIN();
<commit_msg>Cleaning up and adding snapshots and variable binning<commit_after>#include "RooWorkspace.h"
#include "RooAddPdf.h"
#include "RooRealVar.h"
#include "RooMinimizer.h"
#include "TFile.h"
#include "TH1.h"
#include "TRandom.h"
#include "TError.h"
#include "RooStats/HistFactory/Measurement.h"
#include "RooStats/HistFactory/HistoToWorkspaceFactoryFast.h"
#include "RooStats/ModelConfig.h"
#include "RooLinkedListIter.h"
#include "RooRealSumPdf.h"

#include "benchmark/benchmark.h"

using namespace RooFit;
using namespace RooStats;
using namespace HistFactory;

Sample addVariations(Sample asample, int nnps, bool channel_crosstalk, int channel)
{
   for (int nuis = 0; nuis < nnps; ++nuis) {
      TRandom *R = new TRandom(channel * nuis / nnps);
      Double_t random = R->Rndm();
      double uncertainty_up = (1 + random) / sqrt(100);
      double uncertainty_down = (1 - random) / sqrt(100);
      std::cout << "in channel " << channel << "nuisance +/- [" << uncertainty_up << "," << uncertainty_down << "]"
                << std::endl;
      std::string nuis_name = "norm_uncertainty_" + std::to_string(nuis);
      if (!channel_crosstalk) {
         nuis_name = nuis_name + "_channel_" + std::to_string(channel);
      }
      asample.AddOverallSys(nuis_name, uncertainty_up, uncertainty_down);
   }
   return asample;
}

Channel makeChannel(int channel, int nbins, int nnps, bool channel_crosstalk)
{
   std::string channel_name = "Region" + std::to_string(channel);
   Channel chan(channel_name);
   auto Signal_Hist = new TH1F("Signal", "Signal", nbins, 0, nbins);
   auto Background_Hist = new TH1F("Background", "Background", nbins, 0, nbins);
   auto Data_Hist = new TH1F("Data", "Data", nbins, 0, nbins);
   for (Int_t bin = 1; bin <= nbins; ++bin) {
      for (Int_t i = 0; i <= bin; ++i) {
         Signal_Hist->Fill(bin + 0.5);
         Data_Hist->Fill(bin + 0.5);
      }
      for (Int_t i = 0; i <= 20; ++i) {
         Background_Hist->Fill(bin + 0.5);
         Data_Hist->Fill(bin + 0.5);
      }
   }
   chan.SetData(Data_Hist);
   Sample background("background");
   background.SetNormalizeByTheory(false);
   background.SetHisto(Background_Hist);
   background.ActivateStatError();
   Sample signal("signal");
   signal.SetNormalizeByTheory(false);
   signal.SetHisto(Signal_Hist);
   signal.ActivateStatError();
   signal.AddNormFactor("SignalStrength", 1, 0, 3);

   if (nnps > 0) {
      signal = addVariations(signal, nnps, true, channel);
      background = addVariations(background, nnps, false, channel);
   }
   chan.AddSample(background);
   chan.AddSample(signal);
   return chan;
}

void buildBinnedTest(int n_channels = 1, int nbins = 10, int nnps = 1, const char *name_rootfile = "")
{
   bool channel_crosstalk = true;
   Measurement meas("meas", "meas");
   meas.SetPOI("SignalStrength");
   meas.SetLumi(1.0);
   meas.SetLumiRelErr(0.10);
   meas.AddConstantParam("Lumi");
   Channel chan;
   for (int channel = 0; channel < n_channels; ++channel) {
     chan = makeChannel(channel, nbins, nnps, channel_crosstalk);
      meas.AddChannel(chan);
   }
   HistoToWorkspaceFactoryFast hist2workspace(meas);
   RooWorkspace *ws;
   if (n_channels < 2) {
      ws = hist2workspace.MakeSingleChannelModel(meas, chan);
   } else {
      ws = hist2workspace.MakeCombinedModel(meas);
   }
   RooFIter iter = ws->components().fwdIterator();
   RooAbsArg *arg;
   while ((arg = iter.next())) {
      if (arg->IsA() == RooRealSumPdf::Class()) {
         arg->setAttribute("BinnedLikelihood");
         std::cout << "component " << arg->GetName() << " is a binned likelihood" << std::endl;
      }
   }
   ws->SetName("BinnedWorkspace");
   ws->writeToFile(name_rootfile);
}

static void BM_RooFit_BinnedTestMigrad_NChannel(benchmark::State &state)
{
   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int chan = state.range(0);
   int cpu = state.range(1);
   TFile *infile = new TFile("workspace.root");
   if (infile->IsZombie()) {
     buildBinnedTest(chan, 30, 3, "workspace.root");
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile = TFile::Open("workspace.root");
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchmigradnchannellog");
   for (auto _ : state) {
      m.migrad();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;
}

static void BM_RooFit_BinnedTestHesse_NChannel(benchmark::State &state)
{

   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int chan = state.range(0);
   int cpu = state.range(1);
   TFile *infile = new TFile("workspace.root");
   if (infile->IsZombie()) {
     buildBinnedTest(chan, 30, 3, "workspace.root");
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile = TFile::Open("workspace.root");
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooArgSet* params = (RooArgSet*) pdf->getParameters(data) ;
   w->saveSnapshot("no_fit", *params, kTRUE);
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchhessenchannellog");
   m.migrad();
   w->loadSnapshot("no_fit");
   for (auto _ : state) {
      m.hesse();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;

}

static void BM_RooFit_BinnedTestMinos_NChannel(benchmark::State &state)
{

   gErrorIgnoreLevel = kInfo;
   RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
   RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval);
   int chan = state.range(0);
   int cpu = state.range(1);
   TFile *infile = new TFile("workspace.root");
   if (infile->IsZombie()) {
     buildBinnedTest(chan, 30, 3, "workspace.root");
      std::cout << "Workspace for tests was created!" << std::endl;
   }
   infile = TFile::Open("workspace.root");
   RooWorkspace *w = static_cast<RooWorkspace *>(infile->Get("BinnedWorkspace"));
   RooAbsData *data = w->data("obsData");
   ModelConfig *mc = static_cast<ModelConfig *>(w->genobj("ModelConfig"));
   RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName());
   RooAbsReal *nll = pdf->createNLL(*data, NumCPU(cpu, 0));
   RooArgSet* params = (RooArgSet*) pdf->getParameters(data) ;
   w->saveSnapshot("no_fit", *params, kTRUE);
   RooMinimizer m(*nll);
   m.setPrintLevel(-1);
   m.setStrategy(0);
   m.setProfile(0);
   m.setLogFile("benchhessenchannellog");
   m.migrad();
   m.hesse();
   w->loadSnapshot("no_fit");
   for (auto _ : state) {
      m.minos();
   }
   delete data;
   delete infile;
   delete mc;
   delete pdf;
   delete nll;
}

static void ChanArguments(benchmark::internal::Benchmark* b) {
  for (int i = 1; i <= 4; ++i)
    for (int j = 1; j <= 3; ++j)
      b->Args({i, j});
}

BENCHMARK(BM_RooFit_BinnedTestMigrad_NChannel)->Apply(ChanArguments)->UseRealTime()->Unit(benchmark::kMicrosecond)->Iterations(3);
BENCHMARK(BM_RooFit_BinnedTestHesse_NChannel)->Apply(ChanArguments)->UseRealTime()->Unit(benchmark::kMicrosecond)->Iterations(3);
BENCHMARK(BM_RooFit_BinnedTestMinos_NChannel)->Apply(ChanArguments)->UseRealTime()->Unit(benchmark::kMicrosecond)->Iterations(3);

BENCHMARK_MAIN();
<|endoftext|>


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

#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "ui/aura/root_window.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"

namespace xwalk {

NativeAppWindowTizen::NativeAppWindowTizen(
    const NativeAppWindow::CreateParams& create_params)
    : NativeAppWindowViews(create_params),
      indicator_widget_(new TizenSystemIndicatorWidget()),
      allowed_orientations_(ANY) {
  indicator_container_.reset(new WidgetContainerView(indicator_widget_.get()));
}

void NativeAppWindowTizen::Initialize() {
  NativeAppWindowViews::Initialize();

  // Get display info such as device_scale_factor, and current
  // rotation (orientation). NOTE: This is a local copy of the info.
  display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();

  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->AddObserver(this);

  OrientationMask ua_default =
      XWalkBrowserMainPartsTizen::GetAllowedUAOrientations();
  OnAllowedOrientationsChanged(ua_default);

  if (SensorProvider* sensor = SensorProvider::GetInstance()) {
    gfx::Display::Rotation rotation
      = GetClosestAllowedRotation(sensor->GetCurrentRotation());
    display_.set_rotation(rotation);
    ApplyDisplayRotation();
    sensor->AddObserver(this);
  }
}

NativeAppWindowTizen::~NativeAppWindowTizen() {
  if (SensorProvider::GetInstance())
    SensorProvider::GetInstance()->RemoveObserver(this);
  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->RemoveObserver(this);
}

void NativeAppWindowTizen::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add && details.child == this) {
    NativeAppWindowViews::ViewHierarchyChanged(details);
    indicator_widget_->Initialize(GetNativeWindow());
    top_view_layout()->set_top_view(indicator_container_.get());
    AddChildView(indicator_container_.get());
  }
}

void NativeAppWindowTizen::OnWindowBoundsChanged(
    aura::Window* window,
    const gfx::Rect& old_bounds,
    const gfx::Rect& new_bounds) {
  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK_EQ(root_window, window);

  // Change the bounds of child windows to make touch work correctly.
  GetNativeWindow()->parent()->SetBounds(new_bounds);
  GetNativeWindow()->SetBounds(new_bounds);

  GetWidget()->GetRootView()->SetSize(new_bounds.size());
}

void NativeAppWindowTizen::OnWindowVisibilityChanging(
    aura::Window* window, bool visible) {
  if (visible)
    ApplyDisplayRotation();
}

gfx::Transform NativeAppWindowTizen::GetRotationTransform() const {
  // This method assumed a fixed portrait device. As everything
  // is calculated from the fixed position we do not update the
  // display bounds after rotation change.
  gfx::Transform rotate;
  float one_pixel = 1.0f / display_.device_scale_factor();
  switch (display_.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display_.bounds().width() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display_.bounds().height() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display_.bounds().width() - one_pixel,
                       display_.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }

  return rotate;
}

namespace {

// Rotates a binary mask of 4 positions to the left.
unsigned rotl4(unsigned value, int shift) {
  unsigned res = (value << shift);
  if (res > (1 << 4) - 1)
    res = res >> 4;
  return res;
}

bool IsLandscapeOrientation(const gfx::Display::Rotation& rotation) {
  return rotation == gfx::Display::ROTATE_90 ||
         rotation == gfx::Display::ROTATE_270;
}

}  // namespace.

gfx::Display::Rotation NativeAppWindowTizen::GetClosestAllowedRotation(
    gfx::Display::Rotation rotation) const {

  unsigned result = PORTRAIT_PRIMARY;
  // gfx::Display::Rotation starts at portrait-primary and
  // belongs to the set [0:3].
  result = rotl4(result, rotation);

  // Test current orientation
  if (allowed_orientations_ & result)
    return rotation;

  // Test orientation right of current one.
  if (allowed_orientations_ & rotl4(result, 1))
    return static_cast<gfx::Display::Rotation>((rotation + 1) % 4);

  // Test orientation left of current one.
  if (allowed_orientations_ & rotl4(result, 3))
    return static_cast<gfx::Display::Rotation>((rotation + 3) % 4);

  // Test orientation opposite of current one.
  if (allowed_orientations_ & rotl4(result, 2))
    return static_cast<gfx::Display::Rotation>((rotation + 2) % 4);

  NOTREACHED();
  return rotation;
}

Orientation NativeAppWindowTizen::GetCurrentOrientation() const {
  switch (display_.rotation()) {
    case gfx::Display::ROTATE_0:
      return PORTRAIT_PRIMARY;
    case gfx::Display::ROTATE_90:
      return LANDSCAPE_PRIMARY;
    case gfx::Display::ROTATE_180:
      return PORTRAIT_SECONDARY;
    case gfx::Display::ROTATE_270:
      return LANDSCAPE_SECONDARY;
    default:
      NOTREACHED();
      return PORTRAIT_PRIMARY;
  }
}

void NativeAppWindowTizen::OnAllowedOrientationsChanged(
    OrientationMask orientations) {
  allowed_orientations_ = orientations;

  gfx::Display::Rotation rotation
      = GetClosestAllowedRotation(display_.rotation());
  if (display_.rotation() == rotation)
    return;

  display_.set_rotation(rotation);
  ApplyDisplayRotation();
}

void NativeAppWindowTizen::OnRotationChanged(
    gfx::Display::Rotation rotation) {
  // We always store the current sensor position, even if we do not
  // apply it in case the window is invisible.

  rotation = GetClosestAllowedRotation(rotation);
  if (display_.rotation() == rotation)
    return;

  display_.set_rotation(rotation);

  ApplyDisplayRotation();
}

void NativeAppWindowTizen::UpdateTopViewOverlay() {
  top_view_layout()->SetUseOverlay(
      IsLandscapeOrientation(display_.rotation()));
}

void NativeAppWindowTizen::ApplyDisplayRotation() {
  if (observer())
    observer()->OnOrientationChanged(GetCurrentOrientation());

  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  if (!root_window->IsVisible())
    return;
  UpdateTopViewOverlay();
  indicator_widget_->SetDisplay(display_);
  root_window->SetTransform(GetRotationTransform());
}

}  // namespace xwalk
<commit_msg>Fix orientation sometimes getting stuck in current orientation after unlock<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "ui/aura/root_window.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"

namespace xwalk {

NativeAppWindowTizen::NativeAppWindowTizen(
    const NativeAppWindow::CreateParams& create_params)
    : NativeAppWindowViews(create_params),
      indicator_widget_(new TizenSystemIndicatorWidget()),
      allowed_orientations_(ANY) {
  indicator_container_.reset(new WidgetContainerView(indicator_widget_.get()));
}

void NativeAppWindowTizen::Initialize() {
  NativeAppWindowViews::Initialize();

  // Get display info such as device_scale_factor, and current
  // rotation (orientation). NOTE: This is a local copy of the info.
  display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();

  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->AddObserver(this);

  OrientationMask ua_default =
      XWalkBrowserMainPartsTizen::GetAllowedUAOrientations();
  OnAllowedOrientationsChanged(ua_default);

  if (SensorProvider* sensor = SensorProvider::GetInstance()) {
    gfx::Display::Rotation rotation
      = GetClosestAllowedRotation(sensor->GetCurrentRotation());
    display_.set_rotation(rotation);
    ApplyDisplayRotation();
    sensor->AddObserver(this);
  }
}

NativeAppWindowTizen::~NativeAppWindowTizen() {
  if (SensorProvider::GetInstance())
    SensorProvider::GetInstance()->RemoveObserver(this);
  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->RemoveObserver(this);
}

void NativeAppWindowTizen::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add && details.child == this) {
    NativeAppWindowViews::ViewHierarchyChanged(details);
    indicator_widget_->Initialize(GetNativeWindow());
    top_view_layout()->set_top_view(indicator_container_.get());
    AddChildView(indicator_container_.get());
  }
}

void NativeAppWindowTizen::OnWindowBoundsChanged(
    aura::Window* window,
    const gfx::Rect& old_bounds,
    const gfx::Rect& new_bounds) {
  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK_EQ(root_window, window);

  // Change the bounds of child windows to make touch work correctly.
  GetNativeWindow()->parent()->SetBounds(new_bounds);
  GetNativeWindow()->SetBounds(new_bounds);

  GetWidget()->GetRootView()->SetSize(new_bounds.size());
}

void NativeAppWindowTizen::OnWindowVisibilityChanging(
    aura::Window* window, bool visible) {
  if (visible)
    ApplyDisplayRotation();
}

gfx::Transform NativeAppWindowTizen::GetRotationTransform() const {
  // This method assumed a fixed portrait device. As everything
  // is calculated from the fixed position we do not update the
  // display bounds after rotation change.
  gfx::Transform rotate;
  float one_pixel = 1.0f / display_.device_scale_factor();
  switch (display_.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display_.bounds().width() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display_.bounds().height() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display_.bounds().width() - one_pixel,
                       display_.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }

  return rotate;
}

namespace {

// Rotates a binary mask of 4 positions to the left.
unsigned rotl4(unsigned value, int shift) {
  unsigned res = (value << shift);
  if (res > (1 << 4) - 1)
    res = res >> 4;
  return res;
}

bool IsLandscapeOrientation(const gfx::Display::Rotation& rotation) {
  return rotation == gfx::Display::ROTATE_90 ||
         rotation == gfx::Display::ROTATE_270;
}

}  // namespace.

gfx::Display::Rotation NativeAppWindowTizen::GetClosestAllowedRotation(
    gfx::Display::Rotation rotation) const {

  unsigned result = PORTRAIT_PRIMARY;
  // gfx::Display::Rotation starts at portrait-primary and
  // belongs to the set [0:3].
  result = rotl4(result, rotation);

  // Test current orientation
  if (allowed_orientations_ & result)
    return rotation;

  // Test orientation right of current one.
  if (allowed_orientations_ & rotl4(result, 1))
    return static_cast<gfx::Display::Rotation>((rotation + 1) % 4);

  // Test orientation left of current one.
  if (allowed_orientations_ & rotl4(result, 3))
    return static_cast<gfx::Display::Rotation>((rotation + 3) % 4);

  // Test orientation opposite of current one.
  if (allowed_orientations_ & rotl4(result, 2))
    return static_cast<gfx::Display::Rotation>((rotation + 2) % 4);

  NOTREACHED();
  return rotation;
}

Orientation NativeAppWindowTizen::GetCurrentOrientation() const {
  switch (display_.rotation()) {
    case gfx::Display::ROTATE_0:
      return PORTRAIT_PRIMARY;
    case gfx::Display::ROTATE_90:
      return LANDSCAPE_PRIMARY;
    case gfx::Display::ROTATE_180:
      return PORTRAIT_SECONDARY;
    case gfx::Display::ROTATE_270:
      return LANDSCAPE_SECONDARY;
    default:
      NOTREACHED();
      return PORTRAIT_PRIMARY;
  }
}

void NativeAppWindowTizen::OnAllowedOrientationsChanged(
    OrientationMask orientations) {
  allowed_orientations_ = orientations;

  // As we might have been locked before our current orientation
  // might not fit with the sensor orienation.
  gfx::Display::Rotation rotation = display_.rotation();
  if (SensorProvider* sensor = SensorProvider::GetInstance())
    rotation = sensor->GetCurrentRotation();

  rotation = GetClosestAllowedRotation(rotation);
  if (display_.rotation() == rotation)
    return;

  display_.set_rotation(rotation);
  ApplyDisplayRotation();
}

void NativeAppWindowTizen::OnRotationChanged(
    gfx::Display::Rotation rotation) {
  // We always store the current sensor position, even if we do not
  // apply it in case the window is invisible.

  rotation = GetClosestAllowedRotation(rotation);
  if (display_.rotation() == rotation)
    return;

  display_.set_rotation(rotation);

  ApplyDisplayRotation();
}

void NativeAppWindowTizen::UpdateTopViewOverlay() {
  top_view_layout()->SetUseOverlay(
      IsLandscapeOrientation(display_.rotation()));
}

void NativeAppWindowTizen::ApplyDisplayRotation() {
  if (observer())
    observer()->OnOrientationChanged(GetCurrentOrientation());

  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  if (!root_window->IsVisible())
    return;
  UpdateTopViewOverlay();
  indicator_widget_->SetDisplay(display_);
  root_window->SetTransform(GetRotationTransform());
}

}  // namespace xwalk
<|endoftext|>


<commit_before>#include "lexAnalyzer.h"
#include <fstream>

using namespace std;

int main()
{
    ifstream file("main.in");
    string sentence = "";
    while (!file.eof())
    {
        string buffer;
        file >> buffer;
        sentence += ' ' + buffer;
    }
    LexAnalyzer check(sentence);
    if (check.mainProcess())
    {
        cout << "Succesful Reading!" << endl;
    }
    else
    {
        cout << "Reading Failed!" << endl;
    }
    return 0;
}<commit_msg>File closed<commit_after>#include "lexAnalyzer.h"
#include <fstream>

using namespace std;

int main()
{
    ifstream file("main.in");
    string sentence = "";
    while (!file.eof())
    {
        string buffer;
        file >> buffer;
        sentence += ' ' + buffer;
    }
    file.close();
    LexAnalyzer check(sentence);
    if (check.mainProcess())
    {
        cout << "Succesful Reading!" << endl;
    }
    else
    {
        cout << "Reading Failed!" << endl;
    }
    return 0;
}<|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/.
 *
 */

#ifndef ANOVA_ONE_FACTOR_DIALOG_HXX
#define ANOVA_ONE_FACTOR_DIALOG_HXX

#include "global.hxx"
#include "address.hxx"
#include "anyrefdg.hxx"

#include <vcl/fixed.hxx>
#include <vcl/group.hxx>
#include <vcl/lstbox.hxx>

#include "StatisticsInputOutputDialog.hxx"

class ScAnalysisOfVarianceDialog : public ScStatisticsInputOutputDialog
{
public:
    ScAnalysisOfVarianceDialog(
        SfxBindings* pB, SfxChildWindow* pCW,
        Window* pParent, ScViewData* pViewData );

    virtual ~ScAnalysisOfVarianceDialog();

    virtual sal_Bool Close();

    NumericField* mpAlpha;

protected:
    virtual void CalculateInputAndWriteToOutput();
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>just rename header define<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/.
 *
 */

#ifndef ANALYSIS_OF_VARIANCE_DIALOG_HXX
#define ANALYSIS_OF_VARIANCE_DIALOG_HXX

#include "global.hxx"
#include "address.hxx"
#include "anyrefdg.hxx"

#include <vcl/fixed.hxx>
#include <vcl/group.hxx>
#include <vcl/lstbox.hxx>

#include "StatisticsInputOutputDialog.hxx"

class ScAnalysisOfVarianceDialog : public ScStatisticsInputOutputDialog
{
public:
    ScAnalysisOfVarianceDialog(
        SfxBindings* pB, SfxChildWindow* pCW,
        Window* pParent, ScViewData* pViewData );

    virtual ~ScAnalysisOfVarianceDialog();

    virtual sal_Bool Close();

    NumericField* mpAlpha;

protected:
    virtual void CalculateInputAndWriteToOutput();
};

#endif

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


<commit_before>#ifndef _arena_hpp_INCLUDED
#define _arena_hpp_INCLUDED

#include <cassert>
#include <cstdlib>
#include <cstring>

namespace CaDiCaL {

// This memory allocation arena provides fixed size pre-allocated memory for
// the moving garbage collector 'move_non_garbage_clauses' in 'reduce.cpp'
// to hold clauses which should survive garbage collection.  The advantage
// of using a pre-allocated arena are that the allocation order of the
// clauses can be adapted in such a way that clauses watched by the same
// literal are allocated consecutively. A similar technique is implemented
// in MiniSAT and Glucose and gives substantial speed-up in propagations per
// second even though it might even almost double peek memory usage.  Note
// that in MiniSAT this arena is also required to be able to use 32 bit
// references, which we do not want to use anymore.  New learned clauses are
// allocated in CaDiCaL outside of this arena.  The additional 'to' space is
// only allocated for those clauses surviving garbage collection, which
// usually needs much less memory than all clauses.  The net effect is that
// in our implementation the moving garbage collector using this arena only
// roughly needs only 50% more memory.  You can compare both implementations
// with the 'arena' option (which also controls allocation order).

class Internal;

// The standard sequence of using an arena is as follows:
//
//   Arena arena;
//   ...
//   arena.prepare (bytes);
//   ... = arena.copy (bytes1);
//   ... = arena.copy (bytesn);
//   assert (bytes1 + ... + bytesn <= bytes);
//   arena.swap ();
//   ...
//   if (!arena.contains (p)) delete p;
//   ...
//   arena.prepare (bytes);
//   ... = arena.copy (bytes1);
//   ... = arena.copy (bytesn);
//   assert (bytes1 + ... + bytesn <= bytes);
//   arena.swap ();
//   ...
//
// One has to be really careful with references to arena memory.

class Arena {

  Internal * internal;

  struct { char * start, * top, * end; } from, to;

public:

  Arena (Internal *);
  ~Arena ();

  // Does the memory pointed to by 'p' belong to this arena? More precisely
  // to the 'from' space, since that is the only one remaining after 'swap'.
  //
  bool contains (void * p) const {
    char * c = (char *) p;
    return from.start <= c && c < from.top;
  }

  // Prepare 'to' space to hold that amount of memory.  Precondition is that
  // the 'to' space is empty.  The following sequence of 'copy' operations
  // can use as much memory in sum as pre-allocated here.
  //
  void prepare (size_t bytes);

  // Allocate that amount of memory in 'to' space.  This assumes the 'to'
  // space has been prepared to hold enough memory with 'prepare'.  Then
  // copy the memory pointed to by 'p' of size 'bytes'.
  //
  char * copy (const char * p, size_t bytes) {
    char * res = to.top;
    to.top += bytes;
    assert (to.top <= to.end);
    memcpy (res, p, bytes);
    return res;
  }

  // Completely delete 'from' space and then replace 'from' by 'to' (by
  // pointer swapping).  Everything previously allocated (in 'from') and not
  // explicitly copied to 'to' with 'copy' becomes invalid.
  //
  void swap ();
};

};

#endif
<commit_msg>fixed<commit_after>#ifndef _arena_hpp_INCLUDED
#define _arena_hpp_INCLUDED

#include <cassert>
#include <cstdlib>
#include <cstring>

namespace CaDiCaL {

// This memory allocation arena provides fixed size pre-allocated memory for
// the moving garbage collector 'move_non_garbage_clauses' in 'reduce.cpp'
// to hold clauses which should survive garbage collection.  The advantage
// of using a pre-allocated arena is that the allocation order of the
// clauses can be adapted in such a way that clauses watched by the same
// literal are allocated consecutively.  This improves locality and thus is
// more cache friendly. A similar technique is implemented in MiniSAT and
// Glucose and gives substantial speed-up in propagations per second even
// though it might even almost double peek memory usage.  Note that in
// MiniSAT this arena is also required for MiniSAT to use 32 bit clauses
// references instead of 64 bit pointers.  This would restrict the maximum
// number of clauses and thus is a restriction we do not want to use
// anymore.  New learned clauses are allocated in CaDiCaL outside of this
// arena and moved to the arena during garbage collection.  The additional
// 'to' space required for such a moving garbage collector is only allocated
// for those clauses surviving garbage collection, which usually needs much
// less memory than all clauses.  The net effect is that in this
// implementation the moving garbage collector using this arena only needs
// roughly 50% more memory than allocating the clauses directly.  Both
// implementations can be compared by varying the 'arena' option (which also
// controls the allocation order of clauses during moving them).

// The standard sequence of using the arena is as follows:
//
//   Arena arena;
//   ...
//   arena.prepare (bytes);
//   q1 = arena.copy (p1, bytes1);
//   ...
//   qn = arena.copy (pn, bytesn);
//   assert (bytes1 + ... + bytesn <= bytes);
//   arena.swap ();
//   ...
//   if (!arena.contains (q)) delete q;
//   ...
//   arena.prepare (bytes);
//   q1 = arena.copy (p1, bytes1);
//   ...
//   qn = arena.copy (pn, bytesn);
//   assert (bytes1 + ... + bytesn <= bytes);
//   arena.swap ();
//   ...
//
// One has to be really careful with 'qi' references to arena memory.

class Internal;

class Arena {

  Internal * internal;

  struct { char * start, * top, * end; } from, to;

public:

  Arena (Internal *);
  ~Arena ();

  // Prepare 'to' space to hold that amount of memory.  Precondition is that
  // the 'to' space is empty.  The following sequence of 'copy' operations
  // can use as much memory in sum as pre-allocated here.
  //
  void prepare (size_t bytes);

  // Does the memory pointed to by 'p' belong to this arena? More precisely
  // to the 'from' space, since that is the only one remaining after 'swap'.
  //
  bool contains (void * p) const {
    char * c = (char *) p;
    return from.start <= c && c < from.top;
  }

  // Allocate that amount of memory in 'to' space.  This assumes the 'to'
  // space has been prepared to hold enough memory with 'prepare'.  Then
  // copy the memory pointed to by 'p' of size 'bytes'.  Note that it does
  // not matter whether 'p' is in 'from' or allocated outside of the arena.
  //
  char * copy (const char * p, size_t bytes) {
    char * res = to.top;
    to.top += bytes;
    assert (to.top <= to.end);
    memcpy (res, p, bytes);
    return res;
  }

  // Completely delete 'from' space and then replace 'from' by 'to' (by
  // pointer swapping).  Everything previously allocated (in 'from') and not
  // explicitly copied to 'to' with 'copy' becomes invalid.
  //
  void swap ();
};

};

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <thread>
#include <mutex>

// Suppose we have a class:
struct A {
  // That has a variable,
  int m_count;
  // that is accessed simulateously by two threads.
  // Then we need to protect that variable using a mutex, say this one:
  std::mutex m_count_mutex;
// Because, when we don't use locking, then things go wrong.
};

// For convenience, lets instantiate an object of type A globally,
// even though that is normally evil.
A a;

// Consider this thread that accesses m_count without locking!
void thr_no_lock()
{
  // Loop 100000 times, each time reading m_count
  for (int i = 0; i < 100000; ++i)
  {
    // Read m_count.
    int read = a.m_count;
    // Add 1 and write it back.
    a.m_count = read + 1;
  }
  // If the reading and writing was atomic then
  // this loop will have added precisely 100000.
}

// Also have a thread that does the same but with locking:
void thr_with_lock()
{
  for (int i = 0; i < 100000; ++i)
  {
    std::unique_lock<std::mutex> lk(a.m_count_mutex);
    int read = a.m_count;
    a.m_count = read + 1;
  }
}

int main()
{
  // Do the test without locking first.
  a.m_count = 0;
  {
    std::thread t1(thr_no_lock);
    std::thread t2(thr_with_lock);

    // Wait for t1 and t2 to be finished.
    t1.join();
    t2.join();
  }

  // This result will be LESS THAN 200000!
  std::cout << "Afterwards the value of m_count, without locking, is: " << a.m_count << std::endl;

  // And again, but now both threads use locking.
  a.m_count = 0;
  {
    std::thread t1(thr_with_lock);
    std::thread t2(thr_with_lock);

    t1.join();
    t2.join();
  }

  // This result will be precisely 200000!
  std::cout << "Afterwards the value of m_count, with locking, is: " << a.m_count << std::endl;

  // Can you understand why?
}
<commit_msg>Documentation fix.<commit_after>#include <iostream>
#include <thread>
#include <mutex>

// Suppose we have a class:
struct A {
  // That has a variable,
  int m_count;
  // that is accessed simulateously by two threads.
  // Then we need to protect that variable using a mutex, say this one:
  std::mutex m_count_mutex;
  // Because, when we don't use locking, then things go wrong.
};

// For convenience, lets instantiate an object of type A globally,
// even though that is normally evil.
A a;

// Consider this thread that accesses m_count without locking!
void thr_no_lock()
{
  // Loop 100000 times, each loop incrementing m_count by one.
  for (int i = 0; i < 100000; ++i)
  {
    // Read m_count.
    int read = a.m_count;
    // Add 1 and write it back.
    a.m_count = read + 1;
  }
  // If the reading and writing was atomic then
  // this loop will have added precisely 100000.
}

// Also have a thread that does the same but with locking:
void thr_with_lock()
{
  for (int i = 0; i < 100000; ++i)
  {
    std::unique_lock<std::mutex> lk(a.m_count_mutex);
    int read = a.m_count;
    a.m_count = read + 1;
  }
}

int main()
{
  // Do the test without locking first.
  a.m_count = 0;
  {
    std::thread t1(thr_no_lock);
    std::thread t2(thr_with_lock);

    // Wait for t1 and t2 to be finished.
    t1.join();
    t2.join();
  }

  // This result will be LESS THAN 200000!
  std::cout << "Afterwards the value of m_count, without locking, is: " << a.m_count << std::endl;

  // And again, but now both threads use locking.
  a.m_count = 0;
  {
    std::thread t1(thr_with_lock);
    std::thread t2(thr_with_lock);

    t1.join();
    t2.join();
  }

  // This result will be precisely 200000!
  std::cout << "Afterwards the value of m_count, with locking, is: " << a.m_count << std::endl;

  // Can you understand why?
}
<|endoftext|>


<commit_before>//
//  kern_start.hpp
//  AppleALC
//
//  Copyright © 2016 vit9696. All rights reserved.
//

#ifndef kern_start_hpp
#define kern_start_hpp

#include <Headers/kern_util.hpp>

#include <Library/LegacyIOService.h>
#include <sys/types.h>

struct PluginConfiguration {
	const char *product;		// Product name (e.g. xStringify(PRODUCT_NAME))
	size_t version;				// Product version (e.g. parseModuleVersion(xStringify(MODULE_VERSION)))
	const char **disableArg;	// Pointer to disabling boot arguments array
	size_t disableArgNum;		// Number of disabling boot arguments
	const char **debugArg;		// Pointer to debug boot arguments array
	size_t debugArgNum;			// Number of debug boot arguments
	const char **betaArg;		// Pointer to beta boot arguments array
	size_t betaArgNum;			// Number of beta boot arguments
	KernelVersion minKernel;	// Minimal required kernel version
	KernelVersion maxKernel;	// Maximum supported kernel version
	void (*pluginStart)();		// Main function
};

extern PluginConfiguration ADDPR(config);

class EXPORT PRODUCT_NAME : public IOService {
	OSDeclareDefaultStructors(PRODUCT_NAME)
public:
	bool init(OSDictionary *dict) override;
	bool start(IOService *provider) override;
	void stop(IOService *provider) override;
};

#endif /* kern_start_hpp */
<commit_msg>Synced the remaining headers with the previous commit<commit_after>//
//  kern_start.hpp
//  AppleALC
//
//  Copyright © 2016 vit9696. All rights reserved.
//

#ifndef kern_start_hpp
#define kern_start_hpp

#include <Headers/kern_util.hpp>

#include <Library/LegacyIOService.h>
#include <sys/types.h>

struct PluginConfiguration {
	const char *product;		// Product name (e.g. xStringify(PRODUCT_NAME))
	size_t version;				// Product version (e.g. parseModuleVersion(xStringify(MODULE_VERSION)))
	const char **disableArg;	// Pointer to disabling boot arguments array
	size_t disableArgNum;		// Number of disabling boot arguments
	const char **debugArg;		// Pointer to debug boot arguments array
	size_t debugArgNum;			// Number of debug boot arguments
	const char **betaArg;		// Pointer to beta boot arguments array
	size_t betaArgNum;			// Number of beta boot arguments
	KernelVersion minKernel;	// Minimal required kernel version
	KernelVersion maxKernel;	// Maximum supported kernel version
	void (*pluginStart)();		// Main function
};

#ifndef LILU_CUSTOM_KMOD_INIT

extern PluginConfiguration ADDPR(config);

#endif /* LILU_CUSTOM_KMOD_INIT */

#ifndef LILU_CUSTOM_IOKIT_INIT

class EXPORT PRODUCT_NAME : public IOService {
	OSDeclareDefaultStructors(PRODUCT_NAME)
public:
	bool init(OSDictionary *dict) override;
	bool start(IOService *provider) override;
	void stop(IOService *provider) override;
};

#endif /* LILU_CUSTOM_IOKIT_INIT */

#endif /* kern_start_hpp */
<|endoftext|>


<commit_before>// Copyright (c) 2014 Arista Networks, Inc.  All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.

// To facilitate the making of customized sysdb-mount-profiles (in place of the
// brute-force one "EosSdk", see /usr/lib/SysdbMountProfiles/EosSdkAll), an app can
// be started with the env var EOS_PRINT_PROFILES_AND_EXIT pointing to a filename
// where the profile should be written, then exit.
// We are not printing directly (prevents dups, agent name is only known late, some
// debug prints might interfere) so we first insert the profiles into a map.
// The collections of utilities we need for that purposes are defined here, under a
// static class in order not to overly pollute the eos space. They are declared in
// eos/inline/sdk.h.
//
// This code is included as a header file into both sdk.cpp and stubs/sdk.cpp

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

// Initialize static class variables
FILE* print_profiles::print_profiles_fp = 0; // if and where to print
const char* print_profiles::eossdk_progname = 0;
std::map<std::string, bool> print_profiles::profiles_to_print;

// Called in sdk ctor to figure out if recording of managers is needed, if so
// open the target file (its file-pointer will be used later to determine if we
// need to record). The sdk ctor has some complex logic to figure out the agent-name;
// we need that agent-name later when we print the profiles, so it is passed in here.
// (the agent-name is the basename of the executable, unless the AGENT_PROCESS_NAME
// env var is set, in which case it may actually be wrong -- we need basename(exe)).
void print_profiles::set_print_profiles(const char* name) {
   if (getenv("EOS_PRINT_PROFILES_AND_EXIT")) {
      print_profiles_fp = fopen(getenv("EOS_PRINT_PROFILES_AND_EXIT"), "w");
      if (!print_profiles_fp) {
         const char* text =
                    "Error: EOS_PRINT_PROFILES_AND_EXIT must be a writtable file\n";
         fprintf(stderr, text);
         exit(1); // r+2 because of warnings: discarded fprintf rcode + unused var
      }
      eossdk_progname = name;
   } else {
      print_profiles_fp = 0;
   }
}

// called from xxx_mgr_get() to record that this manager is used
void print_profiles::add_profile(const char * profile) {
   if (print_profiles_fp) {
      profiles_to_print[profile] = true;
   }
}

// called from main_loop() or get_event_loop(): at that point all managers must
// have been instantiated, so print the collected profiles and exit.
void print_profiles::write_profiles() {
   if (print_profiles_fp) {
      if (eossdk_progname) {
         fprintf(print_profiles_fp, "agentName:%s\n", eossdk_progname);
      } else {
         // extern const char *__progname; would be to GNU specific...
         char myExe[1000];
         if (readlink("/proc/self/exe", myExe, 1000) != -1) {
            fprintf(print_profiles_fp, "agentName:%s\n", basename(myExe));
         } else {
            const char* text =
                 "Warning: couldn't figure out agent name, edit 'TBD' in profile\n";
            fprintf(stderr, text);
            fprintf(print_profiles_fp, "agentName:!!!TBD!!!\n");
         }
      }
      for (std::map<std::string, bool>::iterator it = profiles_to_print.begin();
           it != profiles_to_print.end(); it++) {
         fprintf(print_profiles_fp, "Include: EosSdk_%s.include\n",
                                     it->first.c_str());
      }
      fclose(print_profiles_fp);
      exit(0);
   }
}

<commit_msg>@5879108 fix format not a string literal and no format arguments error thrown by some compilers<commit_after>// Copyright (c) 2014 Arista Networks, Inc.  All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.

// To facilitate the making of customized sysdb-mount-profiles (in place of the
// brute-force one "EosSdk", see /usr/lib/SysdbMountProfiles/EosSdkAll), an app can
// be started with the env var EOS_PRINT_PROFILES_AND_EXIT pointing to a filename
// where the profile should be written, then exit.
// We are not printing directly (prevents dups, agent name is only known late, some
// debug prints might interfere) so we first insert the profiles into a map.
// The collections of utilities we need for that purposes are defined here, under a
// static class in order not to overly pollute the eos space. They are declared in
// eos/inline/sdk.h.
//
// This code is included as a header file into both sdk.cpp and stubs/sdk.cpp

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

// Initialize static class variables
FILE* print_profiles::print_profiles_fp = 0; // if and where to print
const char* print_profiles::eossdk_progname = 0;
std::map<std::string, bool> print_profiles::profiles_to_print;

// Called in sdk ctor to figure out if recording of managers is needed, if so
// open the target file (its file-pointer will be used later to determine if we
// need to record). The sdk ctor has some complex logic to figure out the agent-name;
// we need that agent-name later when we print the profiles, so it is passed in here.
// (the agent-name is the basename of the executable, unless the AGENT_PROCESS_NAME
// env var is set, in which case it may actually be wrong -- we need basename(exe)).
void print_profiles::set_print_profiles(const char* name) {
   if (getenv("EOS_PRINT_PROFILES_AND_EXIT")) {
      print_profiles_fp = fopen(getenv("EOS_PRINT_PROFILES_AND_EXIT"), "w");
      if (!print_profiles_fp) {
         const char* text =
                    "Error: EOS_PRINT_PROFILES_AND_EXIT must be a writtable file\n";
         fprintf(stderr, "%s", text);
         exit(1); // r+2 because of warnings: discarded fprintf rcode + unused var
      }
      eossdk_progname = name;
   } else {
      print_profiles_fp = 0;
   }
}

// called from xxx_mgr_get() to record that this manager is used
void print_profiles::add_profile(const char * profile) {
   if (print_profiles_fp) {
      profiles_to_print[profile] = true;
   }
}

// called from main_loop() or get_event_loop(): at that point all managers must
// have been instantiated, so print the collected profiles and exit.
void print_profiles::write_profiles() {
   if (print_profiles_fp) {
      if (eossdk_progname) {
         fprintf(print_profiles_fp, "agentName:%s\n", eossdk_progname);
      } else {
         // extern const char *__progname; would be to GNU specific...
         char myExe[1000];
         if (readlink("/proc/self/exe", myExe, 1000) != -1) {
            fprintf(print_profiles_fp, "agentName:%s\n", basename(myExe));
         } else {
            const char* text =
                 "Warning: couldn't figure out agent name, edit 'TBD' in profile\n";
            fprintf(stderr, "%s", text);
            fprintf(print_profiles_fp, "agentName:!!!TBD!!!\n");
         }
      }
      for (std::map<std::string, bool>::iterator it = profiles_to_print.begin();
           it != profiles_to_print.end(); it++) {
         fprintf(print_profiles_fp, "Include: EosSdk_%s.include\n",
                                     it->first.c_str());
      }
      fclose(print_profiles_fp);
      exit(0);
   }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ComboBox.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 12:46:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FORMS_COMBOBOX_HXX_
#define _FORMS_COMBOBOX_HXX_

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLERRORBROADCASTER_HPP_
#include <com/sun/star/sdb/XSQLErrorBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_LISTSOURCETYPE_HPP_
#include <com/sun/star/form/ListSourceType.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef FORMS_ERRORBROADCASTER_HXX
#include "errorbroadcaster.hxx"
#endif
#ifndef FORMS_ENTRYLISTHELPER_HXX
#include "entrylisthelper.hxx"
#endif

//.........................................................................
namespace frm
{

//==================================================================
// OComboBoxModel
//==================================================================
class OComboBoxModel
            :public OBoundControlModel
            ,public OEntryListHelper
            ,public OErrorBroadcaster
            ,public ::comphelper::OAggregationArrayUsageHelper< OComboBoxModel >
{
    ::com::sun::star::uno::Any              m_aBoundColumn;         // obsolet
    ::rtl::OUString                         m_aListSource;          //
    ::rtl::OUString                         m_aDefaultText;         // DefaultText
    ::rtl::OUString                         m_aSaveValue;

    StringSequence                          m_aDesignModeStringItems;
        // upon loading, in some cases we reset fill our string item list ourself. We don't want
        // to lose the user's items then, so we remember them here.

    ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter;

    ::com::sun::star::form::ListSourceType  m_eListSourceType;      // type der list source
    ::com::sun::star::util::Date            m_aNullDate;
    sal_Int32                               m_nFormatKey;
    sal_Int16                               m_nFieldType;
    sal_Int16                               m_nKeyType;
    sal_Bool                                m_bEmptyIsNull;         // LeerString wird als NULL interpretiert

protected:
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>   _getTypes();

public:
    DECLARE_DEFAULT_LEAF_XTOR( OComboBoxModel );

    virtual void SAL_CALL disposing();

    // OPropertySetHelper
    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                throw (::com::sun::star::uno::Exception);
    virtual sal_Bool SAL_CALL convertFastPropertyValue(
                ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
                throw (::com::sun::star::lang::IllegalArgumentException);

    // XLoadListener
    virtual void SAL_CALL reloaded( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    IMPLEMENTATION_NAME(OComboBoxModel);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // UNO
    DECLARE_UNO3_AGG_DEFAULTS(OComboBoxModel, OBoundControlModel);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // XPersistObject
    virtual ::rtl::OUString SAL_CALL    getServiceName() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

    // OAggregationArrayUsageHelper
    virtual void fillProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
        ) const;
    IMPLEMENT_INFO_SERVICE()

    // XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);

    // prevent method hiding
    using OBoundControlModel::getFastPropertyValue;

protected:
    // OBoundControlModel overridables
    virtual ::com::sun::star::uno::Any
                            translateDbColumnToControlValue( );
    virtual sal_Bool        commitControlValueToDbColumn( bool _bPostReset );

    virtual void            onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
    virtual void            onDisconnectedDbColumn();

    virtual ::com::sun::star::uno::Any
                            getDefaultForReset() const;

    virtual sal_Bool        approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );

    // OEntryListHelper overriables
    virtual void    stringItemListChanged( );
    virtual void    connectedExternalListSource( );
    virtual void    disconnectedExternalListSource( );

protected:
    void loadData();

    DECLARE_XCLONEABLE();
};

//==================================================================
// OComboBoxControl
//==================================================================

class OComboBoxControl : public OBoundControl
{
public:
    OComboBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);

    // XServiceInfo
    IMPLEMENTATION_NAME(OComboBoxControl);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
};

//.........................................................................
}
//.........................................................................

#endif // _FORMS_COMBOBOX_HXX_

<commit_msg>INTEGRATION: CWS hb02 (1.10.80); FILE MERGED 2007/02/01 12:09:36 fs 1.10.80.2: #i74051# split describeFixedProperties in describeFixedProperties and describeAggregateProperties 2007/01/31 10:55:24 fs 1.10.80.1: changed handling of properties in the course of #i74051#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ComboBox.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-09 13:22:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FORMS_COMBOBOX_HXX_
#define _FORMS_COMBOBOX_HXX_

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLERRORBROADCASTER_HPP_
#include <com/sun/star/sdb/XSQLErrorBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_LISTSOURCETYPE_HPP_
#include <com/sun/star/form/ListSourceType.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef FORMS_ERRORBROADCASTER_HXX
#include "errorbroadcaster.hxx"
#endif
#ifndef FORMS_ENTRYLISTHELPER_HXX
#include "entrylisthelper.hxx"
#endif

//.........................................................................
namespace frm
{

//==================================================================
// OComboBoxModel
//==================================================================
class OComboBoxModel
            :public OBoundControlModel
            ,public OEntryListHelper
            ,public OErrorBroadcaster
{
    ::com::sun::star::uno::Any              m_aBoundColumn;         // obsolet
    ::rtl::OUString                         m_aListSource;          //
    ::rtl::OUString                         m_aDefaultText;         // DefaultText
    ::rtl::OUString                         m_aSaveValue;

    StringSequence                          m_aDesignModeStringItems;
        // upon loading, in some cases we reset fill our string item list ourself. We don't want
        // to lose the user's items then, so we remember them here.

    ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter;

    ::com::sun::star::form::ListSourceType  m_eListSourceType;      // type der list source
    ::com::sun::star::util::Date            m_aNullDate;
    sal_Int32                               m_nFormatKey;
    sal_Int16                               m_nFieldType;
    sal_Int16                               m_nKeyType;
    sal_Bool                                m_bEmptyIsNull;         // LeerString wird als NULL interpretiert

protected:
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>   _getTypes();

public:
    DECLARE_DEFAULT_LEAF_XTOR( OComboBoxModel );

    virtual void SAL_CALL disposing();

    // OPropertySetHelper
    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                throw (::com::sun::star::uno::Exception);
    virtual sal_Bool SAL_CALL convertFastPropertyValue(
                ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
                throw (::com::sun::star::lang::IllegalArgumentException);

    // XLoadListener
    virtual void SAL_CALL reloaded( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    IMPLEMENTATION_NAME(OComboBoxModel);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // UNO
    DECLARE_UNO3_AGG_DEFAULTS(OComboBoxModel, OBoundControlModel);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

    // XPersistObject
    virtual ::rtl::OUString SAL_CALL    getServiceName() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

    // OControlModel's property handling
    virtual void describeFixedProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
    ) const;
    virtual void describeAggregateProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
    ) const;

    // XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);

    // prevent method hiding
    using OBoundControlModel::getFastPropertyValue;

protected:
    // OBoundControlModel overridables
    virtual ::com::sun::star::uno::Any
                            translateDbColumnToControlValue( );
    virtual sal_Bool        commitControlValueToDbColumn( bool _bPostReset );

    virtual void            onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
    virtual void            onDisconnectedDbColumn();

    virtual ::com::sun::star::uno::Any
                            getDefaultForReset() const;

    virtual sal_Bool        approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );

    // OEntryListHelper overriables
    virtual void    stringItemListChanged( );
    virtual void    connectedExternalListSource( );
    virtual void    disconnectedExternalListSource( );

protected:
    void loadData();

    DECLARE_XCLONEABLE();
};

//==================================================================
// OComboBoxControl
//==================================================================

class OComboBoxControl : public OBoundControl
{
public:
    OComboBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);

    // XServiceInfo
    IMPLEMENTATION_NAME(OComboBoxControl);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
};

//.........................................................................
}
//.........................................................................

#endif // _FORMS_COMBOBOX_HXX_

<|endoftext|>