<commit_before>//
// This file is part of MipTknzr Library Project
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//

/* -------------------------------------------------------------------------- */

#include <assert.h>
#include <sstream>
#include <iostream>
#include <list>
#include <vector>
#include <unordered_map>
#include <memory>
#include <set>
#include <map>
#include <fstream>
#include <string>

#ifdef _UNICODE
#include <locale>
#include <codecvt>
#include <iomanip>
#endif

#include "mip_json_obj.h"
#include "mip_json_parser.h"

/* -------------------------------------------------------------------------- */

int main(int argc, mip::char_t* argv[])
{
    if (argc<2) {
        std::_cerr << _T("File name missing") << std::endl;
        return 1;
    }

    mip::json_parser_t parser(& std::_cout);

    const mip::char_t* filename = argv[1];

    mip::_ifstream is(filename, std::ios::in | std::ios::binary);

    if (!is.is_open()) {
        std::_cerr << _T("Cannot open ") << filename << std::endl;
        return false;
    }

#ifdef _UNICODE
    const std::locale utf16_locale
        = std::locale(
            std::locale(),
            new std::codecvt_utf16<
            wchar_t,
            0x10ffff,
            std::codecvt_mode(std::little_endian | std::consume_header)>());

    is.imbue(utf16_locale);
#endif

    if (!is.is_open() || is.bad()) {
        std::cerr << _T("error reading the input stream");
        return false;
    }

    std::_cout << _T("Parsing ...") << std::endl << std::endl;

    mip::_stringstream errlog;
    auto res = parser.parse(is, errlog);

    std::_cout
        << std::endl << std::endl
        << _T("...done")
        << std::endl << std::endl;

    if (! res.first) {
        std::_cerr
            << std::endl
            << _T("JSON text is Invalid: ")
            << errlog.str()
            << std::endl;
        return 1;
    }

    std::_cout
        << std::endl
        << std::endl
        << _T("JSON is Valid")
        << std::endl
        << std::endl;

    std::_cout
        << _T("Compact representation")
        << std::endl
        << std::endl;

    if (res.second) {
        std::_cout
            << *res.second
            << std::endl;
    }
    else {
        std::_cout << _T("null") << std::endl;
    }

    return 0;
}
<commit_msg>Update jsonvalid.cc<commit_after>//
// This file is part of MipTknzr Library Project
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//

/* -------------------------------------------------------------------------- */

#include <assert.h>
#include <sstream>
#include <iostream>
#include <list>
#include <vector>
#include <unordered_map>
#include <memory>
#include <set>
#include <map>
#include <fstream>
#include <string>

#ifdef _UNICODE
#include <locale>
#include <codecvt>
#include <iomanip>
#endif

#include "mip_json_obj.h"
#include "mip_json_parser.h"

/* -------------------------------------------------------------------------- */

