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

#ifndef CPM_CPM_SUPPORT_HPP
#define CPM_CPM_SUPPORT_HPP

#include "../../lib/cxxopts/src/cxxopts.hpp"

namespace cpm {

struct cpm_registry {
    cpm_registry(void (*function)(cpm::benchmark<>&)){
        benchs.emplace_back(function);
    }

    static std::vector<void(*)(cpm::benchmark<>&)> benchs;
};

template<template<typename...> class TT, typename T>
struct is_specialization_of : std::false_type {};

template<template<typename...> class TT, typename... Args>
struct is_specialization_of<TT, TT<Args...>> : std::true_type {};

template<typename T>
struct is_section : is_specialization_of<cpm::section, std::decay_t<T>> {};

} //end of namespace cpm

//Internal helpers

#define CPM_UNIQUE_DETAIL(x, y) x##y
#define CPM_UNIQUE(x, y) CPM_UNIQUE_DETAIL(x, y)
#define CPM_UNIQUE_NAME(x) CPM_UNIQUE(x, __LINE__)

//Declarations of benchs functions

#define CPM_BENCH()  \
    void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench); \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(bench_)); }              \
    void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench)

//Declaration of section functions

#define CPM_SECTION(name)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi(name);

#define CPM_SECTION_O(name, W, R)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi(name);    \
    bench.warmup = W;                   \
    bench.repeat = R;

#define CPM_SECTION_P(name, policy)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi<policy>(name);

#define CPM_SECTION_PO(name, policy, W, R)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi<policy>(name);      \
    bench.warmup = W;                             \
    bench.repeat = R;

//Normal versions for simple bench
#define CPM_SIMPLE(...) bench.measure_simple(__VA_ARGS__);
#define CPM_GLOBAL(...) bench.measure_global(__VA_ARGS__);
#define CPM_TWO_PASS(...) bench.measure_two_pass(__VA_ARGS__);
#define CPM_TWO_PASS_NS(...) bench.measure_two_pass<false>(__VA_ARGS__);

//Versions with policies

#define CPM_SIMPLE_P(policy, ...)  \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_SIMPLE_P cannot be used inside CPM_SECTION");  \
    bench.measure_simple<policy>(__VA_ARGS__);

#define CPM_GLOBAL_P(policy, ...) \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_GLOBAL_P cannot be used inside CPM_SECTION");  \
    bench.measure_global<policy>(__VA_ARGS__);

#define CPM_TWO_PASS_P(policy, ...) \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_P cannot be used inside CPM_SECTION");  \
    bench.measure_two_pass<true, policy>(__VA_ARGS__);

#define CPM_TWO_PASS_NS_P(policy, ...)  \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_NS_P cannot be used inside CPM_SECTION");  \
    bench.template measure_two_pass<false, policy>(__VA_ARGS__);

//Direct bench functions

#define CPM_DIRECT_BENCH_SIMPLE(...) CPM_BENCH() { CPM_SIMPLE(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS(...) CPM_BENCH() { CPM_TWO_PASS(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS(...) CPM_BENCH() { CPM_TWO_PASS_NS(__VA_ARGS__); }

//Direct bench functions with policies

#define CPM_DIRECT_BENCH_SIMPLE_P(policy,...) CPM_BENCH() { CPM_SIMPLE_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_NS_P(POLICY(policy),__VA_ARGS__); }

//Direct section functions

#define FE_1(WHAT, X) WHAT(X)
#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)
#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)
#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)
#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)
#define FE_6(WHAT, X, ...) WHAT(X)FE_5(WHAT, __VA_ARGS__)
#define FE_7(WHAT, X, ...) WHAT(X)FE_6(WHAT, __VA_ARGS__)
#define FE_8(WHAT, X, ...) WHAT(X)FE_7(WHAT, __VA_ARGS__)

#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME

#define FOR_EACH(action,...) \
  GET_MACRO(__VA_ARGS__,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)

#define FFE_1(WHAT, I, X) WHAT(I,X)
#define FFE_2(WHAT, I, X, ...) WHAT(I,X)FFE_1(WHAT, I, __VA_ARGS__)
#define FFE_3(WHAT, I, X, ...) WHAT(I,X)FFE_2(WHAT, I, __VA_ARGS__)
#define FFE_4(WHAT, I, X, ...) WHAT(I,X)FFE_3(WHAT, I, __VA_ARGS__)
#define FFE_5(WHAT, I, X, ...) WHAT(I,X)FFE_4(WHAT, I, __VA_ARGS__)
#define FFE_6(WHAT, I, X, ...) WHAT(I,X)FFE_5(WHAT, I, __VA_ARGS__)
#define FFE_7(WHAT, I, X, ...) WHAT(I,X)FFE_6(WHAT, I, __VA_ARGS__)
#define FFE_8(WHAT, I, X, ...) WHAT(I,X)FFE_7(WHAT, I, __VA_ARGS__)

#define F_FOR_EACH(action,I,...) \
  GET_MACRO(__VA_ARGS__,FFE_8,FFE_7,FFE_6,FFE_5,FFE_4,FFE_3,FFE_2,FFE_1)(action,I,__VA_ARGS__)

#define EMIT_TWO_PASS(init, X) CPM_TWO_PASS((X).first, init, (X).second);
#define EMIT_TWO_PASS_NS(init, X) CPM_TWO_PASS_NS((X).first, init, (X).second);

#define CPM_SECTION_FUNCTOR(name, ...) \
    (std::make_pair(name, (__VA_ARGS__)))

#define CPM_DIRECT_SECTION_TWO_PASS(name, init, ...) \
    CPM_SECTION(name) \
    F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
    }

#define CPM_DIRECT_SECTION_TWO_PASS_P(name, policy, init, ...) \
    CPM_SECTION_P(name, POLICY(policy)) \
    F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
    }

#define CPM_DIRECT_SECTION_TWO_PASS_NS(name, init, ...) \
    CPM_SECTION(name) \
    F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
    }

#define CPM_DIRECT_SECTION_TWO_PASS_NS_P(name, policy, init, ...) \
    CPM_SECTION_P(name, POLICY(policy)) \
    F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
    }

#define CPM_SECTION_INIT(...) (__VA_ARGS__)

//Helpers to create policy
#define POLICY(...) __VA_ARGS__
#define VALUES_POLICY(...) cpm::values_policy<__VA_ARGS__>
#define NARY_POLICY(...) cpm::simple_nary_policy<__VA_ARGS__>
#define STD_STOP_POLICY cpm::std_stop_policy
#define STOP_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::STOP>
#define TIMEOUT_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::TIMEOUT>

#ifdef CPM_BENCHMARK

int main(int argc, char* argv[]){
    cxxopts::Options options(argv[0], "");

    try {
        options.add_options()
            ("n,name", "Benchmark name", cxxopts::value<std::string>())
            ("t,tag", "Tag name", cxxopts::value<std::string>())
            ("c,configuration", "Configuration", cxxopts::value<std::string>())
            ("o,output", "Output folder", cxxopts::value<std::string>())
            ("h,help", "Print help")
            ;

        options.parse(argc, argv);

        if (options.count("help")){
            std::cout << options.help({""}) << std::endl;
            return 0;
        }

    } catch (const cxxopts::OptionException& e){
        std::cout << "cpm: error parsing options: " << e.what() << std::endl;
        return -1;
    }

    std::string output_folder{"./results"};

    if (options.count("output")){
        output_folder = options["output"].as<std::string>();
    }

    std::string benchmark_name{CPM_BENCHMARK};

    if (options.count("name")){
        benchmark_name = options["name"].as<std::string>();
    }

    std::string tag;

    if (options.count("tag")){
        tag = options["tag"].as<std::string>();
    }

    std::string configuration;

    if (options.count("configuration")){
        configuration = options["configuration"].as<std::string>();
    }

    cpm::benchmark<> bench(benchmark_name, output_folder, tag, configuration);

#ifdef CPM_WARMUP
    bench.warmup = CPM_WARMUP;
#endif

#ifdef CPM_REPEAT
    bench.repeat = CPM_REPEAT;
#endif

    bench.begin();

    for(auto f : cpm::cpm_registry::benchs){
        f(bench);
    }

    return 0;
}

