<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * gluePyBind11.cpp
 *
 *  Created on: Mar 16, 2017
 *      Author: William F Godoy godoywf@ornl.gov
 */

#include <stdexcept>

#include <adios2.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#ifdef ADIOS2_HAVE_MPI
#include <mpi4py/mpi4py.h>
#endif

#include "ADIOSPy.h"
#include "EnginePy.h"
#include "IOPy.h"

#ifdef ADIOS2_HAVE_MPI
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
                                  pybind11::object &object,
                                  const bool debugMode)
{
    MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());

    if (import_mpi4py() < 0)
    {
        throw std::runtime_error("ERROR: could not import mpi4py "
                                 "communicator, in call to ADIOS "
                                 "constructor\n");
    }

    if (mpiCommPtr == nullptr)
    {
        throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
                                 "to ADIOS constructor\n");
    }
    return adios2::ADIOSPy(configFile, *mpiCommPtr, debugMode);
}

adios2::ADIOSPy ADIOSPyInit(pybind11::object &object, const bool debugMode)
{
    MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());

    if (import_mpi4py() < 0)
    {
        throw std::runtime_error("ERROR: could not import mpi4py "
                                 "communicator, in call to ADIOS "
                                 "constructor\n");
    }

    if (mpiCommPtr == nullptr)
    {
        throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
                                 "to ADIOS constructor\n");
    }
    return adios2::ADIOSPy(*mpiCommPtr, debugMode);
}
#else
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
                                  const bool debugMode)
{
    return adios2::ADIOSPy(configFile, debugMode);
}

adios2::ADIOSPy ADIOSPyInit(const bool debugMode)
{
    return adios2::ADIOSPy(debugMode);
}
#endif

PYBIND11_MODULE(adios2, m)
{
#ifdef ADIOS2_HAVE_MPI
    if (import_mpi4py() < 0)
    {
        throw std::runtime_error(
            "ERROR: mpi4py not loaded correctly\n"); /* Python 2.X */
    }
#endif

    // pybind11::module m("adios2", "ADIOS2 Python bindings using pybind11");
    m.doc() = "ADIOS2 Python bindings powered by pybind11";

    m.attr("DebugON") = true;
    m.attr("DebugOFF") = false;
    m.attr("ConstantDims") = true;
    m.attr("VariableDims") = false;
    // enum classes
    pybind11::enum_<adios2::Mode>(m, "Mode")
        .value("Write", adios2::Mode::Write)
        .value("Read", adios2::Mode::Read)
        .value("Append", adios2::Mode::Append)
        .export_values();

    pybind11::enum_<adios2::StepMode>(m, "StepMode")
        .value("Append", adios2::StepMode::Append)
        .value("Update", adios2::StepMode::Update)
        .value("NextAvailable", adios2::StepMode::NextAvailable)
        .value("LatestAvailable", adios2::StepMode::LatestAvailable)
        .export_values();

    pybind11::enum_<adios2::StepStatus>(m, "StepStatus")
        .value("OK", adios2::StepStatus::OK)
        .value("NotReady", adios2::StepStatus::NotReady)
        .value("EndOfStream", adios2::StepStatus::EndOfStream)
        .value("OtherError", adios2::StepStatus::OtherError)
        .export_values();
#ifdef ADIOS2_HAVE_MPI
    m.def("ADIOS", &ADIOSPyInit, "Function that creates an ADIOS class object",
          pybind11::arg("object") = nullptr, pybind11::arg("debugMode") = true);

    m.def("ADIOS", &ADIOSPyInitConfig,
          "Function that creates an ADIOS class "
          "object using a config file",
          pybind11::arg("configFile") = "", pybind11::arg("object") = nullptr,
          pybind11::arg("debugMode") = true);
#else
    m.def("ADIOS", &ADIOSPyInit,
          "Function that creates an ADIOS class object in non MPI mode",
          pybind11::arg("debugMode") = true);

    m.def("ADIOS", &ADIOSPyInitConfig,
          "Function that creates an ADIOS class "
          "object using a config file in non MPI mode",
          pybind11::arg("configFile") = "", pybind11::arg("debugMode") = true);
#endif

    pybind11::class_<adios2::ADIOSPy>(m, "ADIOSPy")
        .def("DeclareIO", &adios2::ADIOSPy::DeclareIO)
        .def("AtIO", &adios2::ADIOSPy::AtIO);

    pybind11::class_<adios2::VariableBase>(m, "Variable")
        .def("SetShape", &adios2::VariableBase::SetShape)
        .def("SetSelection", &adios2::VariableBase::SetSelection)
        .def("SetStepSelection", &adios2::VariableBase::SetStepSelection)
        .def("SelectionSize", &adios2::VariableBase::SelectionSize);

    pybind11::class_<adios2::AttributeBase>(m, "Attribute");

    pybind11::class_<adios2::IOPy>(m, "IOPy")
        .def("SetEngine", &adios2::IOPy::SetEngine)
        .def("SetParameters", &adios2::IOPy::SetParameters,
             pybind11::arg("parameters") = adios2::Params())
        .def("SetParameters", &adios2::IOPy::SetParameters)
        .def("GetParameters", &adios2::IOPy::GetParameters,
             pybind11::return_value_policy::reference_internal)
        .def("AddTransport", &adios2::IOPy::AddTransport)
        .def("DefineVariable", &adios2::IOPy::DefineVariable,
             pybind11::return_value_policy::reference_internal,
             pybind11::arg("name"), pybind11::arg("shape") = adios2::Dims(),
             pybind11::arg("start") = adios2::Dims(),
             pybind11::arg("count") = adios2::Dims(),
             pybind11::arg("isConstantDims") = false,
             pybind11::arg("array") = pybind11::array())
        .def("InquireVariable", &adios2::IOPy::InquireVariable,
             pybind11::return_value_policy::reference_internal)
        .def("DefineAttribute",
             (adios2::AttributeBase *
              (adios2::IOPy::*)(const std::string &, pybind11::array &)) &
                 adios2::IOPy::DefineAttribute,
             pybind11::return_value_policy::reference_internal)
        .def("DefineAttribute",
             (adios2::AttributeBase *
              (adios2::IOPy::*)(const std::string &,
                                const std::vector<std::string> &)) &
                 adios2::IOPy::DefineAttribute,
             pybind11::return_value_policy::reference_internal)
        .def("Open", (adios2::EnginePy(adios2::IOPy::*)(const std::string &,
                                                        const int)) &
                         adios2::IOPy::Open);

    pybind11::class_<adios2::EnginePy>(m, "EnginePy")
        .def("BeginStep", &adios2::EnginePy::BeginStep,
             pybind11::arg("mode") = adios2::StepMode::NextAvailable,
             pybind11::arg("timeoutSeconds") = 0.f)
        .def("PutSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    const pybind11::array &)) &
                            adios2::EnginePy::PutSync)
        .def("PutSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    const std::string &)) &
                            adios2::EnginePy::PutSync)
        .def("PutDeferred",
             (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                         const pybind11::array &)) &
                 adios2::EnginePy::PutDeferred)
        .def("PutDeferred", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                        const std::string &)) &
                                adios2::EnginePy::PutDeferred)
        .def("PerformPuts", &adios2::EnginePy::PerformPuts)
        .def("GetSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    pybind11::array &)) &
                            adios2::EnginePy::GetSync)
        .def("GetSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    std::string &)) &
                            adios2::EnginePy::GetSync)
        .def("GetDeferred", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                        pybind11::array &)) &
                                adios2::EnginePy::GetDeferred)
        .def("GetDeferred", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                        std::string &)) &
                                adios2::EnginePy::GetDeferred)
        .def("PerformGets", &adios2::EnginePy::PerformGets)
        .def("EndStep", &adios2::EnginePy::EndStep)
        .def("WriteStep", &adios2::EnginePy::WriteStep)
        .def("Close", &adios2::EnginePy::Close,
             pybind11::arg("transportIndex") = -1);
}
<commit_msg>Clang-format <commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * gluePyBind11.cpp
 *
 *  Created on: Mar 16, 2017
 *      Author: William F Godoy godoywf@ornl.gov
 */

#include <stdexcept>

#include <adios2.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#ifdef ADIOS2_HAVE_MPI
#include <mpi4py/mpi4py.h>
#endif

#include "ADIOSPy.h"
#include "EnginePy.h"
#include "IOPy.h"

#ifdef ADIOS2_HAVE_MPI
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
                                  pybind11::object &object,
                                  const bool debugMode)
{
    MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());

    if (import_mpi4py() < 0)
    {
        throw std::runtime_error("ERROR: could not import mpi4py "
                                 "communicator, in call to ADIOS "
                                 "constructor\n");
    }

    if (mpiCommPtr == nullptr)
    {
        throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
                                 "to ADIOS constructor\n");
    }
    return adios2::ADIOSPy(configFile, *mpiCommPtr, debugMode);
}

adios2::ADIOSPy ADIOSPyInit(pybind11::object &object, const bool debugMode)
{
    MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());

    if (import_mpi4py() < 0)
    {
        throw std::runtime_error("ERROR: could not import mpi4py "
                                 "communicator, in call to ADIOS "
                                 "constructor\n");
    }

    if (mpiCommPtr == nullptr)
    {
        throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
                                 "to ADIOS constructor\n");
    }
    return adios2::ADIOSPy(*mpiCommPtr, debugMode);
}
#else
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
                                  const bool debugMode)
{
    return adios2::ADIOSPy(configFile, debugMode);
}

adios2::ADIOSPy ADIOSPyInit(const bool debugMode)
{
    return adios2::ADIOSPy(debugMode);
}
#endif