int main(int argc, mip::char_t* argv[])
{
    if (argc<2) {
        std::_cerr << _T("File name missing") << std::endl;
        return 1;
    }

    mip::json_parser_t parser(& std::_cout);

    const mip::char_t* filename = argv[1];

    mip::_ifstream is(filename, std::ios::in | std::ios::binary);

    if (!is.is_open()) {
        std::_cerr << _T("Cannot open ") << filename << std::endl;
        return false;
    }

#ifdef _UNICODE
    const std::locale utf16_locale
        = std::locale(
            std::locale(),
            new std::codecvt_utf16<
            wchar_t,
            0x10ffff,
            std::codecvt_mode(std::little_endian | std::consume_header)>());

    is.imbue(utf16_locale);
#endif

    if (!is.is_open() || is.bad()) {
        std::cerr << _T("error reading the input stream");
        return 1;
    }

    std::_cout << _T("Parsing ...") << std::endl << std::endl;

    mip::_stringstream errlog;
    auto res = parser.parse(is, errlog);

    std::_cout
        << std::endl << std::endl
        << _T("...done")
        << std::endl << std::endl;

    if (! res.first) {
        std::_cerr
            << std::endl
            << _T("JSON text is Invalid: ")
            << errlog.str()
            << std::endl;
        return 1;
    }

    std::_cout
        << std::endl
        << std::endl
        << _T("JSON is Valid")
        << std::endl
        << std::endl;

    std::_cout
        << _T("Compact representation")
        << std::endl
        << std::endl;

    if (res.second) {
        std::_cout
            << *res.second
            << std::endl;
    }
    else {
        std::_cout << _T("null") << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <util/timer.h>

#include <boost/date_time/posix_time/posix_time.hpp>

namespace izenelib{
namespace util{

class TimerThread
{
public:
    TimerThread(uint32_t due_time, uint32_t interval,
                const Timer::TimerCBType& cb)
            : due_time_(due_time),
            interval_(interval),
            callback_(cb),
            stop_(false)
    {
        thread_.reset(new boost::thread(boost::bind(&TimerThread::run, this)));
    }

    ~TimerThread()
    {
    }

    void stop(bool wait = false)
    {
        {
            boost::mutex::scoped_lock lock(mutex_);
            stop_ = true;
            cond_.notify_all();
        }
        if (!wait)
            return;
        if (boost::this_thread::get_id() == thread_->get_id())
        {
            return;
        }
        thread_->join();
    }

    void run()
    {
        {
            boost::mutex::scoped_lock lock(mutex_);
            cond_.timed_wait(lock,boost::get_system_time() + boost::posix_time::milliseconds(due_time_));
            if (stop_)
            {
                callback_ = NULL;
                return;
            }
        }

        callback_();

        if (interval_ == 0)
        {
            callback_ = NULL;
            return;
        }
        else
        {
            while (!stop_)
            {
                {
                    boost::mutex::scoped_lock lock(mutex_);
                    cond_.timed_wait(lock,boost::get_system_time() +
                        boost::posix_time::milliseconds(interval_));
                    if (stop_)
                    {
                        callback_ = NULL;
                        return;
                    }
                }

                callback_();
            }
        }
        callback_ = NULL;
    }

private:
    boost::scoped_ptr<boost::thread> thread_;
    uint32_t due_time_;
    uint32_t interval_;
    Timer::TimerCBType callback_;
    bool stop_;
    boost::condition_variable cond_;
    boost::mutex mutex_;
};

bool Timer::start(uint32_t due_time, uint32_t interval, const TimerCBType& cb)
{
    if (timer_thread_ || cb == NULL)
    {
        // can not start timer twice or without timer callback.
        return false;
    }
    timer_thread_.reset(new TimerThread(due_time, interval, cb));
    return true;
}

void Timer::stop(bool wait)
{
    if (!timer_thread_)
    {
        return;
    }
    timer_thread_->stop(wait);
}

Timer::Timer() {}

Timer::~Timer()
{
}

}
}
<commit_msg>wait until timer thread exit, or maybe invalid memory access.<commit_after>#include <util/timer.h>

#include <boost/date_time/posix_time/posix_time.hpp>

namespace izenelib{
namespace util{

class TimerThread
{
public:
    TimerThread(uint32_t due_time, uint32_t interval,
                const Timer::TimerCBType& cb)
            : due_time_(due_time),
            interval_(interval),
            callback_(cb),
            stop_(false)
    {
        thread_.reset(new boost::thread(boost::bind(&TimerThread::run, this)));
    }

    ~TimerThread()
    {
        stop(true);
    }

    void stop(bool wait = false)
    {
        {
            boost::mutex::scoped_lock lock(mutex_);
            stop_ = true;
            cond_.notify_all();
        }
        if (!wait)
            return;
        if (boost::this_thread::get_id() == thread_->get_id())
        {
            return;
        }
        try{
        thread_->join();
        }catch(const std::exception& e)
        {
            std::cerr << "join timer thread error: " << e.what() << std::endl;
        }
    }

    void run()
    {
        {
            boost::mutex::scoped_lock lock(mutex_);
            cond_.timed_wait(lock,boost::get_system_time() + boost::posix_time::milliseconds(due_time_));
            if (stop_)
            {
                callback_ = NULL;
                return;
            }
        }

        callback_();

        if (interval_ == 0)
        {
            callback_ = NULL;
            return;
        }
        else
        {
            while (!stop_)
            {
                {
                    boost::mutex::scoped_lock lock(mutex_);
                    cond_.timed_wait(lock,boost::get_system_time() +
                        boost::posix_time::milliseconds(interval_));
                    if (stop_)
                    {
                        callback_ = NULL;
                        return;
                    }
                }

                callback_();
            }
        }
        callback_ = NULL;
    }

private:
    boost::scoped_ptr<boost::thread> thread_;
    uint32_t due_time_;
    uint32_t interval_;
    Timer::TimerCBType callback_;
    bool stop_;
    boost::condition_variable cond_;
    boost::mutex mutex_;
};

bool Timer::start(uint32_t due_time, uint32_t interval, const TimerCBType& cb)
{
    if (timer_thread_ || cb == NULL)
    {
        // can not start timer twice or without timer callback.
        return false;
    }
    timer_thread_.reset(new TimerThread(due_time, interval, cb));
    return true;
}

void Timer::stop(bool wait)
{
    if (!timer_thread_)
    {
        return;
    }
    timer_thread_->stop(wait);
}

Timer::Timer() {}

Timer::~Timer()
{
}

}
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file string.hpp
 * \brief Contains string manipulation functions.
 */

#ifndef CPP_UTILS_STRING_HPP
#define CPP_UTILS_STRING_HPP

#include <locale>
#include <algorithm>

namespace cpp {

/*!
 * \brief Left trim the given string.
 * \param s The string to modify
 * \return a reference to the string (s)
 *
 * All the spaces on the left of the string will be removed.
 */
template <typename CharT, typename Traits, typename Allocator>
std::basic_string<CharT, Traits, Allocator>& ltrim(std::basic_string<CharT, Traits, Allocator>& s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

/*!
 * \brief Right trim the given string.
 * \param s The string to modify
 * \return a reference to the string (s)
 *
 * All the spaces on the right of the string will be removed.
 */
template <typename CharT, typename Traits, typename Allocator>
std::basic_string<CharT, Traits, Allocator>& rtrim(std::basic_string<CharT, Traits, Allocator>& s) {
    s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
    return s;
}

/*!
 * \brief Trim the given string.
 * \param s The string to modify
 * \return a reference to the string (s)
 *
 * All the spaces on the left and the right of the string will be removed.
 */
template <typename CharT, typename Traits, typename Allocator>
std::basic_string<CharT, Traits, Allocator>& trim(std::basic_string<CharT, Traits, Allocator>& s) {
    return ltrim(rtrim(s));
}

} //end of the cpp namespace

#endif //CPP_UTILS_STRING_HPP
<commit_msg>Fixes for C++17  (#1)<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file string.hpp
 * \brief Contains string manipulation functions.
 */

#ifndef CPP_UTILS_STRING_HPP
#define CPP_UTILS_STRING_HPP

#include <locale>
#include <algorithm>

namespace cpp {

/*!
 * \brief Left trim the given string.
 * \param s The string to modify
 * \return a reference to the string (s)
 *
 * All the spaces on the left of the string will be removed.
 */
template <typename CharT, typename Traits, typename Allocator>
std::basic_string<CharT, Traits, Allocator>& ltrim(std::basic_string<CharT, Traits, Allocator>& s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
									[](CharT c) {
										return !std::isspace(c);
									}));
    return s;
}

/*!
 * \brief Right trim the given string.
 * \param s The string to modify
 * \return a reference to the string (s)
 *
 * All the spaces on the right of the string will be removed.
 */
template <typename CharT, typename Traits, typename Allocator>
std::basic_string<CharT, Traits, Allocator>& rtrim(std::basic_string<CharT, Traits, Allocator>& s) {
    s.erase(std::find_if(s.rbegin(), s.rend(),
						 [](CharT c) {
							 return !std::isspace(c);
						 }).base(), s.end());
    return s;
}

/*!
 * \brief Trim the given string.
 * \param s The string to modify
 * \return a reference to the string (s)
 *
 * All the spaces on the left and the right of the string will be removed.
 */
template <typename CharT, typename Traits, typename Allocator>
std::basic_string<CharT, Traits, Allocator>& trim(std::basic_string<CharT, Traits, Allocator>& s) {
    return ltrim(rtrim(s));
}

} //end of the cpp namespace

#endif //CPP_UTILS_STRING_HPP
<|endoftext|>


<commit_before>//
//  main.cpp
//  ResumeBuilder
//
//  Created by Terry Black on 9/17/15.

#include <iostream>
#include <string>
using std::string;
using namespace std;

int NumOfGoals;
int NumOfSkills;
int NumOfAwards;
int NumOfJobs;
int NumOfDegrees;
string Age;
string PhoneNumber;
string SchoolName;
string Major;
string Concentration;
string Minor;
string GradDate;
string CommunityInvolvement;
string Name;
string Address;
string Email;
string Credentials;
bool MajorBool;
bool MinorBool;
bool GradDateBool;

int main() {

    cout << "Hello, Welcome to Resume Builder!\n";
    cout << "Input your name:\n";
    getline (cin, Name);
    cout << "How old are you?\n";
    getline (cin, Age);
    cout << "What is your Address?\n";
    getline (cin, Address);
    cout << "What is your Phone Number?\n";
    getline (cin, PhoneNumber);
    cout << "What is your email?\n";
    getline (cin, Email);
    cout << "What is the name of your School?\n";
    getline (cin, SchoolName);
    cout << "What is your Major? If you don't have one, type: 'none'\n";
    getline (cin, Major);
    if (Major == "none") {
        MajorBool = false;
    }else {
        MajorBool = true;
    }
    cout << "What is your Minor? If you don't have one, type 'none'\n";
    getline (cin, Minor);
    if (Minor == "none") {
        MinorBool = false;
    } else {
        MinorBool = true;
    }
    cout << "What is your graduation date? If you are still enrolled or something, type: 'none'\n";
    getline (cin, GradDate);
    if (GradDate == "none") {
        GradDateBool = false;
    } else {
        GradDateBool = true;
    }
    cout << "How many degrees do you have?\n";
     cin >> numOfDegrees;

    return 0;
}

<commit_msg>Update ResumeBuilder.cpp<commit_after>//
//  main.cpp
//  ResumeBuilder
//
//  Created by Terry Black on 9/17/15.

#include <iostream>
using namespace std;

int numOfGoals;
int numOfSkills;
int numOfAwards;
int numOfJobs;
int numOfDegrees;
string age;
string phoneNumber;
string schoolName;
string major;
string concentration;
string minor;
string gradDate;
string communityInvolvement;
string name;
string address;
string email;
string credentials;
bool majorBool;
bool minorBool;
bool gradDateBool;

int main() {

    cout << "Hello, Welcome to Resume Builder!\n";
    cout << "Input your name:\n";
    getline (cin, Name);
    cout << "How old are you?\n";
    getline (cin, Age);
    cout << "What is your Address?\n";
    getline (cin, Address);
    cout << "What is your Phone Number?\n";
    getline (cin, PhoneNumber);
    cout << "What is your email?\n";
    getline (cin, Email);
    cout << "What is the name of your School?\n";
    getline (cin, SchoolName);
    cout << "What is your Major? If you don't have one, type: 'none'\n";
    getline (cin, Major);
    if (Major == "none") {
        MajorBool = false;
    }else {
        MajorBool = true;
    }
    cout << "What is your Minor? If you don't have one, type 'none'\n";
    getline (cin, Minor);
    if (Minor == "none") {
        MinorBool = false;
    } else {
        MinorBool = true;
    }
    cout << "What is your graduation date? If you are still enrolled or something, type: 'none'\n";
    getline (cin, GradDate);
    if (GradDate == "none") {
        GradDateBool = false;
    } else {
        GradDateBool = true;
    }
    cout << "How many degrees do you have?\n";
     cin >> numOfDegrees;

    return 0;
}

<|endoftext|>


<commit_before>///
/// \file AddTaskPiLam.C
/// \author Andrew Kubera, Ohio State University, andrew.kubera@cern.ch
///

///
/// \brief Adds an AliAnalysisTaskFemto analysis object to the global
///        AliAnalysisManager.
///
/// This macro creates and returns an AliAnalysisTaskFemto object. The task
/// is given the config macro "Train/PionLambdaFemto/ConfigFemtoAnalysis.C"
/// which is run to create the analysis objects. This is fixed (for now), and
/// if an alternative is required, you should use the general AddTaskFemto.C
/// macro.
///
/// Subwagons are supported, the name of which will be appended to the task
/// name. The task name by default is "TaskPiLamFemto" which cannot be changed.
///
/// The output container name is fixed at the standard "femtolist".
///
/// \param params A string forwarded to the ConfigFemtoAnalysis macro for
///               parsing. This string is wrapped in double-quotes so escaping
///               some to ensure results is a string is unneccessary.
///
/// \param maco_filename The path to the femto-confuration macro, passed to the
///                      created TaskFemto. If this parameter has no '/' characters,
///                      and the subwagon_suffix is empty, this is reinterpreted
///                      as the subwagon_suffix.
///
/// \param subwagon_suffix If this macro is run in a train with subwagons, this
///                        will be set with the identifier. NOTE: This
///                        parameter may be found in the macro_filename
///                        variable as the  suffix is simply the last argument
///                        passed. To keep from always having to explicitly set
///                        the macro_filename if using the default, this code
///                        will switch the two parameters if there is no '/'
///                        characters in the macro_filename. As such, keep '/'
///                        out of the subwagon_suffix!
///
AliAnalysisTaskFemto* AddTaskPiLam(TString params,
                                   TString macro_filename="",
                                   TString subwagon_suffix="")
{ // Adds a Pion-Lambda Femtoscopy task to the manager

  const TString DEFAULT_MACRO = "$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionLambdaFemto/ConfigFemtoAnalysis.C";

  // Get the global manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskPiLam", "Could not get the global AliAnalysisManager.");
    return NULL;
  }

  const TString default_name = "TaskPiLamFemto";

  // If the macro_filename was set, use it, else use the default
  if (macro_filename == "") {
    macro_filename = DEFAULT_MACRO;
  }
  // If subwagon_suffix was not set and there are no '/' characters in the
  // macro's path, interpret path as the subwagon_suffix and set default path
  if (subwagon_suffix == "" && !macro_filename.Contains("/")) {
    subwagon_suffix = macro_filename;
    macro_filename = DEFAULT_MACRO;
  }

  // build analysis name out of provided suffix
  const TString task_name = (subwagon_suffix == "")
                          ? default_name
                          : TString::Format("%s_%s", default_name, subwagon_suffix);

  cout << "[AddTaskPiLam]\n";
  cout << "   macro: '" << macro_filename << "'\n";
  cout << "   params: '" << params << "'\n";

  // The analysis config macro for PionLambdaFemto accepts a single string
  // argument, which it interprets.
  // This line escapes some escapable characters (backslash, newline, tab)
  // and wraps that string in double quotes, ensuring that the interpreter
  // reads a string when passing to the macro.
  const TString analysis_params = '"' + params.ReplaceAll("\\", "\\\\")
                                              .ReplaceAll("\n", "\\n")
                                              .ReplaceAll("\t", "\\t") + '"';

  AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto(
    task_name,
    macro_filename,
    analysis_params,
    kFALSE
  );

  mgr->AddTask(taskfemto);

  const char *filename = AliAnalysisManager::GetCommonFileName();
  const TString outputfile = TString::Format("%s:%s", filename, "PWG2FEMTO");

  AliAnalysisDataContainer *cout_femto = mgr->CreateContainer("femtolist",
                                                              TList::Class(),
                                                              AliAnalysisManager::kOutputContainer,
                                                              outputfile);

  // connect task to the containers
  mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskfemto, 0, cout_femto);

  // Return the task pointer
  return taskfemto;
}
<commit_msg>PWGCF: PionPionAnalysis - Macro options for output filename and ROOT subdir.<commit_after>///
/// \file AddTaskPiLam.C
/// \author Andrew Kubera, Ohio State University, andrew.kubera@cern.ch
///

///
/// \brief Adds an AliAnalysisTaskFemto analysis object to the global
///        AliAnalysisManager.
///
/// This macro creates and returns an AliAnalysisTaskFemto object. The task
/// is given the config macro "Train/PionLambdaFemto/ConfigFemtoAnalysis.C"
/// which is run to create the analysis objects. This is fixed (for now), and
/// if an alternative is required, you should use the general AddTaskFemto.C
/// macro.
///
/// Subwagons are supported, the name of which will be appended to the task
/// name. The task name by default is "TaskPiLamFemto" which cannot be changed.
///
/// The output container name is fixed at the standard "femtolist".
///
/// \param params A string forwarded to the ConfigFemtoAnalysis macro for
///               parsing. This string is wrapped in double-quotes so escaping
///               some to ensure results is a string is unneccessary.
///
/// \param maco_filename The path to the femto-confuration macro, passed to the
///                      created TaskFemto. If this parameter has no '/' characters,
///                      and the subwagon_suffix is empty, this is reinterpreted
///                      as the subwagon_suffix.
///
/// \param subwagon_suffix If this macro is run in a train with subwagons, this
///                        will be set with the identifier. NOTE: This
///                        parameter may be found in the macro_filename
///                        variable as the  suffix is simply the last argument
///                        passed. To keep from always having to explicitly set
///                        the macro_filename if using the default, this code
///                        will switch the two parameters if there is no '/'
///                        characters in the macro_filename. As such, keep '/'
///                        out of the subwagon_suffix!
///
AliAnalysisTaskFemto* AddTaskPiLam(TString params,
                                   TString macro_filename="",
                                   TString output_filename="",
                                   TString output_container="PWG2FEMTO",
                                   TString subwagon_suffix="")
{ // Adds a Pion-Lambda Femtoscopy task to the manager

  const TString DEFAULT_MACRO = "$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionLambdaFemto/ConfigFemtoAnalysis.C";

  // Get the global manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskPiLam", "Could not get the global AliAnalysisManager.");
    return NULL;
  }

  const TString default_name = "TaskPiLamFemto";

  // If the macro_filename was set, use it, else use the default
  if (macro_filename == "") {
    macro_filename = DEFAULT_MACRO;
  }
  // If subwagon_suffix was not set and there are no '/' characters in the
  // macro's path, interpret path as the subwagon_suffix and set default path
  if (subwagon_suffix == "" && !macro_filename.Contains("/")) {
    subwagon_suffix = macro_filename;
    macro_filename = DEFAULT_MACRO;
  }

  // build analysis name out of provided suffix
  const TString task_name = (subwagon_suffix == "")
                          ? default_name
                          : TString::Format("%s_%s", default_name, subwagon_suffix);

  cout << "[AddTaskPiLam]\n";
  cout << "   macro: '" << macro_filename << "'\n";
  cout << "   params: '" << params << "'\n";

  // The analysis config macro for PionLambdaFemto accepts a single string
  // argument, which it interprets.
  // This line escapes some escapable characters (backslash, newline, tab)
  // and wraps that string in double quotes, ensuring that the interpreter
  // reads a string when passing to the macro.
  const TString analysis_params = '"' + params.ReplaceAll("\\", "\\\\")
                                              .ReplaceAll("\n", "\\n")
                                              .ReplaceAll("\t", "\\t") + '"';

  AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto(
    task_name,
    macro_filename,
    analysis_params,
    kFALSE
  );

  mgr->AddTask(taskfemto);

  if (output_filename == "") {
    output_filename = AliAnalysisManager::GetCommonFileName();
  }

  const TString outputfile = TString::Format("%s:%s", output_filename.Data(), output_container.Data());

  AliAnalysisDataContainer *cout_femto = mgr->CreateContainer("femtolist",
                                                              TList::Class(),
                                                              AliAnalysisManager::kOutputContainer,
                                                              outputfile);

  // connect task to the containers
  mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskfemto, 0, cout_femto);

  // Return the task pointer
  return taskfemto;
}
<|endoftext|>


