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

// include files of own module
#include <helper/statusindicator.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>

namespace framework{

StatusIndicator::StatusIndicator(StatusIndicatorFactory* pFactory)
    : ThreadHelpBase     (        )
    , m_xFactory         (pFactory)
{
}

StatusIndicator::~StatusIndicator()
{
}

void SAL_CALL StatusIndicator::start(const OUString& sText ,
                                           sal_Int32        nRange)
    throw(css::uno::RuntimeException, std::exception)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->start(this, sText, nRange);
    }
}

void SAL_CALL StatusIndicator::end()
    throw(css::uno::RuntimeException, std::exception)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->end(this);
    }
}

void SAL_CALL StatusIndicator::reset()
    throw(css::uno::RuntimeException, std::exception)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->reset(this);
    }
}

void SAL_CALL StatusIndicator::setText(const OUString& sText)
    throw(css::uno::RuntimeException, std::exception)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->setText(this, sText);
    }
}

void SAL_CALL StatusIndicator::setValue(sal_Int32 nValue)
    throw(css::uno::RuntimeException, std::exception)
{
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->setValue(this, nValue);
    }
}

} // namespace framework

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

#include <config_features.h>

#include <helper/statusindicator.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>

namespace framework{

StatusIndicator::StatusIndicator(StatusIndicatorFactory* pFactory)
    : ThreadHelpBase     (        )
    , m_xFactory         (pFactory)
{
}

StatusIndicator::~StatusIndicator()
{
}

void SAL_CALL StatusIndicator::start(const OUString& sText ,
                                           sal_Int32        nRange)
    throw(css::uno::RuntimeException, std::exception)
{
#if !HAVE_FEATURE_DESKTOP
    (void) sText;
    (void) nRange;
#else
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->start(this, sText, nRange);
    }
#endif
}

void SAL_CALL StatusIndicator::end()
    throw(css::uno::RuntimeException, std::exception)
{
#if HAVE_FEATURE_DESKTOP
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->end(this);
    }
#endif
}

void SAL_CALL StatusIndicator::reset()
    throw(css::uno::RuntimeException, std::exception)
{
#if HAVE_FEATURE_DESKTOP
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->reset(this);
    }
#endif
}

void SAL_CALL StatusIndicator::setText(const OUString& sText)
    throw(css::uno::RuntimeException, std::exception)
{
#if !HAVE_FEATURE_DESKTOP
    (void) sText;
#else
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->setText(this, sText);
    }
#endif
}

void SAL_CALL StatusIndicator::setValue(sal_Int32 nValue)
    throw(css::uno::RuntimeException, std::exception)
{
#if !HAVE_FEATURE_DESKTOP
    (void) nValue;
#else
    // SAFE ->
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::task::XStatusIndicatorFactory > xFactory(m_xFactory.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE
    if (xFactory.is())
    {
        StatusIndicatorFactory* pFactory = (StatusIndicatorFactory*)xFactory.get();
        pFactory->setValue(this, nValue);
    }
#endif
}

} // namespace framework

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


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

#include "src/core/lib/debug/stats.h"

#include <mutex>
#include <thread>

#include <grpc/grpc.h>
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
#include <gtest/gtest.h>

namespace grpc {
namespace testing {

class Snapshot {
 public:
  Snapshot() { grpc_stats_collect(&begin_); }

  grpc_stats_data delta() {
    grpc_stats_data now;
    grpc_stats_collect(&now);
    grpc_stats_data delta;
    grpc_stats_diff(&now, &begin_, &delta);
    return delta;
  }