std::vector<void(*)(cpm::benchmark<>&)> cpm::cpm_registry::benchs;

#endif //CPM_BENCHMARK

#endif //CPM_CPM_SUPPORT_HPP
<commit_msg>Fix global construction dependency order<commit_after>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef CPM_CPM_SUPPORT_HPP
#define CPM_CPM_SUPPORT_HPP

#include "../../lib/cxxopts/src/cxxopts.hpp"

namespace cpm {

struct cpm_registry {
    cpm_registry(void (*function)(cpm::benchmark<>&)){
        benchs().emplace_back(function);
    }

    static std::vector<void(*)(cpm::benchmark<>&)>& benchs(){
        static std::vector<void(*)(cpm::benchmark<>&)> vec;
        return vec;
    }
};

template<template<typename...> class TT, typename T>
struct is_specialization_of : std::false_type {};

template<template<typename...> class TT, typename... Args>
struct is_specialization_of<TT, TT<Args...>> : std::true_type {};

template<typename T>
struct is_section : is_specialization_of<cpm::section, std::decay_t<T>> {};

} //end of namespace cpm

//Internal helpers

#define CPM_UNIQUE_DETAIL(x, y) x##y
#define CPM_UNIQUE(x, y) CPM_UNIQUE_DETAIL(x, y)
#define CPM_UNIQUE_NAME(x) CPM_UNIQUE(x, __LINE__)

//Declarations of benchs functions

#define CPM_BENCH()  \
    void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench); \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(bench_)); }              \
    void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench)

//Declaration of section functions

#define CPM_SECTION(name)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi(name);

#define CPM_SECTION_O(name, W, R)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi(name);    \
    bench.warmup = W;                   \
    bench.repeat = R;

#define CPM_SECTION_P(name, policy)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi<policy>(name);

#define CPM_SECTION_PO(name, policy, W, R)                                       \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master);      \
    namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); }        \
    void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) {     \
    auto bench = master.multi<policy>(name);      \
    bench.warmup = W;                             \
    bench.repeat = R;

//Normal versions for simple bench
#define CPM_SIMPLE(...) bench.measure_simple(__VA_ARGS__);
#define CPM_GLOBAL(...) bench.measure_global(__VA_ARGS__);
#define CPM_TWO_PASS(...) bench.measure_two_pass(__VA_ARGS__);
#define CPM_TWO_PASS_NS(...) bench.measure_two_pass<false>(__VA_ARGS__);

//Versions with policies

#define CPM_SIMPLE_P(policy, ...)  \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_SIMPLE_P cannot be used inside CPM_SECTION");  \
    bench.measure_simple<policy>(__VA_ARGS__);

#define CPM_GLOBAL_P(policy, ...) \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_GLOBAL_P cannot be used inside CPM_SECTION");  \
    bench.measure_global<policy>(__VA_ARGS__);

#define CPM_TWO_PASS_P(policy, ...) \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_P cannot be used inside CPM_SECTION");  \
    bench.measure_two_pass<true, policy>(__VA_ARGS__);

#define CPM_TWO_PASS_NS_P(policy, ...)  \
    static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_NS_P cannot be used inside CPM_SECTION");  \
    bench.template measure_two_pass<false, policy>(__VA_ARGS__);

//Direct bench functions

#define CPM_DIRECT_BENCH_SIMPLE(...) CPM_BENCH() { CPM_SIMPLE(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS(...) CPM_BENCH() { CPM_TWO_PASS(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS(...) CPM_BENCH() { CPM_TWO_PASS_NS(__VA_ARGS__); }

//Direct bench functions with policies

#define CPM_DIRECT_BENCH_SIMPLE_P(policy,...) CPM_BENCH() { CPM_SIMPLE_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_NS_P(POLICY(policy),__VA_ARGS__); }

//Direct section functions

#define FE_1(WHAT, X) WHAT(X)
#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)
#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)
#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)
#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)
#define FE_6(WHAT, X, ...) WHAT(X)FE_5(WHAT, __VA_ARGS__)
#define FE_7(WHAT, X, ...) WHAT(X)FE_6(WHAT, __VA_ARGS__)
#define FE_8(WHAT, X, ...) WHAT(X)FE_7(WHAT, __VA_ARGS__)

#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME

#define FOR_EACH(action,...) \
  GET_MACRO(__VA_ARGS__,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)

#define FFE_1(WHAT, I, X) WHAT(I,X)
#define FFE_2(WHAT, I, X, ...) WHAT(I,X)FFE_1(WHAT, I, __VA_ARGS__)
#define FFE_3(WHAT, I, X, ...) WHAT(I,X)FFE_2(WHAT, I, __VA_ARGS__)
#define FFE_4(WHAT, I, X, ...) WHAT(I,X)FFE_3(WHAT, I, __VA_ARGS__)
#define FFE_5(WHAT, I, X, ...) WHAT(I,X)FFE_4(WHAT, I, __VA_ARGS__)
#define FFE_6(WHAT, I, X, ...) WHAT(I,X)FFE_5(WHAT, I, __VA_ARGS__)
#define FFE_7(WHAT, I, X, ...) WHAT(I,X)FFE_6(WHAT, I, __VA_ARGS__)
#define FFE_8(WHAT, I, X, ...) WHAT(I,X)FFE_7(WHAT, I, __VA_ARGS__)

#define F_FOR_EACH(action,I,...) \
  GET_MACRO(__VA_ARGS__,FFE_8,FFE_7,FFE_6,FFE_5,FFE_4,FFE_3,FFE_2,FFE_1)(action,I,__VA_ARGS__)

#define EMIT_TWO_PASS(init, X) CPM_TWO_PASS((X).first, init, (X).second);
#define EMIT_TWO_PASS_NS(init, X) CPM_TWO_PASS_NS((X).first, init, (X).second);

#define CPM_SECTION_FUNCTOR(name, ...) \
    (std::make_pair(name, (__VA_ARGS__)))

#define CPM_DIRECT_SECTION_TWO_PASS(name, init, ...) \
    CPM_SECTION(name) \
    F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
    }

#define CPM_DIRECT_SECTION_TWO_PASS_P(name, policy, init, ...) \
    CPM_SECTION_P(name, POLICY(policy)) \
    F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
    }

#define CPM_DIRECT_SECTION_TWO_PASS_NS(name, init, ...) \
    CPM_SECTION(name) \
    F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
    }

#define CPM_DIRECT_SECTION_TWO_PASS_NS_P(name, policy, init, ...) \
    CPM_SECTION_P(name, POLICY(policy)) \
    F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
    }

#define CPM_SECTION_INIT(...) (__VA_ARGS__)

//Helpers to create policy
#define POLICY(...) __VA_ARGS__
#define VALUES_POLICY(...) cpm::values_policy<__VA_ARGS__>
#define NARY_POLICY(...) cpm::simple_nary_policy<__VA_ARGS__>
#define STD_STOP_POLICY cpm::std_stop_policy
#define STOP_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::STOP>
#define TIMEOUT_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::TIMEOUT>

#ifdef CPM_BENCHMARK

int main(int argc, char* argv[]){
    cxxopts::Options options(argv[0], "");

    try {
        options.add_options()
            ("n,name", "Benchmark name", cxxopts::value<std::string>())
            ("t,tag", "Tag name", cxxopts::value<std::string>())
            ("c,configuration", "Configuration", cxxopts::value<std::string>())
            ("o,output", "Output folder", cxxopts::value<std::string>())
            ("h,help", "Print help")
            ;

        options.parse(argc, argv);

        if (options.count("help")){
            std::cout << options.help({""}) << std::endl;
            return 0;
        }

    } catch (const cxxopts::OptionException& e){
        std::cout << "cpm: error parsing options: " << e.what() << std::endl;
        return -1;
    }

    std::string output_folder{"./results"};

    if (options.count("output")){
        output_folder = options["output"].as<std::string>();
    }

    std::string benchmark_name{CPM_BENCHMARK};

    if (options.count("name")){
        benchmark_name = options["name"].as<std::string>();
    }

    std::string tag;

    if (options.count("tag")){
        tag = options["tag"].as<std::string>();
    }

    std::string configuration;

    if (options.count("configuration")){
        configuration = options["configuration"].as<std::string>();
    }

    cpm::benchmark<> bench(benchmark_name, output_folder, tag, configuration);

#ifdef CPM_WARMUP
    bench.warmup = CPM_WARMUP;
#endif

#ifdef CPM_REPEAT
    bench.repeat = CPM_REPEAT;
#endif

    bench.begin();

    for(auto f : cpm::cpm_registry::benchs()){
        f(bench);
    }

    return 0;
}