<commit_before>AliXiStar *AddTaskXiStar(bool MCcase=kFALSE, bool AODcase=kFALSE, int CutList=0) {

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBF", "No analysis manager to connect to.");
    return NULL;
  }

  //____________________________________________//
  // Create tasks
  AliXiStar *XiStarTask = new AliXiStar("XiStarTask", AODcase, MCcase, CutList);
  if(!XiStarTask) exit(-1);
  mgr->AddTask(XiStarTask);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGLF.outputXiStarAnalysis.root";
  AliAnalysisDataContainer *coutXiStar = mgr->CreateContainer("XiStarOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(XiStarTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(XiStarTask, 1, coutXiStar);

  // Add Physics Selection
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(MCcase);
  mgr->ConnectInput(physSelTask,0,mgr->GetCommonInputContainer());

  // Return the task pointer
  return XiStarTask;
}
<commit_msg>Fix in AddTaskXiStar to remove physics selection (not needed)<commit_after>AliXiStar *AddTaskXiStar(bool MCcase=kFALSE, bool AODcase=kFALSE, int CutList=0) {

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBF", "No analysis manager to connect to.");
    return NULL;
  }

  //____________________________________________//
  // Create tasks
  AliXiStar *XiStarTask = new AliXiStar("XiStarTask", AODcase, MCcase, CutList);
  if(!XiStarTask) exit(-1);
  mgr->AddTask(XiStarTask);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGLF.outputXiStarAnalysis.root";
  AliAnalysisDataContainer *coutXiStar = mgr->CreateContainer("XiStarOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  mgr->ConnectInput(XiStarTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(XiStarTask, 1, coutXiStar);

  // Return the task pointer
  return XiStarTask;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  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 copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/io/robot_eye_grabber.h>
#include <pcl/console/print.h>

/////////////////////////////////////////////////////////////////////////////
pcl::RobotEyeGrabber::RobotEyeGrabber ()
  : terminate_thread_ (false)
  , signal_point_cloud_size_ (1000)
  , data_port_ (443)
  , sensor_address_ (boost::asio::ip::address_v4::any ())
{
  point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> ();
  resetPointCloud ();
}

/////////////////////////////////////////////////////////////////////////////
pcl::RobotEyeGrabber::RobotEyeGrabber (const boost::asio::ip::address& ipAddress, unsigned short port)
  : terminate_thread_ (false)
  , signal_point_cloud_size_ (1000)
  , data_port_ (port)
  , sensor_address_ (ipAddress)
{
  point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> ();
  resetPointCloud ();
}

/////////////////////////////////////////////////////////////////////////////
pcl::RobotEyeGrabber::~RobotEyeGrabber () throw ()
{
  stop ();
  disconnect_all_slots<sig_cb_robot_eye_point_cloud_xyzi> ();
}

/////////////////////////////////////////////////////////////////////////////
std::string
pcl::RobotEyeGrabber::getName () const
{
  return (std::string ("Ocular Robotics RobotEye Grabber"));
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float
pcl::RobotEyeGrabber::getFramesPerSecond () const
{
  return (0.0f);
}

/////////////////////////////////////////////////////////////////////////////
bool
pcl::RobotEyeGrabber::isRunning () const
{
  return (socket_thread_ != NULL);
}

/////////////////////////////////////////////////////////////////////////////
unsigned short
pcl::RobotEyeGrabber::getDataPort () const
{
  return (data_port_);
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::setDataPort (const unsigned short port)
{
  data_port_ = port;
}

/////////////////////////////////////////////////////////////////////////////
const boost::asio::ip::address&
pcl::RobotEyeGrabber::getSensorAddress () const
{
  return (sensor_address_);
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::setSensorAddress (const boost::asio::ip::address& ipAddress)
{
  sensor_address_ = ipAddress;
}

/////////////////////////////////////////////////////////////////////////////
std::size_t
pcl::RobotEyeGrabber::getSignalPointCloudSize () const
{
  return (signal_point_cloud_size_);
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::setSignalPointCloudSize (std::size_t numberOfPoints)
{
  signal_point_cloud_size_ = numberOfPoints;
}

/////////////////////////////////////////////////////////////////////////////
boost::shared_ptr<pcl::PointCloud<pcl::PointXYZI> >
pcl::RobotEyeGrabber::getPointCloud () const
{
  return point_cloud_xyzi_;
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::resetPointCloud ()
{
  point_cloud_xyzi_.reset (new pcl::PointCloud<pcl::PointXYZI>);
  point_cloud_xyzi_->is_dense = true;
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::consumerThreadLoop ()
{
  while (true)
  {
    boost::shared_array<unsigned char> data;
    if (!packet_queue_.dequeue (data))
      return;

    convertPacketData (data.get(), 464);
  }
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::convertPacketData (unsigned char *dataPacket, size_t length)
{
  const size_t bytesPerPoint = 8;
  const size_t totalPoints = length / bytesPerPoint;

  for (int i = 0; i < totalPoints; ++i)
  {
    PointXYZI xyzi;
    computeXYZI (xyzi, dataPacket + i*bytesPerPoint);

    if (pcl::isFinite(xyzi))
    {
      point_cloud_xyzi_->push_back (xyzi);
    }
  }

  if (point_cloud_xyzi_->size () > signal_point_cloud_size_)
  {
    if (point_cloud_signal_->num_slots () > 0)
      point_cloud_signal_->operator() (point_cloud_xyzi_);

    resetPointCloud ();
  }
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::computeXYZI (pcl::PointXYZI& point, unsigned char* pointData)
{
  uint16_t buffer = 0;
  double az = 0.0;
  double el = 0.0;
  double range = 0.0;
  uint16_t intensity = 0;

  buffer = 0x00;
  buffer = pointData[0] << 8;
  buffer |= pointData[1]; // First 2-byte read will be Azimuth
  az = (buffer / 100.0);

  buffer = 0x00;
  buffer =  pointData[2] << 8;
  buffer |= pointData[3]; // Second 2-byte read will be Elevation
  el = (signed short int)buffer / 100.0;

  buffer = 0x00;
  buffer =  pointData[4] << 8;
  buffer |= pointData[5]; // Third 2-byte read will be Range
  range = (signed short int)buffer / 100.0;

  buffer = 0x00;
  buffer =  pointData[6] << 8;
  buffer |= pointData[7]; // Fourth 2-byte read will be Intensity
  intensity = buffer;

  point.x = range * std::cos (el * M_PI/180) * std::sin (az * M_PI/180);
  point.y = range * std::cos (el * M_PI/180) * std::cos (az * M_PI/180);
  point.z = range * std::sin (el * M_PI/180);
  point.intensity = intensity;
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::socketThreadLoop()
{
  asyncSocketReceive();
  io_service_.reset();
  io_service_.run();
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::asyncSocketReceive()
{
  // expecting exactly 464 bytes, using a larger buffer so that if a
  // larger packet arrives unexpectedly we'll notice it.
  socket_->async_receive_from(boost::asio::buffer(receive_buffer_, 500), sender_endpoint_,
    boost::bind(&RobotEyeGrabber::socketCallback, this,
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred));
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::socketCallback(const boost::system::error_code&, std::size_t numberOfBytes)
{
  if (terminate_thread_)
    return;

  if (sensor_address_ == boost::asio::ip::address_v4::any ()
      || sensor_address_ == sender_endpoint_.address ())
  {
    if (numberOfBytes == 464)
    {
      unsigned char *dup = new unsigned char[numberOfBytes];
      memcpy (dup, receive_buffer_, numberOfBytes);
      packet_queue_.enqueue (boost::shared_array<unsigned char>(dup));
    }
  }

  asyncSocketReceive ();
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::start ()
{
  if (isRunning ())
    return;

  boost::asio::ip::udp::endpoint destinationEndpoint (boost::asio::ip::address_v4::any (), data_port_);

  try
  {
	  socket_.reset (new boost::asio::ip::udp::socket (io_service_, destinationEndpoint));
  }
  catch (std::exception &e)
  {
	  PCL_ERROR ("[pcl::RobotEyeGrabber::start] Unable to bind to socket! %s\n", e.what ());
    return;
  }

  terminate_thread_ = false;
  resetPointCloud ();
  consumer_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::consumerThreadLoop, this)));
  socket_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::socketThreadLoop, this)));
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::stop ()
{
  if (!isRunning ())
    return;

  terminate_thread_ = true;

  socket_->close ();
  io_service_.stop ();
  socket_thread_->join ();
  socket_thread_.reset ();
  socket_.reset();

  packet_queue_.stopQueue ();
  consumer_thread_->join ();
  consumer_thread_.reset ();
}
<commit_msg>Fix warnings in io/robot_eye_grabber.cpp<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  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 copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/io/robot_eye_grabber.h>
#include <pcl/console/print.h>

/////////////////////////////////////////////////////////////////////////////
pcl::RobotEyeGrabber::RobotEyeGrabber ()
  : terminate_thread_ (false)
  , signal_point_cloud_size_ (1000)
  , data_port_ (443)
  , sensor_address_ (boost::asio::ip::address_v4::any ())
{
  point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> ();
  resetPointCloud ();
}

/////////////////////////////////////////////////////////////////////////////
pcl::RobotEyeGrabber::RobotEyeGrabber (const boost::asio::ip::address& ipAddress, unsigned short port)
  : terminate_thread_ (false)
  , signal_point_cloud_size_ (1000)
  , data_port_ (port)
  , sensor_address_ (ipAddress)
{
  point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> ();
  resetPointCloud ();
}

/////////////////////////////////////////////////////////////////////////////
pcl::RobotEyeGrabber::~RobotEyeGrabber () throw ()
{
  stop ();
  disconnect_all_slots<sig_cb_robot_eye_point_cloud_xyzi> ();
}

/////////////////////////////////////////////////////////////////////////////
std::string
pcl::RobotEyeGrabber::getName () const
{
  return (std::string ("Ocular Robotics RobotEye Grabber"));
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
float
pcl::RobotEyeGrabber::getFramesPerSecond () const
{
  return (0.0f);
}

/////////////////////////////////////////////////////////////////////////////
bool
pcl::RobotEyeGrabber::isRunning () const
{
  return (socket_thread_ != NULL);
}

/////////////////////////////////////////////////////////////////////////////
unsigned short
pcl::RobotEyeGrabber::getDataPort () const
{
  return (data_port_);
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::setDataPort (const unsigned short port)
{
  data_port_ = port;
}

/////////////////////////////////////////////////////////////////////////////
const boost::asio::ip::address&
pcl::RobotEyeGrabber::getSensorAddress () const
{
  return (sensor_address_);
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::setSensorAddress (const boost::asio::ip::address& ipAddress)
{
  sensor_address_ = ipAddress;
}

/////////////////////////////////////////////////////////////////////////////
std::size_t
pcl::RobotEyeGrabber::getSignalPointCloudSize () const
{
  return (signal_point_cloud_size_);
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::setSignalPointCloudSize (std::size_t numberOfPoints)
{
  signal_point_cloud_size_ = numberOfPoints;
}

/////////////////////////////////////////////////////////////////////////////
boost::shared_ptr<pcl::PointCloud<pcl::PointXYZI> >
pcl::RobotEyeGrabber::getPointCloud () const
{
  return point_cloud_xyzi_;
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::resetPointCloud ()
{
  point_cloud_xyzi_.reset (new pcl::PointCloud<pcl::PointXYZI>);
  point_cloud_xyzi_->is_dense = true;
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::consumerThreadLoop ()
{
  while (true)
  {
    boost::shared_array<unsigned char> data;
    if (!packet_queue_.dequeue (data))
      return;

    convertPacketData (data.get(), 464);
  }
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::convertPacketData (unsigned char *dataPacket, size_t length)
{
  const size_t bytesPerPoint = 8;
  const size_t totalPoints = length / bytesPerPoint;

  for (size_t i = 0; i < totalPoints; ++i)
  {
    PointXYZI xyzi;
    computeXYZI (xyzi, dataPacket + i*bytesPerPoint);

    if (pcl::isFinite(xyzi))
    {
      point_cloud_xyzi_->push_back (xyzi);
    }
  }

  if (point_cloud_xyzi_->size () > signal_point_cloud_size_)
  {
    if (point_cloud_signal_->num_slots () > 0)
      point_cloud_signal_->operator() (point_cloud_xyzi_);

    resetPointCloud ();
  }
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::computeXYZI (pcl::PointXYZI& point, unsigned char* pointData)
{
  uint16_t buffer = 0;
  double az = 0.0;
  double el = 0.0;
  double range = 0.0;
  uint16_t intensity = 0;

  buffer = 0x00;
  buffer = pointData[0] << 8;
  buffer |= pointData[1]; // First 2-byte read will be Azimuth
  az = (buffer / 100.0);

  buffer = 0x00;
  buffer =  pointData[2] << 8;
  buffer |= pointData[3]; // Second 2-byte read will be Elevation
  el = (signed short int)buffer / 100.0;

  buffer = 0x00;
  buffer =  pointData[4] << 8;
  buffer |= pointData[5]; // Third 2-byte read will be Range
  range = (signed short int)buffer / 100.0;

  buffer = 0x00;
  buffer =  pointData[6] << 8;
  buffer |= pointData[7]; // Fourth 2-byte read will be Intensity
  intensity = buffer;

  point.x = range * std::cos (el * M_PI/180) * std::sin (az * M_PI/180);
  point.y = range * std::cos (el * M_PI/180) * std::cos (az * M_PI/180);
  point.z = range * std::sin (el * M_PI/180);
  point.intensity = intensity;
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::socketThreadLoop()
{
  asyncSocketReceive();
  io_service_.reset();
  io_service_.run();
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::asyncSocketReceive()
{
  // expecting exactly 464 bytes, using a larger buffer so that if a
  // larger packet arrives unexpectedly we'll notice it.
  socket_->async_receive_from(boost::asio::buffer(receive_buffer_, 500), sender_endpoint_,
    boost::bind(&RobotEyeGrabber::socketCallback, this,
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred));
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::socketCallback(const boost::system::error_code&, std::size_t numberOfBytes)
{
  if (terminate_thread_)
    return;

  if (sensor_address_ == boost::asio::ip::address_v4::any ()
      || sensor_address_ == sender_endpoint_.address ())
  {
    if (numberOfBytes == 464)
    {
      unsigned char *dup = new unsigned char[numberOfBytes];
      memcpy (dup, receive_buffer_, numberOfBytes);
      packet_queue_.enqueue (boost::shared_array<unsigned char>(dup));
    }
  }

  asyncSocketReceive ();
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::start ()
{
  if (isRunning ())
    return;

  boost::asio::ip::udp::endpoint destinationEndpoint (boost::asio::ip::address_v4::any (), data_port_);

  try
  {
	  socket_.reset (new boost::asio::ip::udp::socket (io_service_, destinationEndpoint));
  }
  catch (std::exception &e)
  {
	  PCL_ERROR ("[pcl::RobotEyeGrabber::start] Unable to bind to socket! %s\n", e.what ());
    return;
  }

  terminate_thread_ = false;
  resetPointCloud ();
  consumer_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::consumerThreadLoop, this)));
  socket_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::socketThreadLoop, this)));
}

/////////////////////////////////////////////////////////////////////////////
void
pcl::RobotEyeGrabber::stop ()
{
  if (!isRunning ())
    return;

  terminate_thread_ = true;

  socket_->close ();
  io_service_.stop ();
  socket_thread_->join ();
  socket_thread_.reset ();
  socket_.reset();

  packet_queue_.stopQueue ();
  consumer_thread_->join ();
  consumer_thread_.reset ();
}
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/****************************************************************************

   OneWayTunnel.cc

   A OneWayTunnel is a module that connects two virtual connections, a
   source vc and a target vc, and copies the data between source and target.

   This class used to be called HttpTunnelVC, but it doesn't seem to have
   anything to do with HTTP, so it has been renamed to OneWayTunnel.
 ****************************************************************************/

#include "P_EventSystem.h"
#include "I_OneWayTunnel.h"

// #define TEST

//////////////////////////////////////////////////////////////////////////////
//
//      OneWayTunnel::OneWayTunnel()
//
//////////////////////////////////////////////////////////////////////////////

ClassAllocator<OneWayTunnel> OneWayTunnelAllocator("OneWayTunnelAllocator");

inline void
transfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)
{
  ink_release_assert(!"Not Implemented.");

  int64_t n = in_buf.reader()->read_avail();
  int64_t o = out_buf.writer()->write_avail();

  if (n > o)
    n = o;
  if (!n)
    return;
  memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n);
  in_buf.reader()->consume(n);
  out_buf.writer()->fill(n);
}

OneWayTunnel::OneWayTunnel()
  : Continuation(nullptr),
    vioSource(nullptr),
    vioTarget(nullptr),
    cont(nullptr),
    manipulate_fn(nullptr),
    n_connections(0),
    lerrno(0),
    single_buffer(false),
    close_source(false),
    close_target(false),
    tunnel_till_done(false),
    tunnel_peer(nullptr),
    free_vcs(true)
{
}

OneWayTunnel *
OneWayTunnel::OneWayTunnel_alloc()
{
  return OneWayTunnelAllocator.alloc();
}

void
OneWayTunnel::OneWayTunnel_free(OneWayTunnel *pOWT)
{
  pOWT->mutex = nullptr;
  OneWayTunnelAllocator.free(pOWT);
}

void
OneWayTunnel::SetupTwoWayTunnel(OneWayTunnel *east, OneWayTunnel *west)
{
  // make sure the both use the same mutex
  ink_assert(east->mutex == west->mutex);

  east->tunnel_peer = west;
  west->tunnel_peer = east;
}

OneWayTunnel::~OneWayTunnel()
{
}

OneWayTunnel::OneWayTunnel(Continuation *aCont, Transform_fn aManipulate_fn, bool aclose_source, bool aclose_target)
  : Continuation(aCont ? aCont->mutex.get() : new_ProxyMutex()),
    cont(aCont),
    manipulate_fn(aManipulate_fn),
    n_connections(2),
    lerrno(0),
    single_buffer(true),
    close_source(aclose_source),
    close_target(aclose_target),
    tunnel_till_done(false),
    free_vcs(false)
{
  ink_assert(!"This form of OneWayTunnel() constructor not supported");
}

void
OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, int size_estimate, ProxyMutex *aMutex,
                   int64_t nbytes, bool asingle_buffer, bool aclose_source, bool aclose_target, Transform_fn aManipulate_fn,
                   int water_mark)
{
  mutex            = aCont ? aCont->mutex.get() : (aMutex ? aMutex : new_ProxyMutex());
  cont             = aMutex ? nullptr : aCont;
  single_buffer    = asingle_buffer;
  manipulate_fn    = aManipulate_fn;
  n_connections    = 2;
  close_source     = aclose_source;
  close_target     = aclose_target;
  lerrno           = 0;
  tunnel_till_done = (nbytes == TUNNEL_TILL_DONE);

  SET_HANDLER(&OneWayTunnel::startEvent);

  int64_t size_index = 0;

  if (size_estimate)
    size_index = buffer_size_to_index(size_estimate);
  else
    size_index = default_large_iobuffer_size;

  Debug("one_way_tunnel", "buffer size index [%" PRId64 "] [%d]", size_index, size_estimate);

  // enqueue read request on vcSource.
  MIOBuffer *buf1 = new_MIOBuffer(size_index);
  MIOBuffer *buf2 = nullptr;
  if (single_buffer)
    buf2 = buf1;
  else
    buf2 = new_MIOBuffer(size_index);

  buf1->water_mark = water_mark;

  SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());
  vioSource = vcSource->do_io_read(this, nbytes, buf1);
  vioTarget = vcTarget->do_io_write(this, nbytes, buf2->alloc_reader(), false);
  ink_assert(vioSource && vioTarget);

  return;
}

void
OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, VIO *SourceVio, IOBufferReader *reader,
                   bool aclose_source, bool aclose_target)
{
  (void)vcSource;
  mutex            = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());
  cont             = aCont;
  single_buffer    = true;
  manipulate_fn    = nullptr;
  n_connections    = 2;
  close_source     = aclose_source;
  close_target     = aclose_target;
  tunnel_till_done = true;

  // Prior to constructing the OneWayTunnel, we initiated a do_io(VIO::READ)
  // on the source VC.  We wish to use the same MIO buffer in the tunnel.

  // do_io() read already posted on vcSource.
  SET_HANDLER(&OneWayTunnel::startEvent);

  SourceVio->set_continuation(this);
  SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());
  vioSource = SourceVio;

  vioTarget = vcTarget->do_io_write(this, TUNNEL_TILL_DONE, reader, false);
  ink_assert(vioSource && vioTarget);
}

void
OneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool aclose_source, bool aclose_target)
{
  mutex            = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());
  cont             = aCont;
  single_buffer    = true;
  manipulate_fn    = nullptr;
  n_connections    = 2;
  close_source     = aclose_source;
  close_target     = aclose_target;
  tunnel_till_done = true;

  // do_io_read() read already posted on vcSource.
  // do_io_write() already posted on vcTarget
  SET_HANDLER(&OneWayTunnel::startEvent);

  ink_assert(SourceVio && TargetVio);

  SourceVio->set_continuation(this);
  TargetVio->set_continuation(this);
  vioSource = SourceVio;
  vioTarget = TargetVio;
}

void
OneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)
{
  if (manipulate_fn)
    manipulate_fn(in_buf, out_buf);
  else if (in_buf.writer() != out_buf.writer())
    transfer_data(in_buf, out_buf);
}

//////////////////////////////////////////////////////////////////////////////
//
//      int OneWayTunnel::startEvent()
//
//////////////////////////////////////////////////////////////////////////////

//
// tunnel was invoked with an event
//
int
OneWayTunnel::startEvent(int event, void *data)
{
  VIO *vio   = (VIO *)data;
  int ret    = VC_EVENT_DONE;
  int result = 0;

#ifdef TEST
  const char *event_origin = (vio == vioSource ? "source" : "target"), *event_name = get_vc_event_name(event);
  printf("OneWayTunnel --- %s received from %s VC\n", event_name, event_origin);
#endif

  if (!vioTarget)
    goto Lerror;

  // handle the event
  //
  switch (event) {
  case ONE_WAY_TUNNEL_EVENT_PEER_CLOSE:
    /* This event is sent out by our peer */
    ink_assert(tunnel_peer);
    tunnel_peer = nullptr;
    free_vcs    = false;
    goto Ldone;

  case VC_EVENT_READ_READY:
    transform(vioSource->buffer, vioTarget->buffer);
    vioTarget->reenable();
    ret = VC_EVENT_CONT;
    break;

  case VC_EVENT_WRITE_READY:
    if (vioSource)
      vioSource->reenable();
    ret = VC_EVENT_CONT;
    break;

  case VC_EVENT_EOS:
    if (!tunnel_till_done && vio->ntodo())
      goto Lerror;
    if (vio == vioSource) {
      transform(vioSource->buffer, vioTarget->buffer);
      goto Lread_complete;
    } else
      goto Ldone;

  Lread_complete:
  case VC_EVENT_READ_COMPLETE:
    // set write nbytes to the current buffer size
    //
    vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail();
    if (vioTarget->nbytes == vioTarget->ndone)
      goto Ldone;
    vioTarget->reenable();
    if (!tunnel_peer)
      close_source_vio(0);
    break;

  Lerror:
  case VC_EVENT_ERROR:
    lerrno = ((VIO *)data)->vc_server->lerrno;
  case VC_EVENT_INACTIVITY_TIMEOUT:
  case VC_EVENT_ACTIVE_TIMEOUT:
    result = -1;
  Ldone:
  case VC_EVENT_WRITE_COMPLETE:
    if (tunnel_peer) {
      // inform the peer:
      tunnel_peer->startEvent(ONE_WAY_TUNNEL_EVENT_PEER_CLOSE, data);
    }
    close_source_vio(result);
    close_target_vio(result);
    connection_closed(result);
    break;

  default:
    ink_assert(!"bad case");
    ret = VC_EVENT_CONT;
    break;
  }
#ifdef TEST
  printf("    (OneWayTunnel returning value: %s)\n", (ret == VC_EVENT_DONE ? "VC_EVENT_DONE" : "VC_EVENT_CONT"));
#endif
  return ret;
}

// If result is Non-zero, the vc should be aborted.
void
OneWayTunnel::close_source_vio(int result)
{
  if (vioSource) {
    if (last_connection() || !single_buffer) {
      free_MIOBuffer(vioSource->buffer.writer());
      vioSource->buffer.clear();
    }
    if (close_source && free_vcs) {
      vioSource->vc_server->do_io_close(result ? lerrno : -1);
    }
    vioSource = nullptr;
    n_connections--;
  }
}

void
OneWayTunnel::close_target_vio(int result, VIO *vio)
{
  (void)vio;
  if (vioTarget) {
    if (last_connection() || !single_buffer) {
      free_MIOBuffer(vioTarget->buffer.writer());
      vioTarget->buffer.clear();
    }
    if (close_target && free_vcs) {
      vioTarget->vc_server->do_io_close(result ? lerrno : -1);
    }
    vioTarget = nullptr;
    n_connections--;
  }
}

//////////////////////////////////////////////////////////////////////////////
//
//      void OneWayTunnel::connection_closed
//
//////////////////////////////////////////////////////////////////////////////
void
OneWayTunnel::connection_closed(int result)
{
  if (cont) {
#ifdef TEST
    cout << "OneWayTunnel::connection_closed() ... calling cont" << endl;
#endif
    cont->handleEvent(result ? VC_EVENT_ERROR : VC_EVENT_EOS, this);
  } else {
    OneWayTunnel_free(this);
  }
}

void
OneWayTunnel::reenable_all()
{
  if (vioSource)
    vioSource->reenable();
  if (vioTarget)
    vioTarget->reenable();
}

bool
OneWayTunnel::last_connection()
{
  return n_connections == 1;
}
<commit_msg>coverity 1021916 : fix missing break<commit_after>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/****************************************************************************

   OneWayTunnel.cc

   A OneWayTunnel is a module that connects two virtual connections, a
   source vc and a target vc, and copies the data between source and target.

   This class used to be called HttpTunnelVC, but it doesn't seem to have
   anything to do with HTTP, so it has been renamed to OneWayTunnel.
 ****************************************************************************/

#include "P_EventSystem.h"
#include "I_OneWayTunnel.h"

// #define TEST

//////////////////////////////////////////////////////////////////////////////
//
//      OneWayTunnel::OneWayTunnel()
//
//////////////////////////////////////////////////////////////////////////////

ClassAllocator<OneWayTunnel> OneWayTunnelAllocator("OneWayTunnelAllocator");

inline void
transfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)
{
  ink_release_assert(!"Not Implemented.");

  int64_t n = in_buf.reader()->read_avail();
  int64_t o = out_buf.writer()->write_avail();

  if (n > o)
    n = o;
  if (!n)
    return;
  memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n);
  in_buf.reader()->consume(n);
  out_buf.writer()->fill(n);
}

OneWayTunnel::OneWayTunnel()
  : Continuation(nullptr),
    vioSource(nullptr),
    vioTarget(nullptr),
    cont(nullptr),
    manipulate_fn(nullptr),
    n_connections(0),
    lerrno(0),
    single_buffer(false),
    close_source(false),
    close_target(false),
    tunnel_till_done(false),
    tunnel_peer(nullptr),
    free_vcs(true)
{
}

OneWayTunnel *
OneWayTunnel::OneWayTunnel_alloc()
{
  return OneWayTunnelAllocator.alloc();
}

void
OneWayTunnel::OneWayTunnel_free(OneWayTunnel *pOWT)
{
  pOWT->mutex = nullptr;
  OneWayTunnelAllocator.free(pOWT);
}

void
OneWayTunnel::SetupTwoWayTunnel(OneWayTunnel *east, OneWayTunnel *west)
{
  // make sure the both use the same mutex
  ink_assert(east->mutex == west->mutex);

  east->tunnel_peer = west;
  west->tunnel_peer = east;
}

OneWayTunnel::~OneWayTunnel()
{
}

OneWayTunnel::OneWayTunnel(Continuation *aCont, Transform_fn aManipulate_fn, bool aclose_source, bool aclose_target)
  : Continuation(aCont ? aCont->mutex.get() : new_ProxyMutex()),
    cont(aCont),
    manipulate_fn(aManipulate_fn),
    n_connections(2),
    lerrno(0),
    single_buffer(true),
    close_source(aclose_source),
    close_target(aclose_target),
    tunnel_till_done(false),
    free_vcs(false)
{
  ink_assert(!"This form of OneWayTunnel() constructor not supported");
}

void
OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, int size_estimate, ProxyMutex *aMutex,
                   int64_t nbytes, bool asingle_buffer, bool aclose_source, bool aclose_target, Transform_fn aManipulate_fn,
                   int water_mark)
{
  mutex            = aCont ? aCont->mutex.get() : (aMutex ? aMutex : new_ProxyMutex());
  cont             = aMutex ? nullptr : aCont;
  single_buffer    = asingle_buffer;
  manipulate_fn    = aManipulate_fn;
  n_connections    = 2;
  close_source     = aclose_source;
  close_target     = aclose_target;
  lerrno           = 0;
  tunnel_till_done = (nbytes == TUNNEL_TILL_DONE);

  SET_HANDLER(&OneWayTunnel::startEvent);

  int64_t size_index = 0;

  if (size_estimate)
    size_index = buffer_size_to_index(size_estimate);
  else
    size_index = default_large_iobuffer_size;

  Debug("one_way_tunnel", "buffer size index [%" PRId64 "] [%d]", size_index, size_estimate);

  // enqueue read request on vcSource.
  MIOBuffer *buf1 = new_MIOBuffer(size_index);
  MIOBuffer *buf2 = nullptr;
  if (single_buffer)
    buf2 = buf1;
  else
    buf2 = new_MIOBuffer(size_index);

  buf1->water_mark = water_mark;

  SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());
  vioSource = vcSource->do_io_read(this, nbytes, buf1);
  vioTarget = vcTarget->do_io_write(this, nbytes, buf2->alloc_reader(), false);
  ink_assert(vioSource && vioTarget);

  return;
}

