<commit_before>/*
 * Copyright 2014 Milian Wolff <mail@milianw.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/**
 * @file heaptrack_interpret.cpp
 *
 * @brief Interpret raw heaptrack data and add Dwarf based debug information.
 */

#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <tuple>
#include <algorithm>

#include <cxxabi.h>
#include <boost/algorithm/string/predicate.hpp>

#include "libbacktrace/backtrace.h"

using namespace std;

namespace {

string demangle(const char* function)
{
    if (!function) {
        return {};
    } else if (function[0] != '_' || function[1] != 'Z') {
        return {function};
    }

    string ret;
    int status = 0;
    char* demangled = abi::__cxa_demangle(function, 0, 0, &status);
    if (demangled) {
        ret = demangled;
        free(demangled);
    }
    return ret;
}

struct AddressInformation
{
    string function;
    string file;
    int line = 0;
};

struct Module
{
    Module(string _fileName, bool isExe, uintptr_t addressStart, uintptr_t addressEnd)
        : fileName(move(_fileName))
        , addressStart(addressStart)
        , addressEnd(addressEnd)
        , isExe(isExe)
        , backtraceState(nullptr)
    {
        if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) {
            return;
        }

        // NOTE: To prevent the same file to be initialized multiple times, we use this map.
        //       There is also no backtrace_free_state so we don't really loose anything...
        static unordered_map<string, backtrace_state*> knownStates;
        auto& state = knownStates[fileName];
        if (!state) {
            state = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false,
                                            [] (void *data, const char *msg, int errnum) {
                                                const Module* module = reinterpret_cast<Module*>(data);
                                                cerr << "Failed to create backtrace state for file " << module->fileName
                                                        << ": " << msg << " (error code " << errnum << ")" << endl;
                                            }, this);
        }
        backtraceState = state;

        if (backtraceState) {
            backtrace_fileline_initialize(backtraceState, addressStart, isExe,
                                          [] (void *data, const char *msg, int errnum) {
                                            const Module* module = reinterpret_cast<Module*>(data);
                                            cerr << "Failed to initialize backtrace fileline for "
                                                 << (module->isExe ? "executable " : "library ") << module->fileName
                                                 << ": " << msg << " (error code " << errnum << ")" << endl;
                                          }, this);
        }
    }

    AddressInformation resolveAddress(uintptr_t address) const
    {
        AddressInformation info;
        if (!backtraceState) {
            return info;
        }

        backtrace_pcinfo(backtraceState, address,
                         [] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int {
                            auto info = reinterpret_cast<AddressInformation*>(data);
                            info->function = demangle(function);
                            info->file = file ? file : "";
                            info->line = line;
                            return 0;
                         }, &emptyErrorCallback, &info);

        if (info.function.empty()) {
            backtrace_syminfo(backtraceState, address,
                              [] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) {
                                if (symname) {
                                    reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);
                                }
                              }, &errorCallback, &info);
        }

        return info;
    }

    static void errorCallback(void */*data*/, const char *msg, int errnum)
    {
        cerr << "Module backtrace error (code " << errnum << "): " << msg << endl;
    }

    static void emptyErrorCallback(void */*data*/, const char */*msg*/, int /*errnum*/)
    {
    }

    bool operator<(const Module& module) const
    {
        return make_tuple(addressStart, addressEnd, fileName)
             < make_tuple(module.addressStart, module.addressEnd, module.fileName);
    }

    bool operator!=(const Module& module) const
    {
        return make_tuple(addressStart, addressEnd, fileName)
            != make_tuple(module.addressStart, module.addressEnd, module.fileName);
    }

    backtrace_state* backtraceState = nullptr;
    string fileName;
    uintptr_t addressStart;
    uintptr_t addressEnd;
    bool isExe;
};

struct Allocation
{
    // backtrace entry point
    size_t ipIndex;
    // number of allocations
    size_t allocations;
    // amount of bytes leaked
    size_t leaked;
};

/**
 * Information for a single call to an allocation function
 */
struct AllocationInfo
{
    size_t ipIndex;
    size_t size;
};

struct ResolvedIP
{
    size_t moduleIndex = 0;
    size_t fileIndex = 0;
    size_t functionIndex = 0;
    int line = 0;
};

struct AccumulatedTraceData
{
    AccumulatedTraceData()
    {
        m_modules.reserve(64);
        m_internedData.reserve(4096);
        m_encounteredIps.reserve(32768);
    }

    ~AccumulatedTraceData()
    {
        cout << dec;
        cout << "# strings: " << m_internedData.size() << '\n';
        cout << "# ips: " << m_encounteredIps.size() << '\n';
    }

    ResolvedIP resolve(const uintptr_t ip)
    {
        if (m_modulesDirty) {
            // sort by addresses, required for binary search below
            sort(m_modules.begin(), m_modules.end());

            for (size_t i = 0; i < m_modules.size(); ++i) {
                const auto& m1 = m_modules[i];
                for (size_t j = i + 1; j < m_modules.size(); ++j) {
                    if (i == j) {
                        continue;
                    }
                    const auto& m2 = m_modules[j];
                    if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||
                        (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))
                    {
                        cerr << "OVERLAPPING MODULES: " << hex
                             << m1.fileName << " (" << m1.addressStart << " to " << m1.addressEnd << ") and "
                             << m2.fileName << " (" << m2.addressStart << " to " << m2.addressEnd << ")\n"
                             << dec;
                    } else if (m2.addressStart >= m1.addressEnd) {
                        break;
                    }
                }
            }

            m_modulesDirty = false;
        }

        ResolvedIP data;
        // find module for this instruction pointer
        auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,
                                    [] (const Module& module, const uintptr_t ip) -> bool {
                                        return module.addressEnd < ip;
                                    });
        if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {
            data.moduleIndex = intern(module->fileName);
            const auto info = module->resolveAddress(ip);
            data.fileIndex = intern(info.file);
            data.functionIndex = intern(info.function);
            data.line = info.line;
        }
        return data;
    }

    size_t intern(const string& str)
    {
        if (str.empty()) {
            return 0;
        }

        auto it = m_internedData.find(str);
        if (it != m_internedData.end()) {
            return it->second;
        }
        const size_t id = m_internedData.size() + 1;
        m_internedData.insert(it, make_pair(str, id));
        cout << "s " << str << '\n';
        return id;
    }

    void addModule(Module&& module)
    {
        m_modules.push_back(move(module));
        m_modulesDirty = true;
    }

    void clearModules()
    {
        // TODO: optimize this, reuse modules that are still valid
        m_modules.clear();
        m_modulesDirty = true;
    }

    size_t addIp(const uintptr_t instructionPointer)
    {
        if (!instructionPointer) {
            return 0;
        }

        auto it = m_encounteredIps.find(instructionPointer);
        if (it != m_encounteredIps.end()) {
            return it->second;
        }

        const size_t ipId = m_encounteredIps.size() + 1;
        m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));

        const auto ip = resolve(instructionPointer);
        cout << "i " << instructionPointer << ' ' << ip.moduleIndex;
        if (ip.functionIndex || ip.fileIndex) {
            cout << ' ' << ip.functionIndex;
            if (ip.fileIndex) {
                cout << ' ' << ip.fileIndex << ' ' << ip.line;
            }
        }
        cout << '\n';
        return ipId;
    }

private:
    vector<Module> m_modules;
    bool m_modulesDirty = false;

    unordered_map<string, size_t> m_internedData;
    unordered_map<uintptr_t, size_t> m_encounteredIps;
};

}

int main(int /*argc*/, char** /*argv*/)
{
    // optimize: we only have a single thread
    ios_base::sync_with_stdio(false);

    AccumulatedTraceData data;

    string line;
    line.reserve(1024);
    stringstream lineIn(ios_base::in);
    lineIn << hex;
    cout << hex;

    while (cin.good()) {
        getline(cin, line);
        if (line.empty()) {
            continue;
        }
        const char mode = line[0];
        lineIn.str(line);
        lineIn.clear();
        // skip mode and leading whitespace
        lineIn.seekg(2);
        if (mode == 'm') {
            string fileName;
            lineIn >> fileName;
            if (fileName == "-") {
                data.clearModules();
            } else {
                bool isExe = false;
                lineIn >> isExe;
                uintptr_t addressStart = 0;
                lineIn >> addressStart;
                uintptr_t addressEnd = 0;
                lineIn >> addressEnd;
                if (lineIn.bad()) {
                    cerr << "failed to parse line: " << line << endl;
                    return 1;
                }
                data.addModule({fileName, isExe, addressStart, addressEnd});
            }
        } else if (mode == 't') {
            uintptr_t instructionPointer = 0;
            size_t parentIndex = 0;
            lineIn >> instructionPointer;
            lineIn >> parentIndex;
            if (lineIn.bad()) {
                cerr << "failed to parse line: " << line << endl;
                return 1;
            }
            // ensure ip is encountered
            const auto ipId = data.addIp(instructionPointer);
            // trace point, map current output index to parent index
            cout << "t " << ipId << ' ' << parentIndex << '\n';
        } else {
            cout << line << '\n';
        }
    }

    return 0;
}
<commit_msg>Cleanup code and also initialize fileline only once.<commit_after>/*
 * Copyright 2014 Milian Wolff <mail@milianw.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/**
 * @file heaptrack_interpret.cpp
 *
 * @brief Interpret raw heaptrack data and add Dwarf based debug information.
 */

#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <tuple>
#include <algorithm>

#include <cxxabi.h>
#include <boost/algorithm/string/predicate.hpp>

#include "libbacktrace/backtrace.h"

using namespace std;

namespace {

string demangle(const char* function)
{
    if (!function) {
        return {};
    } else if (function[0] != '_' || function[1] != 'Z') {
        return {function};
    }

    string ret;
    int status = 0;
    char* demangled = abi::__cxa_demangle(function, 0, 0, &status);
    if (demangled) {
        ret = demangled;
        free(demangled);
    }
    return ret;
}

struct AddressInformation
{
    string function;
    string file;
    int line = 0;
};

struct Module
{
    Module(string _fileName, bool isExe, uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState)
        : fileName(move(_fileName))
        , addressStart(addressStart)
        , addressEnd(addressEnd)
        , isExe(isExe)
        , backtraceState(backtraceState)
    {
    }

    AddressInformation resolveAddress(uintptr_t address) const
    {
        AddressInformation info;
        if (!backtraceState) {
            return info;
        }

        backtrace_pcinfo(backtraceState, address,
                         [] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int {
                            auto info = reinterpret_cast<AddressInformation*>(data);
                            info->function = demangle(function);
                            info->file = file ? file : "";
                            info->line = line;
                            return 0;
                         }, &emptyErrorCallback, &info);

        if (info.function.empty()) {
            backtrace_syminfo(backtraceState, address,
                              [] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) {
                                if (symname) {
                                    reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);
                                }
                              }, &errorCallback, &info);
        }