PYBIND11_MODULE(adios2, m)
{
#ifdef ADIOS2_HAVE_MPI
    if (import_mpi4py() < 0)
    {
        throw std::runtime_error(
            "ERROR: mpi4py not loaded correctly\n"); /* Python 2.X */
    }
#endif

    // pybind11::module m("adios2", "ADIOS2 Python bindings using pybind11");
    m.doc() = "ADIOS2 Python bindings powered by pybind11";

    m.attr("DebugON") = true;
    m.attr("DebugOFF") = false;
    m.attr("ConstantDims") = true;
    m.attr("VariableDims") = false;
    // enum classes
    pybind11::enum_<adios2::Mode>(m, "Mode")
        .value("Write", adios2::Mode::Write)
        .value("Read", adios2::Mode::Read)
        .value("Append", adios2::Mode::Append)
        .export_values();

    pybind11::enum_<adios2::StepMode>(m, "StepMode")
        .value("Append", adios2::StepMode::Append)
        .value("Update", adios2::StepMode::Update)
        .value("NextAvailable", adios2::StepMode::NextAvailable)
        .value("LatestAvailable", adios2::StepMode::LatestAvailable)
        .export_values();

    pybind11::enum_<adios2::StepStatus>(m, "StepStatus")
        .value("OK", adios2::StepStatus::OK)
        .value("NotReady", adios2::StepStatus::NotReady)
        .value("EndOfStream", adios2::StepStatus::EndOfStream)
        .value("OtherError", adios2::StepStatus::OtherError)
        .export_values();
#ifdef ADIOS2_HAVE_MPI
    m.def("ADIOS", &ADIOSPyInit, "Function that creates an ADIOS class object",
          pybind11::arg("object") = nullptr, pybind11::arg("debugMode") = true);

    m.def("ADIOS", &ADIOSPyInitConfig, "Function that creates an ADIOS class "
                                       "object using a config file",
          pybind11::arg("configFile") = "", pybind11::arg("object") = nullptr,
          pybind11::arg("debugMode") = true);
#else
    m.def("ADIOS", &ADIOSPyInit,
          "Function that creates an ADIOS class object in non MPI mode",
          pybind11::arg("debugMode") = true);

    m.def("ADIOS", &ADIOSPyInitConfig,
          "Function that creates an ADIOS class "
          "object using a config file in non MPI mode",
          pybind11::arg("configFile") = "", pybind11::arg("debugMode") = true);
#endif

    pybind11::class_<adios2::ADIOSPy>(m, "ADIOSPy")
        .def("DeclareIO", &adios2::ADIOSPy::DeclareIO)
        .def("AtIO", &adios2::ADIOSPy::AtIO);

    pybind11::class_<adios2::VariableBase>(m, "Variable")
        .def("SetShape", &adios2::VariableBase::SetShape)
        .def("SetSelection", &adios2::VariableBase::SetSelection)
        .def("SetStepSelection", &adios2::VariableBase::SetStepSelection)
        .def("SelectionSize", &adios2::VariableBase::SelectionSize);

    pybind11::class_<adios2::AttributeBase>(m, "Attribute");

    pybind11::class_<adios2::IOPy>(m, "IOPy")
        .def("SetEngine", &adios2::IOPy::SetEngine)
        .def("SetParameters", &adios2::IOPy::SetParameters,
             pybind11::arg("parameters") = adios2::Params())
        .def("SetParameters", &adios2::IOPy::SetParameters)
        .def("GetParameters", &adios2::IOPy::GetParameters,
             pybind11::return_value_policy::reference_internal)
        .def("AddTransport", &adios2::IOPy::AddTransport)
        .def("DefineVariable", &adios2::IOPy::DefineVariable,
             pybind11::return_value_policy::reference_internal,
             pybind11::arg("name"), pybind11::arg("shape") = adios2::Dims(),
             pybind11::arg("start") = adios2::Dims(),
             pybind11::arg("count") = adios2::Dims(),
             pybind11::arg("isConstantDims") = false,
             pybind11::arg("array") = pybind11::array())
        .def("InquireVariable", &adios2::IOPy::InquireVariable,
             pybind11::return_value_policy::reference_internal)
        .def("DefineAttribute",
             (adios2::AttributeBase *
              (adios2::IOPy::*)(const std::string &, pybind11::array &)) &
                 adios2::IOPy::DefineAttribute,
             pybind11::return_value_policy::reference_internal)
        .def("DefineAttribute",
             (adios2::AttributeBase *
              (adios2::IOPy::*)(const std::string &,
                                const std::vector<std::string> &)) &
                 adios2::IOPy::DefineAttribute,
             pybind11::return_value_policy::reference_internal)
        .def("Open", (adios2::EnginePy (adios2::IOPy::*)(const std::string &,
                                                         const int)) &
                         adios2::IOPy::Open);

    pybind11::class_<adios2::EnginePy>(m, "EnginePy")
        .def("BeginStep", &adios2::EnginePy::BeginStep,
             pybind11::arg("mode") = adios2::StepMode::NextAvailable,
             pybind11::arg("timeoutSeconds") = 0.f)
        .def("PutSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    const pybind11::array &)) &
                            adios2::EnginePy::PutSync)
        .def("PutSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    const std::string &)) &
                            adios2::EnginePy::PutSync)
        .def("PutDeferred",
             (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                         const pybind11::array &)) &
                 adios2::EnginePy::PutDeferred)
        .def("PutDeferred", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                        const std::string &)) &
                                adios2::EnginePy::PutDeferred)
        .def("PerformPuts", &adios2::EnginePy::PerformPuts)
        .def("GetSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    pybind11::array &)) &
                            adios2::EnginePy::GetSync)
        .def("GetSync", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                    std::string &)) &
                            adios2::EnginePy::GetSync)
        .def("GetDeferred", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                        pybind11::array &)) &
                                adios2::EnginePy::GetDeferred)
        .def("GetDeferred", (void (adios2::EnginePy::*)(adios2::VariableBase *,
                                                        std::string &)) &
                                adios2::EnginePy::GetDeferred)
        .def("PerformGets", &adios2::EnginePy::PerformGets)
        .def("EndStep", &adios2::EnginePy::EndStep)
        .def("WriteStep", &adios2::EnginePy::WriteStep)
        .def("Close", &adios2::EnginePy::Close,
             pybind11::arg("transportIndex") = -1);
}
<|endoftext|>


<commit_before>// Time:  O((|E| + |V|) * log|V|)
// Space: O(|E| + |V|)

class Solution {
public:
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
        using P = pair<int, int>;
        unordered_map<int, vector<P>> adj;
        for (const auto& flight : flights) {
            int u, v, w;
            tie(u, v, w) = make_tuple(flight[0], flight[1], flight[2]);
            adj[u].emplace_back(v, w);
        }

        using T = tuple<int, int, int>;
        priority_queue<T, vector<T>, greater<T>> min_heap;
        min_heap.emplace(0, src, K + 1);
        while (!min_heap.empty()) {
            int result, u, k;
            tie(result, u, k) = min_heap.top(); min_heap.pop();
            if (u == dst) {
                return result;
            }
            if (k > 0) {
                for (const auto& kvp : adj[u]) {
                    int v, w;
                    tie(v, w) = kvp;
                    min_heap.emplace(result + w, v, k - 1);
                }
            }
        }
        return -1;
    }
};
<commit_msg>Update cheapest-flights-within-k-stops.cpp<commit_after>// Time:  O((|E| + |V|) * log|V|) = O(|E| * log|V|)
// Space: O(|E| + |V|)

class Solution {
public:
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
        using P = pair<int, int>;
        unordered_map<int, vector<P>> adj;
        for (const auto& flight : flights) {
            int u, v, w;
            tie(u, v, w) = make_tuple(flight[0], flight[1], flight[2]);
            adj[u].emplace_back(v, w);
        }

        using T = tuple<int, int, int>;
        priority_queue<T, vector<T>, greater<T>> min_heap;
        min_heap.emplace(0, src, K + 1);
        while (!min_heap.empty()) {
            int result, u, k;
            tie(result, u, k) = min_heap.top(); min_heap.pop();
            if (u == dst) {
                return result;
            }
            if (k > 0) {
                for (const auto& kvp : adj[u]) {
                    int v, w;
                    tie(v, w) = kvp;
                    min_heap.emplace(result + w, v, k - 1);
                }
            }
        }
        return -1;
    }
};
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Barrett Adair

Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

HEADER GUARDS INTENTIONALLY OMITTED
DO NOT INCLUDE THIS HEADER DIRECTLY

*/

template<typename T, typename Return, typename... Args>
struct set_varargs_member_function_qualifiers_t <
    flag_map<int BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::value,
    false, // IsTransactionSafe
    false, // IsNoexcept
    BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...> {

    using type =
        Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS;
};

template<typename T, typename Return, typename... Args>
struct set_varargs_member_function_qualifiers_t <
    flag_map<int BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::value,
    false,
    true,
    BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...> {

    using type =
        Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER;
};

template<typename T, typename Return, typename... Args>
struct set_varargs_member_function_qualifiers_t <
    flag_map<int BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::value,
    true,
    false,
    BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...> {

    using type =
        Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...)
            BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
            BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER;
};

template<typename T, typename Return, typename... Args>
struct set_varargs_member_function_qualifiers_t <
    flag_map<int BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::value,
    true,
    true,
    BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...> {

    using type =
        Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...)
            BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
            BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER
            BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER;
};

#define BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE std::false_type
#include <boost/callable_traits/detail/unguarded/pmf_varargs_3.hpp>

#undef BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#undef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE

#ifdef BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE

#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE std::true_type
#define BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE transaction_safe
#include <boost/callable_traits/detail/unguarded/pmf_varargs_3.hpp>
#endif

#undef BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#undef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE
<commit_msg>Delete pmf_varargs_2.hpp<commit_after><|endoftext|>


<commit_before>/* Cycript - Optimizing JavaScript Compiler/Runtime
 * Copyright (C) 2009-2013  Jay Freeman (saurik)
*/

/* GNU General Public License, Version 3 {{{ */
/*
 * Cycript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Cycript is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cycript.  If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */

#include <dlfcn.h>
#include <mach/mach.h>

#include <mach/machine/thread_status.h>

#include <cstdio>
#include <pthread.h>
#include <unistd.h>

#include "Baton.hpp"
#include "Exception.hpp"
#include "Pooling.hpp"
#include "Trampoline.t.hpp"

extern "C" void __pthread_set_self(pthread_t);

void InjectLibrary(pid_t pid) {
    const char *library(CY_LIBRARY);

    static const size_t Stack_(8 * 1024);
    size_t length(strlen(library) + 1), depth(sizeof(Baton) + length);
    depth = (depth + sizeof(uintptr_t) + 1) / sizeof(uintptr_t) * sizeof(uintptr_t);

    CYPool pool;
    uint8_t *local(pool.malloc<uint8_t>(depth));
    Baton *baton(reinterpret_cast<Baton *>(local));

    baton->__pthread_set_self = &__pthread_set_self;
    baton->pthread_create = &pthread_create;

    baton->mach_thread_self = &mach_thread_self;
    baton->thread_terminate = &thread_terminate;

    baton->dlerror = &dlerror;
    baton->dlsym = &dlsym;

    baton->pid = getpid();
    memcpy(baton->library, library, length);

    vm_size_t size(depth + Stack_);

    mach_port_t self(mach_task_self()), task;
    _krncall(task_for_pid(self, pid, &task));

    vm_address_t stack;
    _krncall(vm_allocate(task, &stack, size, true));
    vm_address_t data(stack + Stack_);

    _krncall(vm_write(task, data, reinterpret_cast<vm_address_t>(baton), depth));

    thread_act_t thread;
    _krncall(thread_create(task, &thread));

    thread_state_flavor_t flavor;
    mach_msg_type_number_t count;

#if defined (__i386__) || defined(__x86_64__)
    x86_thread_state_t state;
    flavor = x86_THREAD_STATE;
    count = x86_THREAD_STATE_COUNT;
#elif defined(__arm__)
    arm_thread_state_t state;
    flavor = ARM_THREAD_STATE;
    count = ARM_THREAD_STATE_COUNT;
#else
    #error XXX: implement
#endif

    memset(&state, 0, sizeof(state));
    mach_msg_type_number_t read(count);
    _krncall(thread_get_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), &read));
    _assert(read == count);

    Trampoline *trampoline;
    size_t push;

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            trampoline = &Trampoline_i386_;
            push = 5;
            break;
        case x86_THREAD_STATE64:
            trampoline = &Trampoline_x86_64_;
            push = 2;
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__)
    trampoline = &Trampoline_armv6_;
    push = 0;
#else
    #error XXX: implement
#endif

    vm_address_t code;
    _krncall(vm_allocate(task, &code, trampoline->size_, true));
    _krncall(vm_write(task, code, reinterpret_cast<vm_address_t>(trampoline->data_), trampoline->size_));
    _krncall(vm_protect(task, code, trampoline->size_, false, VM_PROT_READ | VM_PROT_EXECUTE));

    uint32_t frame[push];
    if (sizeof(frame) != 0)
        memset(frame, 0, sizeof(frame));

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            frame[1] = data;
            state.uts.ts32.__eip = code + trampoline->entry_;
            state.uts.ts32.__esp = stack + Stack_ - sizeof(frame);
            break;
        case x86_THREAD_STATE64:
            state.uts.ts64.__rdi = data;
            state.uts.ts64.__rip = code + trampoline->entry_;
            state.uts.ts64.__rsp = stack + Stack_ - sizeof(frame);
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__)
    state.__r[0] = data;
    state.__sp = stack + Stack_;
    state.__pc = code + trampoline->entry_;

    if ((state.__pc & 0x1) != 0) {
        state.__pc &= ~0x1;
        state.__cpsr |= 0x20;
    }
#else
    #error XXX: implement
#endif

    if (sizeof(frame) != 0)
        _krncall(vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast<vm_address_t>(frame), sizeof(frame)));

    _krncall(thread_set_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), count));
    _krncall(thread_resume(thread));

    _krncall(mach_port_deallocate(self, task));
}
<commit_msg>Make the ARM thread setup code match i386/x86_64.<commit_after>/* Cycript - Optimizing JavaScript Compiler/Runtime
 * Copyright (C) 2009-2013  Jay Freeman (saurik)
*/

/* GNU General Public License, Version 3 {{{ */
/*
 * Cycript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Cycript is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cycript.  If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */

#include <dlfcn.h>
#include <mach/mach.h>

#include <mach/machine/thread_status.h>

#include <cstdio>
#include <pthread.h>
#include <unistd.h>

#include "Baton.hpp"
#include "Exception.hpp"
#include "Pooling.hpp"
#include "Trampoline.t.hpp"

extern "C" void __pthread_set_self(pthread_t);