void
OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, VIO *SourceVio, IOBufferReader *reader,
                   bool aclose_source, bool aclose_target)
{
  (void)vcSource;
  mutex            = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());
  cont             = aCont;
  single_buffer    = true;
  manipulate_fn    = nullptr;
  n_connections    = 2;
  close_source     = aclose_source;
  close_target     = aclose_target;
  tunnel_till_done = true;

  // Prior to constructing the OneWayTunnel, we initiated a do_io(VIO::READ)
  // on the source VC.  We wish to use the same MIO buffer in the tunnel.

  // do_io() read already posted on vcSource.
  SET_HANDLER(&OneWayTunnel::startEvent);

  SourceVio->set_continuation(this);
  SCOPED_MUTEX_LOCK(lock, mutex, this_ethread());
  vioSource = SourceVio;

  vioTarget = vcTarget->do_io_write(this, TUNNEL_TILL_DONE, reader, false);
  ink_assert(vioSource && vioTarget);
}

void
OneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool aclose_source, bool aclose_target)
{
  mutex            = aCont ? aCont->mutex : make_ptr(new_ProxyMutex());
  cont             = aCont;
  single_buffer    = true;
  manipulate_fn    = nullptr;
  n_connections    = 2;
  close_source     = aclose_source;
  close_target     = aclose_target;
  tunnel_till_done = true;

  // do_io_read() read already posted on vcSource.
  // do_io_write() already posted on vcTarget
  SET_HANDLER(&OneWayTunnel::startEvent);

  ink_assert(SourceVio && TargetVio);

  SourceVio->set_continuation(this);
  TargetVio->set_continuation(this);
  vioSource = SourceVio;
  vioTarget = TargetVio;
}