        return info;
    }

    static void errorCallback(void */*data*/, const char *msg, int errnum)
    {
        cerr << "Module backtrace error (code " << errnum << "): " << msg << endl;
    }

    static void emptyErrorCallback(void */*data*/, const char */*msg*/, int /*errnum*/)
    {
    }

    bool operator<(const Module& module) const
    {
        return make_tuple(addressStart, addressEnd, fileName)
             < make_tuple(module.addressStart, module.addressEnd, module.fileName);
    }

    bool operator!=(const Module& module) const
    {
        return make_tuple(addressStart, addressEnd, fileName)
            != make_tuple(module.addressStart, module.addressEnd, module.fileName);
    }

    backtrace_state* backtraceState;
    string fileName;
    uintptr_t addressStart;
    uintptr_t addressEnd;
    bool isExe;
};

struct Allocation
{
    // backtrace entry point
    size_t ipIndex;
    // number of allocations
    size_t allocations;
    // amount of bytes leaked
    size_t leaked;
};

/**
 * Information for a single call to an allocation function
 */
struct AllocationInfo
{
    size_t ipIndex;
    size_t size;
};

struct ResolvedIP
{
    size_t moduleIndex = 0;
    size_t fileIndex = 0;
    size_t functionIndex = 0;
    int line = 0;
};

struct AccumulatedTraceData
{
    AccumulatedTraceData()
    {
        m_modules.reserve(256);
        m_backtraceStates.reserve(64);
        m_internedData.reserve(4096);
        m_encounteredIps.reserve(32768);
    }

    ~AccumulatedTraceData()
    {
        cout << dec;
        cout << "# strings: " << m_internedData.size() << '\n';
        cout << "# ips: " << m_encounteredIps.size() << '\n';
    }

    ResolvedIP resolve(const uintptr_t ip)
    {
        if (m_modulesDirty) {
            // sort by addresses, required for binary search below
            sort(m_modules.begin(), m_modules.end());

            for (size_t i = 0; i < m_modules.size(); ++i) {
                const auto& m1 = m_modules[i];
                for (size_t j = i + 1; j < m_modules.size(); ++j) {
                    if (i == j) {
                        continue;
                    }
                    const auto& m2 = m_modules[j];
                    if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||
                        (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))
                    {
                        cerr << "OVERLAPPING MODULES: " << hex
                             << m1.fileName << " (" << m1.addressStart << " to " << m1.addressEnd << ") and "
                             << m2.fileName << " (" << m2.addressStart << " to " << m2.addressEnd << ")\n"
                             << dec;
                    } else if (m2.addressStart >= m1.addressEnd) {
                        break;
                    }
                }
            }

            m_modulesDirty = false;
        }

        ResolvedIP data;
        // find module for this instruction pointer
        auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,
                                    [] (const Module& module, const uintptr_t ip) -> bool {
                                        return module.addressEnd < ip;
                                    });
        if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {
            data.moduleIndex = intern(module->fileName);
            const auto info = module->resolveAddress(ip);
            data.fileIndex = intern(info.file);
            data.functionIndex = intern(info.function);
            data.line = info.line;
        }
        return data;
    }

    size_t intern(const string& str)
    {
        if (str.empty()) {
            return 0;
        }

        auto it = m_internedData.find(str);
        if (it != m_internedData.end()) {
            return it->second;
        }
        const size_t id = m_internedData.size() + 1;
        m_internedData.insert(it, make_pair(str, id));
        cout << "s " << str << '\n';
        return id;
    }

    void addModule(const string& fileName, const bool isExe, const uintptr_t addressStart, const uintptr_t addressEnd)
    {
        backtrace_state* backtraceState = findBacktraceState(fileName, addressStart, isExe);

        m_modules.emplace_back(fileName, isExe, addressStart, addressEnd, backtraceState);
        m_modulesDirty = true;
    }

    void clearModules()
    {
        // TODO: optimize this, reuse modules that are still valid
        m_modules.clear();
        m_modulesDirty = true;
    }

    size_t addIp(const uintptr_t instructionPointer)
    {
        if (!instructionPointer) {
            return 0;
        }

        auto it = m_encounteredIps.find(instructionPointer);
        if (it != m_encounteredIps.end()) {
            return it->second;
        }

        const size_t ipId = m_encounteredIps.size() + 1;
        m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));

        const auto ip = resolve(instructionPointer);
        cout << "i " << instructionPointer << ' ' << ip.moduleIndex;
        if (ip.functionIndex || ip.fileIndex) {
            cout << ' ' << ip.functionIndex;
            if (ip.fileIndex) {
                cout << ' ' << ip.fileIndex << ' ' << ip.line;
            }
        }
        cout << '\n';
        return ipId;
    }

private:
    /**
     * Prevent the same file from being initialized multiple times.
     * This drastically cuts the memory consumption down
     */
    backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)
    {
        if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) {
            // prevent warning, since this will always fail
            return nullptr;
        }

        auto it = m_backtraceStates.find(fileName);
        if (it != m_backtraceStates.end()) {
            return it->second;
        }
        auto state = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false,
                                            [] (void *data, const char *msg, int errnum) {
                                                const Module* module = reinterpret_cast<Module*>(data);
                                                cerr << "Failed to create backtrace state for file " << module->fileName
                                                        << ": " << msg << " (error code " << errnum << ")" << endl;
                                            }, this);

        if (state) {
            // when we could initialize the backtrace state, we initialize it with the first address
            // we get since that is the lowest one
            backtrace_fileline_initialize(state, addressStart, isExe,
                                        [] (void *data, const char *msg, int errnum) {
                                            const Module* module = reinterpret_cast<Module*>(data);
                                            cerr << "Failed to initialize backtrace fileline for "
                                                << (module->isExe ? "executable " : "library ") << module->fileName
                                                << ": " << msg << " (error code " << errnum << ")" << endl;
                                        }, this);
        }

        m_backtraceStates.insert(it, make_pair(fileName, state));

        return state;
    }

    vector<Module> m_modules;
    unordered_map<string, backtrace_state*> m_backtraceStates;
    bool m_modulesDirty = false;

    unordered_map<string, size_t> m_internedData;
    unordered_map<uintptr_t, size_t> m_encounteredIps;
};

}