void InjectLibrary(pid_t pid) {
    const char *library(CY_LIBRARY);

    static const size_t Stack_(8 * 1024);
    size_t length(strlen(library) + 1), depth(sizeof(Baton) + length);
    depth = (depth + sizeof(uintptr_t) + 1) / sizeof(uintptr_t) * sizeof(uintptr_t);

    CYPool pool;
    uint8_t *local(pool.malloc<uint8_t>(depth));
    Baton *baton(reinterpret_cast<Baton *>(local));

    baton->__pthread_set_self = &__pthread_set_self;
    baton->pthread_create = &pthread_create;

    baton->mach_thread_self = &mach_thread_self;
    baton->thread_terminate = &thread_terminate;

    baton->dlerror = &dlerror;
    baton->dlsym = &dlsym;

    baton->pid = getpid();
    memcpy(baton->library, library, length);

    vm_size_t size(depth + Stack_);

    mach_port_t self(mach_task_self()), task;
    _krncall(task_for_pid(self, pid, &task));

    vm_address_t stack;
    _krncall(vm_allocate(task, &stack, size, true));
    vm_address_t data(stack + Stack_);

    _krncall(vm_write(task, data, reinterpret_cast<vm_address_t>(baton), depth));

    thread_act_t thread;
    _krncall(thread_create(task, &thread));

    thread_state_flavor_t flavor;
    mach_msg_type_number_t count;

#if defined (__i386__) || defined(__x86_64__)
    x86_thread_state_t state;
    flavor = x86_THREAD_STATE;
    count = x86_THREAD_STATE_COUNT;
#elif defined(__arm__)
    arm_thread_state_t state;
    flavor = ARM_THREAD_STATE;
    count = ARM_THREAD_STATE_COUNT;
#else
    #error XXX: implement
#endif

    memset(&state, 0, sizeof(state));
    mach_msg_type_number_t read(count);
    _krncall(thread_get_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), &read));
    _assert(read == count);

    Trampoline *trampoline;
    size_t push;

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            trampoline = &Trampoline_i386_;
            push = 5;
            break;
        case x86_THREAD_STATE64:
            trampoline = &Trampoline_x86_64_;
            push = 2;
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__)
    trampoline = &Trampoline_armv6_;
    push = 0;
#else
    #error XXX: implement
#endif

    vm_address_t code;
    _krncall(vm_allocate(task, &code, trampoline->size_, true));
    _krncall(vm_write(task, code, reinterpret_cast<vm_address_t>(trampoline->data_), trampoline->size_));
    _krncall(vm_protect(task, code, trampoline->size_, false, VM_PROT_READ | VM_PROT_EXECUTE));

    uint32_t frame[push];
    if (sizeof(frame) != 0)
        memset(frame, 0, sizeof(frame));

#if defined(__i386__) || defined(__x86_64__)
    switch (state.tsh.flavor) {
        case i386_THREAD_STATE:
            frame[1] = data;
            state.uts.ts32.__eip = code + trampoline->entry_;
            state.uts.ts32.__esp = stack + Stack_ - sizeof(frame);
            break;
        case x86_THREAD_STATE64:
            state.uts.ts64.__rdi = data;
            state.uts.ts64.__rip = code + trampoline->entry_;
            state.uts.ts64.__rsp = stack + Stack_ - sizeof(frame);
            break;
        default:
            _assert(false);
    }
#elif defined(__arm__)
    state.__r[0] = data;
    state.__pc = code + trampoline->entry_;
    state.__sp = stack + Stack_ - sizeof(frame);

    if ((state.__pc & 0x1) != 0) {
        state.__pc &= ~0x1;
        state.__cpsr |= 0x20;
    }
#else
    #error XXX: implement
#endif

    if (sizeof(frame) != 0)
        _krncall(vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast<vm_address_t>(frame), sizeof(frame)));

    _krncall(thread_set_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), count));
    _krncall(thread_resume(thread));

    _krncall(mach_port_deallocate(self, task));
}
<|endoftext|>


<commit_before>/**
 *  @file FalloffFactory.cpp
 */

/*  $Author$
 *  $Date$
 *  $Revision$
 */

// Copyright 2001  California Institute of Technology

#ifdef WIN32
#pragma warning(disable:4786)
#pragma warning(disable:4503)
#endif

#include <math.h>

#include "FalloffFactory.h"
#include "ctexceptions.h"

namespace Cantera {

  FalloffFactory* FalloffFactory::s_factory = 0;
#if defined(THREAD_SAFE_CANTERA)
  boost::mutex FalloffFactory::falloff_mutex ;
#endif

  //! The 3-parameter Troe falloff parameterization.
  /*!
   * This parameterization is
   * defined by
   * \f[ F = F_{cent}^{1/(1 + f_1^2)} \f]
   * where
   * \f[ F_{cent} = (1 - A)\exp(-T/T_3) + A \exp(-T/T_1) \f]
   * \f[ f_1 = (\log_{10} P_r + C) / \left(N - 0.14
   * (\log_{10} P_r + C)\right) \f]
   * \f[ C = -0.4 - 0.67 \log_{10} F_{cent} \f]
   * \f[ N = 0.75 - 1.27 \log_{10} F_{cent} \f]
   *
   *  There are a few requirements for the parameters
   *
   *   T_3 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   *   T_1 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   * @ingroup falloffGroup
   */
  class Troe3 : public Falloff {
  public:

    /// Default constructor.
    Troe3() : m_a (0.0), m_rt3 (0.0), m_rt1 (0.0) {}

    // Destructor. Does nothing.
    virtual ~Troe3() {}

    /**
     * Initialize.
     * @param c Coefficient vector of length 3,
     * with entries \f$ (A, T_3, T_1) \f$
     */
    virtual void init(const vector_fp& c) {
      m_a  = c[0];

      if (c[1] <= 0.0) {
	if (c[1] == 0.0) {
	  m_rt3 = 1000.;
	} else {
	  throw CanteraError("Troe3::init()", "T3 parameter is less than zero");
	}
      } else {
	m_rt3 = 1.0/c[1];
      }
      if (c[2] <= 0.0) {
	if (c[2] == 0.0) {
	  m_rt1 = 1000.;
	} else {
	  throw CanteraError("Troe3::init()", "T1 parameter is less than zero");
	}
      } else {
	m_rt1 = 1.0/c[2];
      }
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      doublereal Fcent = (1.0 - m_a) * exp(- T * m_rt3 )
	+ m_a * exp(- T * m_rt1 );
      *work = log10( fmaxx( Fcent, SmallNumber ) );
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr,f1,lgf, cc, nn;
      lpr = log10( fmaxx(pr,SmallNumber) );
      cc = -0.4 - 0.67 * (*work);
      nn = 0.75 - 1.27 * (*work);
      f1 = ( lpr + cc )/ ( nn - 0.14 * ( lpr + cc ) );
      lgf = (*work) / ( 1.0 + f1 * f1 );
      return pow(10.0, lgf );
    }

    virtual size_t workSize() { return 1; }

  protected:

    doublereal m_a, m_rt3, m_rt1;

  private:

  };

  //! The 4-parameter Troe falloff parameterization.
  /*!
   * This parameterization is defined by
   *
   * \f[ F = F_{cent}^{1/(1 + f_1^2)} \f]
   * where
   * \f[ F_{cent} = (1 - A)\exp(-T/T_3) + A \exp(-T/T_1) + \exp(-T_2/T) \f]
   * \f[ f_1 = (\log_{10} P_r + C) / \left(N - 0.14
   * (\log_{10} P_r + C)\right) \f]
   * \f[ C = -0.4 - 0.67 \log_{10} F_{cent} \f]
   * \f[ N = 0.75 - 1.27 \log_{10} F_{cent} \f]
   *
   *
   *  There are a few requirements for the parameters
   *
   *   T_3 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   *   T_1 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   *   T_2 is required to be greater than  zero.
   *
   * @ingroup falloffGroup
   */
  class Troe4 : public Falloff {
  public:

    Troe4() : m_a (0.0), m_rt3 (0.0), m_rt1 (0.0),
	      m_t2 (0.0) {}
    virtual ~Troe4() {}

    virtual void init(const vector_fp& c) {
      m_a  = c[0];
      if (c[1] <= 0.0) {
	if (c[1] == 0.0) {
	  m_rt3 = 1000.;
	} else {
	  throw CanteraError("Troe4::init()", "T3 parameter is less than zero");
	}
      } else {
	m_rt3 = 1.0/c[1];
      }
      if (c[2] <= 0.0) {
	if (c[2] == 0.0) {
	  m_rt1 = 1000.;
	} else {
	  throw CanteraError("Troe4::init()", "T1 parameter is less than zero");
	}
      } else {
	m_rt1 = 1.0/c[2];
      }
      if (c[3] < 0.0) {
	throw CanteraError("Troe4::init()", "T2 parameter is less than zero");
      }
      m_t2 = c[3];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      doublereal Fcent = (1.0 - m_a) * exp(- T * m_rt3 )
	+ m_a * exp(- T * m_rt1 )
	+ exp(- m_t2 / T );
      *work = log10( fmaxx( Fcent, SmallNumber ) );
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr,f1,lgf, cc, nn;
      lpr = log10( fmaxx(pr,SmallNumber) );
      cc = -0.4 - 0.67 * (*work);
      nn = 0.75 - 1.27 * (*work);
      f1 = ( lpr + cc )/ ( nn - 0.14 * ( lpr + cc ) );
      lgf = (*work) / ( 1.0 + f1 * f1 );
      return pow(10.0, lgf );
    }

    virtual size_t workSize() { return 1; }

  protected:

    doublereal m_a, m_rt3, m_rt1;
    doublereal m_t2;

  private:
  };

  /**
   * The 3-parameter SRI falloff function.
   *
   *
   *   m_c is required to greater than or equal to zero. If it is zero,
   *   then the corresponding term is set to zero.
   *
   * @ingroup falloffGroup
   */
  class SRI3 : public Falloff {

  public:

    SRI3() {}
    virtual ~SRI3() {}

    virtual void init(const vector_fp& c) {
      m_a = c[0];
      m_b = c[1];

      m_c = c[2];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      *work = m_a * exp( - m_b / T);
      if (m_c != 0.0) *work += exp( - T/m_c );
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr = log10( fmaxx(pr,SmallNumber) );
      doublereal xx = 1.0/(1.0 + lpr*lpr);
      doublereal ff = pow( *work , xx);
      return ff;
    }

    virtual size_t workSize() { return 1; }

  protected:
    doublereal m_a, m_b, m_c;

  private:

  };

  /**
   * The 5-parameter SRI falloff function.
   *
   *
   *   m_c is required to greater than or equal to zero. If it is zero,
   *   then the corresponding term is set to zero.
   *
   *   m_d is required to be greater than zero.
   *
   * @ingroup falloffGroup
   */
  class SRI5 : public Falloff {

  public:
    SRI5() {}
    virtual ~SRI5() {}
    virtual void init(const vector_fp& c) {
      m_a = c[0];
      m_b = c[1];
      m_c = c[2];
      m_d = c[3];
      m_e = c[4];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      *work = m_a * exp( - m_b / T);
      if (m_c != 0.0) *work += exp( - T/m_c );
      work[1] = m_d * pow(T,m_e);
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr = log10( fmaxx(pr,SmallNumber) );
      doublereal xx = 1.0/(1.0 + lpr*lpr);
      return pow( *work, xx) * work[1];
    }

    virtual size_t workSize() { return 2; }

  protected:

    doublereal m_a, m_b, m_c;
    doublereal m_d, m_e;

  private:

  };

  /**
   * Wang-Frenklach falloff function.  Reference: Wang, H., and
   * Frenklach, M., Chem. Phys. Lett. vol. 205, 271 (1993).
   */
  class WF93 : public Falloff {

  public:
    WF93() {}
    virtual ~WF93() {}

    virtual void init(const vector_fp& c) {
      m_a = c[0];
      m_rt1 = 1.0/c[1];
      m_t2 = c[2];
      m_rt3  = 1.0/c[3];
      m_alpha0 = c[4];
      m_alpha1 = c[5];
      m_alpha2 = c[6];
      m_sigma0 = c[7];
      m_sigma1 = c[8];
      m_sigma2 = c[9];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      work[0] = m_alpha0 + (m_alpha1 + m_alpha2*T)*T; // alpha
      work[1] = m_sigma0 + (m_sigma1 + m_sigma2*T)*T; // sigma
      doublereal Fcent = (1.0 - m_a) * exp(- T * m_rt3 )
	+ m_a * exp(- T * m_rt1 ) + exp(-m_t2/T);
      work[2] = log10(Fcent);
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr = log10( fmaxx(pr, SmallNumber) );
      doublereal x = (lpr - work[0])/work[1];
      doublereal flog = work[2]/exp(x*x);
      return pow( 10.0, flog);
    }

    virtual size_t workSize() { return 3; }

  protected:
    //! Value of the \f$ \alpha_0 coefficient
    /*!
     *  This is the fifth coefficient in the xml list
     */
    doublereal m_alpha0;
    doublereal m_alpha1, m_alpha2;
    doublereal m_sigma0, m_sigma1, m_sigma2;
    doublereal m_a, m_rt1, m_t2, m_rt3;

  private:

  };