 private:
  grpc_stats_data begin_;
};

TEST(StatsTest, IncCounters) {
  for (int i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
    Snapshot snapshot;

    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    GRPC_STATS_INC_COUNTER(&exec_ctx, (grpc_stats_counters)i);
    grpc_exec_ctx_finish(&exec_ctx);

    EXPECT_EQ(snapshot.delta().counters[i], 1);
  }
}

TEST(StatsTest, IncSpecificCounter) {
  Snapshot snapshot;

  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  GRPC_STATS_INC_SYSCALL_POLL(&exec_ctx);
  grpc_exec_ctx_finish(&exec_ctx);

  EXPECT_EQ(snapshot.delta().counters[GRPC_STATS_COUNTER_SYSCALL_POLL], 1);
}

static int FindExpectedBucket(int i, int j) {
  if (j < 0) {
    return 0;
  }
  if (j >= grpc_stats_histo_bucket_boundaries[i][grpc_stats_histo_buckets[i]]) {
    return grpc_stats_histo_buckets[i] - 1;
  }
  return std::upper_bound(grpc_stats_histo_bucket_boundaries[i],
                          grpc_stats_histo_bucket_boundaries[i] +
                              grpc_stats_histo_buckets[i],
                          j) -
         grpc_stats_histo_bucket_boundaries[i] - 1;
}

class HistogramTest : public ::testing::TestWithParam<int> {};

TEST_P(HistogramTest, IncHistogram) {
  const int kHistogram = GetParam();
  std::vector<std::thread> threads;
  int cur_bucket = 0;
  auto run = [kHistogram](const std::vector<int>& test_values,
                          int expected_bucket) {
    gpr_log(GPR_DEBUG, "expected_bucket:%d nvalues=%" PRIdPTR, expected_bucket,
            test_values.size());
    for (auto j : test_values) {
      Snapshot snapshot;

      grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
      grpc_stats_inc_histogram[kHistogram](&exec_ctx, j);
      grpc_exec_ctx_finish(&exec_ctx);

      auto delta = snapshot.delta();

      EXPECT_EQ(
          delta
              .histograms[grpc_stats_histo_start[kHistogram] + expected_bucket],
          1)
          << "\nhistogram:" << kHistogram
          << "\nexpected_bucket:" << expected_bucket << "\nj:" << j;
    }
  };
  std::vector<int> test_values;
  for (int j = -1000;
       j < grpc_stats_histo_bucket_boundaries
                   [kHistogram][grpc_stats_histo_buckets[kHistogram] - 1] +
               1000;
       j++) {
    int expected_bucket = FindExpectedBucket(kHistogram, j);
    if (cur_bucket != expected_bucket) {
      threads.emplace_back(
          [test_values, run, cur_bucket]() { run(test_values, cur_bucket); });
      cur_bucket = expected_bucket;
      test_values.clear();
    }
    test_values.push_back(j);
  }
  run(test_values, cur_bucket);
  for (auto& t : threads) {
    t.join();
  }
}

INSTANTIATE_TEST_CASE_P(HistogramTestCases, HistogramTest,
                        ::testing::Range<int>(0, GRPC_STATS_HISTOGRAM_COUNT));

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  grpc_init();
  int ret = RUN_ALL_TESTS();
  grpc_shutdown();
  return ret;
}
<commit_msg>make stats_test skip values far from boundaries<commit_after>/*
 *
 * Copyright 2017 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/core/lib/debug/stats.h"

#include <mutex>
#include <thread>

#include <grpc/grpc.h>
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
#include <gtest/gtest.h>

namespace grpc {
namespace testing {

class Snapshot {
 public:
  Snapshot() { grpc_stats_collect(&begin_); }

  grpc_stats_data delta() {
    grpc_stats_data now;
    grpc_stats_collect(&now);
    grpc_stats_data delta;
    grpc_stats_diff(&now, &begin_, &delta);
    return delta;
  }

 private:
  grpc_stats_data begin_;
};

TEST(StatsTest, IncCounters) {
  for (int i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
    Snapshot snapshot;

    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    GRPC_STATS_INC_COUNTER(&exec_ctx, (grpc_stats_counters)i);
    grpc_exec_ctx_finish(&exec_ctx);

    EXPECT_EQ(snapshot.delta().counters[i], 1);
  }
}

TEST(StatsTest, IncSpecificCounter) {
  Snapshot snapshot;

  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  GRPC_STATS_INC_SYSCALL_POLL(&exec_ctx);
  grpc_exec_ctx_finish(&exec_ctx);

  EXPECT_EQ(snapshot.delta().counters[GRPC_STATS_COUNTER_SYSCALL_POLL], 1);
}

static int FindExpectedBucket(int i, int j) {
  if (j < 0) {
    return 0;
  }
  if (j >= grpc_stats_histo_bucket_boundaries[i][grpc_stats_histo_buckets[i]]) {
    return grpc_stats_histo_buckets[i] - 1;
  }
  return std::upper_bound(grpc_stats_histo_bucket_boundaries[i],
                          grpc_stats_histo_bucket_boundaries[i] +
                              grpc_stats_histo_buckets[i],
                          j) -
         grpc_stats_histo_bucket_boundaries[i] - 1;
}

class HistogramTest : public ::testing::TestWithParam<int> {};

TEST_P(HistogramTest, IncHistogram) {
  const int kHistogram = GetParam();
  std::vector<std::thread> threads;
  int cur_bucket = 0;
  auto run = [kHistogram](const std::vector<int>& test_values,
                          int expected_bucket) {
    gpr_log(GPR_DEBUG, "expected_bucket:%d nvalues=%" PRIdPTR, expected_bucket,
            test_values.size());
    for (auto j : test_values) {
      Snapshot snapshot;

      grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
      grpc_stats_inc_histogram[kHistogram](&exec_ctx, j);
      grpc_exec_ctx_finish(&exec_ctx);

      auto delta = snapshot.delta();

      EXPECT_EQ(
          delta
              .histograms[grpc_stats_histo_start[kHistogram] + expected_bucket],
          1)
          << "\nhistogram:" << kHistogram
          << "\nexpected_bucket:" << expected_bucket << "\nj:" << j;
    }
  };
  std::vector<int> test_values;
  // largest bucket boundary for current histogram type.
  int max_bucket_boundary =
      grpc_stats_histo_bucket_boundaries[kHistogram]
                                        [grpc_stats_histo_buckets[kHistogram] -
                                         1];
  for (int j = -1000; j < max_bucket_boundary + 1000;) {
    int expected_bucket = FindExpectedBucket(kHistogram, j);
    if (cur_bucket != expected_bucket) {
      threads.emplace_back(
          [test_values, run, cur_bucket]() { run(test_values, cur_bucket); });
      cur_bucket = expected_bucket;
      test_values.clear();
    }
    test_values.push_back(j);
    if (j < max_bucket_boundary &&
        FindExpectedBucket(kHistogram, j + 1000) == expected_bucket &&
        FindExpectedBucket(kHistogram, j - 1000) == expected_bucket) {
      // if we are far from bucket boundary, skip values to speed-up the tests
      j += 500;
    } else {
      j++;
    }
  }
  run(test_values, cur_bucket);
  for (auto& t : threads) {
    t.join();
  }
}

INSTANTIATE_TEST_CASE_P(HistogramTestCases, HistogramTest,
                        ::testing::Range<int>(0, GRPC_STATS_HISTOGRAM_COUNT));

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  grpc_init();
  int ret = RUN_ALL_TESTS();
  grpc_shutdown();
  return ret;
}
<|endoftext|>


<commit_before>#include "telnetpp/session.hpp"
#include "telnetpp/detail/generator.hpp"
#include "telnetpp/detail/parser.hpp"
#include "telnetpp/detail/registration.hpp"

namespace telnetpp {

// ==========================================================================
// CONSTRUCTOR
// ==========================================================================
session::session(
    std::function<std::vector<token> (std::string const &)> on_text)
  : visitor_(
        on_text,
        command_router_,
        negotiation_router_,
        subnegotiation_router_)
{
    // By default, the session will respond to WILL/WONT(option) with
    // DONT(option), and to DO/DONT(option) with WONT(option).  This behaviour
    // is overridden with any installed options.
    negotiation_router_.set_unregistered_route(
        [](telnetpp::negotiation const &negotiation)
            -> std::vector<telnetpp::token>
        {
            auto const &request = negotiation.request();

            u8 result =
                (request == telnetpp::will || request == telnetpp::wont)
              ? telnetpp::dont
              : telnetpp::wont;

            return {
                telnetpp::element {
                    telnetpp::negotiation(result, negotiation.option())
                }
            };
        });
}

void session::install(
    command const &cmd,
    std::function<std::vector<token> (command const &)> const &on_command)
{
    command_router_.register_route(cmd, on_command);
}

// ==========================================================================
// INSTALL
// ==========================================================================
void session::install(client_option &option)
{
    detail::register_client_option(
        option, negotiation_router_, subnegotiation_router_);
}

// ==========================================================================
// INSTALL
// ==========================================================================
void session::install(server_option &option)
{
    detail::register_server_option(
        option, negotiation_router_, subnegotiation_router_);
}

// ==========================================================================
// RECEIVE
// ==========================================================================
std::vector<token> session::receive(const u8stream& stream)
{
    using std::begin;
    using std::end;

    unparsed_buffer_.insert(
        end(unparsed_buffer_),
        begin(stream),
        end(stream));

    auto it1 = begin(unparsed_buffer_);
    auto it2 = end(unparsed_buffer_);

    auto parse_results = telnetpp::detail::parse(it1, it2);

    unparsed_buffer_.erase(begin(unparsed_buffer_), it1);

    std::vector<token> results;

    for (auto &&parse_result : parse_results)
    {
        auto result = boost::apply_visitor(visitor_, parse_result);

        results.insert(end(results), begin(result), end(result));
    }

    return results;
}

// ==========================================================================
// SEND
// ==========================================================================
std::vector<boost::variant<u8stream, boost::any>> session::send(
    std::vector<token> const &tokens)
{
    using std::begin;
    using std::end;

    return detail::generate(tokens);
}

}
<commit_msg>Removed raw loop in session; replaced with accumulate.<commit_after>#include "telnetpp/session.hpp"
#include "telnetpp/detail/generator.hpp"
#include "telnetpp/detail/parser.hpp"
#include "telnetpp/detail/registration.hpp"

namespace telnetpp {

// ==========================================================================
// CONSTRUCTOR
// ==========================================================================
session::session(
    std::function<std::vector<token> (std::string const &)> on_text)
  : visitor_(
        on_text,
        command_router_,
        negotiation_router_,
        subnegotiation_router_)
{
    // By default, the session will respond to WILL/WONT(option) with
    // DONT(option), and to DO/DONT(option) with WONT(option).  This behaviour
    // is overridden with any installed options.
    negotiation_router_.set_unregistered_route(
        [](telnetpp::negotiation const &negotiation)
            -> std::vector<telnetpp::token>
        {
            auto const &request = negotiation.request();

            u8 result =
                (request == telnetpp::will || request == telnetpp::wont)
              ? telnetpp::dont
              : telnetpp::wont;

            return {
                telnetpp::element {
                    telnetpp::negotiation(result, negotiation.option())
                }
            };
        });
}

void session::install(
    command const &cmd,
    std::function<std::vector<token> (command const &)> const &on_command)
{
    command_router_.register_route(cmd, on_command);
}

// ==========================================================================
// INSTALL
// ==========================================================================
void session::install(client_option &option)
{
    detail::register_client_option(
        option, negotiation_router_, subnegotiation_router_);
}

// ==========================================================================
// INSTALL
// ==========================================================================
void session::install(server_option &option)
{
    detail::register_server_option(
        option, negotiation_router_, subnegotiation_router_);
}

// ==========================================================================
// RECEIVE
// ==========================================================================
std::vector<token> session::receive(const u8stream& stream)
{
    using std::begin;
    using std::end;

    unparsed_buffer_.insert(
        end(unparsed_buffer_),
        begin(stream),
        end(stream));

    auto it1 = begin(unparsed_buffer_);
    auto it2 = end(unparsed_buffer_);

    auto const &parse_results = telnetpp::detail::parse(it1, it2);

    unparsed_buffer_.erase(begin(unparsed_buffer_), it1);

    auto const &results = std::accumulate(
        parse_results.begin(),
        parse_results.end(),
        std::vector<token>{},
        [this](auto &results, auto const &parse_result)
        {
            auto const &result = boost::apply_visitor(visitor_, parse_result);
            results.insert(end(results), begin(result), end(result));
            return results;
        });

    return results;
}

// ==========================================================================
// SEND
// ==========================================================================
std::vector<boost::variant<u8stream, boost::any>> session::send(
    std::vector<token> const &tokens)
{
    return detail::generate(tokens);
}

}
<|endoftext|>


<commit_before>/*
 *    Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files
 *    (cURLpp), to deal in the Software without restriction,
 *    including without limitation the rights to use, copy, modify, merge,
 *    publish, distribute, sublicense, and/or sell copies of the Software,
 *    and to permit persons to whom the Software is furnished to do so,
 *    subject to the following conditions:
 *
 *    The above copyright notice and this permission notice shall be included
 *    in all copies or substantial portions of the Software.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef CURLPP_HPP
#define CURLPP_HPP

#define LIBCURLPP_VERSION "0.7.1"
#define LIBCURLPP_VERSION_NUM 0x000701

#include <string>
#include <curl/curl.h>

#include "dllfct.h"

namespace cURLpp
{
   /**
    * This function takes care of initializing cURLpp ( also libcURL). If you want
    * to cleanup cURL before your application quits just call cURLpp::terminate().
    * This function should only be called once (no matter how many threads or
    * libcurl sessions that'll be used) by every application that uses libcurl,
    * it will throw a logic_error if you call it twice.
    *
    * The flags option is a bit pattern that tells  libcurl  exact what  features
    * to init, as described below. Set the desired bits by ORing the values together.
    *
    *  CURL_GLOBAL_ALL
    *  Initialize  everything  possible.  This  sets all known bits.
    *
    *  CURL_GLOBAL_SSL
    *  Initialize SSL
    *
    *  CURL_GLOBAL_WIN32
    *  Initialize  the  Win32  socket  libraries.
    *
    *  CURL_GLOBAL_NOTHING
    *  Initialise nothing extra. This sets no bit.
    *
    * NOTE: you cannot call this function twice without first terminating it first.
    * it will throw a logic_error if you do this.
    */
  void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL);

  /**
   * This function takes care of cleaning up cURLpp ( also libcURL). See
   * cURLpp::initialize( long flags ) for momre documentation.
   *
   * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a
   * logic_error if you do this.
   */
  void CURLPPAPI terminate();

  /**
   * This class takes care of initialization and cleaning up cURLpp ( also libcURL )
   * (it will call cURLpp:terminate() in his destructor). If you want to be sure that
   * cURLpp is cleanup after you reached the end of scope of a specific function using
   * cURLpp, instatiate this class. This function call cURLpp::initialize() in his
   * constructor, so you don't have to call it by yourself, when you have decided to
   * use it.
   *
   * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation.
   */
  class CURLPPAPI Cleanup
  {
  public:
    Cleanup();
    ~Cleanup();
  };

  /**
   * This  function  will  convert  the given input string to an URL encoded
   * string and return that as a new allocated string. All input  characters
   * that  are  not a-z, A-Z or 0-9 will be converted to their "URL escaped"
   * version (%NN where NN is a two-digit hexadecimal number).
   */
  std::string CURLPPAPI escape( const std::string& url );

  /**
   * This  function  will  convert  the  given  URL encoded input string to a
   * "plain string" and return that as a new allocated string. All input
   * characters that are URL encoded (%XX) where XX is a two-digit
   * hexadecimal number, or +) will be converted to their plain text versions
   * (up to a ? letter, no + letters to the right of a ? letter will be
   * converted).
   */
  std::string CURLPPAPI unescape( const std::string &url );

  /**
   * this is  a portable wrapper for the getenv() function, meant to emulate
   * its behaviour and provide an identical interface for all operating
   * systems libcurl builds on (including win32). Under unix operating
   * systems, there isn't any point in returning an allocated memory,
   * although other systems won't work  properly if this isn't done. The unix
   * implementation thus have to suffer slightly from the drawbacks of other
   * systems.
   */
  std::string CURLPPAPI getenv( const std::string &name );

  /**
   * Returns  a  human readable string with the version number of libcurl and
   * some of its important components  (like  OpenSSL version).
   *
   * Note:  this  returns  the  actual running lib's version, you might have
   * installed a newer lib's include files in your system  which may turn
   * your LIBCURL_VERSION #define value to differ from this result.
   */
  std::string CURLPPAPI libcurlVersion();

  /**
   * This function returns the number of  seconds  since  January 1st  1970,
   * for the date and time that the datestring parameter specifies. The now
   * parameter is there  and  should  hold the current time to allow the
   * datestring to specify relative dates/times. Read further in the date
   * string parser  section below.
   *
   * PARSING DATES AND TIMES
   * A  "date" is a string, possibly empty, containing many items separated
   * by whitespace.  The whitespace may be omitted when no  ambiguity
   * arises.  The empty string means the beginning of today (i.e., midnight).
   * Order of the  items  is  immaterial.  A date string may contain many
   * flavors of items:
   *
   * calendar date items
   * This can be specified in a number of different ways. Including
   * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72,
   * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72.  The year can also  be
   * omitted, for example: 9/17 or "sep 17".
   *
   * time of the day items
   * This  string specifies the time on a given day. Syntax  supported
   * includes:  18:19:0,  18:19,  6:19pm, 18:19-0500 (for specifying the time
   * zone as well).
   *
   * time zone items
   * Specifies  international  time zone. There are a few acronyms
   * supported,  but  in  general  you   should instead  use  the specific
   * realtive time compared to UTC. Supported formats include: -1200, MST,
   * +0100.
   *
   * day of the week items
   * Specifies a day of the week. If  this  is  mentioned alone it means that
   * day of the week in the future. Days  of  the week may be spelled out in
   * full: `Sunday', `Monday', etc or they may  be  abbreviated  to their
   * first three letters, optionally followed by a period.  The special
   * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur'
   * or `Thurs' for `Thursday' are also allowed. A number may precede a day
   * of the week item to  move forward  supplementary  weeks.   It  is best
   * used in expression like `third monday'.   In  this  context, `last  DAY'
   * or  `next DAY' is also acceptable; they move one week before or after
   * the day  that  DAY  by itself would represent.
   *
   * relative items
   * A  relative item adjusts a date (or the current date if  none)  forward
   * or  backward.   Example   syntax includes:  "1  year",  "1  year  ago",
   * "2 days", "4 weeks". The string `tomorrow' is worth one day in the
   * future (equivalent  to  `day'),  the  string `yesterday' is worth one
   * day in the past (equivalent to `day ago').
   *
   * pure numbers
   * If the decimal number is of the form YYYYMMDD and no other calendar date
   * item appears before  it  in  the date  string,  then  YYYY is read as
   * the year, MM as the month number and DD as the day of the month, for the
   * specified calendar date.
   */
  time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 );

}