#endif //CPM_BENCHMARK

#endif //CPM_CPM_SUPPORT_HPP
<|endoftext|>


<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
        details << "Press B to cancel.";

        u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    if(ret != APP_SUCCESS) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    }
                                } else {
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(netInstall && !exit) {
            netInstall = false;

            screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << appGetResultString(ret) << "\n";
                }

                uiPrompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<commit_msg>Add NAND delete warning, return to network install screen after a successful network install.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
        details << "Press B to cancel.";

        u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            if(netInstall && !exit) {
                screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

                RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
                if(file.fd == NULL) {
                    netInstall = false;
                    continue;
                }

                std::stringstream confirmStream;
                confirmStream << "Install the received application?" << "\n";
                confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
                if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                    AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                    std::stringstream resultMsg;
                    resultMsg << "Install ";
                    if(ret == APP_SUCCESS) {
                        resultMsg << "succeeded!";
                    } else {
                        resultMsg << "failed!" << "\n";
                        resultMsg << appGetResultString(ret) << "\n";
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                }

                fclose(file.fd);
                continue;
            }

            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    if(ret != APP_SUCCESS) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    }
                                } else {
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#ifdef __GNUG__
#pragma implementation "list.h"
#endif

#include "condor_common.h"
#include "condor_config.h"
#include "condor_network.h"
#include "condor_io.h"
#include "sched.h"
#include "alloc.h"
#include "get_daemon_addr.h"
#include "condor_attributes.h"
#include  "list.h"

static char *_FileName_ = __FILE__;		/* Used by EXCEPT (see except.h)     */

#include "condor_qmgr.h"

template class List<PROC_ID>;
template class Item<PROC_ID>;

char	*MyName;
BOOLEAN	TroubleReported;
BOOLEAN All = FALSE;
int nToProcess = 0;
List<PROC_ID> ToProcess;

	// Prototypes of local interest
void ProcArg(const char*);
void notify_schedd();
void usage();
void handle_all();

char* DaemonName = NULL;

int mode;

void
usage()
{
	fprintf( stderr,
		"Usage: %s [-n schedd_name] { -a | cluster | cluster.proc | user } ... \n",
		MyName
	);
	exit( 1 );
}

int
main( int argc, char *argv[] )
{
	char	*arg;
	char	**args = (char **)malloc(sizeof(char *)*(argc - 1)); // args of jobs to be deleted
	int					nArgs = 0;				// number of args to be deleted
	int					i;
	Qmgr_connection*	q;
	char*	daemonname;
	char*	cmd_str;

	MyName = strrchr( argv[0], DIR_DELIM_CHAR );
	if( !MyName ) {
		MyName = argv[0];
	} else {
		MyName++;
	}

	cmd_str = strchr( MyName, '_');
	if (cmd_str && strcmp(cmd_str, "_hold") == MATCH) {
		mode = HELD;
	} else {
		mode = REMOVED;
	}

	config( 0 );

	if( argc < 2 ) {
		usage();
	}

#if !defined(WIN32)
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	for( argv++; arg = *argv; argv++ ) {
		if( arg[0] == '-' && arg[1] == 'a' ) {
			All = TRUE;
		} else {
			if( All ) {
				usage();
			}
			if ( arg[0] == '-' && arg[1] == 'n' ) {
				// use the given name as the schedd name to connect to
				argv++;
				if( ! *argv ) {
					fprintf( stderr, "%s: -n requires another argument\n",
							 MyName);
					exit(1);
				}
				if( !(DaemonName = get_daemon_name(*argv)) ) {
					fprintf( stderr, "%s: unknown host %s\n",
							 MyName, get_host_part(*argv) );
					exit(1);
				}
			} else {
				args[nArgs] = arg;
				nArgs++;
			}
		}
	}

		// Open job queue
	q = ConnectQ(DaemonName);
	if( !q ) {
		if( DaemonName ) {
			fprintf( stderr, "Failed to connect to queue manager %s\n",
					 DaemonName );
		} else {
			fprintf( stderr, "Failed to connect to local queue manager\n" );
		}
		exit(1);
	}

	if( All ) {
		handle_all();
	} else {
			// Set status of requested jobs to REMOVED/HELD
		for(i = 0; i < nArgs; i++) {
			ProcArg(args[i]);
		}
	}

	// Close job queue
	DisconnectQ(q);

	// Now tell the schedd what we did.  We send the schedd the
	// KILL_FRGN_JOB command.  We pass the number of jobs to
	// remove/hold _unless_ one or more of the jobs are to be
	// removed/held via cluster or via user name, in which case we say
	// "-1" jobs to remove/hold.  Telling the schedd there are "-1"
	// jobs to remove forces the schedd to scan the queue looking for
	// jobs which have a REMOVED/HELD status.  If all jobs to be removed/held
	// are via a cluster.proc, we then send the schedd all the
	// cluster.proc numbers to save the schedd from having to scan the
	// entire queue.
	if ( nToProcess != 0 )
		notify_schedd();

#if defined(ALLOC_DEBUG)
	print_alloc_stats();
#endif

	return 0;
}

extern "C" int SetSyscalls( int foo ) { return foo; }

void
notify_schedd()
{
	ReliSock	*sock;
	char		*scheddAddr;
	int			cmd;
	PROC_ID		*job_id;
	int 		i;

	if( (scheddAddr = get_schedd_addr(DaemonName)) == NULL ) {
		if( *DaemonName ) {
			fprintf( stderr, "Can't find schedd address of %s\n", DaemonName);
		} else {
			fprintf( stderr, "Can't find address of local schedd\n" );
		}
		exit(1);
	}

		/* Connect to the schedd */
	sock = new ReliSock;
	if(!sock->connect(scheddAddr)) {
		if( !TroubleReported ) {
			if( *DaemonName ) {
				fprintf( stderr, "Error: Can't connect to schedd %s\n",
						 DaemonName );
			} else {
				fprintf( stderr, "Error: Can't connect to local schedd\n" );
			}
			TroubleReported = 1;
		}
		delete sock;
		return;
	}

	sock->encode();

	cmd = KILL_FRGN_JOB;
	if( !sock->code(cmd) ) {
		fprintf( stderr,
			"Warning: can't send KILL_JOB command to condor scheduler\n" );
		delete sock;
		return;
	}

	if( !sock->code(nToProcess) ) {
		fprintf( stderr,
			"Warning: can't send num jobs to process to schedd (%d)\n",nToProcess );
		delete sock;
		return;
	}

	ToProcess.Rewind();
	for (i=0;i<nToProcess;i++) {
		job_id = ToProcess.Next();
		if( !sock->code(*job_id) ) {
			fprintf( stderr,
				"Error: can't send a proc_id to condor scheduler\n" );
			delete sock;
			return;
		}
	}

	if( !sock->end_of_message() ) {
		fprintf( stderr,
			"Warning: can't send end of message to condor scheduler\n" );
		delete sock;
		return;
	}

	delete sock;
}

void ProcArg(const char* arg)
{
	int		c, p;								// cluster/proc #
	char*	tmp;
	PROC_ID *id;

	if(isdigit(*arg))
	// delete by cluster/proc #
	{
		c = strtol(arg, &tmp, 10);
		if(c <= 0)
		{
			fprintf(stderr, "Invalid cluster # from %s.\n", arg);
			return;
		}
		if(*tmp == '\0')
		// delete the cluster
		{
			char constraint[250];

			sprintf(constraint, "%s == %d", ATTR_CLUSTER_ID, c);

			if (SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)
			{
				fprintf( stderr, "Couldn't find/%s cluster %d.\n",
						 (mode==REMOVED)?"remove":"hold", c);
			} else {
				fprintf(stderr, "Cluster %d %s.\n", c,
						(mode==REMOVED)?"removed":"held");
				nToProcess = -1;
			}
			return;
		}
		if(*tmp == '.')
		{
			p = strtol(tmp + 1, &tmp, 10);
			if(p < 0)
			{
				fprintf( stderr, "Invalid proc # from %s.\n", arg);
				return;
			}
			if(*tmp == '\0')
			// delete a proc
			{
				if(SetAttributeInt(c, p, ATTR_JOB_STATUS, mode ) < 0)
				{
					fprintf( stderr, "Couldn't find/%s job %d.%d.\n",
							 (mode==REMOVED)?"remove":"hold", c, p );
				} else {
					fprintf(stdout, "Job %d.%d %s.\n", c, p,
							(mode==REMOVED)?"removed":"held");
					if ( nToProcess != -1 ) {
						nToProcess++;
						id = new PROC_ID;
						id->proc = p;
						id->cluster = c;
						ToProcess.Append(id);
					}
				}
				return;
			}
			fprintf( stderr, "Warning: unrecognized \"%s\" skipped.\n", arg );
			return;
		}
		fprintf( stderr, "Warning: unrecognized \"%s\" skipped.\n", arg );
	}
	else if(isalpha(*arg))
	// delete by user name
	{
		char	constraint[1000];

		sprintf(constraint, "Owner == \"%s\"", arg);
		if(SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)
		{
			fprintf( stderr, "Couldn't find/%s user %s's job(s).\n",
					 (mode==REMOVED)?"remove":"hold", arg );
		} else {
			fprintf(stdout, "User %s's job(s) %s.\n", arg,
					(mode==REMOVED)?"removed":"held");
			nToProcess = -1;
		}
	}
	else
	{
		fprintf( stderr, "Warning: unrecognized \"%s\" skipped.\n", arg );
	}
}

void
handle_all()
{
	char	constraint[1000];

		// Remove/Hold all jobs... let queue management code decide
		// which ones we can and can not remove.
	sprintf(constraint, "%s >= %d", ATTR_CLUSTER_ID, 0 );
	if( SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0 ) {
		fprintf( stdout, "%s all of your jobs.\n",
				 (mode==REMOVED)?"Removed":"Held" );
	} else {
		fprintf( stdout, "%s all jobs.\n",
				 (mode==REMOVED)?"Removed":"Held" );
	}
	nToProcess = -1;
}
<commit_msg>remove unused daemonname parameter; include sig_install.h to get prototype of install_sig_handler<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#ifdef __GNUG__
#pragma implementation "list.h"
#endif

#include "condor_common.h"
#include "condor_config.h"
#include "condor_network.h"
#include "condor_io.h"
#include "sched.h"
#include "alloc.h"
#include "get_daemon_addr.h"
#include "condor_attributes.h"
#include  "list.h"
#include "sig_install.h"

static char *_FileName_ = __FILE__;		/* Used by EXCEPT (see except.h)     */

#include "condor_qmgr.h"

template class List<PROC_ID>;
template class Item<PROC_ID>;

char	*MyName;
BOOLEAN	TroubleReported;
BOOLEAN All = FALSE;
int nToProcess = 0;
List<PROC_ID> ToProcess;

	// Prototypes of local interest
void ProcArg(const char*);
void notify_schedd();
void usage();
void handle_all();

char* DaemonName = NULL;

int mode;

void
usage()
{
	fprintf( stderr,
		"Usage: %s [-n schedd_name] { -a | cluster | cluster.proc | user } ... \n",
		MyName
	);
	exit( 1 );
}

int
main( int argc, char *argv[] )
{
	char	*arg;
	char	**args = (char **)malloc(sizeof(char *)*(argc - 1)); // args of jobs to be deleted
	int					nArgs = 0;				// number of args to be deleted
	int					i;
	Qmgr_connection*	q;
	char*	cmd_str;

	MyName = strrchr( argv[0], DIR_DELIM_CHAR );
	if( !MyName ) {
		MyName = argv[0];
	} else {
		MyName++;
	}

	cmd_str = strchr( MyName, '_');
	if (cmd_str && strcmp(cmd_str, "_hold") == MATCH) {
		mode = HELD;
	} else {
		mode = REMOVED;
	}

	config( 0 );

	if( argc < 2 ) {
		usage();
	}

#if !defined(WIN32)
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	for( argv++; arg = *argv; argv++ ) {
		if( arg[0] == '-' && arg[1] == 'a' ) {
			All = TRUE;
		} else {
			if( All ) {
				usage();
			}
			if ( arg[0] == '-' && arg[1] == 'n' ) {
				// use the given name as the schedd name to connect to
				argv++;
				if( ! *argv ) {
					fprintf( stderr, "%s: -n requires another argument\n",
							 MyName);
					exit(1);
				}
				if( !(DaemonName = get_daemon_name(*argv)) ) {
					fprintf( stderr, "%s: unknown host %s\n",
							 MyName, get_host_part(*argv) );
					exit(1);
				}
			} else {
				args[nArgs] = arg;
				nArgs++;
			}
		}
	}

		// Open job queue
	q = ConnectQ(DaemonName);
	if( !q ) {
		if( DaemonName ) {
			fprintf( stderr, "Failed to connect to queue manager %s\n",
					 DaemonName );
		} else {
			fprintf( stderr, "Failed to connect to local queue manager\n" );
		}
		exit(1);
	}

	if( All ) {
		handle_all();
	} else {
			// Set status of requested jobs to REMOVED/HELD
		for(i = 0; i < nArgs; i++) {
			ProcArg(args[i]);
		}
	}

	// Close job queue
	DisconnectQ(q);

	// Now tell the schedd what we did.  We send the schedd the
	// KILL_FRGN_JOB command.  We pass the number of jobs to
	// remove/hold _unless_ one or more of the jobs are to be
	// removed/held via cluster or via user name, in which case we say
	// "-1" jobs to remove/hold.  Telling the schedd there are "-1"
	// jobs to remove forces the schedd to scan the queue looking for
	// jobs which have a REMOVED/HELD status.  If all jobs to be removed/held
	// are via a cluster.proc, we then send the schedd all the
	// cluster.proc numbers to save the schedd from having to scan the
	// entire queue.
	if ( nToProcess != 0 )
		notify_schedd();

#if defined(ALLOC_DEBUG)
	print_alloc_stats();
#endif

	return 0;
}

extern "C" int SetSyscalls( int foo ) { return foo; }

void
notify_schedd()
{
	ReliSock	*sock;
	char		*scheddAddr;
	int			cmd;
	PROC_ID		*job_id;
	int 		i;

	if( (scheddAddr = get_schedd_addr(DaemonName)) == NULL ) {
		if( *DaemonName ) {
			fprintf( stderr, "Can't find schedd address of %s\n", DaemonName);
		} else {
			fprintf( stderr, "Can't find address of local schedd\n" );
		}
		exit(1);
	}

		/* Connect to the schedd */
	sock = new ReliSock;
	if(!sock->connect(scheddAddr)) {
		if( !TroubleReported ) {
			if( *DaemonName ) {
				fprintf( stderr, "Error: Can't connect to schedd %s\n",
						 DaemonName );
			} else {
				fprintf( stderr, "Error: Can't connect to local schedd\n" );
			}
			TroubleReported = 1;
		}
		delete sock;
		return;
	}

	sock->encode();

	cmd = KILL_FRGN_JOB;
	if( !sock->code(cmd) ) {
		fprintf( stderr,
			"Warning: can't send KILL_JOB command to condor scheduler\n" );
		delete sock;
		return;
	}

	if( !sock->code(nToProcess) ) {
		fprintf( stderr,
			"Warning: can't send num jobs to process to schedd (%d)\n",nToProcess );
		delete sock;
		return;
	}

	ToProcess.Rewind();
	for (i=0;i<nToProcess;i++) {
		job_id = ToProcess.Next();
		if( !sock->code(*job_id) ) {
			fprintf( stderr,
				"Error: can't send a proc_id to condor scheduler\n" );
			delete sock;
			return;
		}
	}

	if( !sock->end_of_message() ) {
		fprintf( stderr,
			"Warning: can't send end of message to condor scheduler\n" );
		delete sock;
		return;
	}

	delete sock;
}

void ProcArg(const char* arg)
{
	int		c, p;								// cluster/proc #
	char*	tmp;
	PROC_ID *id;

	if(isdigit(*arg))
	// delete by cluster/proc #
	{
		c = strtol(arg, &tmp, 10);
		if(c <= 0)
		{
			fprintf(stderr, "Invalid cluster # from %s.\n", arg);
			return;
		}
		if(*tmp == '\0')
		// delete the cluster
		{
			char constraint[250];

			sprintf(constraint, "%s == %d", ATTR_CLUSTER_ID, c);

			if (SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)
			{
				fprintf( stderr, "Couldn't find/%s cluster %d.\n",
						 (mode==REMOVED)?"remove":"hold", c);
			} else {
				fprintf(stderr, "Cluster %d %s.\n", c,
						(mode==REMOVED)?"removed":"held");
				nToProcess = -1;
			}
			return;
		}
		if(*tmp == '.')
		{
			p = strtol(tmp + 1, &tmp, 10);
			if(p < 0)
			{
				fprintf( stderr, "Invalid proc # from %s.\n", arg);
				return;
			}
			if(*tmp == '\0')
			// delete a proc
			{
				if(SetAttributeInt(c, p, ATTR_JOB_STATUS, mode ) < 0)
				{
					fprintf( stderr, "Couldn't find/%s job %d.%d.\n",
							 (mode==REMOVED)?"remove":"hold", c, p );
				} else {
					fprintf(stdout, "Job %d.%d %s.\n", c, p,
							(mode==REMOVED)?"removed":"held");
					if ( nToProcess != -1 ) {
						nToProcess++;
						id = new PROC_ID;
						id->proc = p;
						id->cluster = c;
						ToProcess.Append(id);
					}
				}
				return;
			}
			fprintf( stderr, "Warning: unrecognized \"%s\" skipped.\n", arg );
			return;
		}
		fprintf( stderr, "Warning: unrecognized \"%s\" skipped.\n", arg );
	}
	else if(isalpha(*arg))
	// delete by user name
	{
		char	constraint[1000];

		sprintf(constraint, "Owner == \"%s\"", arg);
		if(SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0)
		{
			fprintf( stderr, "Couldn't find/%s user %s's job(s).\n",
					 (mode==REMOVED)?"remove":"hold", arg );
		} else {
			fprintf(stdout, "User %s's job(s) %s.\n", arg,
					(mode==REMOVED)?"removed":"held");
			nToProcess = -1;
		}
	}
	else
	{
		fprintf( stderr, "Warning: unrecognized \"%s\" skipped.\n", arg );
	}
}

void
handle_all()
{
	char	constraint[1000];

		// Remove/Hold all jobs... let queue management code decide
		// which ones we can and can not remove.
	sprintf(constraint, "%s >= %d", ATTR_CLUSTER_ID, 0 );
	if( SetAttributeIntByConstraint(constraint,ATTR_JOB_STATUS,mode) < 0 ) {
		fprintf( stdout, "%s all of your jobs.\n",
				 (mode==REMOVED)?"Removed":"Held" );
	} else {
		fprintf( stdout, "%s all jobs.\n",
				 (mode==REMOVED)?"Removed":"Held" );
	}
	nToProcess = -1;
}
<|endoftext|>


<commit_before>#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <3ds.h>

#include "constants.h"
#include "patches.h"

#define log(...) fprintf(stderr, __VA_ARGS__)

int main(int argc, char** argv)
{
	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);
	GetVersionConstants();
    PatchSrvAccess();

// ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper
    // svcBackdoor(PatchProcessWrapper);
    // log("[0x%08X] - Patched process\n", ret);

	// Main loop
	while (aptMainLoop())
	{
		hidScanInput();

		u32 kDown = hidKeysDown();
		if (kDown & KEY_START)
			break;
		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}
<commit_msg>main.cpp: Fix indentation<commit_after>#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <3ds.h>

#include "constants.h"
#include "patches.h"

#define log(...) fprintf(stderr, __VA_ARGS__)

int main(int argc, char** argv)
{
    gfxInitDefault();
    consoleInit(GFX_TOP, NULL);
    GetVersionConstants();
    PatchSrvAccess();

// ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper
    // svcBackdoor(PatchProcessWrapper);
    // log("[0x%08X] - Patched process\n", ret);

    // Main loop
    while (aptMainLoop())
    {
        hidScanInput();

        u32 kDown = hidKeysDown();
        if (kDown & KEY_START)
            break;
        gspWaitForVBlank();
    }

    gfxExit();
    return 0;
}
<|endoftext|>


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

#ifndef ROS_ENV_HPP
#define ROS_ENV_HPP

/*
* ROS includes
*/
#include <ros/ros.h>

/*
* ALDEBARAN includes
*/
#include <qi/os.hpp>

#include <stdlib.h>

#include <boost/algorithm/string.hpp>

namespace alros
{
namespace ros_env
{

/** Queries NAOqi to get the IP
 * @param network_interface the name of the network interface to use. "eth0" by default. If you put your NAO in
 * tethering mode, you will need to put "tether"
 */
static std::string getROSIP(std::string network_interface)
{
  if (network_interface.empty())
    network_interface = "eth0";
  typedef std::map< std::string, std::vector<std::string> > Map_IP;
  static const std::string ip = static_cast<Map_IP>(qi::os::hostIPAddrs())[network_interface][0];
  return ip;
}

static std::string getPrefix()
{
  return "alrosbridge";
}

static void setMasterURI( const std::string& uri, const std::string& network_interface )
{
  if (ros::isInitialized() )
  {
    std::cout << "stopping ros init" << std::endl;
    ros::shutdown();
  }

  setenv("ROS_MASTER_URI", uri.c_str(), 1);

  std::string my_master = "__master="+uri;
  std::map< std::string, std::string > remap;
  remap["__master"] = uri;
  remap["__ip"] = ::alros::ros_env::getROSIP(network_interface);
  // init ros without a sigint-handler in order to shutdown correctly by naoqi
  ros::init( remap, ::alros::ros_env::getPrefix(), ros::init_options::NoSigintHandler );
  // to prevent shutdown based on no existing nodehandle
  ros::start();

  std::cout << "using master ip: " <<  ros::master::getURI() << std::endl;
}

static std::string getMasterURI( )
{
  return getenv("ROS_MASTER_URI");
}

static std::string getCMakePrefixPath()
{
  char *cMakePrefixPath = getenv( "CMAKE_PREFIX_PATH" );
  if (cMakePrefixPath != NULL) {
    return getenv( "CMAKE_PREFIX_PATH" );
  }
  return "";
}

static void adjustSDKPrefix()
{
  std::string cmake_prefix = alros::ros_env::getCMakePrefixPath();
  std::vector<std::string> prefixes;
  boost::split( prefixes, cmake_prefix, boost::is_any_of(":") );

  for (size_t i=0; i<prefixes.size(); i++)
  {
    std::cout << "going to add: " << prefixes[i] << std::endl;
    qi::path::detail::addOptionalSdkPrefix( prefixes[i].c_str() );
  }
}

} // ros_env
} // alros
#endif
<commit_msg>ros_env.hpp write error message when network interface is not found<commit_after>/*
 * Copyright 2015 Aldebaran
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#ifndef ROS_ENV_HPP
#define ROS_ENV_HPP

/*
* ROS includes
*/
#include <ros/ros.h>

/*
* ALDEBARAN includes
*/
#include <qi/os.hpp>

#include <stdlib.h>

#include <boost/algorithm/string.hpp>

namespace alros
{
namespace ros_env
{

/** Queries NAOqi to get the IP
 * @param network_interface the name of the network interface to use. "eth0" by default. If you put your NAO in
 * tethering mode, you will need to put "tether"
 */
static std::string getROSIP(std::string network_interface)
{
  if (network_interface.empty())
    network_interface = "eth0";

  typedef std::map< std::string, std::vector<std::string> > Map_IP;
  Map_IP map_ip = static_cast<Map_IP>(qi::os::hostIPAddrs());
  if ( map_ip.find(network_interface) == map_ip.end() ) {
    std::cerr << "Could not find network interface named " << network_interface << ", pssible interfaces are ... ";
    for (Map_IP::iterator it=map_ip.begin(); it!=map_ip.end(); ++it) std::cerr << it->first <<  " ";
    std::cerr << std::endl;
    exit(1);
  }

  static const std::string ip = map_ip[network_interface][0];
  return ip;
}

static std::string getPrefix()
{
  return "alrosbridge";
}

static void setMasterURI( const std::string& uri, const std::string& network_interface )
{
  if (ros::isInitialized() )
  {
    std::cout << "stopping ros init" << std::endl;
    ros::shutdown();
  }

  setenv("ROS_MASTER_URI", uri.c_str(), 1);

  std::string my_master = "__master="+uri;
  std::map< std::string, std::string > remap;
  remap["__master"] = uri;
  remap["__ip"] = ::alros::ros_env::getROSIP(network_interface);
  // init ros without a sigint-handler in order to shutdown correctly by naoqi
  ros::init( remap, ::alros::ros_env::getPrefix(), ros::init_options::NoSigintHandler );
  // to prevent shutdown based on no existing nodehandle
  ros::start();

  std::cout << "using master ip: " <<  ros::master::getURI() << std::endl;
}

static std::string getMasterURI( )
{
  return getenv("ROS_MASTER_URI");
}

static std::string getCMakePrefixPath()
{
  char *cMakePrefixPath = getenv( "CMAKE_PREFIX_PATH" );
  if (cMakePrefixPath != NULL) {
    return getenv( "CMAKE_PREFIX_PATH" );
  }
  return "";
}

static void adjustSDKPrefix()
{
  std::string cmake_prefix = alros::ros_env::getCMakePrefixPath();
  std::vector<std::string> prefixes;
  boost::split( prefixes, cmake_prefix, boost::is_any_of(":") );

  for (size_t i=0; i<prefixes.size(); i++)
  {
    std::cout << "going to add: " << prefixes[i] << std::endl;
    qi::path::detail::addOptionalSdkPrefix( prefixes[i].c_str() );
  }
}

} // ros_env
} // alros
#endif
<|endoftext|>


<commit_before>/*!
    \file path.inl
    \brief Filesystem path wrapper inline implementation
    \author Ivan Shynkarenka
    \date 11.08.2016
    \copyright MIT License
*/

namespace CppCommon {

inline Path& Path::operator/=(const std::string& path)
{
    if (_path.empty())
        _path = path;
    else
    {
        char last = _path[_path.size() - 1];
        if ((last == '\\') || (last == '/'))
            _path += path;
        else
        {
            _path += separator();
            _path += path;
        }
    }
}

inline char Path::separator()
{
#if defined(_WIN32) || defined(_WIN64)
    return '\\';
#elif defined(unix) || defined(__unix) || defined(__unix__)
    return '/';
#endif
}

inline void swap(Path& path1, Path& path2)
{
    using std::swap;
    swap(path1._path, path2._path);
}

} // namespace CppCommon
<commit_msg>Bugfix<commit_after>/*!
    \file path.inl
    \brief Filesystem path wrapper inline implementation
    \author Ivan Shynkarenka
    \date 11.08.2016
    \copyright MIT License
*/

namespace CppCommon {

inline Path& Path::operator/=(const std::string& path)
{
    if (_path.empty())
        _path = path;
    else
    {
        char last = _path[_path.size() - 1];
        if ((last == '\\') || (last == '/'))
            _path += path;
        else
        {
            _path += separator();
            _path += path;
        }
    }

    return *this;
}

inline char Path::separator()
{
#if defined(_WIN32) || defined(_WIN64)
    return '\\';
#elif defined(unix) || defined(__unix) || defined(__unix__)
    return '/';
#endif
}

inline void swap(Path& path1, Path& path2)
{
    using std::swap;
    swap(path1._path, path2._path);
}

} // namespace CppCommon
<|endoftext|>


<commit_before>// This file is part of NameTag.
//
// Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// NameTag is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// NameTag is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with NameTag.  If not, see <http://www.gnu.org/licenses/>.

#include <cstring>
#include <ctime>
#include <memory>

#include "ner/ner.h"
#include "utils/input.h"

using namespace ufal::nametag;

static void recognize_vertical(const ner& recognizer);
static void recognize_untokenized(const ner& recognizer);

int main(int argc, char* argv[]) {
  bool use_vertical = false;

  int argi = 1;
  if (argi < argc && strcmp(argv[argi], "-v") == 0) argi++, use_vertical = true;
  if (argi >= argc) runtime_errorf("Usage: %s [-v] ner_model", argv[0]);

  eprintf("Loading ner: ");
  unique_ptr<ner> recognizer(ner::load(argv[argi]));
  if (!recognizer) runtime_errorf("Cannot load ner from file '%s'!", argv[argi]);
  eprintf("done\n");

  eprintf("Recognizing: ");
  clock_t now = clock();
  if (use_vertical) recognize_vertical(*recognizer);
  else recognize_untokenized(*recognizer);
  eprintf("done, in %.3f seconds.\n", (clock() - now) / double(CLOCKS_PER_SEC));

  return 0;
}

void recognize_vertical(const ner& recognizer) {
  string line;
  unsigned total_lines = 0;

  vector<string> words;
  vector<string_piece> forms;
  vector<named_entity> entities;
  string entity_ids, entity_text;

  for (bool not_eof = true; not_eof; ) {
    // Read sentence
    words.clear();
    forms.clear();
    while ((not_eof = getline(stdin, line)) && !line.empty()) {
      auto tab = line.find('\t');
      words.emplace_back(tab == string::npos ? line : line.substr(0, tab));
      forms.emplace_back(words.back());
    }

    // Find named entities in the sentence
    if (!forms.empty()) {
      recognizer.recognize(forms, entities);

      for (auto& entity : entities) {
        entity_ids.clear();
        entity_text.clear();
        for (auto i = entity.start; i < entity.start + entity.length; i++) {
          if (i > entity.start) {
            entity_ids += ',';
            entity_text += ' ';
          }
          entity_ids += to_string(total_lines + i + 1);
          entity_text += words[i];
        }
        printf("%s\t%s\t%s\n", entity_ids.c_str(), entity.type.c_str(), entity_text.c_str());
      }
    }

    total_lines += forms.size() + 1;
  }
}

static void encode_entities_and_print(const char* text, size_t length);

void recognize_untokenized(const ner& recognizer) {
  string line, text;
  vector<named_entity> entities;
  vector<size_t> entity_ends;

  for (bool not_eof = true; not_eof; ) {
    // Read block of text
    text.clear();
    while ((not_eof = getline(stdin, line)) && !line.empty()) {
      text += line;
      text += '\n';
    }
    if (not_eof) text += '\n';

    // Tokenize the text and find named entities
    size_t unprinted = 0;
    recognizer.tokenize_and_recognize(text.c_str(), entities);
    for (auto& entity : entities) {
      // Close entities that end sooned than current entity
      while (!entity_ends.empty() && entity_ends.back() < entity.start) {
        if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);
        unprinted = entity_ends.back();
        entity_ends.pop_back();
        fputs("</ne>", stdout);
      }

      // Print text just before the entity, open it and add end to the stack
      if (unprinted < entity.start) encode_entities_and_print(text.c_str() + unprinted, entity.start - unprinted);
      unprinted = entity.start;
      printf("<ne type='%s'>", entity.type.c_str());
      entity_ends.push_back(entity.start + entity.length);
    }

    // Close unclosed entities
    while (!entity_ends.empty()) {
      if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);
      unprinted = entity_ends.back();
      entity_ends.pop_back();
      fputs("</ne>", stdout);
    }
    // Write rest of the text (should be just spaces)
    if (unprinted < text.size()) encode_entities_and_print(text.c_str() + unprinted, text.size() - unprinted);

    if (not_eof) printf("\n");
  }
}