  Falloff* FalloffFactory::newFalloff(int type, const vector_fp& c) {
    Falloff* f;
    switch(type) {
    case TROE3_FALLOFF:
      f = new Troe3(); break;
    case TROE4_FALLOFF:
      f = new Troe4(); break;
    case SRI3_FALLOFF:
      f = new SRI3(); break;
    case SRI5_FALLOFF:
      f = new SRI5(); break;
    case WF_FALLOFF:
      f = new WF93(); break;
    default: return 0;
    }
    f->init(c);
    return f;
  }

}

<commit_msg>doxygen update<commit_after>/**
 *  @file FalloffFactory.cpp
 */

/*  $Author$
 *  $Date$
 *  $Revision$
 */

// Copyright 2001  California Institute of Technology

#ifdef WIN32
#pragma warning(disable:4786)
#pragma warning(disable:4503)
#endif

#include "FalloffFactory.h"
#include "ctexceptions.h"

#include <math.h>

namespace Cantera {

  FalloffFactory* FalloffFactory::s_factory = 0;
#if defined(THREAD_SAFE_CANTERA)
  boost::mutex FalloffFactory::falloff_mutex ;
#endif

  //! The 3-parameter Troe falloff parameterization.
  /*!
   * This parameterization is
   * defined by
   * \f[ F = F_{cent}^{1/(1 + f_1^2)} \f]
   * where
   * \f[ F_{cent} = (1 - A)\exp(-T/T_3) + A \exp(-T/T_1) \f]
   * \f[ f_1 = (\log_{10} P_r + C) / \left(N - 0.14
   * (\log_{10} P_r + C)\right) \f]
   * \f[ C = -0.4 - 0.67 \log_{10} F_{cent} \f]
   * \f[ N = 0.75 - 1.27 \log_{10} F_{cent} \f]
   *
   *  There are a few requirements for the parameters
   *
   *   T_3 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   *   T_1 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   * @ingroup falloffGroup
   */
  class Troe3 : public Falloff {
  public:

    /// Default constructor.
    Troe3() : m_a (0.0), m_rt3 (0.0), m_rt1 (0.0) {}

    // Destructor. Does nothing.
    virtual ~Troe3() {}

    /**
     * Initialize.
     * @param c Coefficient vector of length 3,
     * with entries \f$ (A, T_3, T_1) \f$
     */
    virtual void init(const vector_fp& c) {
      m_a  = c[0];

      if (c[1] <= 0.0) {
	if (c[1] == 0.0) {
	  m_rt3 = 1000.;
	} else {
	  throw CanteraError("Troe3::init()", "T3 parameter is less than zero");
	}
      } else {
	m_rt3 = 1.0/c[1];
      }
      if (c[2] <= 0.0) {
	if (c[2] == 0.0) {
	  m_rt1 = 1000.;
	} else {
	  throw CanteraError("Troe3::init()", "T1 parameter is less than zero");
	}
      } else {
	m_rt1 = 1.0/c[2];
      }
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      doublereal Fcent = (1.0 - m_a) * exp(- T * m_rt3 )
	+ m_a * exp(- T * m_rt1 );
      *work = log10( fmaxx( Fcent, SmallNumber ) );
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr,f1,lgf, cc, nn;
      lpr = log10( fmaxx(pr,SmallNumber) );
      cc = -0.4 - 0.67 * (*work);
      nn = 0.75 - 1.27 * (*work);
      f1 = ( lpr + cc )/ ( nn - 0.14 * ( lpr + cc ) );
      lgf = (*work) / ( 1.0 + f1 * f1 );
      return pow(10.0, lgf );
    }

    virtual size_t workSize() { return 1; }

  protected:

    doublereal m_a, m_rt3, m_rt1;

  private:

  };

  //! The 4-parameter Troe falloff parameterization.
  /*!
   * This parameterization is defined by
   *
   * \f[ F = F_{cent}^{1/(1 + f_1^2)} \f]
   * where
   * \f[ F_{cent} = (1 - A)\exp(-T/T_3) + A \exp(-T/T_1) + \exp(-T_2/T) \f]
   * \f[ f_1 = (\log_{10} P_r + C) / \left(N - 0.14
   * (\log_{10} P_r + C)\right) \f]
   * \f[ C = -0.4 - 0.67 \log_{10} F_{cent} \f]
   * \f[ N = 0.75 - 1.27 \log_{10} F_{cent} \f]
   *
   *
   *  There are a few requirements for the parameters
   *
   *   T_3 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   *   T_1 is required to greater than or equal to zero. If it is zero,
   *   then the term is set to zero.
   *
   *   T_2 is required to be greater than  zero.
   *
   * @ingroup falloffGroup
   */
  class Troe4 : public Falloff {
  public:

    Troe4() : m_a (0.0), m_rt3 (0.0), m_rt1 (0.0),
	      m_t2 (0.0) {}
    virtual ~Troe4() {}

    virtual void init(const vector_fp& c) {
      m_a  = c[0];
      if (c[1] <= 0.0) {
	if (c[1] == 0.0) {
	  m_rt3 = 1000.;
	} else {
	  throw CanteraError("Troe4::init()", "T3 parameter is less than zero");
	}
      } else {
	m_rt3 = 1.0/c[1];
      }
      if (c[2] <= 0.0) {
	if (c[2] == 0.0) {
	  m_rt1 = 1000.;
	} else {
	  throw CanteraError("Troe4::init()", "T1 parameter is less than zero");
	}
      } else {
	m_rt1 = 1.0/c[2];
      }
      if (c[3] < 0.0) {
	throw CanteraError("Troe4::init()", "T2 parameter is less than zero");
      }
      m_t2 = c[3];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      doublereal Fcent = (1.0 - m_a) * exp(- T * m_rt3 )
	+ m_a * exp(- T * m_rt1 )
	+ exp(- m_t2 / T );
      *work = log10( fmaxx( Fcent, SmallNumber ) );
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr,f1,lgf, cc, nn;
      lpr = log10( fmaxx(pr,SmallNumber) );
      cc = -0.4 - 0.67 * (*work);
      nn = 0.75 - 1.27 * (*work);
      f1 = ( lpr + cc )/ ( nn - 0.14 * ( lpr + cc ) );
      lgf = (*work) / ( 1.0 + f1 * f1 );
      return pow(10.0, lgf );
    }

    virtual size_t workSize() { return 1; }

  protected:

    doublereal m_a, m_rt3, m_rt1;
    doublereal m_t2;

  private:
  };

  /**
   * The 3-parameter SRI falloff function.
   *
   *
   *   m_c is required to greater than or equal to zero. If it is zero,
   *   then the corresponding term is set to zero.
   *
   * @ingroup falloffGroup
   */
  class SRI3 : public Falloff {

  public:

    SRI3() {}
    virtual ~SRI3() {}

    virtual void init(const vector_fp& c) {
      m_a = c[0];
      m_b = c[1];

      m_c = c[2];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      *work = m_a * exp( - m_b / T);
      if (m_c != 0.0) *work += exp( - T/m_c );
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr = log10( fmaxx(pr,SmallNumber) );
      doublereal xx = 1.0/(1.0 + lpr*lpr);
      doublereal ff = pow( *work , xx);
      return ff;
    }

    virtual size_t workSize() { return 1; }

  protected:
    doublereal m_a, m_b, m_c;

  private:

  };

  /**
   * The 5-parameter SRI falloff function.
   *
   *
   *   m_c is required to greater than or equal to zero. If it is zero,
   *   then the corresponding term is set to zero.
   *
   *   m_d is required to be greater than zero.
   *
   * @ingroup falloffGroup
   */
  class SRI5 : public Falloff {

  public:
    SRI5() {}
    virtual ~SRI5() {}
    virtual void init(const vector_fp& c) {
      m_a = c[0];
      m_b = c[1];
      m_c = c[2];
      m_d = c[3];
      m_e = c[4];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      *work = m_a * exp( - m_b / T);
      if (m_c != 0.0) *work += exp( - T/m_c );
      work[1] = m_d * pow(T,m_e);
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr = log10( fmaxx(pr,SmallNumber) );
      doublereal xx = 1.0/(1.0 + lpr*lpr);
      return pow( *work, xx) * work[1];
    }

    virtual size_t workSize() { return 2; }

  protected:

    doublereal m_a, m_b, m_c;
    doublereal m_d, m_e;

  private:

  };

  //! Wang-Frenklach falloff function.
  /*!
   *
   * Reference: Wang, H., and
   *            Frenklach, M., Chem. Phys. Lett. vol. 205, 271 (1993).
   *
   *
   * @ingroup falloffGroup
   */
  class WF93 : public Falloff {

  public:

    //! Default constructpr
    WF93() {}

    //! Destructor
    virtual ~WF93() {}

    //! Initialization routine
    /*!
     *  @param c  Vector of 10 doubles
     */
    virtual void init(const vector_fp& c) {
      m_a = c[0];
      m_rt1 = 1.0/c[1];
      m_t2 = c[2];
      m_rt3  = 1.0/c[3];
      m_alpha0 = c[4];
      m_alpha1 = c[5];
      m_alpha2 = c[6];
      m_sigma0 = c[7];
      m_sigma1 = c[8];
      m_sigma2 = c[9];
    }

    virtual void updateTemp(doublereal T, workPtr work) const {
      work[0] = m_alpha0 + (m_alpha1 + m_alpha2*T)*T; // alpha
      work[1] = m_sigma0 + (m_sigma1 + m_sigma2*T)*T; // sigma
      doublereal Fcent = (1.0 - m_a) * exp(- T * m_rt3 )
	+ m_a * exp(- T * m_rt1 ) + exp(-m_t2/T);
      work[2] = log10(Fcent);
    }

    virtual doublereal F(doublereal pr, const_workPtr work) const {
      doublereal lpr = log10( fmaxx(pr, SmallNumber) );
      doublereal x = (lpr - work[0])/work[1];
      doublereal flog = work[2]/exp(x*x);
      return pow( 10.0, flog);
    }

    virtual size_t workSize() { return 3; }

  protected:

    //! Value of the \f$ \alpha_0 \f$ coefficient
    /*!
     *  This is the fifth coefficient in the xml list
     */
    doublereal m_alpha0;

    //! Value of the \f$ \alpha_1 \f$ coefficient
    /*!
     *  This is the 6th coefficient in the xml list
     */
    doublereal m_alpha1;

    //! Value of the \f$ \alpha_2 \f$ coefficient
    /*!
     *  This is the 7th coefficient in the xml list
     */
    doublereal m_alpha2;

    //! Value of the \f$ \sigma_0 \f$ coefficient
    /*!
     *  This is the 8th coefficient in the xml list
     */
    doublereal m_sigma0;

    //! Value of the \f$ \sigma_1 \f$ coefficient
    /*!
     *  This is the 9th coefficient in the xml list
     */
    doublereal m_sigma1;

    //! Value of the \f$ \sigma_2 \f$ coefficient
    /*!
     *  This is the 10th coefficient in the xml list
     */
    doublereal m_sigma2;

    //! Value of the \f$ a \f$ coefficient
    /*!
     *  This is the first coefficient in the xml list
     */
    doublereal m_a;

    //! Value of inverse of the \f$ t1 \f$ coefficient
    /*!
     *  This is the second coefficient in the xml list
     */
    doublereal m_rt1;

    //! Value of the \f$ t2 \f$ coefficient
    /*!
     *  This is the third coefficient in the xml list
     */
    doublereal m_t2;

    //! Value of the inverse of the  \f$ t3 \f$ coefficient
    /*!
     *  This is the 4th coefficient in the xml list
     */
    doublereal m_rt3;

  private:

  };

  Falloff* FalloffFactory::newFalloff(int type, const vector_fp& c) {
    Falloff* f;
    switch(type) {
    case TROE3_FALLOFF:
      f = new Troe3(); break;
    case TROE4_FALLOFF:
      f = new Troe4(); break;
    case SRI3_FALLOFF:
      f = new SRI3(); break;
    case SRI5_FALLOFF:
      f = new SRI5(); break;
    case WF_FALLOFF:
      f = new WF93(); break;
    default: return 0;
    }
    f->init(c);
    return f;
  }

}

<|endoftext|>


<commit_before>#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "optimizations.h"
#include "stmt.h"
#include "view.h"