#endif
<commit_msg>0.7.2-devel<commit_after>/*
 *    Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files
 *    (cURLpp), to deal in the Software without restriction,
 *    including without limitation the rights to use, copy, modify, merge,
 *    publish, distribute, sublicense, and/or sell copies of the Software,
 *    and to permit persons to whom the Software is furnished to do so,
 *    subject to the following conditions:
 *
 *    The above copyright notice and this permission notice shall be included
 *    in all copies or substantial portions of the Software.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef CURLPP_HPP
#define CURLPP_HPP

#define LIBCURLPP_VERSION "0.7.2-devel"
#define LIBCURLPP_VERSION_NUM 0x000702

#include <string>
#include <curl/curl.h>

#include "dllfct.h"

namespace cURLpp
{
   /**
    * This function takes care of initializing cURLpp ( also libcURL). If you want
    * to cleanup cURL before your application quits just call cURLpp::terminate().
    * This function should only be called once (no matter how many threads or
    * libcurl sessions that'll be used) by every application that uses libcurl,
    * it will throw a logic_error if you call it twice.
    *
    * The flags option is a bit pattern that tells  libcurl  exact what  features
    * to init, as described below. Set the desired bits by ORing the values together.
    *
    *  CURL_GLOBAL_ALL
    *  Initialize  everything  possible.  This  sets all known bits.
    *
    *  CURL_GLOBAL_SSL
    *  Initialize SSL
    *
    *  CURL_GLOBAL_WIN32
    *  Initialize  the  Win32  socket  libraries.
    *
    *  CURL_GLOBAL_NOTHING
    *  Initialise nothing extra. This sets no bit.
    *
    * NOTE: you cannot call this function twice without first terminating it first.
    * it will throw a logic_error if you do this.
    */
  void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL);

  /**
   * This function takes care of cleaning up cURLpp ( also libcURL). See
   * cURLpp::initialize( long flags ) for momre documentation.
   *
   * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a
   * logic_error if you do this.
   */
  void CURLPPAPI terminate();

  /**
   * This class takes care of initialization and cleaning up cURLpp ( also libcURL )
   * (it will call cURLpp:terminate() in his destructor). If you want to be sure that
   * cURLpp is cleanup after you reached the end of scope of a specific function using
   * cURLpp, instatiate this class. This function call cURLpp::initialize() in his
   * constructor, so you don't have to call it by yourself, when you have decided to
   * use it.
   *
   * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation.
   */
  class CURLPPAPI Cleanup
  {
  public:
    Cleanup();
    ~Cleanup();
  };

  /**
   * This  function  will  convert  the given input string to an URL encoded
   * string and return that as a new allocated string. All input  characters
   * that  are  not a-z, A-Z or 0-9 will be converted to their "URL escaped"
   * version (%NN where NN is a two-digit hexadecimal number).
   */
  std::string CURLPPAPI escape( const std::string& url );

  /**
   * This  function  will  convert  the  given  URL encoded input string to a
   * "plain string" and return that as a new allocated string. All input
   * characters that are URL encoded (%XX) where XX is a two-digit
   * hexadecimal number, or +) will be converted to their plain text versions
   * (up to a ? letter, no + letters to the right of a ? letter will be
   * converted).
   */
  std::string CURLPPAPI unescape( const std::string &url );

  /**
   * this is  a portable wrapper for the getenv() function, meant to emulate
   * its behaviour and provide an identical interface for all operating
   * systems libcurl builds on (including win32). Under unix operating
   * systems, there isn't any point in returning an allocated memory,
   * although other systems won't work  properly if this isn't done. The unix
   * implementation thus have to suffer slightly from the drawbacks of other
   * systems.
   */
  std::string CURLPPAPI getenv( const std::string &name );

  /**
   * Returns  a  human readable string with the version number of libcurl and
   * some of its important components  (like  OpenSSL version).
   *
   * Note:  this  returns  the  actual running lib's version, you might have
   * installed a newer lib's include files in your system  which may turn
   * your LIBCURL_VERSION #define value to differ from this result.
   */
  std::string CURLPPAPI libcurlVersion();

  /**
   * This function returns the number of  seconds  since  January 1st  1970,
   * for the date and time that the datestring parameter specifies. The now
   * parameter is there  and  should  hold the current time to allow the
   * datestring to specify relative dates/times. Read further in the date
   * string parser  section below.
   *
   * PARSING DATES AND TIMES
   * A  "date" is a string, possibly empty, containing many items separated
   * by whitespace.  The whitespace may be omitted when no  ambiguity
   * arises.  The empty string means the beginning of today (i.e., midnight).
   * Order of the  items  is  immaterial.  A date string may contain many
   * flavors of items:
   *
   * calendar date items
   * This can be specified in a number of different ways. Including
   * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72,
   * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72.  The year can also  be
   * omitted, for example: 9/17 or "sep 17".
   *
   * time of the day items
   * This  string specifies the time on a given day. Syntax  supported
   * includes:  18:19:0,  18:19,  6:19pm, 18:19-0500 (for specifying the time
   * zone as well).
   *
   * time zone items
   * Specifies  international  time zone. There are a few acronyms
   * supported,  but  in  general  you   should instead  use  the specific
   * realtive time compared to UTC. Supported formats include: -1200, MST,
   * +0100.
   *
   * day of the week items
   * Specifies a day of the week. If  this  is  mentioned alone it means that
   * day of the week in the future. Days  of  the week may be spelled out in
   * full: `Sunday', `Monday', etc or they may  be  abbreviated  to their
   * first three letters, optionally followed by a period.  The special
   * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur'
   * or `Thurs' for `Thursday' are also allowed. A number may precede a day
   * of the week item to  move forward  supplementary  weeks.   It  is best
   * used in expression like `third monday'.   In  this  context, `last  DAY'
   * or  `next DAY' is also acceptable; they move one week before or after
   * the day  that  DAY  by itself would represent.
   *
   * relative items
   * A  relative item adjusts a date (or the current date if  none)  forward
   * or  backward.   Example   syntax includes:  "1  year",  "1  year  ago",
   * "2 days", "4 weeks". The string `tomorrow' is worth one day in the
   * future (equivalent  to  `day'),  the  string `yesterday' is worth one
   * day in the past (equivalent to `day ago').
   *
   * pure numbers
   * If the decimal number is of the form YYYYMMDD and no other calendar date
   * item appears before  it  in  the date  string,  then  YYYY is read as
   * the year, MM as the month number and DD as the day of the month, for the
   * specified calendar date.
   */
  time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 );

}