void encode_entities_and_print(const char* text, size_t length) {
  const char* to_print = text;
  while (length) {
    while (length && *text != '<' && *text != '>' && *text != '&' && *text != '"')
      text++, length--;

    if (length) {
      if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
      fputs(*text == '<' ? "<" : *text == '>' ? ">" : *text == '&' ? "&" : """, stdout);
      text++, length--;
      to_print = text;
    }
  }
  if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
}
<commit_msg>Remove surplus printf("\n"), use quotation marks...<commit_after>// This file is part of NameTag.
//
// Copyright 2013 by Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// NameTag is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// NameTag is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with NameTag.  If not, see <http://www.gnu.org/licenses/>.

#include <cstring>
#include <ctime>
#include <memory>

#include "ner/ner.h"
#include "utils/input.h"

using namespace ufal::nametag;

static void recognize_vertical(const ner& recognizer);
static void recognize_untokenized(const ner& recognizer);

int main(int argc, char* argv[]) {
  bool use_vertical = false;

  int argi = 1;
  if (argi < argc && strcmp(argv[argi], "-v") == 0) argi++, use_vertical = true;
  if (argi >= argc) runtime_errorf("Usage: %s [-v] ner_model", argv[0]);

  eprintf("Loading ner: ");
  unique_ptr<ner> recognizer(ner::load(argv[argi]));
  if (!recognizer) runtime_errorf("Cannot load ner from file '%s'!", argv[argi]);
  eprintf("done\n");

  eprintf("Recognizing: ");
  clock_t now = clock();
  if (use_vertical) recognize_vertical(*recognizer);
  else recognize_untokenized(*recognizer);
  eprintf("done, in %.3f seconds.\n", (clock() - now) / double(CLOCKS_PER_SEC));

  return 0;
}

void recognize_vertical(const ner& recognizer) {
  string line;
  unsigned total_lines = 0;

  vector<string> words;
  vector<string_piece> forms;
  vector<named_entity> entities;
  string entity_ids, entity_text;

  for (bool not_eof = true; not_eof; ) {
    // Read sentence
    words.clear();
    forms.clear();
    while ((not_eof = getline(stdin, line)) && !line.empty()) {
      auto tab = line.find('\t');
      words.emplace_back(tab == string::npos ? line : line.substr(0, tab));
      forms.emplace_back(words.back());
    }

    // Find named entities in the sentence
    if (!forms.empty()) {
      recognizer.recognize(forms, entities);

      for (auto& entity : entities) {
        entity_ids.clear();
        entity_text.clear();
        for (auto i = entity.start; i < entity.start + entity.length; i++) {
          if (i > entity.start) {
            entity_ids += ',';
            entity_text += ' ';
          }
          entity_ids += to_string(total_lines + i + 1);
          entity_text += words[i];
        }
        printf("%s\t%s\t%s\n", entity_ids.c_str(), entity.type.c_str(), entity_text.c_str());
      }
    }

    total_lines += forms.size() + 1;
  }
}

static void encode_entities_and_print(const char* text, size_t length);

void recognize_untokenized(const ner& recognizer) {
  string line, text;
  vector<named_entity> entities;
  vector<size_t> entity_ends;

  for (bool not_eof = true; not_eof; ) {
    // Read block of text
    text.clear();
    while ((not_eof = getline(stdin, line)) && !line.empty()) {
      text += line;
      text += '\n';
    }
    if (not_eof) text += '\n';

    // Tokenize the text and find named entities
    size_t unprinted = 0;
    recognizer.tokenize_and_recognize(text.c_str(), entities);
    for (auto& entity : entities) {
      // Close entities that end sooned than current entity
      while (!entity_ends.empty() && entity_ends.back() < entity.start) {
        if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);
        unprinted = entity_ends.back();
        entity_ends.pop_back();
        fputs("</ne>", stdout);
      }

      // Print text just before the entity, open it and add end to the stack
      if (unprinted < entity.start) encode_entities_and_print(text.c_str() + unprinted, entity.start - unprinted);
      unprinted = entity.start;
      printf("<ne type=\"%s\">", entity.type.c_str());
      entity_ends.push_back(entity.start + entity.length);
    }

    // Close unclosed entities
    while (!entity_ends.empty()) {
      if (unprinted < entity_ends.back()) encode_entities_and_print(text.c_str() + unprinted, entity_ends.back() - unprinted);
      unprinted = entity_ends.back();
      entity_ends.pop_back();
      fputs("</ne>", stdout);
    }
    // Write rest of the text (should be just spaces)
    if (unprinted < text.size()) encode_entities_and_print(text.c_str() + unprinted, text.size() - unprinted);
  }
}

void encode_entities_and_print(const char* text, size_t length) {
  const char* to_print = text;
  while (length) {
    while (length && *text != '<' && *text != '>' && *text != '&' && *text != '"')
      text++, length--;

    if (length) {
      if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
      fputs(*text == '<' ? "<" : *text == '>' ? ">" : *text == '&' ? "&" : """, stdout);
      text++, length--;
      to_print = text;
    }
  }
  if (to_print < text) fwrite(to_print, 1, text - to_print, stdout);
}
<|endoftext|>