int main(int /*argc*/, char** /*argv*/)
{
    // optimize: we only have a single thread
    ios_base::sync_with_stdio(false);

    AccumulatedTraceData data;

    string line;
    line.reserve(1024);
    stringstream lineIn(ios_base::in);
    lineIn << hex;
    cout << hex;

    while (cin.good()) {
        getline(cin, line);
        if (line.empty()) {
            continue;
        }
        const char mode = line[0];
        lineIn.str(line);
        lineIn.clear();
        // skip mode and leading whitespace
        lineIn.seekg(2);
        if (mode == 'm') {
            string fileName;
            lineIn >> fileName;
            if (fileName == "-") {
                data.clearModules();
            } else {
                bool isExe = false;
                lineIn >> isExe;
                uintptr_t addressStart = 0;
                lineIn >> addressStart;
                uintptr_t addressEnd = 0;
                lineIn >> addressEnd;
                if (lineIn.bad()) {
                    cerr << "failed to parse line: " << line << endl;
                    return 1;
                }
                data.addModule(fileName, isExe, addressStart, addressEnd);
            }
        } else if (mode == 't') {
            uintptr_t instructionPointer = 0;
            size_t parentIndex = 0;
            lineIn >> instructionPointer;
            lineIn >> parentIndex;
            if (lineIn.bad()) {
                cerr << "failed to parse line: " << line << endl;
                return 1;
            }
            // ensure ip is encountered
            const auto ipId = data.addIp(instructionPointer);
            // trace point, map current output index to parent index
            cout << "t " << ipId << ' ' << parentIndex << '\n';
        } else {
            cout << line << '\n';
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <cmath>
#include <vector>

#include "ev3api.h"
#include "InOutManager.h"
#include "Strategy.h"
#include "SelfPositionManager.h"
#include "SoundPlayTask.h"
void LineTraceStrategy::Run()
{
	auto InOut = InOutManager::GetInstance();
	uint IntegralCount = 5;

	double pk = CurrentPID.PGain, pi = CurrentPID.IGain, pd = CurrentPID.DGain, power = CurrentPID.BasePower;

	int light = InOut->InputData.ReflectLight;

	// 今回の偏差
	int diff =  (int)light - CenterValue;

	// 積分処理
	IntegralDiff.push_back(diff);
	if(IntegralDiff.size() > IntegralCount) IntegralDiff.erase(IntegralDiff.begin());

	// 積分偏差
	double intDiff = 0.0;
	for(int d : IntegralDiff)
		intDiff  += d;
 	intDiff /= IntegralDiff.size();

	// 	ステアリング値
	int steering = pk * diff + pi * intDiff + (diff - PrevDiff) * pd;

	if(steering > 100) steering = 100;
	if(steering < -100) steering = -100;

	if (steering > 0)
	{
		InOut->OutputData.LeftMotorPower = (int8_t)(power + steering < 100 ? power + steering : 100);
		InOut->OutputData.RightMotorPower = (int8_t)(power - steering > 0 ? power - steering : 0);
	}
	else
	{
		InOut->OutputData.LeftMotorPower = (int8_t)(power + steering > 0 ? power + steering : 0);
		InOut->OutputData.RightMotorPower = (int8_t)(power - steering < 100 ? power - steering : 100);
	}

	PrevDiff = diff;
	if(SelfPositionManager::GetInstance()->PositionX < 1800)
	{
		InOut->Forward(0);
		InOut->WriteOutputMotor();
		PlaySound(LineTraceEnd);
		ext_tsk();

	}

}<commit_msg>ライントレース時の操舵角演算を固定値から比率に変更<commit_after>#include <cmath>
#include <vector>

#include "ev3api.h"
#include "InOutManager.h"
#include "Strategy.h"
#include "SelfPositionManager.h"
#include "SoundPlayTask.h"
void LineTraceStrategy::Run()
{
	auto InOut = InOutManager::GetInstance();
	uint IntegralCount = 5;

	double pk = CurrentPID.PGain, pi = CurrentPID.IGain, pd = CurrentPID.DGain, power = CurrentPID.BasePower;

	int light = InOut->InputData.ReflectLight;

	// 今回の偏差
	int diff =  (int)light - CenterValue;

	// 積分処理
	IntegralDiff.push_back(diff);
	if(IntegralDiff.size() > IntegralCount) IntegralDiff.erase(IntegralDiff.begin());

	// 積分偏差
	double intDiff = 0.0;
	for(int d : IntegralDiff)
		intDiff  += d;
 	intDiff /= IntegralDiff.size();

	// ステアリング値
	int steering = pk * diff + pi * intDiff + (diff - PrevDiff) * pd;

	/// 微分偏差計算用の前回の偏差
	PrevDiff = diff;

	// ステアリング値は0-100の範囲内
	if(steering > 100) steering = 100;
	if(steering < -100) steering = -100;

	// 右側へ
	if (steering > 0)
	{
		InOut->OutputData.LeftMotorPower = (int8_t)power;
		InOut->OutputData.RightMotorPower = (int8_t)(power * (100.0 - steering) / 100.0);
	}
	// 左側へ
	else
	{
		InOut->OutputData.LeftMotorPower = (int8_t)(power * (100.0 + steering) / 100.0);
		InOut->OutputData.RightMotorPower = (int8_t)power;
	}

	if(SelfPositionManager::GetInstance()->PositionX < 1800)
	{
		InOut->Forward(0);
		InOut->WriteOutputMotor();
		PlaySound(LineTraceEnd);
		ext_tsk();

	}

}<|endoftext|>


<commit_before>#ifndef __libfixmath_fix16_hpp__
#define __libfixmath_fix16_hpp__

class Fix16 {
	public:
		fix16_t value;

		Fix16() { value = 0; }
		Fix16(const Fix16 &inValue)  { value = inValue.value;             }
		Fix16(const fix16_t inValue) { value = inValue;                   }
		Fix16(const float inValue)   { value = fix16_from_float(inValue); }
		Fix16(const double inValue)  { value = fix16_from_dbl(inValue);   }
		Fix16(const int16_t inValue) { value = fix16_from_int(inValue);   }

		operator fix16_t() { return value;                 }
		operator double()  { return fix16_to_dbl(value);   }
		operator float()   { return fix16_to_float(value); }
		operator int16_t() { return fix16_to_int(value);   }

		Fix16 & operator=(const Fix16 &rhs)  { value = rhs.value;             return *this; }
		Fix16 & operator=(const fix16_t rhs) { value = rhs;                   return *this; }
		Fix16 & operator=(const double rhs)  { value = fix16_from_dbl(rhs);   return *this; }
		Fix16 & operator=(const float rhs)   { value = fix16_from_float(rhs); return *this; }
		Fix16 & operator=(const int16_t rhs) { value = fix16_from_int(rhs);   return *this; }

		Fix16 & operator+=(const Fix16 &rhs)  { value += rhs.value;             return *this; }
		Fix16 & operator+=(const fix16_t rhs) { value += rhs;                   return *this; }
		Fix16 & operator+=(const double rhs)  { value += fix16_from_dbl(rhs);   return *this; }
		Fix16 & operator+=(const float rhs)   { value += fix16_from_float(rhs); return *this; }
		Fix16 & operator+=(const int16_t rhs) { value += fix16_from_int(rhs);   return *this; }

		Fix16 & operator-=(const Fix16 &rhs)  { value -= rhs.value; return *this; }
		Fix16 & operator-=(const fix16_t rhs) { value -= rhs; return *this; }
		Fix16 & operator-=(const double rhs)  { value -= fix16_from_dbl(rhs); return *this; }
		Fix16 & operator-=(const float rhs)   { value -= fix16_from_float(rhs); return *this; }
		Fix16 & operator-=(const int16_t rhs) { value -= fix16_from_int(rhs); return *this; }

		Fix16 & operator*=(const Fix16 &rhs)  { value = fix16_mul(value, rhs.value); return *this; }
		Fix16 & operator*=(const fix16_t rhs) { value = fix16_mul(value, rhs); return *this; }
		Fix16 & operator*=(const double rhs)  { value = fix16_mul(value, fix16_from_dbl(rhs)); return *this; }
		Fix16 & operator*=(const float rhs)   { value = fix16_mul(value, fix16_from_float(rhs)); return *this; }
		Fix16 & operator*=(const int16_t rhs) { value *= rhs; return *this; }

		Fix16 & operator/=(const Fix16 &rhs)  { value = fix16_div(value, rhs.value); return *this; }
		Fix16 & operator/=(const fix16_t rhs) { value = fix16_div(value, rhs); return *this; }
		Fix16 & operator/=(const double rhs)  { value = fix16_div(value, fix16_from_dbl(rhs)); return *this; }
		Fix16 & operator/=(const float rhs)   { value = fix16_div(value, fix16_from_float(rhs)); return *this; }
		Fix16 & operator/=(const int16_t rhs) { value /= rhs; return *this; }

		const Fix16 operator+(const Fix16 &other) const  { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const fix16_t other) const { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const double other) const  { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const float other) const   { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const int16_t other) const { Fix16 ret = *this; ret += other; return ret; }

		const Fix16 sadd(const Fix16 &other)  const { Fix16 ret = fix16_sadd(value, other.value);             return ret; }
		const Fix16 sadd(const fix16_t other) const { Fix16 ret = fix16_sadd(value, other);                   return ret; }
		const Fix16 sadd(const double other)  const { Fix16 ret = fix16_sadd(value, fix16_from_dbl(other));   return ret; }
		const Fix16 sadd(const float other)   const { Fix16 ret = fix16_sadd(value, fix16_from_float(other)); return ret; }
		const Fix16 sadd(const int16_t other) const { Fix16 ret = fix16_sadd(value, fix16_from_int(other));   return ret; }

		const Fix16 operator-(const Fix16 &other) const  { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const fix16_t other) const { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const double other) const  { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const float other) const   { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const int16_t other) const { Fix16 ret = *this; ret -= other; return ret; }

		const Fix16 ssub(const Fix16 &other)  const { Fix16 ret = fix16_sadd(value, -other.value);             return ret; }
		const Fix16 ssub(const fix16_t other) const { Fix16 ret = fix16_sadd(value, -other);                   return ret; }
		const Fix16 ssub(const double other)  const { Fix16 ret = fix16_sadd(value, -fix16_from_dbl(other));   return ret; }
		const Fix16 ssub(const float other)   const { Fix16 ret = fix16_sadd(value, -fix16_from_float(other)); return ret; }
		const Fix16 ssub(const int16_t other) const { Fix16 ret = fix16_sadd(value, -fix16_from_int(other));   return ret; }

		const Fix16 operator*(const Fix16 &other) const  { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const fix16_t other) const { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const double other) const  { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const float other) const   { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const int16_t other) const { Fix16 ret = *this; ret *= other; return ret; }

		const Fix16 smul(const Fix16 &other)  const { Fix16 ret = fix16_smul(value, other.value);             return ret; }
		const Fix16 smul(const fix16_t other) const { Fix16 ret = fix16_smul(value, other);                   return ret; }
		const Fix16 smul(const double other)  const { Fix16 ret = fix16_smul(value, fix16_from_dbl(other));   return ret; }
		const Fix16 smul(const float other)   const { Fix16 ret = fix16_smul(value, fix16_from_float(other)); return ret; }
		const Fix16 smul(const int16_t other) const { Fix16 ret = fix16_smul(value, fix16_from_int(other));   return ret; }

		const Fix16 operator/(const Fix16 &other) const  { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const fix16_t other) const { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const double other) const  { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const float other) const   { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const int16_t other) const { Fix16 ret = *this; ret /= other; return ret; }

		const Fix16 sdiv(const Fix16 &other)  const { Fix16 ret = fix16_sdiv(value, other.value);             return ret; }
		const Fix16 sdiv(const fix16_t other) const { Fix16 ret = fix16_sdiv(value, other);                   return ret; }
		const Fix16 sdiv(const double other)  const { Fix16 ret = fix16_sdiv(value, fix16_from_dbl(other));   return ret; }
		const Fix16 sdiv(const float other)   const { Fix16 ret = fix16_sdiv(value, fix16_from_float(other)); return ret; }
		const Fix16 sdiv(const int16_t other) const { Fix16 ret = fix16_sdiv(value, fix16_from_int(other));   return ret; }

		const int operator==(const Fix16 &other)  const { return (value == other.value);             }
		const int operator==(const fix16_t other) const { return (value == other);                   }
		const int operator==(const double other)  const { return (value == fix16_from_dbl(other));   }
		const int operator==(const float other)   const { return (value == fix16_from_float(other)); }
		const int operator==(const int16_t other) const { return (value == fix16_from_int(other));   }

		const int operator!=(const Fix16 &other)  const { return (value != other.value);             }
		const int operator!=(const fix16_t other) const { return (value != other);                   }
		const int operator!=(const double other)  const { return (value != fix16_from_dbl(other));   }
		const int operator!=(const float other)   const { return (value != fix16_from_float(other)); }
		const int operator!=(const int16_t other) const { return (value != fix16_from_int(other));   }

		const int operator<=(const Fix16 &other)  const { return (value <= other.value);             }
		const int operator<=(const fix16_t other) const { return (value <= other);                   }
		const int operator<=(const double other)  const { return (value <= fix16_from_dbl(other));   }
		const int operator<=(const float other)   const { return (value <= fix16_from_float(other)); }
		const int operator<=(const int16_t other) const { return (value <= fix16_from_int(other));   }

		const int operator>=(const Fix16 &other)  const { return (value >= other.value);             }
		const int operator>=(const fix16_t other) const { return (value >= other);                   }
		const int operator>=(const double other)  const { return (value >= fix16_from_dbl(other));   }
		const int operator>=(const float other)   const { return (value >= fix16_from_float(other)); }
		const int operator>=(const int16_t other) const { return (value >= fix16_from_int(other));   }

		const int operator< (const Fix16 &other)  const { return (value <  other.value);             }
		const int operator< (const fix16_t other) const { return (value <  other);                   }
		const int operator< (const double other)  const { return (value <  fix16_from_dbl(other));   }
		const int operator< (const float other)   const { return (value <  fix16_from_float(other)); }
		const int operator< (const int16_t other) const { return (value <  fix16_from_int(other));   }

		const int operator> (const Fix16 &other)  const { return (value >  other.value);             }
		const int operator> (const fix16_t other) const { return (value >  other);                   }
		const int operator> (const double other)  const { return (value >  fix16_from_dbl(other));   }
		const int operator> (const float other)   const { return (value >  fix16_from_float(other)); }
		const int operator> (const int16_t other) const { return (value >  fix16_from_int(other));   }

		Fix16  sin() { return Fix16(fix16_sin(value));  }
		Fix16  cos() { return Fix16(fix16_cos(value));  }
		Fix16  tan() { return Fix16(fix16_tan(value));  }
		Fix16 asin() { return Fix16(fix16_asin(value)); }
		Fix16 acos() { return Fix16(fix16_acos(value)); }
		Fix16 atan() { return Fix16(fix16_atan(value)); }
		Fix16 atan2(const Fix16 &inY) { return Fix16(fix16_atan2(value, inY.value)); }
		Fix16 sqrt() { return Fix16(fix16_sqrt(value)); }
};

#endif
<commit_msg>Added a patch to make operator results constant in the C++ interface as suggested in Issue 15.<commit_after>#ifndef __libfixmath_fix16_hpp__
#define __libfixmath_fix16_hpp__

class Fix16 {
	public:
		fix16_t value;

		Fix16() { value = 0; }
		Fix16(const Fix16 &inValue)  { value = inValue.value;             }
		Fix16(const fix16_t inValue) { value = inValue;                   }
		Fix16(const float inValue)   { value = fix16_from_float(inValue); }
		Fix16(const double inValue)  { value = fix16_from_dbl(inValue);   }
		Fix16(const int16_t inValue) { value = fix16_from_int(inValue);   }

		operator fix16_t() const { return value;                 }
		operator double()  const { return fix16_to_dbl(value);   }
		operator float()   const { return fix16_to_float(value); }
		operator int16_t() const { return fix16_to_int(value);   }

		Fix16 & operator=(const Fix16 &rhs)  { value = rhs.value;             return *this; }
		Fix16 & operator=(const fix16_t rhs) { value = rhs;                   return *this; }
		Fix16 & operator=(const double rhs)  { value = fix16_from_dbl(rhs);   return *this; }
		Fix16 & operator=(const float rhs)   { value = fix16_from_float(rhs); return *this; }
		Fix16 & operator=(const int16_t rhs) { value = fix16_from_int(rhs);   return *this; }

		Fix16 & operator+=(const Fix16 &rhs)  { value += rhs.value;             return *this; }
		Fix16 & operator+=(const fix16_t rhs) { value += rhs;                   return *this; }
		Fix16 & operator+=(const double rhs)  { value += fix16_from_dbl(rhs);   return *this; }
		Fix16 & operator+=(const float rhs)   { value += fix16_from_float(rhs); return *this; }
		Fix16 & operator+=(const int16_t rhs) { value += fix16_from_int(rhs);   return *this; }

		Fix16 & operator-=(const Fix16 &rhs)  { value -= rhs.value; return *this; }
		Fix16 & operator-=(const fix16_t rhs) { value -= rhs; return *this; }
		Fix16 & operator-=(const double rhs)  { value -= fix16_from_dbl(rhs); return *this; }
		Fix16 & operator-=(const float rhs)   { value -= fix16_from_float(rhs); return *this; }
		Fix16 & operator-=(const int16_t rhs) { value -= fix16_from_int(rhs); return *this; }

		Fix16 & operator*=(const Fix16 &rhs)  { value = fix16_mul(value, rhs.value); return *this; }
		Fix16 & operator*=(const fix16_t rhs) { value = fix16_mul(value, rhs); return *this; }
		Fix16 & operator*=(const double rhs)  { value = fix16_mul(value, fix16_from_dbl(rhs)); return *this; }
		Fix16 & operator*=(const float rhs)   { value = fix16_mul(value, fix16_from_float(rhs)); return *this; }
		Fix16 & operator*=(const int16_t rhs) { value *= rhs; return *this; }

		Fix16 & operator/=(const Fix16 &rhs)  { value = fix16_div(value, rhs.value); return *this; }
		Fix16 & operator/=(const fix16_t rhs) { value = fix16_div(value, rhs); return *this; }
		Fix16 & operator/=(const double rhs)  { value = fix16_div(value, fix16_from_dbl(rhs)); return *this; }
		Fix16 & operator/=(const float rhs)   { value = fix16_div(value, fix16_from_float(rhs)); return *this; }
		Fix16 & operator/=(const int16_t rhs) { value /= rhs; return *this; }

		const Fix16 operator+(const Fix16 &other) const  { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const fix16_t other) const { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const double other) const  { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const float other) const   { Fix16 ret = *this; ret += other; return ret; }
		const Fix16 operator+(const int16_t other) const { Fix16 ret = *this; ret += other; return ret; }

		const Fix16 sadd(const Fix16 &other)  const { Fix16 ret = fix16_sadd(value, other.value);             return ret; }
		const Fix16 sadd(const fix16_t other) const { Fix16 ret = fix16_sadd(value, other);                   return ret; }
		const Fix16 sadd(const double other)  const { Fix16 ret = fix16_sadd(value, fix16_from_dbl(other));   return ret; }
		const Fix16 sadd(const float other)   const { Fix16 ret = fix16_sadd(value, fix16_from_float(other)); return ret; }
		const Fix16 sadd(const int16_t other) const { Fix16 ret = fix16_sadd(value, fix16_from_int(other));   return ret; }

		const Fix16 operator-(const Fix16 &other) const  { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const fix16_t other) const { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const double other) const  { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const float other) const   { Fix16 ret = *this; ret -= other; return ret; }
		const Fix16 operator-(const int16_t other) const { Fix16 ret = *this; ret -= other; return ret; }

		const Fix16 ssub(const Fix16 &other)  const { Fix16 ret = fix16_sadd(value, -other.value);             return ret; }
		const Fix16 ssub(const fix16_t other) const { Fix16 ret = fix16_sadd(value, -other);                   return ret; }
		const Fix16 ssub(const double other)  const { Fix16 ret = fix16_sadd(value, -fix16_from_dbl(other));   return ret; }
		const Fix16 ssub(const float other)   const { Fix16 ret = fix16_sadd(value, -fix16_from_float(other)); return ret; }
		const Fix16 ssub(const int16_t other) const { Fix16 ret = fix16_sadd(value, -fix16_from_int(other));   return ret; }

		const Fix16 operator*(const Fix16 &other) const  { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const fix16_t other) const { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const double other) const  { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const float other) const   { Fix16 ret = *this; ret *= other; return ret; }
		const Fix16 operator*(const int16_t other) const { Fix16 ret = *this; ret *= other; return ret; }

		const Fix16 smul(const Fix16 &other)  const { Fix16 ret = fix16_smul(value, other.value);             return ret; }
		const Fix16 smul(const fix16_t other) const { Fix16 ret = fix16_smul(value, other);                   return ret; }
		const Fix16 smul(const double other)  const { Fix16 ret = fix16_smul(value, fix16_from_dbl(other));   return ret; }
		const Fix16 smul(const float other)   const { Fix16 ret = fix16_smul(value, fix16_from_float(other)); return ret; }
		const Fix16 smul(const int16_t other) const { Fix16 ret = fix16_smul(value, fix16_from_int(other));   return ret; }

		const Fix16 operator/(const Fix16 &other) const  { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const fix16_t other) const { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const double other) const  { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const float other) const   { Fix16 ret = *this; ret /= other; return ret; }
		const Fix16 operator/(const int16_t other) const { Fix16 ret = *this; ret /= other; return ret; }

		const Fix16 sdiv(const Fix16 &other)  const { Fix16 ret = fix16_sdiv(value, other.value);             return ret; }
		const Fix16 sdiv(const fix16_t other) const { Fix16 ret = fix16_sdiv(value, other);                   return ret; }
		const Fix16 sdiv(const double other)  const { Fix16 ret = fix16_sdiv(value, fix16_from_dbl(other));   return ret; }
		const Fix16 sdiv(const float other)   const { Fix16 ret = fix16_sdiv(value, fix16_from_float(other)); return ret; }
		const Fix16 sdiv(const int16_t other) const { Fix16 ret = fix16_sdiv(value, fix16_from_int(other));   return ret; }

		const int operator==(const Fix16 &other)  const { return (value == other.value);             }
		const int operator==(const fix16_t other) const { return (value == other);                   }
		const int operator==(const double other)  const { return (value == fix16_from_dbl(other));   }
		const int operator==(const float other)   const { return (value == fix16_from_float(other)); }
		const int operator==(const int16_t other) const { return (value == fix16_from_int(other));   }

		const int operator!=(const Fix16 &other)  const { return (value != other.value);             }
		const int operator!=(const fix16_t other) const { return (value != other);                   }
		const int operator!=(const double other)  const { return (value != fix16_from_dbl(other));   }
		const int operator!=(const float other)   const { return (value != fix16_from_float(other)); }
		const int operator!=(const int16_t other) const { return (value != fix16_from_int(other));   }

		const int operator<=(const Fix16 &other)  const { return (value <= other.value);             }
		const int operator<=(const fix16_t other) const { return (value <= other);                   }
		const int operator<=(const double other)  const { return (value <= fix16_from_dbl(other));   }
		const int operator<=(const float other)   const { return (value <= fix16_from_float(other)); }
		const int operator<=(const int16_t other) const { return (value <= fix16_from_int(other));   }

		const int operator>=(const Fix16 &other)  const { return (value >= other.value);             }
		const int operator>=(const fix16_t other) const { return (value >= other);                   }
		const int operator>=(const double other)  const { return (value >= fix16_from_dbl(other));   }
		const int operator>=(const float other)   const { return (value >= fix16_from_float(other)); }
		const int operator>=(const int16_t other) const { return (value >= fix16_from_int(other));   }

		const int operator< (const Fix16 &other)  const { return (value <  other.value);             }
		const int operator< (const fix16_t other) const { return (value <  other);                   }
		const int operator< (const double other)  const { return (value <  fix16_from_dbl(other));   }
		const int operator< (const float other)   const { return (value <  fix16_from_float(other)); }
		const int operator< (const int16_t other) const { return (value <  fix16_from_int(other));   }

		const int operator> (const Fix16 &other)  const { return (value >  other.value);             }
		const int operator> (const fix16_t other) const { return (value >  other);                   }
		const int operator> (const double other)  const { return (value >  fix16_from_dbl(other));   }
		const int operator> (const float other)   const { return (value >  fix16_from_float(other)); }
		const int operator> (const int16_t other) const { return (value >  fix16_from_int(other));   }

		Fix16  sin() { return Fix16(fix16_sin(value));  }
		Fix16  cos() { return Fix16(fix16_cos(value));  }
		Fix16  tan() { return Fix16(fix16_tan(value));  }
		Fix16 asin() { return Fix16(fix16_asin(value)); }
		Fix16 acos() { return Fix16(fix16_acos(value)); }
		Fix16 atan() { return Fix16(fix16_atan(value)); }
		Fix16 atan2(const Fix16 &inY) { return Fix16(fix16_atan2(value, inY.value)); }
		Fix16 sqrt() { return Fix16(fix16_sqrt(value)); }
};

#endif
<|endoftext|>


<commit_before>#pragma once

#include <cstdlib>
#include <sstream>
#include <iostream>
#include <string>

#include <algorithm>

// cpl::Flags
#include <cpl/include/flags.hpp>

// cpl::net::IP
#include <cpl/include/ip.hpp>

void
show_help(std::string a, std::string b, void* d) {
	auto flags = reinterpret_cast<cpl::Flags*>(d);
	flags->print_usage();
	exit(0);
}

void
set_listen(std::string a, std::string b, void* d) {
	auto addr = reinterpret_cast<cpl::net::IP*>(d);
	addr->set(b);
}

void
set_listen_port(std::string a, std::string b, void* d) {
	auto listen_port = reinterpret_cast<int*>(d);
	*listen_port = atoi(b.c_str());
}

void
add_peers(std::string a, std::string b, void* d) {
	auto peers = reinterpret_cast<std::vector<std::string>*>(d);

	std::istringstream ss(b);
	std::string token;

	while (std::getline(ss, token, ',')) {
		peers->push_back(token);
	}

	for (auto p: *peers) {
		std::cout << "added peer: " << p << std::endl;
	}
}
<commit_msg>Remove <algorithm><commit_after>#pragma once

#include <cstdlib>
#include <sstream>
#include <iostream>
#include <string>

// cpl::Flags
#include <cpl/include/flags.hpp>

// cpl::net::IP
#include <cpl/include/ip.hpp>

void
show_help(std::string a, std::string b, void* d) {
	auto flags = reinterpret_cast<cpl::Flags*>(d);
	flags->print_usage();
	exit(0);
}

void
set_listen(std::string a, std::string b, void* d) {
	auto addr = reinterpret_cast<cpl::net::IP*>(d);
	addr->set(b);
}

void
set_listen_port(std::string a, std::string b, void* d) {
	auto listen_port = reinterpret_cast<int*>(d);
	*listen_port = atoi(b.c_str());
}

void
add_peers(std::string a, std::string b, void* d) {
	auto peers = reinterpret_cast<std::vector<std::string>*>(d);

	std::istringstream ss(b);
	std::string token;

	while (std::getline(ss, token, ',')) {
		peers->push_back(token);
	}

	for (auto p: *peers) {
		std::cout << "added peer: " << p << std::endl;
	}
}
<|endoftext|>


<commit_before>#include <QtGui/QApplication>

#include "mainwindow.h"

#include <iostream>
#include <mongo/client/dbclient.h>
#include <mongo/client/gridfs.h>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDebug>

using namespace mongo;
using std::cout;
using std::endl;

QString m_fileName = "/home/marcus/ssd/src/avogadro/testfiles/benzene.mold";
QFileInfo info(m_fileName);

int main(int argc, char *argv[])
{

  QCoreApplication::setOrganizationName("Kitware");
  QCoreApplication::setOrganizationDomain("kitware.com");
  QCoreApplication::setApplicationName("MoleQueue");
  QCoreApplication::setApplicationVersion("0.1.0");
  QApplication app(argc, argv);

  ChemData::MainWindow window;
  window.show();
  return app.exec();

  DBClientConnection c;
  try {
    c.connect("localhost");
    cout << "connected OK" << endl;
  }
  catch (DBException &e) {
    cout << "caught " << e.what() << endl;
    return 1;
  }

  QFile file("/home/marcus/SBIR_chem_data.csv");
  file.open(QIODevice::ReadOnly);
  file.readLine();
  while (!file.atEnd()) {
    QString tmp = file.readLine();
    QStringList cmp = tmp.split(",");
    if (cmp.size() == 5) {
      qDebug() << "String:" << cmp[0];
      BSONObj p = BSONObjBuilder().genOID()
                                  .append("CAS", cmp[0].trimmed().toStdString())
                                  .append("Set", cmp[1].trimmed().toStdString())
                                  .append("Observed", cmp[2].toDouble())
                                  .append("Predicted log Sw (MLR)", cmp[3].toDouble())
                                  .append("Predicted log Sw (RF)", cmp[4].toDouble())
                                  .obj();
      c.insert("chem.import", p);
    }
    else
      qDebug() << "Wrong size" << cmp.size() << tmp;
  }

  return 0;

  GridFS gfs(c, "tutorial", "fs");
  BSONObj ret = gfs.storeFile(m_fileName.toStdString(),
                              info.fileName().toStdString());
  BSONObj b = BSONObjBuilder().genOID()
                              .appendElements(ret)
            .append("fileInserted", "01")
            .obj();

  BSONObj p = BSONObjBuilder().genOID()
                               .append("name", "Joe")
             .append("age", 33)
             .obj();
  c.insert("tutorial.persons", p);
  c.insert("tutorial.persons", b);

  cout << "count: " << c.count("tutorial.persons") << endl;
  auto_ptr<DBClientCursor> cursor =
    c.query("tutorial.persons");//QUERY("age" << 33));
  while (cursor->more())
    cout << cursor->next().toString() << endl;
}

<commit_msg>Set the correct application name for ChemData<commit_after>#include <QtGui/QApplication>

#include "mainwindow.h"

#include <iostream>
#include <mongo/client/dbclient.h>
#include <mongo/client/gridfs.h>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDebug>

using namespace mongo;
using std::cout;
using std::endl;

QString m_fileName = "/home/marcus/ssd/src/avogadro/testfiles/benzene.mold";
QFileInfo info(m_fileName);

int main(int argc, char *argv[])
{

  QCoreApplication::setOrganizationName("Kitware");
  QCoreApplication::setOrganizationDomain("kitware.com");
  QCoreApplication::setApplicationName("ChemData");
  QCoreApplication::setApplicationVersion("0.1.0");
  QApplication app(argc, argv);

  ChemData::MainWindow window;
  window.show();
  return app.exec();

  DBClientConnection c;
  try {
    c.connect("localhost");
    cout << "connected OK" << endl;
  }
  catch (DBException &e) {
    cout << "caught " << e.what() << endl;
    return 1;
  }

  QFile file("/home/marcus/SBIR_chem_data.csv");
  file.open(QIODevice::ReadOnly);
  file.readLine();
  while (!file.atEnd()) {
    QString tmp = file.readLine();
    QStringList cmp = tmp.split(",");
    if (cmp.size() == 5) {
      qDebug() << "String:" << cmp[0];
      BSONObj p = BSONObjBuilder().genOID()
                                  .append("CAS", cmp[0].trimmed().toStdString())
                                  .append("Set", cmp[1].trimmed().toStdString())
                                  .append("Observed", cmp[2].toDouble())
                                  .append("Predicted log Sw (MLR)", cmp[3].toDouble())
                                  .append("Predicted log Sw (RF)", cmp[4].toDouble())
                                  .obj();
      c.insert("chem.import", p);
    }
    else
      qDebug() << "Wrong size" << cmp.size() << tmp;
  }

  return 0;

  GridFS gfs(c, "tutorial", "fs");
  BSONObj ret = gfs.storeFile(m_fileName.toStdString(),
                              info.fileName().toStdString());
  BSONObj b = BSONObjBuilder().genOID()
                              .appendElements(ret)
            .append("fileInserted", "01")
            .obj();

  BSONObj p = BSONObjBuilder().genOID()
                               .append("name", "Joe")
             .append("age", 33)
             .obj();
  c.insert("tutorial.persons", p);
  c.insert("tutorial.persons", b);

  cout << "count: " << c.count("tutorial.persons") << endl;
  auto_ptr<DBClientCursor> cursor =
    c.query("tutorial.persons");//QUERY("age" << 33));
  while (cursor->more())
    cout << cursor->next().toString() << endl;
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2009  George Kiagiadakis <kiagiadakis.george@gmail.com>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "pad.h"
#include "caps.h"
#include "element.h"
#include "query.h"
#include "event.h"
#include <QtCore/QDebug>
#include <gst/gstpad.h>
#include <gst/gstutils.h>

namespace QGst {

//static
PadPtr Pad::create(PadDirection direction, const char *name)
{
    GstPad *pad = gst_pad_new(name, static_cast<GstPadDirection>(direction));
    if (pad) {
        gst_object_ref_sink(pad);
    }
    return PadPtr::wrap(pad, false);
}

PadDirection Pad::direction() const
{
    return static_cast<PadDirection>(gst_pad_get_direction(object<GstPad>()));
}

ElementPtr Pad::parentElement() const
{
    return ElementPtr::wrap(gst_pad_get_parent_element(object<GstPad>()), false);
}

PadPtr Pad::peer() const
{
    return PadPtr::wrap(gst_pad_get_peer(object<GstPad>()), false);
}

bool Pad::isLinked() const
{
    return gst_pad_is_linked(object<GstPad>());
}

bool Pad::canLink(const PadPtr & sink) const
{
    return gst_pad_can_link(object<GstPad>(), sink);
}

PadLinkReturn Pad::link(const PadPtr & sink)
{
    return static_cast<PadLinkReturn>(gst_pad_link(object<GstPad>(), sink));
}

bool Pad::unlink(const PadPtr & sink)
{
    return gst_pad_unlink(object<GstPad>(), sink);
}

CapsPtr Pad::caps() const
{
    return CapsPtr::wrap(gst_pad_get_current_caps(object<GstPad>()), false);
}

CapsPtr Pad::allowedCaps() const
{
    return CapsPtr::wrap(gst_pad_get_allowed_caps(object<GstPad>()), false);
}

CapsPtr Pad::negotiatedCaps() const
{
    return CapsPtr::wrap(gst_pad_get_current_caps(object<GstPad>()), false);
}

bool Pad::setCaps(const CapsPtr & caps)
{
    if (caps.isNull() || !caps->isFixed()) {
        return false;
    }
    CapsEventPtr event = CapsEvent::create(caps);
    return sendEvent(event);
}

bool Pad::isActive() const
{
    return gst_pad_is_active(object<GstPad>());
}

bool Pad::setActive(bool active)
{
    return gst_pad_set_active(object<GstPad>(), active);
}

bool Pad::isBlocked() const
{
    return gst_pad_is_blocked(object<GstPad>());
}

bool Pad::isBlocking() const
{
    return gst_pad_is_blocking(object<GstPad>());
}

bool Pad::query(const QueryPtr & query)
{
    return gst_pad_query(object<GstPad>(), query);
}

bool Pad::sendEvent(const EventPtr &event)
{
    if (direction() == PadSrc) {
        return gst_pad_push_event(object<GstPad>(), static_cast<GstEvent *>(event));
    } else {
        return gst_pad_send_event(object<GstPad>(), static_cast<GstEvent *>(event));
    }
}

}
<commit_msg>Revert "src/QGst/pad.cpp detect pad type and chose the right pad event sending call."<commit_after>/*
    Copyright (C) 2009  George Kiagiadakis <kiagiadakis.george@gmail.com>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "pad.h"
#include "caps.h"
#include "element.h"
#include "query.h"
#include "event.h"
#include <QtCore/QDebug>
#include <gst/gstpad.h>
#include <gst/gstutils.h>

namespace QGst {

//static
PadPtr Pad::create(PadDirection direction, const char *name)
{
    GstPad *pad = gst_pad_new(name, static_cast<GstPadDirection>(direction));
    if (pad) {
        gst_object_ref_sink(pad);
    }
    return PadPtr::wrap(pad, false);
}

PadDirection Pad::direction() const
{
    return static_cast<PadDirection>(gst_pad_get_direction(object<GstPad>()));
}

ElementPtr Pad::parentElement() const
{
    return ElementPtr::wrap(gst_pad_get_parent_element(object<GstPad>()), false);
}

PadPtr Pad::peer() const
{
    return PadPtr::wrap(gst_pad_get_peer(object<GstPad>()), false);
}

bool Pad::isLinked() const
{
    return gst_pad_is_linked(object<GstPad>());
}

bool Pad::canLink(const PadPtr & sink) const
{
    return gst_pad_can_link(object<GstPad>(), sink);
}

PadLinkReturn Pad::link(const PadPtr & sink)
{
    return static_cast<PadLinkReturn>(gst_pad_link(object<GstPad>(), sink));
}

bool Pad::unlink(const PadPtr & sink)
{
    return gst_pad_unlink(object<GstPad>(), sink);
}

CapsPtr Pad::caps() const
{
    return CapsPtr::wrap(gst_pad_get_current_caps(object<GstPad>()), false);
}

CapsPtr Pad::allowedCaps() const
{
    return CapsPtr::wrap(gst_pad_get_allowed_caps(object<GstPad>()), false);
}

CapsPtr Pad::negotiatedCaps() const
{
    return CapsPtr::wrap(gst_pad_get_current_caps(object<GstPad>()), false);
}

bool Pad::setCaps(const CapsPtr & caps)
{
    if (caps.isNull() || !caps->isFixed()) {
        return false;
    }
    CapsEventPtr event = CapsEvent::create(caps);
    return sendEvent(event);
}

bool Pad::isActive() const
{
    return gst_pad_is_active(object<GstPad>());
}

bool Pad::setActive(bool active)
{
    return gst_pad_set_active(object<GstPad>(), active);
}

bool Pad::isBlocked() const
{
    return gst_pad_is_blocked(object<GstPad>());
}

bool Pad::isBlocking() const
{
    return gst_pad_is_blocking(object<GstPad>());
}

bool Pad::query(const QueryPtr & query)
{
    return gst_pad_query(object<GstPad>(), query);
}

bool Pad::sendEvent(const EventPtr &event)
{
    return gst_pad_send_event(object<GstPad>(), event);
}

}
<|endoftext|>


<commit_before>#include "mqtt_tcp_server.hpp"
#include "stream.hpp"
#include <signal.h>

using boost::asio::ip::tcp;

MqttTcpServer::MqttTcpServer(int port):
    _ioService(),
    _signals(_ioService),
    _acceptor(_ioService, tcp::endpoint(tcp::v4(), port)),
    _connectionManager(),
    _socket(_ioService)
{

    _signals.add(SIGINT);
    _signals.add(SIGTERM);

#ifdef SIGQUIT
    _signals.add(SIGQUIT);
#endif

    doAwaitStop();
    doAccept();
}

void MqttTcpServer::run() {
    _ioService.run();
}

void MqttTcpServer::doAwaitStop() {
    _signals.async_wait([this](boost::system::error_code, int) {
            _acceptor.close();
            _connectionManager.stopAll();
        });
}

namespace {
class MqttTcpConnection: public Connection, public MqttConnection {
public:
    MqttTcpConnection(const MqttTcpConnection&) = delete;
    MqttTcpConnection& operator=(const MqttTcpConnection&) = delete;

    enum { BUFFER_SIZE = 16384 };
    explicit MqttTcpConnection(boost::asio::ip::tcp::socket socket,
                               ConnectionManager& manager,
                               MqttServer& server):
        Connection(std::move(socket), manager),
        _mqttServer(server),
        _stream(BUFFER_SIZE) {

    }

    virtual void handleRead(std::size_t numBytes) override {
        _stream.read(_mqttServer, *this, getBytes(numBytes));
    }

    virtual void write(std::vector<ubyte> bytes) override {
        writeBytes(bytes);
    }

    virtual void disconnect() override {
        stop();
    }

private:

    MqttServer& _mqttServer;
    MqttStream _stream;

};
} //anonymous namespace

void MqttTcpServer::doAccept() {
    _acceptor.async_accept(_socket,
                           [this](boost::system::error_code error) {
                               if(!_acceptor.is_open()) return;
                               if(!error) {
                                   _connectionManager.start(std::make_shared<MqttTcpConnection>(
                                                                std::move(_socket),
                                                                _connectionManager,
                                                                _mqttServer));
                               }

                               doAccept();
                           });
}
<commit_msg>Added _connected variable to MqttTcpConnection just like the D version. loadtest works ok until the system runs out of memory due to memory leakage<commit_after>#include "mqtt_tcp_server.hpp"
#include "stream.hpp"
#include <signal.h>

using boost::asio::ip::tcp;

MqttTcpServer::MqttTcpServer(int port):
    _ioService(),
    _signals(_ioService),
    _acceptor(_ioService, tcp::endpoint(tcp::v4(), port)),
    _connectionManager(),
    _socket(_ioService)
{

    _signals.add(SIGINT);
    _signals.add(SIGTERM);

#ifdef SIGQUIT
    _signals.add(SIGQUIT);
#endif

    doAwaitStop();
    doAccept();
}

void MqttTcpServer::run() {
    _ioService.run();
}

void MqttTcpServer::doAwaitStop() {
    _signals.async_wait([this](boost::system::error_code, int) {
            _acceptor.close();
            _connectionManager.stopAll();
        });
}

namespace {
class MqttTcpConnection: public Connection, public MqttConnection {
public:
    MqttTcpConnection(const MqttTcpConnection&) = delete;
    MqttTcpConnection& operator=(const MqttTcpConnection&) = delete;

    enum { BUFFER_SIZE = 16384 };
    explicit MqttTcpConnection(boost::asio::ip::tcp::socket socket,
                               ConnectionManager& manager,
                               MqttServer& server):
        Connection(std::move(socket), manager),
        _connected(true),
        _mqttServer(server),
        _stream(BUFFER_SIZE) {

    }

    virtual void handleRead(std::size_t numBytes) override {
        if(_connected) _stream.read(_mqttServer, *this, getBytes(numBytes));
    }

    virtual void write(std::vector<ubyte> bytes) override {
        if(_connected) writeBytes(bytes);
    }

    virtual void disconnect() override {
        _connected = false;
        stop();
    }

private:

    bool _connected;
    MqttServer& _mqttServer;
    MqttStream _stream;

};
} //anonymous namespace

void MqttTcpServer::doAccept() {
    _acceptor.async_accept(_socket,
                           [this](boost::system::error_code error) {
                               if(!_acceptor.is_open()) return;
                               if(!error) {
                                   _connectionManager.start(std::make_shared<MqttTcpConnection>(
                                                                std::move(_socket),
                                                                _connectionManager,
                                                                _mqttServer));
                               }

                               doAccept();
                           });
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include "AliMUONDigit.h"

//-----------------------------------------------------------------------------
/// \class AliMUONDigit
/// A class representing a digit (with MC information if possible)
/// in the MUON spectrometer either in tracking or trigger chambers.
///
/// A digit holds the signal (proportional to a charge) on a pad
/// (or strip).
///
/// This class is used to represent either sdigits (purely simulated digit,
/// with no electronic noise whatsoever) or digits (simulated ones but
/// including electronic noise and de-calibration, to closely ressemble real ones).
//-----------------------------------------------------------------------------

/// \cond CLASSIMP
ClassImp(AliMUONDigit)
/// \endcond

//_____________________________________________________________________________
AliMUONDigit::AliMUONDigit()
:
AliMUONVDigit(),
fDetElemId(0),
fManuId(0),
fManuChannel(0),
fSignal(0.0),
fPadX(-1),
fPadY(-1),
fCathode(0),
fADC(0),
fFlags(0),
fNtracks(0),
fTcharges(0x0),
fTracks(0x0),
fHit(0),
fStatusMap(0)
{
  /// Default constructor
}

//_____________________________________________________________________________
AliMUONDigit::AliMUONDigit(Int_t detElemId, Int_t manuId,
                           Int_t manuChannel, Int_t cathode)
:
AliMUONVDigit(detElemId,manuId,manuChannel,cathode),
fDetElemId(detElemId),
fManuId(manuId),
fManuChannel(manuChannel),
fSignal(0.0),
fPadX(-1),
fPadY(-1),
fCathode(cathode),
fADC(0),
fFlags(0),
fNtracks(0),
fTcharges(0x0),
fTracks(0x0),
fHit(0),
fStatusMap(0)
{
  /// Normal constructor
}

//_____________________________________________________________________________
AliMUONDigit::AliMUONDigit(const AliMUONDigit& digit)
: AliMUONVDigit(),
fDetElemId(0),
fManuId(0),
fManuChannel(0),
fSignal(0.0),
fPadX(-1),
fPadY(-1),
fCathode(0),
fADC(0),
fFlags(0),
fNtracks(0),
fTcharges(0x0),
fTracks(0x0),
fHit(0),
fStatusMap(0)
{
  /// Copy constructor

   (static_cast<const AliMUONDigit&>(digit)).Copy(*this);
}

//_____________________________________________________________________________
AliMUONDigit::~AliMUONDigit()
{
  /// Destructor

  delete[] fTcharges;
  delete[] fTracks;
}

//_____________________________________________________________________________
void
AliMUONDigit::AddTrack(Int_t trackNumber, Float_t trackCharge)
{
  /// Add 1 track information to the track list we keep.
  /// The implementation below is dumb, you've been warned !

  // First check if track is already there, in which
  // case we simply increment its charge.
  for ( Int_t i = 0; i < Ntracks(); ++i )
  {
      if ( Track(i) == trackNumber )
      {
        fTcharges[i] += trackCharge;
        return;
      }
  }

  // Nope. It's a brand new track. Make a new array to get space
  // for it, copy the old array into new one, and add the track.
  Int_t* newTracks = new Int_t[fNtracks+1];
  Float_t* newTcharges = new Float_t[fNtracks+1];

  for ( Int_t i = 0; i < fNtracks; ++i )
  {
    newTracks[i] = fTracks[i];
    newTcharges[i] = fTcharges[i];
  }

  newTracks[fNtracks] = trackNumber;
  newTcharges[fNtracks] = trackCharge;

  delete[] fTracks;
  delete[] fTcharges;

  fTracks = newTracks;
  fTcharges = newTcharges;

  ++fNtracks;
}

//_____________________________________________________________________________
void
AliMUONDigit::Clear(Option_t*)
{
  /// Reset this digit, in particular the internal arrays are deleted.

  delete[] fTracks;
  delete[] fTcharges;
  fTracks=0x0;
  fTcharges=0x0;
  fNtracks=0;
}

//______________________________________________________________________________
void
AliMUONDigit::Copy(TObject& obj) const
{
  /// Copy this line to line.

  TObject::Copy(obj);
  AliMUONDigit& digit = static_cast<AliMUONDigit&>(obj);

  digit.fDetElemId = fDetElemId;
  digit.fManuId = fManuId;
  digit.fManuChannel = fManuChannel;
  digit.fSignal = fSignal;

  digit.fPadX = fPadX;
  digit.fPadY = fPadY;
  digit.fCathode = fCathode;
  digit.fADC = fADC;
  digit.fFlags = fFlags;

  digit.fNtracks = fNtracks;

  delete[] digit.fTcharges;
  delete[] digit.fTracks;

  if ( fNtracks )
  {
    digit.fTcharges = new Float_t[fNtracks];
    digit.fTracks = new Int_t[fNtracks];
  }

  for ( Int_t i=0; i<fNtracks; ++i )
  {
    digit.fTcharges[i] = fTcharges[i];
    digit.fTracks[i] = fTracks[i];
  }

  digit.fHit = fHit;
  digit.fStatusMap = fStatusMap;
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsNoiseOnly() const
{
  /// Whether this (simulated only) digit is only due to noise.

  return (fFlags & fgkNoiseOnlyMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsSaturated() const
{
  /// Whether this digit is saturated or not.

  return (fFlags & fgkSaturatedMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsCalibrated() const
{
  /// Whether this digit is calibrated or not

  return (fFlags & fgkCalibratedMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsUsed() const
{
  /// Whether this digit is used or not (in a cluster, for instance)

  return (fFlags & fgkUsedMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsEfficiencyApplied() const
{
  /// Whether this digit had efficiency applied or not

  return (fFlags & fgkEfficiencyMask );
}

//_____________________________________________________________________________
void
AliMUONDigit::Used(Bool_t value)
{
  /// Set the Used status of this digit.

  if ( value )
  {
    fFlags |= fgkUsedMask;
  }
  else
  {
    fFlags ^= fgkUsedMask;
  }
}

//_____________________________________________________________________________
void
AliMUONDigit::Calibrated(Bool_t value)
{
  /// Set the Calibrated status of this digit.

  if ( value )
  {
    fFlags |= fgkCalibratedMask;
  }
  else
  {
    fFlags ^= fgkCalibratedMask;
  }
}

//_____________________________________________________________________________
void
AliMUONDigit::EfficiencyApplied(Bool_t value)
{
  /// Set the EfficiencyApplied status of this digit.

  if ( value )
  {
    fFlags |= fgkEfficiencyMask;
  }
  else
  {
    fFlags ^= fgkEfficiencyMask;
  }
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::MergeWith(const AliMUONVDigit& src)
{
  /// Merge with src.

  Bool_t check = ( src.DetElemId() == DetElemId() &&
                   src.PadX() == PadX() &&
                   src.PadY() == PadY() &&
                   src.Cathode() == Cathode() );
  if (!check)
  {
    return kFALSE;
  }

  AddCharge(src.Charge());
  for ( Int_t i = 0; i < src.Ntracks(); ++i )
  {
    AddTrack(src.Track(i),src.TrackCharge(i));
  }
  return kTRUE;
}

//_____________________________________________________________________________
void
AliMUONDigit::NoiseOnly(Bool_t value)
{
  /// Set the NoiseOnly status of this digit.

  if ( value )
  {
    fFlags |= fgkNoiseOnlyMask;
  }
  else
  {
    fFlags ^= fgkNoiseOnlyMask;
  }
}

//_____________________________________________________________________________
AliMUONDigit&
AliMUONDigit::operator=(const AliMUONDigit& digit)
{
  /// Assignement operator.

  if ( this != &digit )
  {
    digit.Copy(*this);
  }
  return *this;
}

//_____________________________________________________________________________
void
AliMUONDigit::PatchTracks(Int_t mask)
{
  /// Add mask to each track number.

  for ( Int_t i = 0; i < Ntracks(); ++i )
  {
    fTracks[i] += mask;
  }
}

//_____________________________________________________________________________
void
AliMUONDigit::Saturated(Bool_t value)
{
  /// Set the saturation status of this digit.

  if ( value )
  {
    fFlags |= fgkSaturatedMask;
  }
  else
  {
    fFlags ^= fgkSaturatedMask;
  }
}

//_____________________________________________________________________________
Int_t
AliMUONDigit::Track(Int_t i) const
{
  /// Return the i-th track number (if i is >=0 and < Ntracks()) or -1.

  if ( i >= 0 && i < fNtracks )
  {
    return fTracks[i];
  }

  return -1;
}

//_____________________________________________________________________________
Float_t
AliMUONDigit::TrackCharge(Int_t i) const
{
  /// Return the i-th track charge (if i is >=0 and < Ntracjs()) or -1.

  if ( i >= 0 && i < fNtracks )
  {
    return fTcharges[i];
  }

  return -1;
}

//_____________________________________________________________________________
UInt_t
AliMUONDigit::GetUniqueID() const
{
  /// Return a single integer with id information

  return BuildUniqueID(DetElemId(),ManuId(),ManuChannel(),Cathode());
}
<commit_msg>Fixed uncorrect resetting of status flags<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include "AliMUONDigit.h"

//-----------------------------------------------------------------------------
/// \class AliMUONDigit
/// A class representing a digit (with MC information if possible)
/// in the MUON spectrometer either in tracking or trigger chambers.
///
/// A digit holds the signal (proportional to a charge) on a pad
/// (or strip).
///
/// This class is used to represent either sdigits (purely simulated digit,
/// with no electronic noise whatsoever) or digits (simulated ones but
/// including electronic noise and de-calibration, to closely ressemble real ones).
//-----------------------------------------------------------------------------

/// \cond CLASSIMP
ClassImp(AliMUONDigit)
/// \endcond

//_____________________________________________________________________________
AliMUONDigit::AliMUONDigit()
:
AliMUONVDigit(),
fDetElemId(0),
fManuId(0),
fManuChannel(0),
fSignal(0.0),
fPadX(-1),
fPadY(-1),
fCathode(0),
fADC(0),
fFlags(0),
fNtracks(0),
fTcharges(0x0),
fTracks(0x0),
fHit(0),
fStatusMap(0)
{
  /// Default constructor
}

//_____________________________________________________________________________
AliMUONDigit::AliMUONDigit(Int_t detElemId, Int_t manuId,
                           Int_t manuChannel, Int_t cathode)
:
AliMUONVDigit(detElemId,manuId,manuChannel,cathode),
fDetElemId(detElemId),
fManuId(manuId),
fManuChannel(manuChannel),
fSignal(0.0),
fPadX(-1),
fPadY(-1),
fCathode(cathode),
fADC(0),
fFlags(0),
fNtracks(0),
fTcharges(0x0),
fTracks(0x0),
fHit(0),
fStatusMap(0)
{
  /// Normal constructor
}

//_____________________________________________________________________________
AliMUONDigit::AliMUONDigit(const AliMUONDigit& digit)
: AliMUONVDigit(),
fDetElemId(0),
fManuId(0),
fManuChannel(0),
fSignal(0.0),
fPadX(-1),
fPadY(-1),
fCathode(0),
fADC(0),
fFlags(0),
fNtracks(0),
fTcharges(0x0),
fTracks(0x0),
fHit(0),
fStatusMap(0)
{
  /// Copy constructor

   (static_cast<const AliMUONDigit&>(digit)).Copy(*this);
}

//_____________________________________________________________________________
AliMUONDigit::~AliMUONDigit()
{
  /// Destructor

  delete[] fTcharges;
  delete[] fTracks;
}

//_____________________________________________________________________________
void
AliMUONDigit::AddTrack(Int_t trackNumber, Float_t trackCharge)
{
  /// Add 1 track information to the track list we keep.
  /// The implementation below is dumb, you've been warned !

  // First check if track is already there, in which
  // case we simply increment its charge.
  for ( Int_t i = 0; i < Ntracks(); ++i )
  {
      if ( Track(i) == trackNumber )
      {
        fTcharges[i] += trackCharge;
        return;
      }
  }

  // Nope. It's a brand new track. Make a new array to get space
  // for it, copy the old array into new one, and add the track.
  Int_t* newTracks = new Int_t[fNtracks+1];
  Float_t* newTcharges = new Float_t[fNtracks+1];

  for ( Int_t i = 0; i < fNtracks; ++i )
  {
    newTracks[i] = fTracks[i];
    newTcharges[i] = fTcharges[i];
  }

  newTracks[fNtracks] = trackNumber;
  newTcharges[fNtracks] = trackCharge;

  delete[] fTracks;
  delete[] fTcharges;

  fTracks = newTracks;
  fTcharges = newTcharges;

  ++fNtracks;
}

//_____________________________________________________________________________
void
AliMUONDigit::Clear(Option_t*)
{
  /// Reset this digit, in particular the internal arrays are deleted.

  delete[] fTracks;
  delete[] fTcharges;
  fTracks=0x0;
  fTcharges=0x0;
  fNtracks=0;
}

//______________________________________________________________________________
void
AliMUONDigit::Copy(TObject& obj) const
{
  /// Copy this line to line.

  TObject::Copy(obj);
  AliMUONDigit& digit = static_cast<AliMUONDigit&>(obj);

  digit.fDetElemId = fDetElemId;
  digit.fManuId = fManuId;
  digit.fManuChannel = fManuChannel;
  digit.fSignal = fSignal;

  digit.fPadX = fPadX;
  digit.fPadY = fPadY;
  digit.fCathode = fCathode;
  digit.fADC = fADC;
  digit.fFlags = fFlags;

  digit.fNtracks = fNtracks;

  delete[] digit.fTcharges;
  delete[] digit.fTracks;

  if ( fNtracks )
  {
    digit.fTcharges = new Float_t[fNtracks];
    digit.fTracks = new Int_t[fNtracks];
  }

  for ( Int_t i=0; i<fNtracks; ++i )
  {
    digit.fTcharges[i] = fTcharges[i];
    digit.fTracks[i] = fTracks[i];
  }

  digit.fHit = fHit;
  digit.fStatusMap = fStatusMap;
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsNoiseOnly() const
{
  /// Whether this (simulated only) digit is only due to noise.

  return (fFlags & fgkNoiseOnlyMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsSaturated() const
{
  /// Whether this digit is saturated or not.

  return (fFlags & fgkSaturatedMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsCalibrated() const
{
  /// Whether this digit is calibrated or not

  return (fFlags & fgkCalibratedMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsUsed() const
{
  /// Whether this digit is used or not (in a cluster, for instance)

  return (fFlags & fgkUsedMask );
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::IsEfficiencyApplied() const
{
  /// Whether this digit had efficiency applied or not

  return (fFlags & fgkEfficiencyMask );
}

//_____________________________________________________________________________
void
AliMUONDigit::Used(Bool_t value)
{
  /// Set the Used status of this digit.

  if ( value )
  {
    fFlags |= fgkUsedMask;
  }
  else
  {
    fFlags &= ~fgkUsedMask;
  }
}

//_____________________________________________________________________________
void
AliMUONDigit::Calibrated(Bool_t value)
{
  /// Set the Calibrated status of this digit.

  if ( value )
  {
    fFlags |= fgkCalibratedMask;
  }
  else
  {
    fFlags &= ~fgkCalibratedMask;
  }
}

//_____________________________________________________________________________
void
AliMUONDigit::EfficiencyApplied(Bool_t value)
{
  /// Set the EfficiencyApplied status of this digit.

  if ( value )
  {
    fFlags |= fgkEfficiencyMask;
  }
  else
  {
    fFlags &= ~fgkEfficiencyMask;
  }
}

//_____________________________________________________________________________
Bool_t
AliMUONDigit::MergeWith(const AliMUONVDigit& src)
{
  /// Merge with src.

  Bool_t check = ( src.DetElemId() == DetElemId() &&
                   src.PadX() == PadX() &&
                   src.PadY() == PadY() &&
                   src.Cathode() == Cathode() );
  if (!check)
  {
    return kFALSE;
  }

  AddCharge(src.Charge());
  for ( Int_t i = 0; i < src.Ntracks(); ++i )
  {
    AddTrack(src.Track(i),src.TrackCharge(i));
  }
  return kTRUE;
}

//_____________________________________________________________________________
void
AliMUONDigit::NoiseOnly(Bool_t value)
{
  /// Set the NoiseOnly status of this digit.

  if ( value )
  {
    fFlags |= fgkNoiseOnlyMask;
  }
  else
  {
    fFlags &= ~fgkNoiseOnlyMask;
  }
}

//_____________________________________________________________________________
AliMUONDigit&
AliMUONDigit::operator=(const AliMUONDigit& digit)
{
  /// Assignement operator.

  if ( this != &digit )
  {
    digit.Copy(*this);
  }
  return *this;
}

//_____________________________________________________________________________
void
AliMUONDigit::PatchTracks(Int_t mask)
{
  /// Add mask to each track number.

  for ( Int_t i = 0; i < Ntracks(); ++i )
  {
    fTracks[i] += mask;
  }
}

//_____________________________________________________________________________
void
AliMUONDigit::Saturated(Bool_t value)
{
  /// Set the saturation status of this digit.

  if ( value )
  {
    fFlags |= fgkSaturatedMask;
  }
  else
  {
    fFlags &= ~fgkSaturatedMask;
  }
}

//_____________________________________________________________________________
Int_t
AliMUONDigit::Track(Int_t i) const
{
  /// Return the i-th track number (if i is >=0 and < Ntracks()) or -1.

  if ( i >= 0 && i < fNtracks )
  {
    return fTracks[i];
  }

  return -1;
}

//_____________________________________________________________________________
Float_t
AliMUONDigit::TrackCharge(Int_t i) const
{
  /// Return the i-th track charge (if i is >=0 and < Ntracjs()) or -1.

  if ( i >= 0 && i < fNtracks )
  {
    return fTcharges[i];
  }

  return -1;
}

//_____________________________________________________________________________
UInt_t
AliMUONDigit::GetUniqueID() const
{
  /// Return a single integer with id information

  return BuildUniqueID(DetElemId(),ManuId(),ManuChannel(),Cathode());
}
<|endoftext|>


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

#include "CodeGenerationVisitor.h"

#include "expressions/ReferenceExpression.h"
#include "expressions/MetaCallExpression.h"

#include "ModelBase/src/nodes/NameText.h"

#include "declarations/MetaDefinition.h"
#include "expressions/BooleanLiteral.h"

namespace OOModel {

CodeGenerationVisitor::CodeGenerationVisitor(QMap<QString, Model::Node *> args) : args_{args} {}

void CodeGenerationVisitor::init()
{
	addType<ReferenceExpression>(visitReferenceExpression);
	addType<Model::NameText>(visitNameText);
	addType<MetaCallExpression>(visitMetaCallExpression);
}

void CodeGenerationVisitor::visitReferenceExpression(CodeGenerationVisitor* v, OOModel::ReferenceExpression* n)
{
	auto input = n->name();

	if (!input.contains("##"))
	{
		if (auto argument = v->args_[input])
		{
			if (auto argumentReference = DCast<ReferenceExpression>(argument))
			{
				// case: there exists a replacement and it is another ReferenceExpression
				// -> copy name (replacing it would cause child nodes of n to disappear)

				n->setName(argumentReference->name());
			}
			else
			{
				// case: there exists a replacement and it is not a ReferenceExpression
				// -> replace node

				auto p = n->parent();

				p->beginModification("change node in code generation visitor");

				auto cloned = argument->clone();
				p->replaceChild(n, cloned);

				p->endModification();

				// visit the cloned tree and return to avoid visiting the children of n
				v->visitChildren(cloned);
				return;
			}
		}
	}
	else
	{
		// case: n's name is a concatenated identifier (a##b)
		// -> build identifier

		QStringList parts = input.split("##");

		for (auto i = 0; i < parts.size(); i++)
			if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]]))
				parts[i] = argument->name();

		n->setName(parts.join(""));
	}

	v->visitChildren(n);
}

void CodeGenerationVisitor::visitNameText(CodeGenerationVisitor* v, Model::NameText* n)
{
	auto input = n->get();

	if (!input.contains("##"))
	{
		if (auto argument = DCast<ReferenceExpression>(v->args_[input]))
		{
			// case: n's name is an existing argument of type ReferenceExpression
			// -> copy name as new text

			n->set(argument->name());
		}
	}
	else
	{
		// case: n's text is a concatenated text (a##b)
		// -> build text

		QStringList parts = input.split("##");

		for (auto i = 0; i < parts.size(); i++)
			if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]]))
				parts[i] = argument->name();

		n->set(parts.join(""));
	}

	v->visitChildren(n);
}

void CodeGenerationVisitor::visitMetaCallExpression(CodeGenerationVisitor* v, MetaCallExpression* n)
{
	/*
	 * process arguments before generating.
	 * this ensures proper argument propagation.
	 */
	for (auto child : n->children()) v->visit(child);

	if (!n->metaDefinition())
	{
		// case: unresolved meta definition
		// -> check if it is a predefined meta function

		if (auto metaDef = DCast<ReferenceExpression>(n->callee()))
			v->handlePredefinedFunction(metaDef->name(), n);
	}
	else
	{
		// case: resolved meta definition
		// -> generate recursively

		n->generate();
	}
}

void CodeGenerationVisitor::handlePredefinedFunction(QString function, MetaCallExpression* n)
{
	if (function == "SET_OVERRIDE_FLAG")
	{
		if (n->arguments()->size() != 1)
		{
			qDebug() << function << "#arguments != 1";
			return;
		}

		if (auto argument = DCast<ReferenceExpression>(n->arguments()->first()))
			if (auto flag = DCast<BooleanLiteral>(args_[argument->name()]))
				if (auto p = n->firstAncestorOfType<Declaration>())
					p->modifiers()->set(Modifier::Override, flag->value());
	}
}

}
<commit_msg>Fix CodeGenerationVisitor to consistently declare tree modifications<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2015 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "CodeGenerationVisitor.h"

#include "expressions/ReferenceExpression.h"
#include "expressions/MetaCallExpression.h"

#include "ModelBase/src/nodes/NameText.h"

#include "declarations/MetaDefinition.h"
#include "expressions/BooleanLiteral.h"

namespace OOModel {

CodeGenerationVisitor::CodeGenerationVisitor(QMap<QString, Model::Node *> args) : args_{args} {}

void CodeGenerationVisitor::init()
{
	addType<ReferenceExpression>(visitReferenceExpression);
	addType<Model::NameText>(visitNameText);
	addType<MetaCallExpression>(visitMetaCallExpression);
}

void CodeGenerationVisitor::visitReferenceExpression(CodeGenerationVisitor* v, OOModel::ReferenceExpression* n)
{
	auto input = n->name();

	if (!input.contains("##"))
	{
		if (auto argument = v->args_[input])
		{
			if (auto argumentReference = DCast<ReferenceExpression>(argument))
			{
				// case: there exists a replacement and it is another ReferenceExpression
				// -> copy name (replacing it would cause child nodes of n to disappear)

				n->beginModification("change node in code generation visitor");

				n->setName(argumentReference->name());

				n->endModification();
			}
			else
			{
				// case: there exists a replacement and it is not a ReferenceExpression
				// -> replace node

				auto p = n->parent();

				p->beginModification("change node in code generation visitor");

				auto cloned = argument->clone();
				p->replaceChild(n, cloned);

				p->endModification();

				// visit the cloned tree and return to avoid visiting the children of n
				v->visitChildren(cloned);
				return;
			}
		}
	}
	else
	{
		// case: n's name is a concatenated identifier (a##b)
		// -> build identifier

		QStringList parts = input.split("##");
		bool modified = false;

		for (auto i = 0; i < parts.size(); i++)
			if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]]))
			{
				parts[i] = argument->name();
				modified = true;
			}

		if (modified)
		{
			n->beginModification("change node in code generation visitor");

			n->setName(parts.join(""));

			n->endModification();
		}
	}

	v->visitChildren(n);
}