#endif
<|endoftext|>


<commit_before>          // can be just the necessary schema
  class {{tupletypename}} {
    // Invariant: data stored in _fields is always in the representation
    // specified by _scheme.

    public:
    {% for ft in fieldtypes %}
        {{ft}} f{{loop.index - 1}};
    {% endfor %}

    static constexpr int numFields() {
      return {{numfields}};
    }

    // size of all fields in struct removing only end padding
    static size_t fieldsSize() {
        const {{tupletypename}} _t;
        return

        {% if numfields == 1 %}
            sizeof(_t.f0);
         {% else %}
            ((char*)&_t.f{{numfields-1}}) + sizeof(_t.f{{numfields-1}}) - ((char*)&_t);
         {% endif %}
    }

    // debugging function to get storage sizes
    static void print_representation() {
        const {{tupletypename}} _t;

        {% if numfields == 1 %}
        std::cout << _t.fieldsSize() << std::endl;
        {% else %}
        {% for i in range(1, numfields) %}
        std::cout << (((char*)&_t.f{{i}}) - ((char*)&_t.f{{i-1}})) << ",";
        {% endfor %}
        std::cout << (_t.fieldsSize() - (((char*)&_t.f{{numfields-2}}) - ((char*)&_t)));
        std::cout << std::endl;
        {% endif %}

    }

    {{tupletypename}} () {
      // no-op
    }

    //template <typename OT>
    //{{tupletypename}} (const OT& other) {
    //  std::memcpy(this, &other, sizeof({{tupletypename}}));
    //}
    {{tupletypename}} ({% for ft in fieldtypes %}
                               const {{ft}}& a{{loop.index-1}}
                               {% if not loop.last %},{% endif %}
                       {% endfor %}
                       ) {
        {% for i in range(numfields) %}
            f{{i}} = a{{i}};
        {% endfor %}
    }

    {# list of types comma separated #}
    {# TODO: uncomment when jinja 2.8 is released with support for set blocks
    {% set types_comma %}
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
    {% endset %}
    #}

    {{tupletypename}}(const std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
            >& o) {
        {% for i in range(numfields) %}
            f{{i}} = std::get<{{i}}>(o);
        {% endfor %}
     }

     std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
     > to_tuple() {

        std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
        > r;
        {% for i in range(numfields) %}
            std::get<{{i}}>(r) = f{{i}};
        {% endfor %}
        return r;
     }

    // shamelessly terrible disambiguation: one solution is named factory methods
    //{{tupletypename}} (std::vector<int64_t> vals, bool ignore1, bool ignore2) {
    //    {% for i in range(numfields) %}
    //        f{{i}} = vals[{{i}}];
    //    {% endfor %}
    //}

    // use the tuple schema to interpret the input stream
    static {{tupletypename}} fromIStream(std::istream& ss, char delim=' ') {
        {{tupletypename}} _ret;

        {% for i in range(numfields) %}
            {% if fieldtypes[i] == string_type_name %}
               {
               std::string _temp;
               std::getline(ss, _temp, delim);
               // beware; truncate= true, so unckecked truncation for stringlen >= MAX_STR_LEN!
               _ret.f{{i}} = to_array<MAX_STR_LEN, std::string, true>(_temp);
               }
            {% else %}
               {
               // use operator>> to parse into proper numeric type
               ss >> _ret.f{{i}};
               //throw away the next delimiter
               std::string _temp;
               std::getline(ss, _temp, delim);
               }
            {% endif %}
        {% endfor %}

        return _ret;
    }

    void toOStream(std::ostream& os) const {
        os.write((char*)this, this->fieldsSize());
    }

    void toOStreamAscii(std::ostream& os) const {
        os
        {% for i in range(numfields-1) %}
        << f{{i}} << " "
        {% endfor %}
        << f{{numfields-1}} << std::endl;
    }

    //template <typename Tuple, typename T>
    //{{tupletypename}} (const Tuple& v0, const T& from) {
    //    constexpr size_t v0_size = std::tuple_size<Tuple>::value;
    //    constexpr int from_size = T::numFields();
    //    static_assert({{tupletypename}}::numFields() == (v0_size + from_size), "constructor only works on same number of total fields");
    //    TupleUtils::assign<0, decltype(_scheme)>(_fields, v0);
    //    std::memcpy(((char*)&_fields)+v0_size*sizeof(int64_t), &(from._fields), from_size*sizeof(int64_t));
    //}

    //template <typename Tuple>
    //{{tupletypename}} (const Tuple& v0) {
    //    static_assert({{tupletypename}}::numFields() == (std::tuple_size<Tuple>::value), "constructor only works on same number of total fields");
    //    TupleUtils::assign<0, decltype(_scheme)>(_fields, v0);
    //}

    std::ostream& dump(std::ostream& o) const {
      o << "Materialized(";

      {% for i in range(numfields) %}
        o << f{{i}} << ",";
      {% endfor %}

      o << ")";
      return o;
    }

    {{additional_code}}
  } {{after_def_code}};

  std::ostream& operator<< (std::ostream& o, const {{tupletypename}}& t) {
    return t.dump(o);
  }

<commit_msg>allow for 0 size tuple<commit_after>          // can be just the necessary schema
  class {{tupletypename}} {
    // Invariant: data stored in _fields is always in the representation
    // specified by _scheme.

    public:
    {% for ft in fieldtypes %}
        {{ft}} f{{loop.index - 1}};
    {% endfor %}

    static constexpr int numFields() {
      return {{numfields}};
    }

    // size of all fields in struct removing only end padding
    static size_t fieldsSize() {
        const {{tupletypename}} _t;
        return

        {% if numfields == 0 %}
            0;
        {% elif numfields == 1 %}
            sizeof(_t.f0);
         {% else %}
            ((char*)&_t.f{{numfields-1}}) + sizeof(_t.f{{numfields-1}}) - ((char*)&_t);
         {% endif %}
    }

    // debugging function to get storage sizes
    static void print_representation() {
        const {{tupletypename}} _t;

        {% if numfields == 0 %}
            // noop
        {% elif numfields == 1 %}
        std::cout << _t.fieldsSize() << std::endl;
        {% else %}
        {% for i in range(1, numfields) %}
        std::cout << (((char*)&_t.f{{i}}) - ((char*)&_t.f{{i-1}})) << ",";
        {% endfor %}
        std::cout << (_t.fieldsSize() - (((char*)&_t.f{{numfields-2}}) - ((char*)&_t)));
        std::cout << std::endl;
        {% endif %}

    }

    {{tupletypename}} () {
      // no-op
    }

    //template <typename OT>
    //{{tupletypename}} (const OT& other) {
    //  std::memcpy(this, &other, sizeof({{tupletypename}}));
    //}
    {{tupletypename}} ({% for ft in fieldtypes %}
                               const {{ft}}& a{{loop.index-1}}
                               {% if not loop.last %},{% endif %}
                       {% endfor %}
                       ) {
        {% for i in range(numfields) %}
            f{{i}} = a{{i}};
        {% endfor %}
    }

    {# list of types comma separated #}
    {# TODO: uncomment when jinja 2.8 is released with support for set blocks
    {% set types_comma %}
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
    {% endset %}
    #}

    {{tupletypename}}(const std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
            >& o) {
        {% for i in range(numfields) %}
            f{{i}} = std::get<{{i}}>(o);
        {% endfor %}
     }

     std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
     > to_tuple() {

        std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
        > r;
        {% for i in range(numfields) %}
            std::get<{{i}}>(r) = f{{i}};
        {% endfor %}
        return r;
     }

    // shamelessly terrible disambiguation: one solution is named factory methods
    //{{tupletypename}} (std::vector<int64_t> vals, bool ignore1, bool ignore2) {
    //    {% for i in range(numfields) %}
    //        f{{i}} = vals[{{i}}];
    //    {% endfor %}
    //}

    // use the tuple schema to interpret the input stream
    static {{tupletypename}} fromIStream(std::istream& ss, char delim=' ') {
        {{tupletypename}} _ret;

        {% for i in range(numfields) %}
            {% if fieldtypes[i] == string_type_name %}
               {
               std::string _temp;
               std::getline(ss, _temp, delim);
               // beware; truncate= true, so unckecked truncation for stringlen >= MAX_STR_LEN!
               _ret.f{{i}} = to_array<MAX_STR_LEN, std::string, true>(_temp);
               }
            {% else %}
               {
               // use operator>> to parse into proper numeric type
               ss >> _ret.f{{i}};
               //throw away the next delimiter
               std::string _temp;
               std::getline(ss, _temp, delim);
               }
            {% endif %}
        {% endfor %}

        return _ret;
    }

    void toOStream(std::ostream& os) const {
        os.write((char*)this, this->fieldsSize());
    }

    void toOStreamAscii(std::ostream& os) const {
        os
        {% for i in range(numfields-1) %}
        << f{{i}} << " "
        {% endfor %}
        << f{{numfields-1}} << std::endl;
    }

    //template <typename Tuple, typename T>
    //{{tupletypename}} (const Tuple& v0, const T& from) {
    //    constexpr size_t v0_size = std::tuple_size<Tuple>::value;
    //    constexpr int from_size = T::numFields();
    //    static_assert({{tupletypename}}::numFields() == (v0_size + from_size), "constructor only works on same number of total fields");
    //    TupleUtils::assign<0, decltype(_scheme)>(_fields, v0);
    //    std::memcpy(((char*)&_fields)+v0_size*sizeof(int64_t), &(from._fields), from_size*sizeof(int64_t));
    //}

    //template <typename Tuple>
    //{{tupletypename}} (const Tuple& v0) {
    //    static_assert({{tupletypename}}::numFields() == (std::tuple_size<Tuple>::value), "constructor only works on same number of total fields");
    //    TupleUtils::assign<0, decltype(_scheme)>(_fields, v0);
    //}

    std::ostream& dump(std::ostream& o) const {
      o << "Materialized(";

      {% for i in range(numfields) %}
        o << f{{i}} << ",";
      {% endfor %}

      o << ")";
      return o;
    }

    {{additional_code}}
  } {{after_def_code}};

  std::ostream& operator<< (std::ostream& o, const {{tupletypename}}& t) {
    return t.dump(o);
  }

<|endoftext|>


<commit_before>
#include "IntegrateTFDH.h"

#include "Element.h"
#include "PlasmaFunctions.h"
#include "PlasmaState.h"
#include "PhysicalConstants.h"
#include "RadialFunction.h"

#include <cmath>
#include <vector>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>

#include <iostream>

namespace {

  struct TfdhParams {
    const Element& e;
    const PlasmaState& p;
    TfdhParams(const Element& re, const PlasmaState& rp) : e(re), p(rp) {}
  };

  int tfdhOde(double r, const double f[], double dfdr[], void *params) {
    const double& qe = PhysicalConstantsCGS::ElectronCharge;
    const double phi = qe*f[0]/r;
    const PlasmaState& p = static_cast<TfdhParams*>(params)->p;
    const double ne = Plasma::ne(phi, p);
    const double ionChargeDensity = Plasma::totalIonChargeDensity(phi, p);
    dfdr[0] = f[1];
    dfdr[1] = -4.0*M_PI*qe * r * (ionChargeDensity - ne);
    return 0;
  }
}

RadialFunction TFDH::solve(const Element& e, const PlasmaState& p)
{
  // set parameters here:
  const double ri = 1e-10;
  const double rf = 1e-6;

  const double dv0 = rootfindPotential(e, p, ri, rf);
  return integrateODE(e, p, ri, rf, dv0);
}

RadialFunction TFDH::integrateODE(const Element& e, const PlasmaState& p,
    const double r_init, const double r_final, const double dv0)
{
  const double dr_start = r_init;
  const double eps_abs = 1e-6;
  const double eps_rel = 0;
  TfdhParams params(e,p);
  gsl_odeiv2_system sys = {tfdhOde, nullptr, 2, &params};
  gsl_odeiv2_driver* d = gsl_odeiv2_driver_alloc_y_new(&sys,
      gsl_odeiv2_step_rk8pd, dr_start, eps_abs, eps_rel);

  // TODO -- clean all this up
  const double& qe = PhysicalConstantsCGS::ElectronCharge;
  double r = r_init;
  double solution[2] = {qe*e.Z + r_init*dv0, dv0};

  std::vector<double> radii, potentials;

  const int numsteps = 100;
  for (int i=0; i<numsteps; ++i) {
    const double ri = r_init + (i+1)*(r_final-r_init)/numsteps;
    const int status = gsl_odeiv2_driver_apply(d, &r, ri, solution);
    assert(status==GSL_SUCCESS);
    radii.push_back(ri);
    potentials.push_back(solution[0]/ri);
  }

  gsl_odeiv2_driver_free(d);
  return RadialFunction(radii, potentials);
}

double TFDH::rootfindPotential(const Element& e, const PlasmaState& p,
    const double r_init, const double r_final)
{
  // find interval that brackets correct potential
  const double dv = 1.0;
  double v0 = 0;
  double v1 = 0;

  const int num_tries = 100;
  for (int i=0; i<num_tries; ++i) {
    const auto& rf = integrateODE(e, p, r_init, r_final, v0);
    if (rf.data.back() < 0.0) break;
    v1 = v0;
    v0 -= dv;
  }

  // iterate guess
  // avoid fancy rootfinders here, because we aren't dealing with a smooth
  // function and its root -- rather, we are trying to find the boundary
  // between two distinct sets: dv0 too large, dv0 too small
  const int num_root_tries = 100;
  double v_try;
  for (int i=0; i<num_root_tries; ++i) {
    v_try = (v0+v1)/2.0;
    if (v_try==v0 or v_try==v1) // underflow
      return v_try;

    const auto& rf = integrateODE(e, p, r_init, r_final, v_try);
    if (rf.data.back() >= 0.0) {
      v1 = v_try;
    } else {
      v0 = v_try;
    }
  }

  return v_try;
}

<commit_msg>Remove unused include<commit_after>
#include "IntegrateTFDH.h"

#include "Element.h"
#include "PlasmaFunctions.h"
#include "PlasmaState.h"
#include "PhysicalConstants.h"
#include "RadialFunction.h"

#include <cmath>
#include <vector>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>

namespace {

  struct TfdhParams {
    const Element& e;
    const PlasmaState& p;
    TfdhParams(const Element& re, const PlasmaState& rp) : e(re), p(rp) {}
  };

  int tfdhOde(double r, const double f[], double dfdr[], void *params) {
    const double& qe = PhysicalConstantsCGS::ElectronCharge;
    const double phi = qe*f[0]/r;
    const PlasmaState& p = static_cast<TfdhParams*>(params)->p;
    const double ne = Plasma::ne(phi, p);
    const double ionChargeDensity = Plasma::totalIonChargeDensity(phi, p);
    dfdr[0] = f[1];
    dfdr[1] = -4.0*M_PI*qe * r * (ionChargeDensity - ne);
    return 0;
  }
}

RadialFunction TFDH::solve(const Element& e, const PlasmaState& p)
{
  // set parameters here:
  const double ri = 1e-10;
  const double rf = 1e-6;

  const double dv0 = rootfindPotential(e, p, ri, rf);
  return integrateODE(e, p, ri, rf, dv0);
}

RadialFunction TFDH::integrateODE(const Element& e, const PlasmaState& p,
    const double r_init, const double r_final, const double dv0)
{
  const double dr_start = r_init;
  const double eps_abs = 1e-6;
  const double eps_rel = 0;
  TfdhParams params(e,p);
  gsl_odeiv2_system sys = {tfdhOde, nullptr, 2, &params};
  gsl_odeiv2_driver* d = gsl_odeiv2_driver_alloc_y_new(&sys,
      gsl_odeiv2_step_rk8pd, dr_start, eps_abs, eps_rel);

  // TODO -- clean all this up
  const double& qe = PhysicalConstantsCGS::ElectronCharge;
  double r = r_init;
  double solution[2] = {qe*e.Z + r_init*dv0, dv0};

  std::vector<double> radii, potentials;

  const int numsteps = 100;
  for (int i=0; i<numsteps; ++i) {
    const double ri = r_init + (i+1)*(r_final-r_init)/numsteps;
    const int status = gsl_odeiv2_driver_apply(d, &r, ri, solution);
    assert(status==GSL_SUCCESS);
    radii.push_back(ri);
    potentials.push_back(solution[0]/ri);
  }

  gsl_odeiv2_driver_free(d);
  return RadialFunction(radii, potentials);
}

double TFDH::rootfindPotential(const Element& e, const PlasmaState& p,
    const double r_init, const double r_final)
{
  // find interval that brackets correct potential
  const double dv = 1.0;
  double v0 = 0;
  double v1 = 0;

  const int num_tries = 100;
  for (int i=0; i<num_tries; ++i) {
    const auto& rf = integrateODE(e, p, r_init, r_final, v0);
    if (rf.data.back() < 0.0) break;
    v1 = v0;
    v0 -= dv;
  }

  // iterate guess
  // avoid fancy rootfinders here, because we aren't dealing with a smooth
  // function and its root -- rather, we are trying to find the boundary
  // between two distinct sets: dv0 too large, dv0 too small
  const int num_root_tries = 100;
  double v_try;
  for (int i=0; i<num_root_tries; ++i) {
    v_try = (v0+v1)/2.0;
    if (v_try==v0 or v_try==v1) // underflow
      return v_try;

    const auto& rf = integrateODE(e, p, r_init, r_final, v_try);
    if (rf.data.back() >= 0.0) {
      v1 = v_try;
    } else {
      v0 = v_try;
    }
  }

  return v_try;
}

<|endoftext|>


<commit_before>#include "agenda.h"
#include "errors.h"
#include <condition_variable>
#include <unistd.h>
#include <thread>

using namespace es3;

agenda_ptr agenda::make_new(size_t thread_num)
{
	return agenda_ptr(new agenda(thread_num));
}

agenda::agenda(size_t thread_num) : num_working_()
{
	thread_num_ = thread_num>0 ? thread_num : sysconf(_SC_NPROCESSORS_ONLN)+1;
}

namespace es3
{
	class task_executor
	{
		agenda_ptr agenda_;
	public:
		task_executor(agenda_ptr agenda) : agenda_(agenda) {}

		sync_task_ptr claim_task()
		{
			while(true)
			{
				u_guard_t lock(agenda_->m_);
				if (agenda_->tasks_.empty())
				{
					if (agenda_->num_working_==0)
						return sync_task_ptr();
					else
					{
						agenda_->condition_.wait(lock);
						continue;
					}
				}

				for(auto iter=agenda_->tasks_.begin();
					iter!=agenda_->tasks_.end();++iter)
				{
					sync_task_ptr cur_task = *iter;
					//Check if there are too many tasks of this type running
					int cur_num=agenda_->classes_[cur_task->get_class()];
					if (cur_task->get_class_limit()!=-1 &&
							cur_task->get_class_limit()<=cur_num)
						continue;

					agenda_->tasks_.erase(iter);
					agenda_->num_working_++;
					agenda_->classes_[cur_task->get_class()]++;
					return cur_task;
				}
			}
		}

		void cleanup(sync_task_ptr cur_task)
		{
			u_guard_t lock(agenda_->m_);
			agenda_->num_working_--;
			agenda_->classes_[cur_task->get_class()]--;
			if (agenda_->tasks_.empty() && agenda_->num_working_==0 ||
					cur_task->get_class_limit()!=-1)
				agenda_->condition_.notify_all();
		}

		void operator ()()
		{
			while(true)
			{
				sync_task_ptr cur_task=claim_task();
				if (!cur_task)
					break;

				for(int f=0; f<10; ++f)
				{
					try
					{
						(*cur_task)(agenda_);
						break;
					} catch (const es3_exception &ex)
					{
						const result_code_t &code = ex.err();
						if (code.code()==errNone)
						{
							VLOG(1) << "INFO: " << ex.what();
							continue;
						} else if (code.code()==errWarn)
						{
							VLOG(0) << "WARN: " << ex.what();
							continue;
						} else
						{
							VLOG(0) << ex.what();
							break;
						}
					} catch(...)
					{
						cleanup(cur_task);
						throw;
					}
				}

				cleanup(cur_task);
			}
		}
	};
}

void agenda::schedule(sync_task_ptr task)
{
	u_guard_t lock(m_);
	agenda_ptr ptr = shared_from_this();
	tasks_.push_back(task);
	condition_.notify_one();
}

void agenda::run()
{
	std::vector<std::thread> threads;
	for(int f=0;f<thread_num_;++f)
		threads.push_back(std::thread(task_executor(shared_from_this())));

	for(int f=0;f<thread_num_;++f)
		threads.at(f).join();
}
<commit_msg>Fix bad behavior<commit_after>#include "agenda.h"
#include "errors.h"
#include <condition_variable>
#include <unistd.h>
#include <thread>

using namespace es3;

agenda_ptr agenda::make_new(size_t thread_num)
{
	return agenda_ptr(new agenda(thread_num));
}

agenda::agenda(size_t thread_num) : num_working_()
{
	thread_num_ = thread_num>0 ? thread_num : sysconf(_SC_NPROCESSORS_ONLN)+1;
}

namespace es3
{
	class task_executor
	{
		agenda_ptr agenda_;
	public:
		task_executor(agenda_ptr agenda) : agenda_(agenda) {}

		sync_task_ptr claim_task()
		{
			while(true)
			{
				u_guard_t lock(agenda_->m_);
				if (agenda_->tasks_.empty())
				{
					if (agenda_->num_working_==0)
						return sync_task_ptr();
				}

				for(auto iter=agenda_->tasks_.begin();
					iter!=agenda_->tasks_.end();++iter)
				{
					sync_task_ptr cur_task = *iter;
					//Check if there are too many tasks of this type running
					int cur_num=agenda_->classes_[cur_task->get_class()];
					if (cur_task->get_class_limit()!=-1 &&
							cur_task->get_class_limit()<=cur_num)
						continue;

					agenda_->tasks_.erase(iter);
					agenda_->num_working_++;
					agenda_->classes_[cur_task->get_class()]++;
					return cur_task;
				}

				agenda_->condition_.wait(lock);
			}
		}

		void cleanup(sync_task_ptr cur_task)
		{
			u_guard_t lock(agenda_->m_);
			agenda_->num_working_--;
			agenda_->classes_[cur_task->get_class()]--;
			if (agenda_->tasks_.empty() && agenda_->num_working_==0 ||
					cur_task->get_class_limit()!=-1)
				agenda_->condition_.notify_all();
		}

		void operator ()()
		{
			while(true)
			{
				sync_task_ptr cur_task=claim_task();
				if (!cur_task)
					break;

				for(int f=0; f<10; ++f)
				{
					try
					{
						(*cur_task)(agenda_);
						break;
					} catch (const es3_exception &ex)
					{
						const result_code_t &code = ex.err();
						if (code.code()==errNone)
						{
							VLOG(1) << "INFO: " << ex.what();
							continue;
						} else if (code.code()==errWarn)
						{
							VLOG(0) << "WARN: " << ex.what();
							continue;
						} else
						{
							VLOG(0) << ex.what();
							break;
						}
					} catch(...)
					{
						cleanup(cur_task);
						throw;
					}
				}

				cleanup(cur_task);
			}
		}
	};
}

void agenda::schedule(sync_task_ptr task)
{
	u_guard_t lock(m_);
	agenda_ptr ptr = shared_from_this();
	tasks_.push_back(task);
	condition_.notify_one();
}

void agenda::run()
{
	std::vector<std::thread> threads;
	for(int f=0;f<thread_num_;++f)
		threads.push_back(std::thread(task_executor(shared_from_this())));

	for(int f=0;f<thread_num_;++f)
		threads.at(f).join();
}
<|endoftext|>


<commit_before>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2003 Jory Stone.  All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** 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
**
** See http://www.matroska.org/license/lgpl/ for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

/*!
	\file
	\version \$Id: MemIOCallback.cpp 693 2004-07-31 08:56:28Z robux4 $
	\author Jory Stone <jcsston @ toughguy.net>
*/

#include "ebml/MemIOCallback.h"
#include "ebml/Debug.h"
#include "ebml/EbmlConfig.h"

START_LIBEBML_NAMESPACE

MemIOCallback::MemIOCallback(uint64 DefaultSize)
{
	//The default size of the buffer is 128 bytes
	dataBuffer = (binary *)malloc(DefaultSize);
	if (dataBuffer == NULL) {
		mOk = false;
		std::stringstream Msg;
		Msg << "Failed to alloc memory block of size ";
// not working with VC6		Msg << DefaultSize;
		mLastErrorStr = Msg.str();
		return;
	}

	dataBufferMemorySize = DefaultSize;
	dataBufferPos = 0;
	dataBufferTotalSize = 0;
	mOk = true;
}

MemIOCallback::~MemIOCallback()
{
	if (dataBuffer != NULL)
		free(dataBuffer);
}

uint32 MemIOCallback::read(void *Buffer, size_t Size)
{
	if (Buffer == NULL || Size < 1)
		return 0;
	//If the size is larger than than the amount left in the buffer
	if (Size + dataBufferPos > dataBufferTotalSize)
	{
		//We will only return the remaining data
		memcpy(Buffer, dataBuffer + dataBufferPos, dataBufferTotalSize - dataBufferPos);
		dataBufferPos = dataBufferTotalSize;
		return dataBufferTotalSize - dataBufferPos;
	}

	//Well... We made it here, so do a quick and simple copy
	memcpy(Buffer, dataBuffer+dataBufferPos, Size);
	dataBufferPos += Size;

	return Size;
}

void MemIOCallback::setFilePointer(int64 Offset, seek_mode Mode)
{
	if (Mode == seek_beginning)
		dataBufferPos = Offset;
	else if (Mode == seek_current)
		dataBufferPos = dataBufferPos + Offset;
	else if (Mode == seek_end)
		dataBufferPos = dataBufferTotalSize + Offset;
}

size_t MemIOCallback::write(const void *Buffer, size_t Size)
{
	if (dataBufferMemorySize < dataBufferPos + Size)
	{
		//We need more memory!
		dataBuffer = (binary *)realloc((void *)dataBuffer, dataBufferPos + Size);
	}
	memcpy(dataBuffer+dataBufferPos, Buffer, Size);
	dataBufferPos += Size;
	if (dataBufferPos > dataBufferTotalSize)
		dataBufferTotalSize = dataBufferPos;

	return Size;
}

uint32 MemIOCallback::write(IOCallback & IOToRead, size_t Size)
{
	if (dataBufferMemorySize < dataBufferPos + Size)
	{
		//We need more memory!
		dataBuffer = (binary *)realloc((void *)dataBuffer, dataBufferPos + Size);
	}
	IOToRead.readFully(&dataBuffer[dataBufferPos], Size);
	dataBufferTotalSize = Size;
	return Size;
}

END_LIBEBML_NAMESPACE
<commit_msg>libebml: fix the size returned by MemIOCallback::read() when reaching the end of the buffer<commit_after>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2003 Jory Stone.  All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** 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
**
** See http://www.matroska.org/license/lgpl/ for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

/*!
	\file
	\version \$Id: MemIOCallback.cpp 693 2004-07-31 08:56:28Z robux4 $
	\author Jory Stone <jcsston @ toughguy.net>
*/

#include "ebml/MemIOCallback.h"
#include "ebml/Debug.h"
#include "ebml/EbmlConfig.h"

START_LIBEBML_NAMESPACE

MemIOCallback::MemIOCallback(uint64 DefaultSize)
{
	//The default size of the buffer is 128 bytes
	dataBuffer = (binary *)malloc(DefaultSize);
	if (dataBuffer == NULL) {
		mOk = false;
		std::stringstream Msg;
		Msg << "Failed to alloc memory block of size ";
// not working with VC6		Msg << DefaultSize;
		mLastErrorStr = Msg.str();
		return;
	}

	dataBufferMemorySize = DefaultSize;
	dataBufferPos = 0;
	dataBufferTotalSize = 0;
	mOk = true;
}

MemIOCallback::~MemIOCallback()
{
	if (dataBuffer != NULL)
		free(dataBuffer);
}

uint32 MemIOCallback::read(void *Buffer, size_t Size)
{
	if (Buffer == NULL || Size < 1)
		return 0;
	//If the size is larger than than the amount left in the buffer
	if (Size + dataBufferPos > dataBufferTotalSize)
	{
		//We will only return the remaining data
		memcpy(Buffer, dataBuffer + dataBufferPos, dataBufferTotalSize - dataBufferPos);
        uint64 oldDataPos = dataBufferPos;
		dataBufferPos = dataBufferTotalSize;
		return dataBufferTotalSize - oldDataPos;
	}

	//Well... We made it here, so do a quick and simple copy
	memcpy(Buffer, dataBuffer+dataBufferPos, Size);
	dataBufferPos += Size;

	return Size;
}

void MemIOCallback::setFilePointer(int64 Offset, seek_mode Mode)
{
	if (Mode == seek_beginning)
		dataBufferPos = Offset;
	else if (Mode == seek_current)
		dataBufferPos = dataBufferPos + Offset;
	else if (Mode == seek_end)
		dataBufferPos = dataBufferTotalSize + Offset;
}

size_t MemIOCallback::write(const void *Buffer, size_t Size)
{
	if (dataBufferMemorySize < dataBufferPos + Size)
	{
		//We need more memory!
		dataBuffer = (binary *)realloc((void *)dataBuffer, dataBufferPos + Size);
	}
	memcpy(dataBuffer+dataBufferPos, Buffer, Size);
	dataBufferPos += Size;
	if (dataBufferPos > dataBufferTotalSize)
		dataBufferTotalSize = dataBufferPos;

	return Size;
}

uint32 MemIOCallback::write(IOCallback & IOToRead, size_t Size)
{
	if (dataBufferMemorySize < dataBufferPos + Size)
	{
		//We need more memory!
		dataBuffer = (binary *)realloc((void *)dataBuffer, dataBufferPos + Size);
	}
	IOToRead.readFully(&dataBuffer[dataBufferPos], Size);
	dataBufferTotalSize = Size;
	return Size;
}

END_LIBEBML_NAMESPACE
<|endoftext|>


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

#include "MouseEventImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

// MouseEvent

void MouseEventImp::initMouseEvent(const std::u16string& typeArg, bool canBubbleArg, bool cancelableArg, html::Window viewArg, int detailArg,
                                   int screenXArg, int screenYArg, int clientXArg, int clientYArg, bool ctrlKeyArg, bool altKeyArg, bool shiftKeyArg, bool metaKeyArg, unsigned short buttonArg, events::EventTarget relatedTargetArg)
{
    screenX = screenXArg;
    screenY = screenYArg;
    clientX = clientXArg;
    clientY = clientYArg;
    ctrlKey = ctrlKeyArg;
    altKey = altKeyArg;
    shiftKey = shiftKeyArg;
    metaKey = metaKeyArg;
    button = buttonArg;
    relatedTarget = relatedTargetArg;
    initUIEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg);
}

bool MouseEventImp::getModifierState(const std::u16string& keyArg)
{
}

Nullable<std::u16string> MouseEventImp::getRegion()
{
    // TODO: implement me!
    return u"";
}

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

#include "MouseEventImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

// MouseEvent

void MouseEventImp::initMouseEvent(const std::u16string& typeArg, bool canBubbleArg, bool cancelableArg, html::Window viewArg, int detailArg,
                                   int screenXArg, int screenYArg, int clientXArg, int clientYArg, bool ctrlKeyArg, bool altKeyArg, bool shiftKeyArg, bool metaKeyArg, unsigned short buttonArg, events::EventTarget relatedTargetArg)
{
    screenX = screenXArg;
    screenY = screenYArg;
    clientX = clientXArg;
    clientY = clientYArg;
    ctrlKey = ctrlKeyArg;
    altKey = altKeyArg;
    shiftKey = shiftKeyArg;
    metaKey = metaKeyArg;
    button = buttonArg;
    relatedTarget = relatedTargetArg;
    initUIEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg);
}

bool MouseEventImp::getModifierState(const std::u16string& keyArg)
{
    // TODO: implement me!
    return false;
}

Nullable<std::u16string> MouseEventImp::getRegion()
{
    // TODO: implement me!
    return u"";
}

}}}}  // org::w3c::dom::bootstrap
<|endoftext|>