<commit_before>#ifndef SILICIUM_ERROR_OR_HPP
#define SILICIUM_ERROR_OR_HPP

#include <silicium/optional.hpp>
#include <boost/system/system_error.hpp>
#include <boost/throw_exception.hpp>
#include <system_error>

namespace Si
{
	namespace detail
	{
		inline SILICIUM_NORETURN void throw_system_error(boost::system::error_code error)
		{
			boost::throw_exception(boost::system::system_error(error));
		}

		inline SILICIUM_NORETURN void throw_system_error(std::error_code error)
		{
			boost::throw_exception(std::system_error(error));
		}
	}

	template <class Value, class Error = boost::system::error_code>
	struct error_or
	{
		error_or() BOOST_NOEXCEPT
		{
		}

		error_or(Value value) BOOST_NOEXCEPT
			: storage(std::move(value))
		{
		}

		error_or(Error error) BOOST_NOEXCEPT
			: storage(std::move(error))
		{
		}

#ifdef _MSC_VER
		error_or(error_or &&other) BOOST_NOEXCEPT
			: storage(std::move(other.storage))
		{
		}

		error_or(error_or const &other)
			: storage(other.storage)
		{
		}

		error_or &operator = (error_or &&other) BOOST_NOEXCEPT
		{
			storage = std::move(other.storage);
			return *this;
		}