void
OneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)
{
  if (manipulate_fn)
    manipulate_fn(in_buf, out_buf);
  else if (in_buf.writer() != out_buf.writer())
    transfer_data(in_buf, out_buf);
}

//////////////////////////////////////////////////////////////////////////////
//
//      int OneWayTunnel::startEvent()
//
//////////////////////////////////////////////////////////////////////////////

//
// tunnel was invoked with an event
//
int
OneWayTunnel::startEvent(int event, void *data)
{
  VIO *vio   = (VIO *)data;
  int ret    = VC_EVENT_DONE;
  int result = 0;

#ifdef TEST
  const char *event_origin = (vio == vioSource ? "source" : "target"), *event_name = get_vc_event_name(event);
  printf("OneWayTunnel --- %s received from %s VC\n", event_name, event_origin);
#endif

  if (!vioTarget)
    goto Lerror;

  // handle the event
  //
  switch (event) {
  case ONE_WAY_TUNNEL_EVENT_PEER_CLOSE:
    /* This event is sent out by our peer */
    ink_assert(tunnel_peer);
    tunnel_peer = nullptr;
    free_vcs    = false;
    goto Ldone;
    break; // fix coverity

  case VC_EVENT_READ_READY:
    transform(vioSource->buffer, vioTarget->buffer);
    vioTarget->reenable();
    ret = VC_EVENT_CONT;
    break;

  case VC_EVENT_WRITE_READY:
    if (vioSource)
      vioSource->reenable();
    ret = VC_EVENT_CONT;
    break;

  case VC_EVENT_EOS:
    if (!tunnel_till_done && vio->ntodo())
      goto Lerror;
    if (vio == vioSource) {
      transform(vioSource->buffer, vioTarget->buffer);
      goto Lread_complete;
    } else {
      goto Ldone;
    }
    break; // fix coverity
  case VC_EVENT_READ_COMPLETE:
  Lread_complete:
    // set write nbytes to the current buffer size
    //
    vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail();
    if (vioTarget->nbytes == vioTarget->ndone)
      goto Ldone;
    vioTarget->reenable();
    if (!tunnel_peer)
      close_source_vio(0);
    break;

  case VC_EVENT_ERROR:
  Lerror:
    lerrno = ((VIO *)data)->vc_server->lerrno;
  case VC_EVENT_INACTIVITY_TIMEOUT:
  case VC_EVENT_ACTIVE_TIMEOUT:
    result = -1;
  case VC_EVENT_WRITE_COMPLETE:
  Ldone:
    if (tunnel_peer) {
      // inform the peer:
      tunnel_peer->startEvent(ONE_WAY_TUNNEL_EVENT_PEER_CLOSE, data);
    }
    close_source_vio(result);
    close_target_vio(result);
    connection_closed(result);
    break;

  default:
    ink_assert(!"bad case");
    ret = VC_EVENT_CONT;
    break;
  }
#ifdef TEST
  printf("    (OneWayTunnel returning value: %s)\n", (ret == VC_EVENT_DONE ? "VC_EVENT_DONE" : "VC_EVENT_CONT"));
#endif
  return ret;
}