<commit_before>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)

#include "ceres/corrector.h"

#include <cstddef>
#include <cmath>
#include "ceres/internal/eigen.h"
#include "glog/logging.h"

namespace ceres {
namespace internal {

Corrector::Corrector(double sq_norm, const double rho[3]) {
  CHECK_GE(sq_norm, 0.0);
  CHECK_GT(rho[1], 0.0);
  sqrt_rho1_ = sqrt(rho[1]);

  // If sq_norm = 0.0, the correction becomes trivial, the residual
  // and the jacobian are scaled by the squareroot of the derivative
  // of rho. Handling this case explicitly avoids the divide by zero
  // error that would occur below.
  //
  // The case where rho'' < 0 also gets special handling. Technically
  // it shouldn't, and the computation of the scaling should proceed
  // as below, however we found in experiments that applying the
  // curvature correction when rho'' < 0, which is the case when we
  // are in the outlier region slows down the convergence of the
  // algorithm significantly.
  //
  // Thus, we have divided the action of the robustifier into two
  // parts. In the inliner region, we do the full second order
  // correction which re-wights the gradient of the function by the
  // square root of the derivative of rho, and the Gauss-Newton
  // Hessian gets both the scaling and the rank-1 curvature
  // correction. Normaly, alpha is upper bounded by one, but with this
  // change, alpha is bounded above by zero.
  //
  // Empirically we have observed that the full Triggs correction and
  // the clamped correction both start out as very good approximations
  // to the loss function when we are in the convex part of the
  // function, but as the function starts transitioning from convex to
  // concave, the Triggs approximation diverges more and more and
  // ultimately becomes linear. The clamped Triggs model however
  // remains quadratic.
  //
  // The reason why the Triggs approximation becomes so poor is
  // because the curvature correction that it applies to the gauss
  // newton hessian goes from being a full rank correction to a rank
  // deficient correction making the inversion of the Hessian fraught
  // with all sorts of misery and suffering.
  //
  // The clamped correction retains its quadratic nature and inverting it
  // is always well formed.
  if ((sq_norm == 0.0) || (rho[2] <= 0.0)) {
    residual_scaling_ = sqrt_rho1_;
    alpha_sq_norm_ = 0.0;
    return;
  }

  // Calculate the smaller of the two solutions to the equation
  //
  // 0.5 *  alpha^2 - alpha - rho'' / rho' *  z'z = 0.
  //
  // Start by calculating the discriminant D.
  const double D = 1.0 + 2.0 * sq_norm*rho[2] / rho[1];

  // Since both rho[1] and rho[2] are guaranteed to be positive at
  // this point, we know that D > 1.0.

  const double alpha = 1.0 - sqrt(D);

  // Calculate the constants needed by the correction routines.
  residual_scaling_ = sqrt_rho1_ / (1 - alpha);
  alpha_sq_norm_ = alpha / sq_norm;
}

void Corrector::CorrectResiduals(int nrow, double* residuals) {
  DCHECK(residuals != NULL);
  VectorRef r_ref(residuals, nrow);
  // Equation 11 in BANS.
  r_ref *= residual_scaling_;
}

void Corrector::CorrectJacobian(int nrow, int ncol,
                                double* residuals, double* jacobian) {
  DCHECK(residuals != NULL);
  DCHECK(jacobian != NULL);
  ConstVectorRef r_ref(residuals, nrow);
  MatrixRef j_ref(jacobian, nrow, ncol);

  // Equation 11 in BANS.
  j_ref = sqrt_rho1_ * (j_ref - alpha_sq_norm_ *
                        r_ref * (r_ref.transpose() * j_ref));
}

}  // namespace internal
}  // namespace ceres
<commit_msg>Speedup corrector.cc<commit_after>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)