		error_or &operator = (error_or const &other)
		{
			storage = other.storage;
			return *this;
		}
#endif

		bool is_error() const BOOST_NOEXCEPT
		{
			return Si::visit<bool>(
						storage,
						[](Value const &) { return false; },
						[](Error const &) { return true; });
		}

		Si::optional<Error> error() const BOOST_NOEXCEPT
		{
			return Si::visit<Si::optional<Error>>(
						storage,
						[](Value const &) { return Si::optional<Error>(); },
						[](Error const &e) { return e; });
		}

#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
		Value &get() &
		{
			return Si::visit<Value &>(
						storage,
						[](Value &value) -> Value & { return value; },
						[](Error const &e) -> Value & { detail::throw_system_error(e); });
		}
#endif

		Value &&get()
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&&
#endif
		{
			return Si::visit<Value &&>(
						storage,
						[](Value &value) -> Value && { return std::move(value); },
						[](Error const &e) -> Value && { detail::throw_system_error(e); });
		}

		Value const &get() const
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&
#endif
		{
			return Si::visit<Value const &>(
						storage,
						[](Value const &value) -> Value const & { return value; },
						[](Error const &e) -> Value const & { detail::throw_system_error(e); });
		}

		Value *get_ptr() BOOST_NOEXCEPT
		{
			return Si::visit<Value *>(
						storage,
						[](Value &value) -> Value * { return &value; },
						[](Error const &) -> Value * { return nullptr; });
		}