void
reachingDefinitionsAnalysis(FnSymbol* fn,
                            Vec<SymExpr*>& defs,
                            Map<SymExpr*,int>& defMap,
                            Vec<SymExpr*>& useSet,
                            Vec<SymExpr*>& defSet,
                            Vec<Vec<bool>*>& IN) {
  Vec<Symbol*> locals;
  Map<Symbol*,int> localMap;
  buildLocalsVectorMap(fn, locals, localMap);
  buildDefUseSets(locals, fn, defSet, useSet);

//   Vec<SymExpr*> ndefs;
//   Map<SymExpr*,int> ndefMap;

//   buildDefsVectorMap(locals, ndefs, ndefMap);

  int i = 0;
  forv_Vec(Symbol, sym, locals) {
    forv_Vec(SymExpr, se, defSet) {
      if (se && se->var == sym) {
        defs.add(se);
        defMap.put(se, i++);
      }
    }
  }

//   bool dd = false;

//   if (ndefs.n != defs.n) {
//     dd = true;
//   } else {
//     forv_Vec(SymExpr, nse, ndefs) {
//       bool good = false;
//       forv_Vec(SymExpr, se, defs) {
//         if (se == nse) {
//           good = true;
//           break;
//         }
//       }
//       if (!good) {
//         dd = true;
//         break;
//       }
//     }

//     forv_Vec(SymExpr, se, defs) {
//       bool good = false;
//       forv_Vec(SymExpr, nse, ndefs) {
//         if (se == nse) {
//           good = true;
//           break;
//         }
//       }
//       if (!good) {
//         dd = true;
//         break;
//       }
//     }
//   }

//   if (dd) {
//     printf("difference detected\n");
//     printf("old:\n");
//     forv_Vec(SymExpr, se, defs) {
//       printf("%s[%d]\n", se->var->name, se->var->id);
//     }
//     printf("new:\n");
//     forv_Vec(SymExpr, se, ndefs) {
//       printf("%s[%d]\n", se->var->name, se->var->id);
//     }
//   }

  Vec<Vec<bool>*> KILL;
  Vec<Vec<bool>*> GEN;
  Vec<Vec<bool>*> OUT;

  forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
    Vec<Symbol*> bbDefSet;
    Vec<bool>* kill = new Vec<bool>();
    Vec<bool>* gen = new Vec<bool>();
    Vec<bool>* in = new Vec<bool>();
    Vec<bool>* out = new Vec<bool>();
    forv_Vec(SymExpr, def, defs) {
      gen->add(false);
      in->add(false);
      out->add(false);
    }
    for (int i = bb->exprs.n-1; i >= 0; i--) {
      Expr* expr = bb->exprs.v[i];
      Vec<BaseAST*> asts;
      collect_asts(&asts, expr);
      forv_Vec(BaseAST, ast, asts) {
        if (SymExpr* se = toSymExpr(ast)) {
          if (defSet.set_in(se)) {
            if (!bbDefSet.set_in(se->var))
              gen->v[defMap.get(se)] = true;
            bbDefSet.set_add(se->var);
          }
        }
      }
    }
    forv_Vec(SymExpr, def, defs) {
      kill->add((bbDefSet.set_in(def->var)) ? true : false);
    }
    KILL.add(kill);
    GEN.add(gen);
    IN.add(in);
    OUT.add(out);
  }

#ifdef DEBUG_REACHING
  list_view(fn);
  printBasicBlocks(fn);
  printDefsVector(defs, defMap);
  printf("KILL:\n"); printBitVectorSets(KILL);
  printf("GEN:\n"); printBitVectorSets(GEN);
  printf("IN:\n"); printBitVectorSets(IN);
  printf("OUT:\n"); printBitVectorSets(OUT);
#endif

  forwardFlowAnalysis(fn, GEN, KILL, IN, OUT, false);

#ifdef DEBUG_REACHING
  printf("IN:\n"); printBitVectorSets(IN);
  printf("OUT:\n"); printBitVectorSets(OUT);
#endif

  forv_Vec(Vec<bool>, gen, GEN)
    delete gen;

  forv_Vec(Vec<bool>, kill, KILL)
    delete kill;

  forv_Vec(Vec<bool>, out, OUT)
    delete out;
}

void
buildDefUseChains(FnSymbol* fn,
                  Map<SymExpr*,Vec<SymExpr*>*>& DU,
                  Map<SymExpr*,Vec<SymExpr*>*>& UD) {
  buildBasicBlocks(fn);

  Vec<SymExpr*> defs;
  Map<SymExpr*,int> defMap;
  Vec<SymExpr*> useSet;
  Vec<SymExpr*> defSet;
  Vec<Vec<bool>*> IN;
  reachingDefinitionsAnalysis(fn, defs, defMap, useSet, defSet, IN);

  //
  // map from symbol to index into defs vector where defs of symbol
  // begin
  //
  Map<Symbol*,int> defsIndexMap;
  Symbol* last = 0;
  int i = 0;
  forv_Vec(SymExpr, se, defs) {
    if (se->var != last)
      defsIndexMap.put(se->var, i);
    last = se->var;
    i++;
  }

  forv_Vec(SymExpr, def, defs) {
    DU.put(def, new Vec<SymExpr*>());
  }

  for (int i = 0; i < fn->basicBlocks->n; i++) {
    BasicBlock* bb = fn->basicBlocks->v[i];
    Vec<bool>* in = IN.v[i];
    forv_Vec(Expr, expr, bb->exprs) {
      Vec<BaseAST*> asts;
      collect_asts(&asts, expr);
      forv_Vec(BaseAST, ast, asts) {
        if (SymExpr* se = toSymExpr(ast)) {
          if (useSet.set_in(se)) {
            UD.put(se, new Vec<SymExpr*>());
            for (int j = defsIndexMap.get(se->var); j < defs.n; j++) {
              if (defs.v[j]->var != se->var)
                break;
              if (in->v[j]) {
                DU.get(defs.v[j])->add(se);
                UD.get(se)->add(defs.v[j]);
              }
            }
          }
        }
      }
      forv_Vec(BaseAST, ast, asts) {
        if (SymExpr* se = toSymExpr(ast)) {
          if (defSet.set_in(se)) {
            for (int j = defsIndexMap.get(se->var); j < defs.n; j++) {
              if (defs.v[j]->var != se->var)
                break;
              if (defs.v[j] == se)
                in->v[j] = true;
              else
                in->v[j] = false;
            }
          }
        }
      }
    }
  }

  forv_Vec(Vec<bool>, in, IN)
    delete in;
}

void
freeDefUseChains(Map<SymExpr*,Vec<SymExpr*>*>& DU,
                 Map<SymExpr*,Vec<SymExpr*>*>& UD) {
  Vec<SymExpr*> keys;
  DU.get_keys(keys);
  forv_Vec(SymExpr, key, keys) {
    delete DU.get(key);
  }
  keys.clear();
  UD.get_keys(keys);
  forv_Vec(SymExpr, key, keys) {
    delete UD.get(key);
  }
}
<commit_msg>fixed performance slip of dead code elimination<commit_after>#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "optimizations.h"
#include "stmt.h"
#include "view.h"

void
reachingDefinitionsAnalysis(FnSymbol* fn,
                            Vec<SymExpr*>& defs,
                            Map<SymExpr*,int>& defMap,
                            Vec<SymExpr*>& useSet,
                            Vec<SymExpr*>& defSet,
                            Vec<Vec<bool>*>& IN) {
  Vec<Symbol*> locals;
  Map<Symbol*,int> localMap;
  buildLocalsVectorMap(fn, locals, localMap);
  buildDefUseSets(locals, fn, defSet, useSet);

  //
  // compute defs and defMap in an order such that defs of the same
  // variable are adjacent (this is important!); use localDefsMap to
  // make this linear; localDefsMap is like the defMap computed by
  // buildDefUseMaps, but is computed from the defSet in this more
  // efficient manner
  //
  Map<Symbol*,Vec<SymExpr*>*> localDefsMap;
  forv_Vec(Symbol, sym, locals) {
    localDefsMap.put(sym, new Vec<SymExpr*>());
  }
  forv_Vec(SymExpr, se, defSet) {
    if (se)
      localDefsMap.get(se->var)->add(se);
  }
  int i = 0;
  forv_Vec(Symbol, sym, locals) {
    Vec<SymExpr*>* symDefs = localDefsMap.get(sym);
    forv_Vec(SymExpr, se, *symDefs) {
      defs.add(se);
      defMap.put(se, i++);
    }
  }
  forv_Vec(Symbol, sym, locals) {
    delete localDefsMap.get(sym);
  }

  Vec<Vec<bool>*> KILL;
  Vec<Vec<bool>*> GEN;
  Vec<Vec<bool>*> OUT;

  forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
    Vec<Symbol*> bbDefSet;
    Vec<bool>* kill = new Vec<bool>();
    Vec<bool>* gen = new Vec<bool>();
    Vec<bool>* in = new Vec<bool>();
    Vec<bool>* out = new Vec<bool>();
    forv_Vec(SymExpr, def, defs) {
      gen->add(false);
      in->add(false);
      out->add(false);
    }
    for (int i = bb->exprs.n-1; i >= 0; i--) {
      Expr* expr = bb->exprs.v[i];
      Vec<BaseAST*> asts;
      collect_asts(&asts, expr);
      forv_Vec(BaseAST, ast, asts) {
        if (SymExpr* se = toSymExpr(ast)) {
          if (defSet.set_in(se)) {
            if (!bbDefSet.set_in(se->var))
              gen->v[defMap.get(se)] = true;
            bbDefSet.set_add(se->var);
          }
        }
      }
    }
    forv_Vec(SymExpr, def, defs) {
      kill->add((bbDefSet.set_in(def->var)) ? true : false);
    }
    KILL.add(kill);
    GEN.add(gen);
    IN.add(in);
    OUT.add(out);
  }

#ifdef DEBUG_REACHING
  list_view(fn);
  printBasicBlocks(fn);
  printDefsVector(defs, defMap);
  printf("KILL:\n"); printBitVectorSets(KILL);
  printf("GEN:\n"); printBitVectorSets(GEN);
  printf("IN:\n"); printBitVectorSets(IN);
  printf("OUT:\n"); printBitVectorSets(OUT);
#endif

  forwardFlowAnalysis(fn, GEN, KILL, IN, OUT, false);

#ifdef DEBUG_REACHING
  printf("IN:\n"); printBitVectorSets(IN);
  printf("OUT:\n"); printBitVectorSets(OUT);
#endif

  forv_Vec(Vec<bool>, gen, GEN)
    delete gen;

  forv_Vec(Vec<bool>, kill, KILL)
    delete kill;

  forv_Vec(Vec<bool>, out, OUT)
    delete out;
}

void
buildDefUseChains(FnSymbol* fn,
                  Map<SymExpr*,Vec<SymExpr*>*>& DU,
                  Map<SymExpr*,Vec<SymExpr*>*>& UD) {
  buildBasicBlocks(fn);

  Vec<SymExpr*> defs;
  Map<SymExpr*,int> defMap;
  Vec<SymExpr*> useSet;
  Vec<SymExpr*> defSet;
  Vec<Vec<bool>*> IN;
  reachingDefinitionsAnalysis(fn, defs, defMap, useSet, defSet, IN);

  //
  // map from symbol to index into defs vector where defs of symbol
  // begin
  //
  Map<Symbol*,int> defsIndexMap;
  Symbol* last = 0;
  int i = 0;
  forv_Vec(SymExpr, se, defs) {
    if (se->var != last)
      defsIndexMap.put(se->var, i);
    last = se->var;
    i++;
  }

  forv_Vec(SymExpr, def, defs) {
    DU.put(def, new Vec<SymExpr*>());
  }

  for (int i = 0; i < fn->basicBlocks->n; i++) {
    BasicBlock* bb = fn->basicBlocks->v[i];
    Vec<bool>* in = IN.v[i];
    forv_Vec(Expr, expr, bb->exprs) {
      Vec<BaseAST*> asts;
      collect_asts(&asts, expr);
      forv_Vec(BaseAST, ast, asts) {
        if (SymExpr* se = toSymExpr(ast)) {
          if (useSet.set_in(se)) {
            UD.put(se, new Vec<SymExpr*>());
            for (int j = defsIndexMap.get(se->var); j < defs.n; j++) {
              if (defs.v[j]->var != se->var)
                break;
              if (in->v[j]) {
                DU.get(defs.v[j])->add(se);
                UD.get(se)->add(defs.v[j]);
              }
            }
          }
        }
      }
      forv_Vec(BaseAST, ast, asts) {
        if (SymExpr* se = toSymExpr(ast)) {
          if (defSet.set_in(se)) {
            for (int j = defsIndexMap.get(se->var); j < defs.n; j++) {
              if (defs.v[j]->var != se->var)
                break;
              if (defs.v[j] == se)
                in->v[j] = true;
              else
                in->v[j] = false;
            }
          }
        }
      }
    }
  }

  forv_Vec(Vec<bool>, in, IN)
    delete in;
}