#include "ceres/corrector.h"

#include <cstddef>
#include <cmath>
#include "ceres/internal/eigen.h"
#include "glog/logging.h"

namespace ceres {
namespace internal {

Corrector::Corrector(double sq_norm, const double rho[3]) {
  CHECK_GE(sq_norm, 0.0);
  CHECK_GT(rho[1], 0.0);
  sqrt_rho1_ = sqrt(rho[1]);

  // If sq_norm = 0.0, the correction becomes trivial, the residual
  // and the jacobian are scaled by the squareroot of the derivative
  // of rho. Handling this case explicitly avoids the divide by zero
  // error that would occur below.
  //
  // The case where rho'' < 0 also gets special handling. Technically
  // it shouldn't, and the computation of the scaling should proceed
  // as below, however we found in experiments that applying the
  // curvature correction when rho'' < 0, which is the case when we
  // are in the outlier region slows down the convergence of the
  // algorithm significantly.
  //
  // Thus, we have divided the action of the robustifier into two
  // parts. In the inliner region, we do the full second order
  // correction which re-wights the gradient of the function by the
  // square root of the derivative of rho, and the Gauss-Newton
  // Hessian gets both the scaling and the rank-1 curvature
  // correction. Normaly, alpha is upper bounded by one, but with this
  // change, alpha is bounded above by zero.
  //
  // Empirically we have observed that the full Triggs correction and
  // the clamped correction both start out as very good approximations
  // to the loss function when we are in the convex part of the
  // function, but as the function starts transitioning from convex to
  // concave, the Triggs approximation diverges more and more and
  // ultimately becomes linear. The clamped Triggs model however
  // remains quadratic.
  //
  // The reason why the Triggs approximation becomes so poor is
  // because the curvature correction that it applies to the gauss
  // newton hessian goes from being a full rank correction to a rank
  // deficient correction making the inversion of the Hessian fraught
  // with all sorts of misery and suffering.
  //
  // The clamped correction retains its quadratic nature and inverting it
  // is always well formed.
  if ((sq_norm == 0.0) || (rho[2] <= 0.0)) {
    residual_scaling_ = sqrt_rho1_;
    alpha_sq_norm_ = 0.0;
    return;
  }

  // Calculate the smaller of the two solutions to the equation
  //
  // 0.5 *  alpha^2 - alpha - rho'' / rho' *  z'z = 0.
  //
  // Start by calculating the discriminant D.
  const double D = 1.0 + 2.0 * sq_norm*rho[2] / rho[1];

  // Since both rho[1] and rho[2] are guaranteed to be positive at
  // this point, we know that D > 1.0.

  const double alpha = 1.0 - sqrt(D);

  // Calculate the constants needed by the correction routines.
  residual_scaling_ = sqrt_rho1_ / (1 - alpha);
  alpha_sq_norm_ = alpha / sq_norm;
}

void Corrector::CorrectResiduals(int nrow, double* residuals) {
  DCHECK(residuals != NULL);
  VectorRef r_ref(residuals, nrow);
  // Equation 11 in BANS.
  r_ref *= residual_scaling_;
}

void Corrector::CorrectJacobian(int nrow, int ncol,
                                double* residuals, double* jacobian) {
  DCHECK(residuals != NULL);
  DCHECK(jacobian != NULL);

  if (nrow == 1) {
    // Specialization for the case where the residual is a scalar.
    VectorRef j_ref(jacobian, ncol);
    j_ref *= sqrt_rho1_ * (1.0 - alpha_sq_norm_ * pow(*residuals, 2));
  } else {
    ConstVectorRef r_ref(residuals, nrow);
    MatrixRef j_ref(jacobian, nrow, ncol);

    // Equation 11 in BANS.
    j_ref = sqrt_rho1_ * (j_ref - alpha_sq_norm_ *
                          r_ref * (r_ref.transpose() * j_ref));
  }
}

}  // namespace internal
}  // namespace ceres
<|endoftext|>