		Value const *get_ptr() const BOOST_NOEXCEPT
		{
			return Si::visit<Value const *>(
						storage,
						[](Value const &value) -> Value const * { return &value; },
						[](Error const &) -> Value const * { return nullptr; });
		}

	private:

		fast_variant<Value, Error> storage;
	};
}

#endif
<commit_msg>add operator -> and get_optional to error_or<commit_after>#ifndef SILICIUM_ERROR_OR_HPP
#define SILICIUM_ERROR_OR_HPP

#include <silicium/optional.hpp>
#include <boost/system/system_error.hpp>
#include <boost/throw_exception.hpp>
#include <system_error>

namespace Si
{
	namespace detail
	{
		inline SILICIUM_NORETURN void throw_system_error(boost::system::error_code error)
		{
			boost::throw_exception(boost::system::system_error(error));
		}

		inline SILICIUM_NORETURN void throw_system_error(std::error_code error)
		{
			boost::throw_exception(std::system_error(error));
		}
	}

	template <class Value, class Error = boost::system::error_code>
	struct error_or
	{
		error_or() BOOST_NOEXCEPT
		{
		}

		error_or(Value value) BOOST_NOEXCEPT
			: storage(std::move(value))
		{
		}

		error_or(Error error) BOOST_NOEXCEPT
			: storage(std::move(error))
		{
		}

#ifdef _MSC_VER
		error_or(error_or &&other) BOOST_NOEXCEPT
			: storage(std::move(other.storage))
		{
		}