void
freeDefUseChains(Map<SymExpr*,Vec<SymExpr*>*>& DU,
                 Map<SymExpr*,Vec<SymExpr*>*>& UD) {
  Vec<SymExpr*> keys;
  DU.get_keys(keys);
  forv_Vec(SymExpr, key, keys) {
    delete DU.get(key);
  }
  keys.clear();
  UD.get_keys(keys);
  forv_Vec(SymExpr, key, keys) {
    delete UD.get(key);
  }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkArchetypeSeriesFileNames.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef _itkArchetypeSeriesFileNames_h
#define _itkArchetypeSeriesFileNames_h

#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

#include "itkArchetypeSeriesFileNames.h"
#include "itkRegularExpressionSeriesFileNames.h"
#include <itksys/SystemTools.hxx>
#include <stdio.h>
#include <algorithm>

namespace itk
{

ArchetypeSeriesFileNames
::ArchetypeSeriesFileNames() :
  m_Archetype("")
{
}

void
ArchetypeSeriesFileNames
::SetArchetype( const std::string &archetype )
{
  if (archetype != m_Archetype)
    {
    m_Archetype = archetype;
    this->Modified();
    m_ArchetypeMTime.Modified();
    }
}

ArchetypeSeriesFileNames::VectorSizeType
ArchetypeSeriesFileNames
::GetNumberOfGroupings()
{
  if (m_ScanTime < m_ArchetypeMTime)
    {
    this->Scan();
    }

  return m_Groupings.size();
}

const std::vector<std::string> &
ArchetypeSeriesFileNames
::GetFileNames( VectorSizeType group)
{
  if (m_ScanTime < m_ArchetypeMTime)
    {
    this->Scan();
    }

  if (group < m_Groupings.size())
    {
    m_FileNames = m_Groupings[group];
    }
  else
    {
    m_FileNames.clear();
    }

  return m_FileNames;
}

void
ArchetypeSeriesFileNames
::Scan()
{
  // For each group of contiguous numbers in m_Archetype, create a
  // regular expression that is identical to m_Archetype except that
  // it replaces that group of numbers with the pattern ([0-9]+).
  // Each of these new strings will then be passed into a
  // RegularExpressionSeriesFileNames to generate the list of those
  // files that fit that pattern.

  m_Groupings.clear();

  std::string unixArchetype = m_Archetype;
  itksys::SystemTools::ConvertToUnixSlashes(unixArchetype);

  if (itksys::SystemTools::FileIsDirectory( unixArchetype.c_str() ))
    {
    return;
    }

  // Parse the fileNameName and fileNamePath
  std::string origFileName = itksys::SystemTools::GetFilenameName( unixArchetype.c_str() );
  std::string fileNamePath = itksys::SystemTools::GetFilenamePath( unixArchetype.c_str() );
  std::string pathPrefix;

  // "Clean" the filename by escaping any special characters with backslashes.
  // This allows us to pass in filenames that include these special characters.
  std::string fileName;
  for( unsigned int j = 0; j < origFileName.length(); j++ )
    {
    char oneChar = origFileName[j];
    if( oneChar == '^' ||
        oneChar == '$' ||
        oneChar == '.' ||
        oneChar == '[' ||
        oneChar == ']' ||
        oneChar == '-' ||
        oneChar == '*' ||
        oneChar == '+' ||
        oneChar == '?' ||
        oneChar == '(' ||
        oneChar == ')' )
      {
      fileName += "\\";
      }
    fileName += oneChar;
    }

  // If there is no "/" in the name, the directory is not specified.
  // In that case, use the default ".".  This is necessary for the RegularExpressionSeriesFileNames.
  if (fileNamePath == "")
    {
    fileNamePath = ".";
    pathPrefix = "./";
    }
  else
    {
    pathPrefix = "";
    }

  StringVectorType regExpFileNameVector;
  std::string regExpString = "([0-9]+)";
  IntVectorType numGroupStart;
  IntVectorType numGroupLength;
  int sIndex;
  std::string::iterator sit;
  for (sit = fileName.begin(); sit < fileName.end(); sit++)
    {
    // If the element is a number, find its starting index and length.
    if ((*sit) >= '0' && (*sit) <= '9')
      {
      sIndex = sit - fileName.begin();
      numGroupStart.push_back( sIndex );

      // Loop to one past the end of the group of numbers.
      while ( sit != fileName.end() && (*sit) >= '0' && (*sit) <= '9' )
        {
        ++sit;
        }

      numGroupLength.push_back( (sit - fileName.begin()) - sIndex );
      }
    }

  // Create a set of regular expressions, one for each group of
  // numbers in m_FileName. We walk the regular expression groups
  // from right to left since numbers at the end of filenames are more
  // likely to be image numbers.
  // It is also necessary to walk backward so that the numGroupStart
  // indices remain correct since the length of numbers we are replacing may
  // be different from the length of regExpString.
  IntVectorType::reverse_iterator numGroupLengthItr = numGroupLength.rbegin();
  IntVectorType::reverse_iterator numGroupStartItr  = numGroupStart.rbegin();
  while( numGroupLengthItr != numGroupLength.rend() &&
         numGroupStartItr != numGroupStart.rend() )
    {
    std::string regExpFileName = fileName;

    regExpFileName.replace(*numGroupStartItr,*numGroupLengthItr,regExpString);
    // Include only filenames that exactly match this regular expression.  Don't
    // match filenames that have this string as a substring (ie. that have extra
    // prefixes or suffixes).
    regExpFileName = "^" + regExpFileName + "$";
    regExpFileNameVector.push_back( regExpFileName );
    ++numGroupLengthItr;
    ++numGroupStartItr;
    }

  // Use a RegularExpressionSeriesFileNames to find the files to return
  StringVectorType names;

  StringVectorType::const_iterator regExpFileNameVectorItr =
    regExpFileNameVector.begin();
  while( regExpFileNameVectorItr != regExpFileNameVector.end())
    {
    itk::RegularExpressionSeriesFileNames::Pointer fit = itk::RegularExpressionSeriesFileNames::New();
    fit->SetDirectory( fileNamePath.c_str() );
    fit->SetRegularExpression( regExpFileNameVectorItr->c_str() );
    fit->SetSubMatch(1);
    fit->NumericSortOn();
    names = fit->GetFileNames();

    std::vector<std::string>::iterator ait;
    ait = std::find(names.begin(), names.end(), pathPrefix + unixArchetype);

    // Accept the list if it contains the archetype and is not the
    // "trivial" list (containing only the archetype)
    if ( ait != names.end() && names.size() > 1)
      {
      m_Groupings.push_back(names);
      }
    ++regExpFileNameVectorItr;
    }

  // If the group list is empty, create a single group containing the
  // archetype.
  if ( m_Groupings.size() == 0 && itksys::SystemTools::FileExists(unixArchetype.c_str()))
    {
    std::vector<std::string> tlist;

    tlist.push_back( unixArchetype );
    m_Groupings.push_back( tlist );
    }

  m_ScanTime.Modified();
}

void
ArchetypeSeriesFileNames
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Archetype: " << m_Archetype << std::endl;
  os << indent << "Number of groupings: "
     << const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings() << std::endl;

  for (unsigned int j = 0; j < const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings(); j++)
    {
    os << indent << "Grouping #" << j << std::endl;
    StringVectorType group = const_cast<ArchetypeSeriesFileNames*>(this)->GetFileNames(j);
    StringVectorType::const_iterator groupItr = group.begin();
    unsigned int i = 0;
    while( groupItr != group.end() )
      {
      os << indent << indent << "Filenames[" << i << "]: " << *groupItr << std::endl;
      ++i;
      ++groupItr;
      }
    }
}
} //namespace ITK

#endif
<commit_msg>BUG: The Scan() method accelerates the increments of an iterator, and      then uses it without verifying if it has passed the end.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkArchetypeSeriesFileNames.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef _itkArchetypeSeriesFileNames_h
#define _itkArchetypeSeriesFileNames_h

#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

#include "itkArchetypeSeriesFileNames.h"
#include "itkRegularExpressionSeriesFileNames.h"
#include <itksys/SystemTools.hxx>
#include <stdio.h>
#include <algorithm>

namespace itk
{

ArchetypeSeriesFileNames
::ArchetypeSeriesFileNames() :
  m_Archetype("")
{
}

void
ArchetypeSeriesFileNames
::SetArchetype( const std::string &archetype )
{
  if (archetype != m_Archetype)
    {
    m_Archetype = archetype;
    this->Modified();
    m_ArchetypeMTime.Modified();
    }
}

ArchetypeSeriesFileNames::VectorSizeType
ArchetypeSeriesFileNames
::GetNumberOfGroupings()
{
  if (m_ScanTime < m_ArchetypeMTime)
    {
    this->Scan();
    }

  return m_Groupings.size();
}

const std::vector<std::string> &
ArchetypeSeriesFileNames
::GetFileNames( VectorSizeType group)
{
  if (m_ScanTime < m_ArchetypeMTime)
    {
    this->Scan();
    }

  if (group < m_Groupings.size())
    {
    m_FileNames = m_Groupings[group];
    }
  else
    {
    m_FileNames.clear();
    }

  return m_FileNames;
}

void
ArchetypeSeriesFileNames
::Scan()
{
  // For each group of contiguous numbers in m_Archetype, create a
  // regular expression that is identical to m_Archetype except that
  // it replaces that group of numbers with the pattern ([0-9]+).
  // Each of these new strings will then be passed into a
  // RegularExpressionSeriesFileNames to generate the list of those
  // files that fit that pattern.

  m_Groupings.clear();

  std::string unixArchetype = m_Archetype;
  itksys::SystemTools::ConvertToUnixSlashes(unixArchetype);

  if (itksys::SystemTools::FileIsDirectory( unixArchetype.c_str() ))
    {
    return;
    }

  // Parse the fileNameName and fileNamePath
  std::string origFileName = itksys::SystemTools::GetFilenameName( unixArchetype.c_str() );
  std::string fileNamePath = itksys::SystemTools::GetFilenamePath( unixArchetype.c_str() );
  std::string pathPrefix;

  // "Clean" the filename by escaping any special characters with backslashes.
  // This allows us to pass in filenames that include these special characters.
  std::string fileName;
  for( unsigned int j = 0; j < origFileName.length(); j++ )
    {
    char oneChar = origFileName[j];
    if( oneChar == '^' ||
        oneChar == '$' ||
        oneChar == '.' ||
        oneChar == '[' ||
        oneChar == ']' ||
        oneChar == '-' ||
        oneChar == '*' ||
        oneChar == '+' ||
        oneChar == '?' ||
        oneChar == '(' ||
        oneChar == ')' )
      {
      fileName += "\\";
      }
    fileName += oneChar;
    }

  // If there is no "/" in the name, the directory is not specified.
  // In that case, use the default ".".  This is necessary for the RegularExpressionSeriesFileNames.
  if (fileNamePath == "")
    {
    fileNamePath = ".";
    pathPrefix = "./";
    }
  else
    {
    pathPrefix = "";
    }

  StringVectorType regExpFileNameVector;
  std::string regExpString = "([0-9]+)";
  IntVectorType numGroupStart;
  IntVectorType numGroupLength;
  int sIndex;
  std::string::iterator sit;
  for (sit = fileName.begin(); sit < fileName.end(); sit++)
    {
    // If the element is a number, find its starting index and length.
    if ((*sit) >= '0' && (*sit) <= '9')
      {
      sIndex = sit - fileName.begin();
      numGroupStart.push_back( sIndex );

      // Loop to one past the end of the group of numbers.
      while ( sit != fileName.end() && (*sit) >= '0' && (*sit) <= '9' )
        {
        ++sit;
        }

      if( sit == fileName.end() )
        {
        break;
        }

      numGroupLength.push_back( (sit - fileName.begin()) - sIndex );
      }
    }

  // Create a set of regular expressions, one for each group of
  // numbers in m_FileName. We walk the regular expression groups
  // from right to left since numbers at the end of filenames are more
  // likely to be image numbers.
  // It is also necessary to walk backward so that the numGroupStart
  // indices remain correct since the length of numbers we are replacing may
  // be different from the length of regExpString.
  IntVectorType::reverse_iterator numGroupLengthItr = numGroupLength.rbegin();
  IntVectorType::reverse_iterator numGroupStartItr  = numGroupStart.rbegin();
  while( numGroupLengthItr != numGroupLength.rend() &&
         numGroupStartItr != numGroupStart.rend() )
    {
    std::string regExpFileName = fileName;

    regExpFileName.replace(*numGroupStartItr,*numGroupLengthItr,regExpString);
    // Include only filenames that exactly match this regular expression.  Don't
    // match filenames that have this string as a substring (ie. that have extra
    // prefixes or suffixes).
    regExpFileName = "^" + regExpFileName + "$";
    regExpFileNameVector.push_back( regExpFileName );
    ++numGroupLengthItr;
    ++numGroupStartItr;
    }

  // Use a RegularExpressionSeriesFileNames to find the files to return
  StringVectorType names;

  StringVectorType::const_iterator regExpFileNameVectorItr =
    regExpFileNameVector.begin();
  while( regExpFileNameVectorItr != regExpFileNameVector.end())
    {
    itk::RegularExpressionSeriesFileNames::Pointer fit = itk::RegularExpressionSeriesFileNames::New();
    fit->SetDirectory( fileNamePath.c_str() );
    fit->SetRegularExpression( regExpFileNameVectorItr->c_str() );
    fit->SetSubMatch(1);
    fit->NumericSortOn();
    names = fit->GetFileNames();

    std::vector<std::string>::iterator ait;
    ait = std::find(names.begin(), names.end(), pathPrefix + unixArchetype);

    // Accept the list if it contains the archetype and is not the
    // "trivial" list (containing only the archetype)
    if ( ait != names.end() && names.size() > 1)
      {
      m_Groupings.push_back(names);
      }
    ++regExpFileNameVectorItr;
    }

  // If the group list is empty, create a single group containing the
  // archetype.
  if ( m_Groupings.size() == 0 && itksys::SystemTools::FileExists(unixArchetype.c_str()))
    {
    std::vector<std::string> tlist;

    tlist.push_back( unixArchetype );
    m_Groupings.push_back( tlist );
    }

  m_ScanTime.Modified();
}

void
ArchetypeSeriesFileNames
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Archetype: " << m_Archetype << std::endl;
  os << indent << "Number of groupings: "
     << const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings() << std::endl;