// If result is Non-zero, the vc should be aborted.
void
OneWayTunnel::close_source_vio(int result)
{
  if (vioSource) {
    if (last_connection() || !single_buffer) {
      free_MIOBuffer(vioSource->buffer.writer());
      vioSource->buffer.clear();
    }
    if (close_source && free_vcs) {
      vioSource->vc_server->do_io_close(result ? lerrno : -1);
    }
    vioSource = nullptr;
    n_connections--;
  }
}

void
OneWayTunnel::close_target_vio(int result, VIO *vio)
{
  (void)vio;
  if (vioTarget) {
    if (last_connection() || !single_buffer) {
      free_MIOBuffer(vioTarget->buffer.writer());
      vioTarget->buffer.clear();
    }
    if (close_target && free_vcs) {
      vioTarget->vc_server->do_io_close(result ? lerrno : -1);
    }
    vioTarget = nullptr;
    n_connections--;
  }
}

//////////////////////////////////////////////////////////////////////////////
//
//      void OneWayTunnel::connection_closed
//
//////////////////////////////////////////////////////////////////////////////
void
OneWayTunnel::connection_closed(int result)
{
  if (cont) {
#ifdef TEST
    cout << "OneWayTunnel::connection_closed() ... calling cont" << endl;
#endif
    cont->handleEvent(result ? VC_EVENT_ERROR : VC_EVENT_EOS, this);
  } else {
    OneWayTunnel_free(this);
  }
}

void
OneWayTunnel::reenable_all()
{
  if (vioSource)
    vioSource->reenable();
  if (vioTarget)
    vioTarget->reenable();
}

bool
OneWayTunnel::last_connection()
{
  return n_connections == 1;
}
<|endoftext|>


<commit_before>/*++

Module Name:

    FASTA.cpp

Abstract:

    FASTA reader

Authors:

    Bill Bolosky, August, 2011

Environment:

    User mode service.

Revision History:

    Adapted from Matei Zaharia's Scala implementation.

--*/

#include "stdafx.h"
#include "Compat.h"
#include "FASTA.h"

    const Genome *