		error_or(error_or const &other)
			: storage(other.storage)
		{
		}

		error_or &operator = (error_or &&other) BOOST_NOEXCEPT
		{
			storage = std::move(other.storage);
			return *this;
		}

		error_or &operator = (error_or const &other)
		{
			storage = other.storage;
			return *this;
		}
#endif

		bool is_error() const BOOST_NOEXCEPT
		{
			return Si::visit<bool>(
						storage,
						[](Value const &) { return false; },
						[](Error const &) { return true; });
		}

		Si::optional<Error> error() const BOOST_NOEXCEPT
		{
			return Si::visit<Si::optional<Error>>(
						storage,
						[](Value const &) { return Si::optional<Error>(); },
						[](Error const &e) { return e; });
		}

#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
		Value &get() &
		{
			return Si::visit<Value &>(
						storage,
						[](Value &value) -> Value & { return value; },
						[](Error const &e) -> Value & { detail::throw_system_error(e); });
		}
#endif

		Value &&get()
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&&
#endif
		{
			return Si::visit<Value &&>(
						storage,
						[](Value &value) -> Value && { return std::move(value); },
						[](Error const &e) -> Value && { detail::throw_system_error(e); });
		}

		Value const &get() const
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&
#endif
		{
			return Si::visit<Value const &>(
						storage,
						[](Value const &value) -> Value const & { return value; },
						[](Error const &e) -> Value const & { detail::throw_system_error(e); });
		}

		Value *get_ptr() BOOST_NOEXCEPT
		{
			return Si::visit<Value *>(
						storage,
						[](Value &value) -> Value * { return &value; },
						[](Error const &) -> Value * { return nullptr; });
		}

		Value const *get_ptr() const BOOST_NOEXCEPT
		{
			return Si::visit<Value const *>(
						storage,
						[](Value const &value) -> Value const * { return &value; },
						[](Error const &) -> Value const * { return nullptr; });
		}

		Value *operator -> ()
		{
			return &get();
		}

		Value const *operator -> () const
		{
			return &get();
		}

		boost::optional<Value> get_optional() &&
		{
			auto *value = get_ptr();
			if (!value)
			{
				return boost::none;
			}
			return std::move(*value);
		}

	private:

		fast_variant<Value, Error> storage;
	};
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2010 2011 2012 Helge Bahmann <hcb@chaoticmind.net>
 * Copyright 2011 2012 2013 2014 2015 Nico Reißmann <nico.reissmann@gmail.com>
 * See COPYING for terms of redistribution.
 */

#ifndef JIVE_RVSDG_TYPE_HPP
#define JIVE_RVSDG_TYPE_HPP

#include <memory>
#include <string>

namespace jive {

class type {
public:
	virtual
	~type() noexcept;

protected:
	inline constexpr
	type() noexcept
	{}

public:
	virtual bool
	operator==(const jive::type & other) const noexcept = 0;

	inline bool
	operator!=(const jive::type & other) const noexcept
	{
		return !(*this == other);
	}

	virtual std::unique_ptr<type>
	copy() const = 0;

	virtual std::string
	debug_string() const = 0;
};

class valuetype : public jive::type {
public:
	virtual
	~valuetype() noexcept;

protected:
	inline constexpr
	valuetype() noexcept
	: jive::type()
	{}
};

class statetype : public jive::type {
public:
	virtual
	~statetype() noexcept;

protected:
	inline constexpr
	statetype() noexcept
	: jive::type()
	{}
};

}

#endif
<commit_msg>rvsdg: add is function for types<commit_after>/*
 * Copyright 2010 2011 2012 Helge Bahmann <hcb@chaoticmind.net>
 * Copyright 2011 2012 2013 2014 2015 Nico Reißmann <nico.reissmann@gmail.com>
 * See COPYING for terms of redistribution.
 */

#ifndef JIVE_RVSDG_TYPE_HPP
#define JIVE_RVSDG_TYPE_HPP

#include <memory>
#include <string>

namespace jive {

class type {
public:
	virtual
	~type() noexcept;

protected:
	inline constexpr
	type() noexcept
	{}

public:
	virtual bool
	operator==(const jive::type & other) const noexcept = 0;

	inline bool
	operator!=(const jive::type & other) const noexcept
	{
		return !(*this == other);
	}

	virtual std::unique_ptr<type>
	copy() const = 0;

	virtual std::string
	debug_string() const = 0;
};

class valuetype : public jive::type {
public:
	virtual
	~valuetype() noexcept;

protected:
	inline constexpr
	valuetype() noexcept
	: jive::type()
	{}
};

class statetype : public jive::type {
public:
	virtual
	~statetype() noexcept;

protected:
	inline constexpr
	statetype() noexcept
	: jive::type()
	{}
};

template <class T> static inline bool
is(const jive::type & type) noexcept
{
	static_assert(std::is_base_of<jive::type, T>::value,
		"Template parameter T must be derived from jive::type.");

	return dynamic_cast<const T*>(&type) != nullptr;
}

}

#endif
<|endoftext|>


<commit_before>// File: btBoostDynamicsCollisionDispatcher.hpp
#ifndef _btBoostDynamicsCollisionDispatcher_hpp
#define _btBoostDynamicsCollisionDispatcher_hpp

#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
#include <btBulletDynamicsCommon.h>

using namespace boost::python;

btCollisionDispatcher*
make_CollisionDispatcher(btCollisionConfiguration& config)
{
	return new btCollisionDispatcher(&config);
}

void defineCollisionDispatcher()
{
    enum_<btCollisionDispatcher::DispatcherFlags>("DispatcherFlags")
        .value("CD_STATIC_STATIC_REPORTED",
        	btCollisionDispatcher::CD_STATIC_STATIC_REPORTED)
        .value("CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD",
        	btCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD)
        .value("CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION",
        	btCollisionDispatcher::CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION)
        .export_values()
    ;

    class_<btCollisionDispatcher, bases<btDispatcher> >
        ("btCollisionDispatcher", no_init)
    	.def("__init__", make_constructor(&make_CollisionDispatcher))
    	.add_property("flags",
    		&btCollisionDispatcher::getDispatcherFlags,
    		&btCollisionDispatcher::setDispatcherFlags)
    ;
}

#endif // _btBoostDynamicsCollisionDispatcher_hpp
<commit_msg>Add pure abstract base class and mark noncopyable<commit_after>// File: btBoostDynamicsCollisionDispatcher.hpp
#ifndef _btBoostDynamicsCollisionDispatcher_hpp
#define _btBoostDynamicsCollisionDispatcher_hpp

#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
#include <btBulletDynamicsCommon.h>

using namespace boost::python;

btCollisionDispatcher*
make_CollisionDispatcher(btCollisionConfiguration& config)
{
	return new btCollisionDispatcher(&config);
}

void defineCollisionDispatcher()
{
    enum_<btCollisionDispatcher::DispatcherFlags>("DispatcherFlags")
        .value("CD_STATIC_STATIC_REPORTED",
        	btCollisionDispatcher::CD_STATIC_STATIC_REPORTED)
        .value("CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD",
        	btCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD)
        .value("CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION",
        	btCollisionDispatcher::CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION)
        .export_values()
    ;

    class_<btDispatcher, boost::noncopyable>("btDispatcher", no_init);

    class_<btCollisionDispatcher, bases<btDispatcher>, boost::noncopyable>
        ("btCollisionDispatcher", no_init)
    	.def("__init__", make_constructor(&make_CollisionDispatcher))
    	.add_property("flags",
    		&btCollisionDispatcher::getDispatcherFlags,
    		&btCollisionDispatcher::setDispatcherFlags)
    ;
}

#endif // _btBoostDynamicsCollisionDispatcher_hpp
<|endoftext|>