  for (unsigned int j = 0; j < const_cast<ArchetypeSeriesFileNames*>(this)->GetNumberOfGroupings(); j++)
    {
    os << indent << "Grouping #" << j << std::endl;
    StringVectorType group = const_cast<ArchetypeSeriesFileNames*>(this)->GetFileNames(j);
    StringVectorType::const_iterator groupItr = group.begin();
    unsigned int i = 0;
    while( groupItr != group.end() )
      {
      os << indent << indent << "Filenames[" << i << "]: " << *groupItr << std::endl;
      ++i;
      ++groupItr;
      }
    }
}
} //namespace ITK

#endif
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkMovieGenerator.h"
#include <mitkRenderingManager.h>
#include "mitkGL.h"
#include "mitkConfig.h"

#ifdef WIN32
#ifndef __GNUC__
//#if ! (_MSC_VER >= 1400)
#include "mitkMovieGeneratorWin32.h"
//#endif
#endif
#endif
#ifndef GL_BGR
#define GL_BGR GL_BGR_EXT
#endif

mitk::MovieGenerator::Pointer mitk::MovieGenerator::New()
{
  Pointer smartPtr;
  MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create();
  if(rawPtr == NULL) {

#ifdef WIN32
#ifndef __GNUC__
//#if ! (_MSC_VER >= 1400)
    mitk::MovieGenerator::Pointer wp = static_cast<mitk::MovieGenerator*>(mitk::MovieGeneratorWin32::New());
    return wp;
//#endif
#endif
#endif
  }
  smartPtr = rawPtr;
  if(rawPtr != NULL) rawPtr->UnRegister();
  return smartPtr;
}

bool mitk::MovieGenerator::WriteMovie()
{
  bool ok = false;
  if (m_stepper)
  {
    if (m_renderer) m_renderer->GetRenderWindow()->MakeCurrent();
    //m_stepper->First();
    RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());

    ok = InitGenerator();
    if (!ok)
    {
      TerminateGenerator();
      return false;
    }
    int imgSize = 3 * m_width * m_height;
    printf( "Video size = %i x %i\n", m_width, m_height );
    GLbyte *data = new GLbyte[imgSize];
    for (unsigned int i=0; i<m_stepper->GetSteps(); i++)
    {
      if (m_renderer) m_renderer->GetRenderWindow()->MakeCurrent();
      RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());
      glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data );
      AddFrame( data );
      m_stepper->Next();
    }
    ok = TerminateGenerator();
    delete[] data;
  }
  return ok;
}

bool mitk::MovieGenerator::WriteCurrentFrameToMovie()
{
  if (m_renderer)
  {
    m_renderer->GetRenderWindow()->MakeCurrent();

    if(!m_initialized)
    {
      RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());
      m_initialized = InitGenerator();
    }
    if (!m_initialized)
    {
      TerminateGenerator();
      return false;
    }
    int imgSize = 3 * m_width * m_height;
    GLbyte *data = new GLbyte[imgSize];

    RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());
    glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data );
    AddFrame( data );
    delete[] data;
  }
  return true;
}

void mitk::MovieGenerator::ReleaseMovieWriter()
{
  TerminateGenerator();
  m_initialized = false;
}

void mitk::MovieGenerator::SetFrameRate(unsigned int rate)
{
  m_FrameRate = rate;
}

unsigned int mitk::MovieGenerator::GetFrameRate()
{
  return m_FrameRate;
}

<commit_msg>CHG (#1226): Enable writing of movies without coloured frame<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkMovieGenerator.h"
#include <mitkRenderingManager.h>
#include "mitkGL.h"
#include "mitkConfig.h"

#ifdef WIN32
#ifndef __GNUC__
//#if ! (_MSC_VER >= 1400)
#include "mitkMovieGeneratorWin32.h"
//#endif
#endif
#endif
#ifndef GL_BGR
#define GL_BGR GL_BGR_EXT
#endif

mitk::MovieGenerator::Pointer mitk::MovieGenerator::New()
{
  Pointer smartPtr;
  MovieGenerator *rawPtr = ::itk::ObjectFactory<MovieGenerator>::Create();
  if(rawPtr == NULL) {

#ifdef WIN32
#ifndef __GNUC__
//#if ! (_MSC_VER >= 1400)
    mitk::MovieGenerator::Pointer wp = static_cast<mitk::MovieGenerator*>(mitk::MovieGeneratorWin32::New());
    return wp;
//#endif
#endif
#endif
  }
  smartPtr = rawPtr;
  if(rawPtr != NULL) rawPtr->UnRegister();
  return smartPtr;
}

bool mitk::MovieGenerator::WriteMovie()
{
  bool ok = false;
  if (m_stepper)
  {
    if (m_renderer) m_renderer->GetRenderWindow()->MakeCurrent();
    //m_stepper->First();
    RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());

    ok = InitGenerator();
    if (!ok)
    {
      TerminateGenerator();
      return false;
    }
    int imgSize = 3 * m_width * m_height;
    printf( "Video size = %i x %i\n", m_width, m_height );
    GLbyte *data = new GLbyte[imgSize];
    for (unsigned int i=0; i<m_stepper->GetSteps(); i++)
    {
      if (m_renderer) m_renderer->GetRenderWindow()->MakeCurrent();
      RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());
      glReadPixels( 5, 5, m_width-5, m_height-5, GL_BGR, GL_UNSIGNED_BYTE, (void*)data );
      AddFrame( data );
      m_stepper->Next();
    }
    ok = TerminateGenerator();
    delete[] data;
  }
  return ok;
}

bool mitk::MovieGenerator::WriteCurrentFrameToMovie()
{
  if (m_renderer)
  {
    m_renderer->GetRenderWindow()->MakeCurrent();

    if(!m_initialized)
    {
      RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());
      m_initialized = InitGenerator();
    }
    if (!m_initialized)
    {
      TerminateGenerator();
      return false;
    }
    int imgSize = 3 * m_width * m_height;
    GLbyte *data = new GLbyte[imgSize];

    RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow());
    glReadPixels( 0, 0, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void*)data );
    AddFrame( data );
    delete[] data;
  }
  return true;
}

void mitk::MovieGenerator::ReleaseMovieWriter()
{
  TerminateGenerator();
  m_initialized = false;
}

void mitk::MovieGenerator::SetFrameRate(unsigned int rate)
{
  m_FrameRate = rate;
}

unsigned int mitk::MovieGenerator::GetFrameRate()
{
  return m_FrameRate;
}

<|endoftext|>


<commit_before>#include "сomplex_t.hpp"
complex_t::complex_t() : a(0.0), b(0.0)
{}
complex_t::complex_t(double x, double y) : a(x), b(y)
{}
complex_t::complex_t(const complex_t&cop)
{
	a = cop.a;
	b = cop.b;
}
double complex_t::a_()
{
	return a;
}

double complex_t::b_()
{
	return b;
}
bool complex_t::operator == (const complex_t& c2) const
{
	if ((a == c2.a) && (b == c2.b))
		return true;
}

complex_t complex_t::operator = (const complex_t& result)
{
	if (this == &result) {
		return *this;
	}
	a = result.a;
	b = result.b;
	return *this;
}
istream& operator >> (istream&cin, complex_t& result)
{
	cout << "Please enter real complex part:" << endl;
	cin >> result.a;
	cout << "Please enter imaginary complex part:" << endl;
	cin >> result.b;
	cout << endl;
	return cin;
}

ostream& operator << (ostream&cout, complex_t& result)
{
	if (result.b < 0)
	{
		cout << result.a << result.b << "i" << endl;
	}
	else
		cout << result.a << "+" << result.b << "i" << endl;
	return cout;
}
complex_t complex_t::operator * (const complex_t& c2)
{
	return complex_t(a*c2.a - b*c2.b, a*c2.b + c2.a*b);
}

complex_t complex_t::operator / (const complex_t& c2)
{
	return complex_t((a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b), (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b));
}

complex_t complex_t::operator += (const complex_t& c2)
{
	a += c2.a;
	b += c2.b;
	return *this;
}