void CodeGenerationVisitor::visitNameText(CodeGenerationVisitor* v, Model::NameText* n)
{
	auto input = n->get();

	if (!input.contains("##"))
	{
		if (auto argument = DCast<ReferenceExpression>(v->args_[input]))
		{
			// case: n's name is an existing argument of type ReferenceExpression
			// -> copy name as new text

			n->beginModification("change node in code generation visitor");

			n->set(argument->name());

			n->endModification();
		}
	}
	else
	{
		// case: n's text is a concatenated text (a##b)
		// -> build text

		QStringList parts = input.split("##");
		bool modified = false;

		for (auto i = 0; i < parts.size(); i++)
			if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]]))
			{
				parts[i] = argument->name();
				modified = true;
			}

		if (modified)
		{
			n->beginModification("change node in code generation visitor");

			n->set(parts.join(""));

			n->endModification();
		}
	}

	v->visitChildren(n);
}

void CodeGenerationVisitor::visitMetaCallExpression(CodeGenerationVisitor* v, MetaCallExpression* n)
{
	/*
	 * process arguments before generating.
	 * this ensures proper argument propagation.
	 */
	v->visitChildren(n);

	if (!n->metaDefinition())
	{
		// case: unresolved meta definition
		// -> check if it is a predefined meta function

		if (auto metaDef = DCast<ReferenceExpression>(n->callee()))
			v->handlePredefinedFunction(metaDef->name(), n);
	}
	else
	{
		// case: resolved meta definition
		// -> generate recursively

		n->generate();
	}
}

void CodeGenerationVisitor::handlePredefinedFunction(QString function, MetaCallExpression* n)
{
	if (function == "SET_OVERRIDE_FLAG")
	{
		if (n->arguments()->size() != 1)
		{
			qDebug() << function << "#arguments != 1";
			return;
		}

		if (auto argument = DCast<ReferenceExpression>(n->arguments()->first()))
			if (auto flag = DCast<BooleanLiteral>(args_[argument->name()]))
				if (auto p = n->firstAncestorOfType<Declaration>())
					p->modifiers()->set(Modifier::Override, flag->value());
	}
}

}
<|endoftext|>