ReadFASTAGenome(const char *fileName)
{
    //
    // We need to know a bound on the size of the genome before we create the Genome object.
    // A bound is the number of bytes in the FASTA file, because we store at most one base per
    // byte.  Get the file size to use for this bound.
    //
    _int64 fileSize = QueryFileSize(fileName);

    if (fileSize >> 32 != 0) {
        fprintf(stderr,"This tool only works with genomes with 2^32 bases or fewer.\n");
        return NULL;
    }

    Genome *genome = new Genome((unsigned) fileSize, (unsigned)fileSize);

    FILE *fastaFile = fopen(fileName, "r");
    if (fastaFile == NULL) {
        fprintf(stderr,"Unable to open FASTA file '%s' (even though we already got its size)\n",fileName);
        delete genome;
        return NULL;
    }

    const size_t lineBufferSize = 4096;
    char lineBuffer[lineBufferSize];

    while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) {
        if (lineBuffer[0] == '>') {
            char* space = strchr(lineBuffer, ' ');
            char* tab = strchr(lineBuffer, '\t');
            char* end = space !=NULL ? (tab != NULL ? min(space, tab) : space)
                : tab != NULL ? tab : NULL;
            // Go up to blank, or remove the trailing newline from fgets
            end = end != NULL ? end : (lineBuffer + strlen(lineBuffer) - 1);
            *end = '\0';
            genome->startPiece(lineBuffer+1);
        } else {
            //
            // Convert it to upper case and truncate the newline before adding it to the genome.
            //

            char *newline = strchr(lineBuffer, '\n');
            if (NULL != newline) {
                *newline = 0;
            }

            //
            // But convert any 'N' to 'n'.  This is so we don't match the N from the genome with N
            // in reads (where we just do a straight text comparison.
            //
            size_t lineLen = strlen(lineBuffer);

			for (unsigned i = 0; i < lineLen; i++) {
              lineBuffer[i] = toupper(lineBuffer[i]);
            }

			for (unsigned i = 0; i < lineLen; i++) {
                if ('N' == lineBuffer[i]) {
                    lineBuffer[i] = 'n';
                }
            }
            genome->addData(lineBuffer);
        }
    }

    fclose(fastaFile);
    return genome;
}

//
// TODO: Reduce code duplication with the mutator.
//
bool AppendFASTAGenome(const Genome *genome, FILE *fasta, const char *prefix="")
{
    int nPieces = genome->getNumPieces();
    const Genome::Piece *pieces = genome->getPieces();
    for (int i = 0; i < nPieces; ++i) {
        const Genome::Piece &piece = pieces[i];
        unsigned start = piece.beginningOffset;
        unsigned end = i + 1 < nPieces ? pieces[i + 1].beginningOffset : genome->getCountOfBases();
        unsigned size = end - start;
        const char *bases = genome->getSubstring(start, size);

        fprintf(fasta, ">%s%s\n", prefix, piece.name);
        fwrite(bases, 1, size, fasta);
        fputc('\n', fasta);
    }
    return !ferror(fasta);
}
<commit_msg>Fix compile error due to added "min"<commit_after>/*++

Module Name:

    FASTA.cpp

Abstract:

    FASTA reader

Authors:

    Bill Bolosky, August, 2011

Environment:

    User mode service.

Revision History:

    Adapted from Matei Zaharia's Scala implementation.

--*/

#include "stdafx.h"
#include "Compat.h"
#include "FASTA.h"

using namespace std;

    const Genome *
ReadFASTAGenome(const char *fileName)
{
    //
    // We need to know a bound on the size of the genome before we create the Genome object.
    // A bound is the number of bytes in the FASTA file, because we store at most one base per
    // byte.  Get the file size to use for this bound.
    //
    _int64 fileSize = QueryFileSize(fileName);

    if (fileSize >> 32 != 0) {
        fprintf(stderr,"This tool only works with genomes with 2^32 bases or fewer.\n");
        return NULL;
    }

    Genome *genome = new Genome((unsigned) fileSize, (unsigned)fileSize);

    FILE *fastaFile = fopen(fileName, "r");
    if (fastaFile == NULL) {
        fprintf(stderr,"Unable to open FASTA file '%s' (even though we already got its size)\n",fileName);
        delete genome;
        return NULL;
    }

    const size_t lineBufferSize = 4096;
    char lineBuffer[lineBufferSize];

    while (NULL != fgets(lineBuffer,lineBufferSize,fastaFile)) {
        if (lineBuffer[0] == '>') {
            char* space = strchr(lineBuffer, ' ');
            char* tab = strchr(lineBuffer, '\t');
            char* end = space !=NULL ? (tab != NULL ? min(space, tab) : space)
                : tab != NULL ? tab : NULL;
            // Go up to blank, or remove the trailing newline from fgets
            end = end != NULL ? end : (lineBuffer + strlen(lineBuffer) - 1);
            *end = '\0';
            genome->startPiece(lineBuffer+1);
        } else {
            //
            // Convert it to upper case and truncate the newline before adding it to the genome.
            //

            char *newline = strchr(lineBuffer, '\n');
            if (NULL != newline) {
                *newline = 0;
            }

            //
            // But convert any 'N' to 'n'.  This is so we don't match the N from the genome with N
            // in reads (where we just do a straight text comparison.
            //
            size_t lineLen = strlen(lineBuffer);

			for (unsigned i = 0; i < lineLen; i++) {
              lineBuffer[i] = toupper(lineBuffer[i]);
            }

			for (unsigned i = 0; i < lineLen; i++) {
                if ('N' == lineBuffer[i]) {
                    lineBuffer[i] = 'n';
                }
            }
            genome->addData(lineBuffer);
        }
    }

    fclose(fastaFile);
    return genome;
}

//
// TODO: Reduce code duplication with the mutator.
//
bool AppendFASTAGenome(const Genome *genome, FILE *fasta, const char *prefix="")
{
    int nPieces = genome->getNumPieces();
    const Genome::Piece *pieces = genome->getPieces();
    for (int i = 0; i < nPieces; ++i) {
        const Genome::Piece &piece = pieces[i];
        unsigned start = piece.beginningOffset;
        unsigned end = i + 1 < nPieces ? pieces[i + 1].beginningOffset : genome->getCountOfBases();
        unsigned size = end - start;
        const char *bases = genome->getSubstring(start, size);

        fprintf(fasta, ">%s%s\n", prefix, piece.name);
        fwrite(bases, 1, size, fasta);
        fputc('\n', fasta);
    }
    return !ferror(fasta);
}
<|endoftext|>


<commit_before>//
//  CSwing.cpp
//  SwingGame
//
//  Created by Tim Brier on 31/10/2014.
//  Copyright (c) 2014 tbrier. All rights reserved.
//

// =============================================================================
// Include Files
// -----------------------------------------------------------------------------
#include "CSwing.hpp"
#include "CSwingGame.hpp"
#include "CLevel.hpp"
#include "CollisionHandler.hpp"

// =============================================================================
// Static variables
// -----------------------------------------------------------------------------
static float sMaxLength = 500.0f;
static float sClimbSpeed = 100.0f;

// =============================================================================
// CSwing constructor/destructor
// -----------------------------------------------------------------------------
CSwing::CSwing(CPlayer *theBob, CLevel *theParentLevel)
:   mBob(theBob),
    mParentLevel(theParentLevel),
    mAttached(false)
{

}

CSwing::~CSwing()
{
    // Unregister this x-able
    if (mAttached)
    {
        CSwingGame::UnregisterRenderable(this);
        CSwingGame::UnregisterUpdateable(this);
    }
}

// =============================================================================
// CSwing::AttemptToAttach
// Find the first point between the bob and the aim point to attach to
// -----------------------------------------------------------------------------
void CSwing::AttemptToAttach(CVector2f theAimPoint)
{
    // Attach the swing if we can find a valid anchor point
    CVector2f anchorPoint;
    if (IsThereAValidAnchor(theAimPoint, &anchorPoint))
    {
        // Make sure we detach from any existing swing
        Detach();

        // Now attach
        mAttached = true;

        mOrigin = anchorPoint;
        mLength = GetDistanceToBob();

        // Throw away any velocity that isn't perpendicular to the swing
        CVector2f v = mBob->GetVelocity();
        CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());
        mBob->SetVelocity(newV);

        // Register ourselves now we're active
        CSwingGame::RegisterRenderable(this);
        CSwingGame::RegisterUpdateable(this);
    }
}

// =============================================================================
// CSwing::Detach
// -----------------------------------------------------------------------------
void CSwing::Detach()
{
    if (mAttached)
    {
        mAttached = false;
        CSwingGame::UnregisterUpdateable(this);
        CSwingGame::UnregisterRenderable(this);
    }
}

// =============================================================================
// CSwing::AttenuateGravity
// Alter the affect of gravity based on the swings angle
// -----------------------------------------------------------------------------
CVector2f CSwing::AttenuateGravity(CVector2f gravity)
{
    // If we're not attached then don't affect gravity
    if (!mAttached)
    {
        return gravity;
    }

    // Throw away any component of the gravity that isn't perpendicular to the
    // swing
    return gravity.GetComponentInDirection(GetPerpendicularDirection());
}

// =============================================================================
// CSwing::Draw
// -----------------------------------------------------------------------------
void CSwing::Draw(CWindow *theWindow)
{
    theWindow->DrawLine(CLine(mOrigin, mBob->GetPosition()), CColour::Black);
}

// =============================================================================
// CSwing::Update
// -----------------------------------------------------------------------------
void CSwing::Update(CTime elapsedTime)
{
    if (mAttached)
    {
        HandleInput(elapsedTime);

        // Adjust the velocity so it is perpendicular to the swing
        CVector2f v = mBob->GetVelocity();
        CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());
        newV.Normalise();
        newV *= v.GetMagnitude();
        mBob->SetVelocity(newV);

        // Make sure the bob isn't further away from the origin than the length
        // of the swing
        CVector2f bobToOrigin = mOrigin - mBob->GetPosition();
        float distance = bobToOrigin.GetMagnitude();
        if (distance > mLength)
        {
            // Move by the difference between the distance and length
            float moveDistance = distance - mLength;
            bobToOrigin.Normalise();
            bobToOrigin *= moveDistance;
            mBob->GetShape()->move(bobToOrigin);
        }

        HandleCollisions();
    }
}

// =============================================================================
// CSwing::IsAttached
// -----------------------------------------------------------------------------
bool CSwing::IsAttached()
{
    return mAttached;
}

// =============================================================================
// CSwing::GetDistanceToBob
// -----------------------------------------------------------------------------
float CSwing::GetDistanceToBob()
{
    CVector2f bobPosition = mBob->GetPosition();
    CVector2f bobToOrigin = mOrigin - bobPosition;
    return bobToOrigin.GetMagnitude();
}