complex_t complex_t::operator -= (const complex_t& c2)
{
	a -= c2.a;
	b -= c2.b;
	return *this;
}
complex_t complex_t::operator /= (const complex_t& c2)
{
	float a_ = (a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	b = (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	a = a_;
	return *this;
}

complex_t complex_t::operator *= (const complex_t& c2)
{
	float a_ = a*c2.a - b*c2.b;
	b = a*c2.b + c2.a*b;
	a = a_;
	return *this;
}
<commit_msg>Update сomplex_t.cpp<commit_after>#include "сomplex_t.hpp"
complex_t::complex_t() : a(0.0), b(0.0)
{}
complex_t::complex_t(double x, double y) : a(x), b(y)
{}
complex_t::complex_t(const complex_t&cop)
{
	a = cop.a;
	b = cop.b;
}
double complex_t::a_()
{
	return a;
}

double complex_t::b_()
{
	return b;
}
bool complex_t::operator == (const complex_t& c2) const
{
	if ((a == c2.a) && (b == c2.b))
		return true;
}

complex_t complex_t::operator = (const complex_t& result)
{
	if (this == &result) {
		return *this;
	}
	a = result.a;
	b = result.b;
	return *this;
}
istream& operator >> (istream&cin, complex_t& result)
{
	cout << "Please enter real complex part:" << endl;
	cin >> result.a;
	cout << "Please enter imaginary complex part:" << endl;
	cin >> result.b;
	cout << endl;
	return cin;
}

ostream& operator << (ostream&cout, complex_t& result)
{
	if (result.b < 0)
	{
		cout << result.a << result.b << "i" << endl;
	}
	else
		cout << result.a << "+" << result.b << "i" << endl;
	return cout;
}
complex_t complex_t::operator * (const complex_t& c2) const
{
	return complex_t(a*c2.a - b*c2.b, a*c2.b + c2.a*b);
}

complex_t complex_t::operator / (const complex_t& c2) const
{
	return complex_t((a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b), (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b));
}

complex_t complex_t::operator += (const complex_t& c2)
{
	a += c2.a;
	b += c2.b;
	return *this;
}

complex_t complex_t::operator -= (const complex_t& c2)
{
	a -= c2.a;
	b -= c2.b;
	return *this;
}
complex_t complex_t::operator /= (const complex_t& c2)
{
	float a_ = (a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	b = (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	a = a_;
	return *this;
}

complex_t complex_t::operator *= (const complex_t& c2)
{
	float a_ = a*c2.a - b*c2.b;
	b = a*c2.b + c2.a*b;
	a = a_;
	return *this;
}
<|endoftext|>


<commit_before>//===-- Opcode.cpp ----------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Core/Opcode.h"

#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/Stream.h"
#include "lldb/lldb-forward.h" // for DataBufferSP

#include <memory> // for make_shared

#include <inttypes.h> // for PRIx64

using namespace lldb;
using namespace lldb_private;

int Opcode::Dump(Stream *s, uint32_t min_byte_width) {
  int bytes_written = 0;
  switch (m_type) {
  case Opcode::eTypeInvalid:
    bytes_written = s->PutCString("<invalid>");
    break;
  case Opcode::eType8:
    bytes_written = s->Printf("0x%2.2x", m_data.inst8);
    break;
  case Opcode::eType16:
    bytes_written = s->Printf("0x%4.4x", m_data.inst16);
    break;
  case Opcode::eType16_2:
  case Opcode::eType32:
    bytes_written = s->Printf("0x%8.8x", m_data.inst32);
    break;

  case Opcode::eType64:
    bytes_written = s->Printf("0x%16.16" PRIx64, m_data.inst64);
    break;

  case Opcode::eTypeBytes:
    for (uint32_t i = 0; i < m_data.inst.length; ++i) {
      if (i > 0)
        bytes_written += s->PutChar(' ');
      bytes_written += s->Printf("%2.2x", m_data.inst.bytes[i]);
    }
    break;
  }

  // Add spaces to make sure bytes dispay comes out even in case opcodes aren't
  // all the same size
  if (static_cast<uint32_t>(bytes_written) < min_byte_width)
    bytes_written = s->Printf("%*s", min_byte_width - bytes_written, "");
  return bytes_written;
}

lldb::ByteOrder Opcode::GetDataByteOrder() const {
  if (m_byte_order != eByteOrderInvalid) {
    return m_byte_order;
  }
  switch (m_type) {
  case Opcode::eTypeInvalid:
    break;
  case Opcode::eType8:
  case Opcode::eType16:
  case Opcode::eType16_2:
  case Opcode::eType32:
  case Opcode::eType64:
    return endian::InlHostByteOrder();
  case Opcode::eTypeBytes:
    break;
  }
  return eByteOrderInvalid;
}

uint32_t Opcode::GetData(DataExtractor &data) const {
  uint32_t byte_size = GetByteSize();
  uint8_t swap_buf[8];
  const void *buf = nullptr;

  if (byte_size > 0) {
    if (!GetEndianSwap()) {
      if (m_type == Opcode::eType16_2) {
        // 32 bit thumb instruction, we need to sizzle this a bit
        swap_buf[0] = m_data.inst.bytes[2];
        swap_buf[1] = m_data.inst.bytes[3];
        swap_buf[2] = m_data.inst.bytes[0];
        swap_buf[3] = m_data.inst.bytes[1];
        buf = swap_buf;
      } else {
        buf = GetOpcodeDataBytes();
      }
    } else {
      switch (m_type) {
      case Opcode::eTypeInvalid:
        break;
      case Opcode::eType8:
        buf = GetOpcodeDataBytes();
        break;
      case Opcode::eType16:
        *(uint16_t *)swap_buf = llvm::ByteSwap_16(m_data.inst16);
        buf = swap_buf;
        break;
      case Opcode::eType16_2:
        swap_buf[0] = m_data.inst.bytes[1];
        swap_buf[1] = m_data.inst.bytes[0];
        swap_buf[2] = m_data.inst.bytes[3];
        swap_buf[3] = m_data.inst.bytes[2];
        buf = swap_buf;
        break;
      case Opcode::eType32:
        *(uint32_t *)swap_buf = llvm::ByteSwap_32(m_data.inst32);
        buf = swap_buf;
        break;
      case Opcode::eType64:
        *(uint32_t *)swap_buf = llvm::ByteSwap_64(m_data.inst64);
        buf = swap_buf;
        break;
      case Opcode::eTypeBytes:
        buf = GetOpcodeDataBytes();
        break;
      }
    }
  }
  if (buf != nullptr) {
    DataBufferSP buffer_sp;

    buffer_sp = std::make_shared<DataBufferHeap>(buf, byte_size);
    data.SetByteOrder(GetDataByteOrder());
    data.SetData(buffer_sp);
    return byte_size;
  }
  data.Clear();
  return 0;
}
<commit_msg>Remove manual byte counting from Opcode::Dump<commit_after>//===-- Opcode.cpp ----------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Core/Opcode.h"

#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/Stream.h"
#include "lldb/lldb-forward.h" // for DataBufferSP

#include <memory> // for make_shared

#include <inttypes.h> // for PRIx64

using namespace lldb;
using namespace lldb_private;

int Opcode::Dump(Stream *s, uint32_t min_byte_width) {
  const uint32_t previous_bytes = s->GetWrittenBytes();
  switch (m_type) {
  case Opcode::eTypeInvalid:
    s->PutCString("<invalid>");
    break;
  case Opcode::eType8:
    s->Printf("0x%2.2x", m_data.inst8);
    break;
  case Opcode::eType16:
    s->Printf("0x%4.4x", m_data.inst16);
    break;
  case Opcode::eType16_2:
  case Opcode::eType32:
    s->Printf("0x%8.8x", m_data.inst32);
    break;

  case Opcode::eType64:
    s->Printf("0x%16.16" PRIx64, m_data.inst64);
    break;

  case Opcode::eTypeBytes:
    for (uint32_t i = 0; i < m_data.inst.length; ++i) {
      if (i > 0)
        s->PutChar(' ');
      s->Printf("%2.2x", m_data.inst.bytes[i]);
    }
    break;
  }

  uint32_t bytes_written_so_far = s->GetWrittenBytes() - previous_bytes;
  // Add spaces to make sure bytes display comes out even in case opcodes aren't
  // all the same size.
  if (bytes_written_so_far < min_byte_width)
    s->Printf("%*s", min_byte_width - bytes_written_so_far, "");
  return s->GetWrittenBytes() - previous_bytes;
}

lldb::ByteOrder Opcode::GetDataByteOrder() const {
  if (m_byte_order != eByteOrderInvalid) {
    return m_byte_order;
  }
  switch (m_type) {
  case Opcode::eTypeInvalid:
    break;
  case Opcode::eType8:
  case Opcode::eType16:
  case Opcode::eType16_2:
  case Opcode::eType32:
  case Opcode::eType64:
    return endian::InlHostByteOrder();
  case Opcode::eTypeBytes:
    break;
  }
  return eByteOrderInvalid;
}

uint32_t Opcode::GetData(DataExtractor &data) const {
  uint32_t byte_size = GetByteSize();
  uint8_t swap_buf[8];
  const void *buf = nullptr;

  if (byte_size > 0) {
    if (!GetEndianSwap()) {
      if (m_type == Opcode::eType16_2) {
        // 32 bit thumb instruction, we need to sizzle this a bit
        swap_buf[0] = m_data.inst.bytes[2];
        swap_buf[1] = m_data.inst.bytes[3];
        swap_buf[2] = m_data.inst.bytes[0];
        swap_buf[3] = m_data.inst.bytes[1];
        buf = swap_buf;
      } else {
        buf = GetOpcodeDataBytes();
      }
    } else {
      switch (m_type) {
      case Opcode::eTypeInvalid:
        break;
      case Opcode::eType8:
        buf = GetOpcodeDataBytes();
        break;
      case Opcode::eType16:
        *(uint16_t *)swap_buf = llvm::ByteSwap_16(m_data.inst16);
        buf = swap_buf;
        break;
      case Opcode::eType16_2:
        swap_buf[0] = m_data.inst.bytes[1];
        swap_buf[1] = m_data.inst.bytes[0];
        swap_buf[2] = m_data.inst.bytes[3];
        swap_buf[3] = m_data.inst.bytes[2];
        buf = swap_buf;
        break;
      case Opcode::eType32:
        *(uint32_t *)swap_buf = llvm::ByteSwap_32(m_data.inst32);
        buf = swap_buf;
        break;
      case Opcode::eType64:
        *(uint32_t *)swap_buf = llvm::ByteSwap_64(m_data.inst64);
        buf = swap_buf;
        break;
      case Opcode::eTypeBytes:
        buf = GetOpcodeDataBytes();
        break;
      }
    }
  }
  if (buf != nullptr) {
    DataBufferSP buffer_sp;

    buffer_sp = std::make_shared<DataBufferHeap>(buf, byte_size);
    data.SetByteOrder(GetDataByteOrder());
    data.SetData(buffer_sp);
    return byte_size;
  }
  data.Clear();
  return 0;
}
<|endoftext|>


<commit_before>#include "сomplex_t.hpp"
complex_t::complex_t() : a(0.0), b(0.0)
{}
complex_t::complex_t(double x, double y) : a(x), b(y)
{}
complex_t::complex_t(const complex_t&cop)
{
	a = cop.a;
	b = cop.b;
}
double complex_t::a_() const
{
	return a;
}

double complex_t::b_() const
{
	return b;
}
bool complex_t::operator == (const complex_t& c2) const
{
	if ((a == c2.a) && (b == c2.b))
		return true;
}

complex_t complex_t::operator = (const complex_t& result)
{
	if (this != &result)
	{
	a = result.a;
	b = result.b;
	return *this;
	}

}
istream& operator >> (istream&cin, complex_t& result)
{
	cout << "Please enter real complex part:" << endl;
	cin >> result.a;
	cout << "Please enter imaginary complex part:" << endl;
	cin >> result.b;
	cout << endl;
	return cin;
}

ostream& operator << (ostream&cout, complex_t& result)
{
	if (result.b < 0)
	{
		cout << result.a << result.b << "i" << endl;
	}
	else
		cout << result.a << "+" << result.b << "i" << endl;
	return cout;
}
complex_t complex_t::operator * (const complex_t& c2) const
{
	return complex_t(a*c2.a - b*c2.b, a*c2.b + c2.a*b);
}

complex_t complex_t::operator / (const complex_t& c2) const
{
	return complex_t((a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b), (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b));
}

complex_t complex_t::operator += (const complex_t& c2)
{
	a += c2.a;
	b += c2.b;
	return *this;
}

complex_t complex_t::operator -= (const complex_t& c2)
{
	a -= c2.a;
	b -= c2.b;
	return *this;
}
complex_t complex_t::operator /= (const complex_t& c2)
{
	float a_ = (a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	b = (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	a = a_;
	return *this;
}

complex_t complex_t::operator *= (const complex_t& c2)
{
	float a_ = a*c2.a - b*c2.b;
	b = a*c2.b + c2.a*b;
	a = a_;
	return *this;
}
<commit_msg>Update сomplex_t.cpp<commit_after>#include "сomplex_t.hpp"
complex_t::complex_t() : a(0.0), b(0.0)
{}
complex_t::complex_t(double x, double y) : a(x), b(y)
{}
complex_t::complex_t(const complex_t&cop)
{
	a = cop.a;
	b = cop.b;
}
double complex_t::a_() const
{
	return a;
}

double complex_t::b_() const
{
	return b;
}
bool complex_t::operator == (const complex_t& c2) const
{
	if ((a == c2.a) && (b == c2.b))
		return true;
}

complex_t complex_t::operator = (const complex_t& result)
{
	if (this != &result)
	{
	a = result.a;
	b = result.b;
	return *this;
	}

}
istream& operator >> (istream&cin,const complex_t& result)
{
	cout << "Please enter real complex part:" << endl;
	cin >> result.a;
	cout << "Please enter imaginary complex part:" << endl;
	cin >> result.b;
	cout << endl;
	return cin;
}

ostream& operator << (ostream&cout,const complex_t& result)
{
	if (result.b < 0)
	{
		cout << result.a << result.b << "i" << endl;
	}
	else
		cout << result.a << "+" << result.b << "i" << endl;
	return cout;
}
complex_t complex_t::operator * (const complex_t& c2) const
{
	return complex_t(a*c2.a - b*c2.b, a*c2.b + c2.a*b);
}

complex_t complex_t::operator / (const complex_t& c2) const
{
	return complex_t((a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b), (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b));
}

complex_t complex_t::operator += (const complex_t& c2)
{
	a += c2.a;
	b += c2.b;
	return *this;
}

complex_t complex_t::operator -= (const complex_t& c2)
{
	a -= c2.a;
	b -= c2.b;
	return *this;
}
complex_t complex_t::operator /= (const complex_t& c2)
{
	float a_ = (a*c2.a + b*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	b = (c2.a*b - a*c2.b) / (c2.a*c2.a + c2.b*c2.b);
	a = a_;
	return *this;
}

complex_t complex_t::operator *= (const complex_t& c2)
{
	float a_ = a*c2.a - b*c2.b;
	b = a*c2.b + c2.a*b;
	a = a_;
	return *this;
}
<|endoftext|>