// =============================================================================
// CSwing::IsThereAValidAnchor
// -----------------------------------------------------------------------------
bool CSwing::IsThereAValidAnchor(CVector2f theAimPoint, CVector2f *anchor)
{
    bool theResult = false;

    // Find the direction from the bob to the aim point
    CVector2f bobPosition = mBob->GetPosition();
    CVector2f aimDirection = theAimPoint - bobPosition;
    aimDirection.Normalise();

    // Create a line from the bob to the max distance away that a swing could
    // reach in the aim direction
    CLine longestPossile = CLine(bobPosition,
                                 bobPosition + (aimDirection * sMaxLength));

    // Find the closest intersection of this line and any obstacle lines to the
    // bob
    *anchor = longestPossile.GetEnd();
    float currentDistanceToAnchor = sMaxLength;

    std::list<CPhysicsBody *> theObstacles = mParentLevel->GetObstacles();
    FOR_EACH_IN_LIST(CPhysicsBody*, theObstacles)
    {
        std::list<CVector2f> theIntersections;
        if (CollisionHandler::AreIntersecting(longestPossile,
                                              *((*it)->GetShape()),
                                              &theIntersections))
        {
            theResult = true;
            FOR_EACH_IN_LIST(CVector2f, theIntersections)
            {
                CVector2f thisIntersection = (*it);
                CVector2f bobToThis = thisIntersection - bobPosition;
                float distanceToThis = bobToThis.GetMagnitude();
                if (distanceToThis < currentDistanceToAnchor)
                {
                    *anchor = thisIntersection;
                    currentDistanceToAnchor = distanceToThis;
                }
            }
        }
    }

    return theResult;
}

// =============================================================================
// CSwing::GetPerpendicularDirection
// -----------------------------------------------------------------------------
CVector2f CSwing::GetPerpendicularDirection()
{
    CVector2f originToBob = mBob->GetPosition() - mOrigin;
    originToBob.Normalise();

    CVector2f perpendicularDirection;
    perpendicularDirection.x = originToBob.y;
    perpendicularDirection.y = -originToBob.x;

    return perpendicularDirection;
}

// =============================================================================
// CSwing::HandleInput
// -----------------------------------------------------------------------------
void CSwing::HandleInput(CTime elapsedTime)
{
    CVector2f climbOffset = CVector2f(0.0f, 0.0f);
    CVector2f climbDirection = mOrigin - mBob->GetPosition();
    climbDirection.Normalise();

    // Climb while w is pressed
    if (CKeyboard::isKeyPressed(CKeyboard::W))
    {
        climbOffset += climbDirection * sClimbSpeed * elapsedTime.asSeconds();
    }

    // Descend while s is presses
    if (CKeyboard::isKeyPressed(CKeyboard::S))
    {
        climbOffset -= climbDirection * sClimbSpeed * elapsedTime.asSeconds();
    }

    if (climbOffset .GetMagnitude() > 0)
    {
        mBob->MoveFixedDistanceUntilCollision(climbOffset);
        mLength = GetDistanceToBob();
    }
}

// =============================================================================
// CSwing::HandleCollisions
// -----------------------------------------------------------------------------
void CSwing::HandleCollisions()
{

}<commit_msg>Don't allow swing to extend beyon max length<commit_after>//
//  CSwing.cpp
//  SwingGame
//
//  Created by Tim Brier on 31/10/2014.
//  Copyright (c) 2014 tbrier. All rights reserved.
//

// =============================================================================
// Include Files
// -----------------------------------------------------------------------------
#include "CSwing.hpp"
#include "CSwingGame.hpp"
#include "CLevel.hpp"
#include "CollisionHandler.hpp"

// =============================================================================
// Static variables
// -----------------------------------------------------------------------------
static float sMaxLength = 500.0f;
static float sClimbSpeed = 100.0f;

// =============================================================================
// CSwing constructor/destructor
// -----------------------------------------------------------------------------
CSwing::CSwing(CPlayer *theBob, CLevel *theParentLevel)
:   mBob(theBob),
    mParentLevel(theParentLevel),
    mAttached(false)
{

}

CSwing::~CSwing()
{
    // Unregister this x-able
    if (mAttached)
    {
        CSwingGame::UnregisterRenderable(this);
        CSwingGame::UnregisterUpdateable(this);
    }
}

// =============================================================================
// CSwing::AttemptToAttach
// Find the first point between the bob and the aim point to attach to
// -----------------------------------------------------------------------------
void CSwing::AttemptToAttach(CVector2f theAimPoint)
{
    // Attach the swing if we can find a valid anchor point
    CVector2f anchorPoint;
    if (IsThereAValidAnchor(theAimPoint, &anchorPoint))
    {
        // Make sure we detach from any existing swing
        Detach();

        // Now attach
        mAttached = true;

        mOrigin = anchorPoint;
        mLength = GetDistanceToBob();

        // Throw away any velocity that isn't perpendicular to the swing
        CVector2f v = mBob->GetVelocity();
        CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());
        mBob->SetVelocity(newV);

        // Register ourselves now we're active
        CSwingGame::RegisterRenderable(this);
        CSwingGame::RegisterUpdateable(this);
    }
}

// =============================================================================
// CSwing::Detach
// -----------------------------------------------------------------------------
void CSwing::Detach()
{
    if (mAttached)
    {
        mAttached = false;
        CSwingGame::UnregisterUpdateable(this);
        CSwingGame::UnregisterRenderable(this);
    }
}

// =============================================================================
// CSwing::AttenuateGravity
// Alter the affect of gravity based on the swings angle
// -----------------------------------------------------------------------------
CVector2f CSwing::AttenuateGravity(CVector2f gravity)
{
    // If we're not attached then don't affect gravity
    if (!mAttached)
    {
        return gravity;
    }

    // Throw away any component of the gravity that isn't perpendicular to the
    // swing
    return gravity.GetComponentInDirection(GetPerpendicularDirection());
}

// =============================================================================
// CSwing::Draw
// -----------------------------------------------------------------------------
void CSwing::Draw(CWindow *theWindow)
{
    theWindow->DrawLine(CLine(mOrigin, mBob->GetPosition()), CColour::Black);
}

// =============================================================================
// CSwing::Update
// -----------------------------------------------------------------------------
void CSwing::Update(CTime elapsedTime)
{
    if (mAttached)
    {
        HandleInput(elapsedTime);

        // Adjust the velocity so it is perpendicular to the swing
        CVector2f v = mBob->GetVelocity();
        CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());
        newV.Normalise();
        newV *= v.GetMagnitude();
        mBob->SetVelocity(newV);

        // Make sure the bob isn't further away from the origin than the length
        // of the swing
        CVector2f bobToOrigin = mOrigin - mBob->GetPosition();
        float distance = bobToOrigin.GetMagnitude();
        if (distance > mLength)
        {
            // Move by the difference between the distance and length
            float moveDistance = distance - mLength;
            bobToOrigin.Normalise();
            bobToOrigin *= moveDistance;
            mBob->GetShape()->move(bobToOrigin);
        }

        HandleCollisions();
    }
}

// =============================================================================
// CSwing::IsAttached
// -----------------------------------------------------------------------------
bool CSwing::IsAttached()
{
    return mAttached;
}

// =============================================================================
// CSwing::GetDistanceToBob
// -----------------------------------------------------------------------------
float CSwing::GetDistanceToBob()
{
    CVector2f bobPosition = mBob->GetPosition();
    CVector2f bobToOrigin = mOrigin - bobPosition;
    return bobToOrigin.GetMagnitude();
}

// =============================================================================
// CSwing::IsThereAValidAnchor
// -----------------------------------------------------------------------------
bool CSwing::IsThereAValidAnchor(CVector2f theAimPoint, CVector2f *anchor)
{
    bool theResult = false;

    // Find the direction from the bob to the aim point
    CVector2f bobPosition = mBob->GetPosition();
    CVector2f aimDirection = theAimPoint - bobPosition;
    aimDirection.Normalise();

    // Create a line from the bob to the max distance away that a swing could
    // reach in the aim direction
    CLine longestPossile = CLine(bobPosition,
                                 bobPosition + (aimDirection * sMaxLength));

    // Find the closest intersection of this line and any obstacle lines to the
    // bob
    *anchor = longestPossile.GetEnd();
    float currentDistanceToAnchor = sMaxLength;

    std::list<CPhysicsBody *> theObstacles = mParentLevel->GetObstacles();
    FOR_EACH_IN_LIST(CPhysicsBody*, theObstacles)
    {
        std::list<CVector2f> theIntersections;
        if (CollisionHandler::AreIntersecting(longestPossile,
                                              *((*it)->GetShape()),
                                              &theIntersections))
        {
            theResult = true;
            FOR_EACH_IN_LIST(CVector2f, theIntersections)
            {
                CVector2f thisIntersection = (*it);
                CVector2f bobToThis = thisIntersection - bobPosition;
                float distanceToThis = bobToThis.GetMagnitude();
                if (distanceToThis < currentDistanceToAnchor)
                {
                    *anchor = thisIntersection;
                    currentDistanceToAnchor = distanceToThis;
                }
            }
        }
    }

    return theResult;
}

// =============================================================================
// CSwing::GetPerpendicularDirection
// -----------------------------------------------------------------------------
CVector2f CSwing::GetPerpendicularDirection()
{
    CVector2f originToBob = mBob->GetPosition() - mOrigin;
    originToBob.Normalise();

    CVector2f perpendicularDirection;
    perpendicularDirection.x = originToBob.y;
    perpendicularDirection.y = -originToBob.x;

    return perpendicularDirection;
}

// =============================================================================
// CSwing::HandleInput
// -----------------------------------------------------------------------------
void CSwing::HandleInput(CTime elapsedTime)
{
    CVector2f climbOffset = CVector2f(0.0f, 0.0f);
    CVector2f climbDirection = mOrigin - mBob->GetPosition();
    climbDirection.Normalise();

    // Climb while w is pressed
    if (CKeyboard::isKeyPressed(CKeyboard::W))
    {
        climbOffset += climbDirection * sClimbSpeed * elapsedTime.asSeconds();
    }

    // Descend while s is presses
    if (CKeyboard::isKeyPressed(CKeyboard::S))
    {
        climbOffset -= climbDirection * sClimbSpeed * elapsedTime.asSeconds();
    }

    if (climbOffset .GetMagnitude() > 0)
    {
        mBob->MoveFixedDistanceUntilCollision(climbOffset);
        mLength = GetDistanceToBob();
        mLength = std::min(mLength, sMaxLength);
    }
}

// =============================================================================
// CSwing::HandleCollisions
// -----------------------------------------------------------------------------
void CSwing::HandleCollisions()
{

}<|endoftext|>