<commit_before>void build(Solution &s)
{
    auto &tess = s.addProject("google.tesseract", "master");
    tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");

    auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
    {
        libtesseract.setChecks("libtesseract");

        libtesseract.ExportAllSymbols = true;
        libtesseract.PackageDefinitions = true;
        libtesseract +=
            "src/api/.*\\.cpp"_rr,
            "src/api/.*\\.h"_rr,
            "src/api/tess_version.h.in",
            "src/arch/.*\\.cpp"_rr,
            "src/arch/.*\\.h"_rr,
            "src/ccmain/.*\\.cpp"_rr,
            "src/ccmain/.*\\.h"_rr,
            "src/ccstruct/.*\\.cpp"_rr,
            "src/ccstruct/.*\\.h"_rr,
            "src/ccutil/.*\\.cpp"_rr,
            "src/ccutil/.*\\.h"_rr,
            "src/classify/.*\\.cpp"_rr,
            "src/classify/.*\\.h"_rr,
            "src/cutil/.*\\.cpp"_rr,
            "src/cutil/.*\\.h"_rr,
            "src/dict/.*\\.cpp"_rr,
            "src/dict/.*\\.h"_rr,
            "src/lstm/.*\\.cpp"_rr,
            "src/lstm/.*\\.h"_rr,
            "src/opencl/.*\\.cpp"_rr,
            "src/opencl/.*\\.h"_rr,
            "src/textord/.*\\.cpp"_rr,
            "src/textord/.*\\.h"_rr,
            "src/viewer/.*\\.cpp"_rr,
            "src/viewer/.*\\.h"_rr,
            "src/vs2010/port/.*"_rr,
            "src/wordrec/.*\\.cpp"_rr,
            "src/wordrec/.*\\.h"_rr;

        libtesseract -=
            "src/api/tesseractmain.cpp",
            "src/viewer/svpaint.cpp";

        libtesseract.Public +=
            "src/vs2010/port"_id,
            "src/opencl"_id,
            "src/ccmain"_id,
            "src/api"_id,
            "src/dict"_id,
            "src/viewer"_id,
            "src/wordrec"_id,
            "src/ccstruct"_id,
            "src/cutil"_id,
            "src/textord"_id,
            "src/ccutil"_id,
            "src/lstm"_id,
            "src/classify"_id,
            "src/arch"_id;

        if (libtesseract.getCompilerType() == CompilerType::MSVC ||
            libtesseract.getCompilerType() == CompilerType::ClangCl)
        {
            libtesseract += "__SSE4_1__"_def;
            libtesseract.CompileOptions.push_back("-arch:AVX2");
        }

        libtesseract.Public += "HAVE_CONFIG_H"_d;
        libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
        libtesseract.Public += "HAVE_LIBARCHIVE"_d;
        libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
        libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;

        libtesseract.Public += "org.sw.demo.danbloomberg.leptonica-master"_dep;
        libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;

        if (libtesseract.getSettings().TargetOS.Type == OSType::Windows)
        {
            libtesseract.Public += "ws2_32.lib"_l;
            libtesseract.Protected += "NOMINMAX"_def;
        }

        libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
        libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
        libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
        libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
        libtesseract.configureFile("src/api/tess_version.h.in", "tess_version.h");
    }

    //
    auto &tesseract = tess.addExecutable("tesseract");
    tesseract += "src/api/tesseractmain.cpp";
    tesseract += libtesseract;

    //
    auto &tessopt = tess.addStaticLibrary("tessopt");
    tessopt += "src/training/tessopt.*"_rr;
    tessopt.Public += "training"_id;
    tessopt.Public += libtesseract;

    //
    auto &common_training = tess.addStaticLibrary("common_training");
    common_training +=
        "src/training/commandlineflags.cpp",
        "src/training/commandlineflags.h",
        "src/training/commontraining.cpp",
        "src/training/commontraining.h";
    common_training.Public += "training"_id;
    common_training.Public += tessopt;

    //
    auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
    unicharset_training +=
        "src/training/fileio.*"_rr,
        "src/training/icuerrorcode.*"_rr,
        "src/training/icuerrorcode.h",
        "src/training/lang_model_helpers.*"_rr,
        "src/training/lstmtester.*"_rr,
        "src/training/normstrngs.*"_rr,
        "src/training/unicharset_training_utils.*"_rr,
        "src/training/validat.*"_rr;
    unicharset_training.Public += "training"_id;
    unicharset_training.Public += common_training;
    unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;

    //
#define ADD_EXE(n, ...)               \
    auto &n = tess.addExecutable(#n); \
    n += "src/training/" #n ".*"_rr;  \
    n.Public += __VA_ARGS__;          \
    n

    ADD_EXE(ambiguous_words, libtesseract);
    ADD_EXE(classifier_tester, common_training);
    ADD_EXE(combine_lang_model, unicharset_training);
    ADD_EXE(combine_tessdata, libtesseract);
    ADD_EXE(cntraining, common_training);
    ADD_EXE(dawg2wordlist, libtesseract);
    ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
    ADD_EXE(shapeclustering, common_training);
    ADD_EXE(unicharset_extractor, unicharset_training);
    ADD_EXE(wordlist2dawg, libtesseract);
    ADD_EXE(lstmeval, unicharset_training);
    ADD_EXE(lstmtraining, unicharset_training);
    ADD_EXE(set_unicharset_properties, unicharset_training);

    ADD_EXE(text2image, unicharset_training);
    text2image +=
        "src/training/boxchar.cpp",
        "src/training/boxchar.h",
        "src/training/degradeimage.cpp",
        "src/training/degradeimage.h",
        "src/training/icuerrorcode.h",
        "src/training/ligature_table.cpp",
        "src/training/ligature_table.h",
        "src/training/normstrngs.cpp",
        "src/training/normstrngs.h",
        "src/training/pango_font_info.cpp",
        "src/training/pango_font_info.h",
        "src/training/stringrenderer.cpp",
        "src/training/stringrenderer.h",
        "src/training/text2image.cpp",
        "src/training/tlog.cpp",
        "src/training/tlog.h",
        "src/training/util.h";
    text2image.Public += "org.sw.demo.gnome.pango.pangocairo-1"_dep;
}

void check(Checker &c)
{
    auto &s = c.addSet("libtesseract");
    s.checkFunctionExists("getline");
    s.checkIncludeExists("dlfcn.h");
    s.checkIncludeExists("inttypes.h");
    s.checkIncludeExists("limits.h");
    s.checkIncludeExists("malloc.h");
    s.checkIncludeExists("memory.h");
    s.checkIncludeExists("stdbool.h");
    s.checkIncludeExists("stdint.h");
    s.checkIncludeExists("stdlib.h");
    s.checkIncludeExists("string.h");
    s.checkIncludeExists("sys/ipc.h");
    s.checkIncludeExists("sys/shm.h");
    s.checkIncludeExists("sys/stat.h");
    s.checkIncludeExists("sys/types.h");
    s.checkIncludeExists("sys/wait.h");
    s.checkIncludeExists("tiffio.h");
    s.checkIncludeExists("unistd.h");
    s.checkTypeSize("long long int");
    s.checkTypeSize("mbstate_t");
    s.checkTypeSize("off_t");
    s.checkTypeSize("size_t");
    s.checkTypeSize("void *");
    s.checkTypeSize("wchar_t");
    s.checkTypeSize("_Bool");
    {
        auto &c = s.checkSymbolExists("snprintf");
        c.Parameters.Includes.push_back("stdio.h");
    }
}
<commit_msg>Replace CR-LF line endings by LF<commit_after>void build(Solution &s)
{
    auto &tess = s.addProject("google.tesseract", "master");
    tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");

    auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
    {
        libtesseract.setChecks("libtesseract");

        libtesseract.ExportAllSymbols = true;
        libtesseract.PackageDefinitions = true;
        libtesseract +=
            "src/api/.*\\.cpp"_rr,
            "src/api/.*\\.h"_rr,
            "src/api/tess_version.h.in",
            "src/arch/.*\\.cpp"_rr,
            "src/arch/.*\\.h"_rr,
            "src/ccmain/.*\\.cpp"_rr,
            "src/ccmain/.*\\.h"_rr,
            "src/ccstruct/.*\\.cpp"_rr,
            "src/ccstruct/.*\\.h"_rr,
            "src/ccutil/.*\\.cpp"_rr,
            "src/ccutil/.*\\.h"_rr,
            "src/classify/.*\\.cpp"_rr,
            "src/classify/.*\\.h"_rr,
            "src/cutil/.*\\.cpp"_rr,
            "src/cutil/.*\\.h"_rr,
            "src/dict/.*\\.cpp"_rr,
            "src/dict/.*\\.h"_rr,
            "src/lstm/.*\\.cpp"_rr,
            "src/lstm/.*\\.h"_rr,
            "src/opencl/.*\\.cpp"_rr,
            "src/opencl/.*\\.h"_rr,
            "src/textord/.*\\.cpp"_rr,
            "src/textord/.*\\.h"_rr,
            "src/viewer/.*\\.cpp"_rr,
            "src/viewer/.*\\.h"_rr,
            "src/vs2010/port/.*"_rr,
            "src/wordrec/.*\\.cpp"_rr,
            "src/wordrec/.*\\.h"_rr;

        libtesseract -=
            "src/api/tesseractmain.cpp",
            "src/viewer/svpaint.cpp";

        libtesseract.Public +=
            "src/vs2010/port"_id,
            "src/opencl"_id,
            "src/ccmain"_id,
            "src/api"_id,
            "src/dict"_id,
            "src/viewer"_id,
            "src/wordrec"_id,
            "src/ccstruct"_id,
            "src/cutil"_id,
            "src/textord"_id,
            "src/ccutil"_id,
            "src/lstm"_id,
            "src/classify"_id,
            "src/arch"_id;

        if (libtesseract.getCompilerType() == CompilerType::MSVC ||
            libtesseract.getCompilerType() == CompilerType::ClangCl)
        {
            libtesseract += "__SSE4_1__"_def;
            libtesseract.CompileOptions.push_back("-arch:AVX2");
        }

        libtesseract.Public += "HAVE_CONFIG_H"_d;
        libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
        libtesseract.Public += "HAVE_LIBARCHIVE"_d;
        libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
        libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;

        libtesseract.Public += "org.sw.demo.danbloomberg.leptonica-master"_dep;
        libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;

        if (libtesseract.getSettings().TargetOS.Type == OSType::Windows)
        {
            libtesseract.Public += "ws2_32.lib"_l;
            libtesseract.Protected += "NOMINMAX"_def;
        }

        libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
        libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
        libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
        libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
        libtesseract.configureFile("src/api/tess_version.h.in", "tess_version.h");
    }

    //
    auto &tesseract = tess.addExecutable("tesseract");
    tesseract += "src/api/tesseractmain.cpp";
    tesseract += libtesseract;

    //
    auto &tessopt = tess.addStaticLibrary("tessopt");
    tessopt += "src/training/tessopt.*"_rr;
    tessopt.Public += "training"_id;
    tessopt.Public += libtesseract;

    //
    auto &common_training = tess.addStaticLibrary("common_training");
    common_training +=
        "src/training/commandlineflags.cpp",
        "src/training/commandlineflags.h",
        "src/training/commontraining.cpp",
        "src/training/commontraining.h";
    common_training.Public += "training"_id;
    common_training.Public += tessopt;

    //
    auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
    unicharset_training +=
        "src/training/fileio.*"_rr,
        "src/training/icuerrorcode.*"_rr,
        "src/training/icuerrorcode.h",
        "src/training/lang_model_helpers.*"_rr,
        "src/training/lstmtester.*"_rr,
        "src/training/normstrngs.*"_rr,
        "src/training/unicharset_training_utils.*"_rr,
        "src/training/validat.*"_rr;
    unicharset_training.Public += "training"_id;
    unicharset_training.Public += common_training;
    unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;

    //
#define ADD_EXE(n, ...)               \
    auto &n = tess.addExecutable(#n); \
    n += "src/training/" #n ".*"_rr;  \
    n.Public += __VA_ARGS__;          \
    n

    ADD_EXE(ambiguous_words, libtesseract);
    ADD_EXE(classifier_tester, common_training);
    ADD_EXE(combine_lang_model, unicharset_training);
    ADD_EXE(combine_tessdata, libtesseract);
    ADD_EXE(cntraining, common_training);
    ADD_EXE(dawg2wordlist, libtesseract);
    ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
    ADD_EXE(shapeclustering, common_training);
    ADD_EXE(unicharset_extractor, unicharset_training);
    ADD_EXE(wordlist2dawg, libtesseract);
    ADD_EXE(lstmeval, unicharset_training);
    ADD_EXE(lstmtraining, unicharset_training);
    ADD_EXE(set_unicharset_properties, unicharset_training);

    ADD_EXE(text2image, unicharset_training);
    text2image +=
        "src/training/boxchar.cpp",
        "src/training/boxchar.h",
        "src/training/degradeimage.cpp",
        "src/training/degradeimage.h",
        "src/training/icuerrorcode.h",
        "src/training/ligature_table.cpp",
        "src/training/ligature_table.h",
        "src/training/normstrngs.cpp",
        "src/training/normstrngs.h",
        "src/training/pango_font_info.cpp",
        "src/training/pango_font_info.h",
        "src/training/stringrenderer.cpp",
        "src/training/stringrenderer.h",
        "src/training/text2image.cpp",
        "src/training/tlog.cpp",
        "src/training/tlog.h",
        "src/training/util.h";
    text2image.Public += "org.sw.demo.gnome.pango.pangocairo-1"_dep;
}

void check(Checker &c)
{
    auto &s = c.addSet("libtesseract");
    s.checkFunctionExists("getline");
    s.checkIncludeExists("dlfcn.h");
    s.checkIncludeExists("inttypes.h");
    s.checkIncludeExists("limits.h");
    s.checkIncludeExists("malloc.h");
    s.checkIncludeExists("memory.h");
    s.checkIncludeExists("stdbool.h");
    s.checkIncludeExists("stdint.h");
    s.checkIncludeExists("stdlib.h");
    s.checkIncludeExists("string.h");
    s.checkIncludeExists("sys/ipc.h");
    s.checkIncludeExists("sys/shm.h");
    s.checkIncludeExists("sys/stat.h");
    s.checkIncludeExists("sys/types.h");
    s.checkIncludeExists("sys/wait.h");
    s.checkIncludeExists("tiffio.h");
    s.checkIncludeExists("unistd.h");
    s.checkTypeSize("long long int");
    s.checkTypeSize("mbstate_t");
    s.checkTypeSize("off_t");
    s.checkTypeSize("size_t");
    s.checkTypeSize("void *");
    s.checkTypeSize("wchar_t");
    s.checkTypeSize("_Bool");
    {
        auto &c = s.checkSymbolExists("snprintf");
        c.Parameters.Includes.push_back("stdio.h");
    }
}
<|endoftext|>


<commit_before>void build(Solution &s)
{
    auto &tess = s.addProject("google.tesseract", "master");
    tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");

    auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
    {
        libtesseract.setChecks("libtesseract");

        libtesseract.ExportAllSymbols = true;
        libtesseract.PackageDefinitions = true;
        libtesseract +=
            "src/api/.*\\.cpp"_rr,
            "src/api/.*\\.h"_rr,
            "src/api/tess_version.h.in",
            "src/arch/.*\\.cpp"_rr,
            "src/arch/.*\\.h"_rr,
            "src/ccmain/.*\\.cpp"_rr,
            "src/ccmain/.*\\.h"_rr,
            "src/ccstruct/.*\\.cpp"_rr,
            "src/ccstruct/.*\\.h"_rr,
            "src/ccutil/.*\\.cpp"_rr,
            "src/ccutil/.*\\.h"_rr,
            "src/classify/.*\\.cpp"_rr,
            "src/classify/.*\\.h"_rr,
            "src/cutil/.*\\.cpp"_rr,
            "src/cutil/.*\\.h"_rr,
            "src/dict/.*\\.cpp"_rr,
            "src/dict/.*\\.h"_rr,
            "src/lstm/.*\\.cpp"_rr,
            "src/lstm/.*\\.h"_rr,
            "src/opencl/.*\\.cpp"_rr,
            "src/opencl/.*\\.h"_rr,
            "src/textord/.*\\.cpp"_rr,
            "src/textord/.*\\.h"_rr,
            "src/viewer/.*\\.cpp"_rr,
            "src/viewer/.*\\.h"_rr,
            "src/wordrec/.*\\.cpp"_rr,
            "src/wordrec/.*\\.h"_rr;

        libtesseract -=
            "src/api/tesseractmain.cpp",
            "src/viewer/svpaint.cpp";

        libtesseract.Public +=
            "src/opencl"_id,
            "src/ccmain"_id,
            "src/api"_id,
            "src/dict"_id,
            "src/viewer"_id,
            "src/wordrec"_id,
            "src/ccstruct"_id,
            "src/cutil"_id,
            "src/textord"_id,
            "src/ccutil"_id,
            "src/lstm"_id,
            "src/classify"_id,
            "src/arch"_id;

        if (libtesseract.getCompilerType() == CompilerType::MSVC ||
            libtesseract.getCompilerType() == CompilerType::ClangCl)
        {
            libtesseract += "__SSE4_1__"_def;
            libtesseract.CompileOptions.push_back("-arch:AVX2");

            libtesseract -=
                "src/arch/dotproductfma.cpp";
        }

        libtesseract.Public += "HAVE_CONFIG_H"_d;
        libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
        libtesseract.Public += "HAVE_LIBARCHIVE"_d;
        libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
        libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;

        libtesseract.Public += "org.sw.demo.danbloomberg.leptonica-master"_dep;
        libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;

        if (libtesseract.getSettings().TargetOS.Type == OSType::Windows)
        {
            libtesseract.Public += "ws2_32.lib"_l;
            libtesseract.Protected += "NOMINMAX"_def;
        }

        libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
        libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
        libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
        libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
        libtesseract.configureFile("src/api/tess_version.h.in", "tess_version.h");
    }

    //
    auto &tesseract = tess.addExecutable("tesseract");
    tesseract += "src/api/tesseractmain.cpp";
    tesseract += libtesseract;

    //
    auto &tessopt = tess.addStaticLibrary("tessopt");
    tessopt += "src/training/tessopt.*"_rr;
    tessopt.Public += libtesseract;

    //
    auto &common_training = tess.addStaticLibrary("common_training");
    common_training +=
        "src/training/commandlineflags.cpp",
        "src/training/commandlineflags.h",
        "src/training/commontraining.cpp",
        "src/training/commontraining.h";
    common_training.Public += tessopt;

    //
    auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
    unicharset_training +=
        "src/training/icuerrorcode.*"_rr,
        "src/training/icuerrorcode.h",
        "src/training/lang_model_helpers.*"_rr,
        "src/training/lstmtester.*"_rr,
        "src/training/lstmtrainer.*"_rr,
        "src/training/normstrngs.*"_rr,
        "src/training/unicharset_training_utils.*"_rr,
        "src/training/validat.*"_rr;
    unicharset_training.Public += common_training;
    unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;

    //
#define ADD_EXE(n, ...)               \
    auto &n = tess.addExecutable(#n); \
    n += "src/training/" #n ".*"_rr;  \
    n.Public += __VA_ARGS__;          \
    n

    ADD_EXE(ambiguous_words, libtesseract);
    ADD_EXE(classifier_tester, common_training);
    ADD_EXE(combine_lang_model, unicharset_training);
    ADD_EXE(combine_tessdata, libtesseract);
    ADD_EXE(cntraining, common_training);
    ADD_EXE(dawg2wordlist, libtesseract);
    ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
    ADD_EXE(shapeclustering, common_training);
    ADD_EXE(unicharset_extractor, unicharset_training);
    ADD_EXE(wordlist2dawg, libtesseract);
    ADD_EXE(lstmeval, unicharset_training);
    ADD_EXE(lstmtraining, unicharset_training);
    ADD_EXE(set_unicharset_properties, unicharset_training);

    ADD_EXE(text2image, unicharset_training);
    text2image +=
        "src/training/boxchar.cpp",
        "src/training/boxchar.h",
        "src/training/degradeimage.cpp",
        "src/training/degradeimage.h",
        "src/training/icuerrorcode.h",
        "src/training/ligature_table.cpp",
        "src/training/ligature_table.h",
        "src/training/normstrngs.cpp",
        "src/training/normstrngs.h",
        "src/training/pango_font_info.cpp",
        "src/training/pango_font_info.h",
        "src/training/stringrenderer.cpp",
        "src/training/stringrenderer.h",
        "src/training/text2image.cpp",
        "src/training/tlog.cpp",
        "src/training/tlog.h",
        "src/training/util.h";
    text2image.Public += "org.sw.demo.gnome.pango.pangocairo-1"_dep;
}

void check(Checker &c)
{
    auto &s = c.addSet("libtesseract");
    s.checkFunctionExists("getline");
    s.checkIncludeExists("dlfcn.h");
    s.checkIncludeExists("inttypes.h");
    s.checkIncludeExists("limits.h");
    s.checkIncludeExists("malloc.h");
    s.checkIncludeExists("memory.h");
    s.checkIncludeExists("stdbool.h");
    s.checkIncludeExists("stdint.h");
    s.checkIncludeExists("stdlib.h");
    s.checkIncludeExists("string.h");
    s.checkIncludeExists("sys/ipc.h");
    s.checkIncludeExists("sys/shm.h");
    s.checkIncludeExists("sys/stat.h");
    s.checkIncludeExists("sys/types.h");
    s.checkIncludeExists("sys/wait.h");
    s.checkIncludeExists("tiffio.h");
    s.checkIncludeExists("unistd.h");
    s.checkTypeSize("long long int");
    s.checkTypeSize("mbstate_t");
    s.checkTypeSize("off_t");
    s.checkTypeSize("size_t");
    s.checkTypeSize("void *");
    s.checkTypeSize("wchar_t");
    s.checkTypeSize("_Bool");
    {
        auto &c = s.checkSymbolExists("snprintf");
        c.Parameters.Includes.push_back("stdio.h");
    }
}
<commit_msg>[sw] Install tess headers.<commit_after>void build(Solution &s)
{
    auto &tess = s.addProject("google.tesseract", "master");
    tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");

    auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
    {
        libtesseract.setChecks("libtesseract");

        libtesseract.ExportAllSymbols = true;
        libtesseract.PackageDefinitions = true;
        libtesseract +=
            "src/api/.*\\.cpp"_rr,
            "src/api/.*\\.h"_rr,
            "src/api/tess_version.h.in",
            "src/arch/.*\\.cpp"_rr,
            "src/arch/.*\\.h"_rr,
            "src/ccmain/.*\\.cpp"_rr,
            "src/ccmain/.*\\.h"_rr,
            "src/ccstruct/.*\\.cpp"_rr,
            "src/ccstruct/.*\\.h"_rr,
            "src/ccutil/.*\\.cpp"_rr,
            "src/ccutil/.*\\.h"_rr,
            "src/classify/.*\\.cpp"_rr,
            "src/classify/.*\\.h"_rr,
            "src/cutil/.*\\.cpp"_rr,
            "src/cutil/.*\\.h"_rr,
            "src/dict/.*\\.cpp"_rr,
            "src/dict/.*\\.h"_rr,
            "src/lstm/.*\\.cpp"_rr,
            "src/lstm/.*\\.h"_rr,
            "src/opencl/.*\\.cpp"_rr,
            "src/opencl/.*\\.h"_rr,
            "src/textord/.*\\.cpp"_rr,
            "src/textord/.*\\.h"_rr,
            "src/viewer/.*\\.cpp"_rr,
            "src/viewer/.*\\.h"_rr,
            "src/wordrec/.*\\.cpp"_rr,
            "src/wordrec/.*\\.h"_rr;

        libtesseract -=
            "src/api/tesseractmain.cpp",
            "src/viewer/svpaint.cpp";

        libtesseract.Public +=
            "src/opencl"_id,
            "src/ccmain"_id,
            "src/api"_id,
            "src/dict"_id,
            "src/viewer"_id,
            "src/wordrec"_id,
            "src/ccstruct"_id,
            "src/cutil"_id,
            "src/textord"_id,
            "src/ccutil"_id,
            "src/lstm"_id,
            "src/classify"_id,
            "src/arch"_id;

        if (libtesseract.getCompilerType() == CompilerType::MSVC ||
            libtesseract.getCompilerType() == CompilerType::ClangCl)
        {
            libtesseract += "__SSE4_1__"_def;
            libtesseract.CompileOptions.push_back("-arch:AVX2");

            libtesseract -=
                "src/arch/dotproductfma.cpp";
        }

        libtesseract.Public += "HAVE_CONFIG_H"_d;
        libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
        libtesseract.Public += "HAVE_LIBARCHIVE"_d;
        libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
        libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;

        libtesseract.Public += "org.sw.demo.danbloomberg.leptonica-master"_dep;
        libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;

        if (libtesseract.getSettings().TargetOS.Type == OSType::Windows)
        {
            libtesseract.Public += "ws2_32.lib"_l;
            libtesseract.Protected += "NOMINMAX"_def;
        }

        libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
        libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
        libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
        libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
        libtesseract.configureFile("src/api/tess_version.h.in", "tess_version.h");

        // install
        if (!libtesseract.DryRun)
        {
            const Files files
            {
                // from api/makefile.am
                "src/api/apitypes.h",
                "src/api/baseapi.h",
                "src/api/capi.h",
                "src/api/renderer.h",
                "tess_version.h",

                //from arch/makefile.am
                "src/arch/dotproduct.h",
                "src/arch/intsimdmatrix.h",
                "src/arch/simddetect.h",

                //from ccmain/makefile.am
                "src/ccmain/thresholder.h",
                "src/ccmain/ltrresultiterator.h",
                "src/ccmain/pageiterator.h",
                "src/ccmain/resultiterator.h",
                "src/ccmain/osdetect.h",

                //from ccstruct/makefile.am
                "src/ccstruct/publictypes.h",

                //from ccutil/makefile.am
                "src/ccutil/basedir.h",
                "src/ccutil/errcode.h",
                "src/ccutil/fileerr.h",
                "src/ccutil/genericvector.h",
                "src/ccutil/helpers.h",
                "src/ccutil/params.h",
                "src/ccutil/ocrclass.h",
                "src/ccutil/platform.h",
                "src/ccutil/serialis.h",
                "src/ccutil/strngs.h",
                "src/ccutil/unichar.h",
                "src/ccutil/unicharcompress.h",
                "src/ccutil/unicharmap.h",
                "src/ccutil/unicharset.h",

                //from lstm/makefile.am
                "src/lstm/convolve.h",
                "src/lstm/ctc.h",
                "src/lstm/fullyconnected.h",
                "src/lstm/functions.h",
                "src/lstm/input.h",
                "src/lstm/lstm.h",
                "src/lstm/lstmrecognizer.h",
                "src/lstm/maxpool.h",
                "src/lstm/networkbuilder.h",
                "src/lstm/network.h",
                "src/lstm/networkio.h",
                "src/lstm/networkscratch.h",
                "src/lstm/parallel.h",
                "src/lstm/plumbing.h",
                "src/lstm/recodebeam.h",
                "src/lstm/reconfig.h",
                "src/lstm/reversed.h",
                "src/lstm/series.h",
                "src/lstm/static_shape.h",
                "src/lstm/stridemap.h",
                "src/lstm/tfnetwork.h",
                "src/lstm/weightmatrix.h",
            };

            auto d = libtesseract.BinaryDir / "tesseract";
            fs::create_directories(d);
            for (auto f : files)
            {
                libtesseract.check_absolute(f);
                fs::copy_file(f, d / f.filename(), fs::copy_options::overwrite_existing);
            }
        }
    }

    //
    auto &tesseract = tess.addExecutable("tesseract");
    tesseract += "src/api/tesseractmain.cpp";
    tesseract += libtesseract;

    //
    auto &tessopt = tess.addStaticLibrary("tessopt");
    tessopt += "src/training/tessopt.*"_rr;
    tessopt.Public += libtesseract;

    //
    auto &common_training = tess.addStaticLibrary("common_training");
    common_training +=
        "src/training/commandlineflags.cpp",
        "src/training/commandlineflags.h",
        "src/training/commontraining.cpp",
        "src/training/commontraining.h";
    common_training.Public += tessopt;

    //
    auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
    unicharset_training +=
        "src/training/icuerrorcode.*"_rr,
        "src/training/icuerrorcode.h",
        "src/training/lang_model_helpers.*"_rr,
        "src/training/lstmtester.*"_rr,
        "src/training/lstmtrainer.*"_rr,
        "src/training/normstrngs.*"_rr,
        "src/training/unicharset_training_utils.*"_rr,
        "src/training/validat.*"_rr;
    unicharset_training.Public += common_training;
    unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;

    //
#define ADD_EXE(n, ...)               \
    auto &n = tess.addExecutable(#n); \
    n += "src/training/" #n ".*"_rr;  \
    n.Public += __VA_ARGS__;          \
    n

    ADD_EXE(ambiguous_words, libtesseract);
    ADD_EXE(classifier_tester, common_training);
    ADD_EXE(combine_lang_model, unicharset_training);
    ADD_EXE(combine_tessdata, libtesseract);
    ADD_EXE(cntraining, common_training);
    ADD_EXE(dawg2wordlist, libtesseract);
    ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
    ADD_EXE(shapeclustering, common_training);
    ADD_EXE(unicharset_extractor, unicharset_training);
    ADD_EXE(wordlist2dawg, libtesseract);
    ADD_EXE(lstmeval, unicharset_training);
    ADD_EXE(lstmtraining, unicharset_training);
    ADD_EXE(set_unicharset_properties, unicharset_training);

    ADD_EXE(text2image, unicharset_training);
    text2image +=
        "src/training/boxchar.cpp",
        "src/training/boxchar.h",
        "src/training/degradeimage.cpp",
        "src/training/degradeimage.h",
        "src/training/icuerrorcode.h",
        "src/training/ligature_table.cpp",
        "src/training/ligature_table.h",
        "src/training/normstrngs.cpp",
        "src/training/normstrngs.h",
        "src/training/pango_font_info.cpp",
        "src/training/pango_font_info.h",
        "src/training/stringrenderer.cpp",
        "src/training/stringrenderer.h",
        "src/training/text2image.cpp",
        "src/training/tlog.cpp",
        "src/training/tlog.h",
        "src/training/util.h";
    text2image.Public += "org.sw.demo.gnome.pango.pangocairo-1"_dep;
}

void check(Checker &c)
{
    auto &s = c.addSet("libtesseract");
    s.checkFunctionExists("getline");
    s.checkIncludeExists("dlfcn.h");
    s.checkIncludeExists("inttypes.h");
    s.checkIncludeExists("limits.h");
    s.checkIncludeExists("malloc.h");
    s.checkIncludeExists("memory.h");
    s.checkIncludeExists("stdbool.h");
    s.checkIncludeExists("stdint.h");
    s.checkIncludeExists("stdlib.h");
    s.checkIncludeExists("string.h");
    s.checkIncludeExists("sys/ipc.h");
    s.checkIncludeExists("sys/shm.h");
    s.checkIncludeExists("sys/stat.h");
    s.checkIncludeExists("sys/types.h");
    s.checkIncludeExists("sys/wait.h");
    s.checkIncludeExists("tiffio.h");
    s.checkIncludeExists("unistd.h");
    s.checkTypeSize("long long int");
    s.checkTypeSize("mbstate_t");
    s.checkTypeSize("off_t");
    s.checkTypeSize("size_t");
    s.checkTypeSize("void *");
    s.checkTypeSize("wchar_t");
    s.checkTypeSize("_Bool");
    {
        auto &c = s.checkSymbolExists("snprintf");
        c.Parameters.Includes.push_back("stdio.h");
    }
}
<|endoftext|>


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

/* $Id$ */

//_________________________________________________________________________
//  Hits class for PHOS
//  A hit in PHOS is the sum of all hits in a single crystal
//*--
//*-- Author: Maxime Volkov (RRC KI) & Yves Schutz (SUBATECH) & Dmitri Peressounko (RRC KI & SUBATECH)

// --- ROOT system ---

// --- Standard library ---

// --- AliRoot header files ---
#include "AliPHOSHit.h"

ClassImp(AliPHOSHit)

  //____________________________________________________________________________
  AliPHOSHit::AliPHOSHit(const AliPHOSHit & hit) : AliHit(hit)
{
  // copy ctor
  fX       = hit.fX ;
  fY       = hit.fY ;
  fZ       = hit.fZ ;
  fId      = hit.fId ;
  fELOS    = hit.fELOS ;
  fTrack   = hit.fTrack ;
  fTime    = hit.fTime  ;

}

//____________________________________________________________________________
AliPHOSHit::AliPHOSHit(Int_t shunt, Int_t track, Int_t id, Float_t *hits): AliHit(shunt, track)
{
  //
  // Create a CPV hit object
  //

  fX          = hits[0] ;
  fY          = hits[1] ;
  fZ          = hits[2] ;
  fTime       = hits[3] ;
  fId         = id ;
  fELOS       = hits[4] ;
}
//____________________________________________________________________________
Bool_t AliPHOSHit::operator==(AliPHOSHit const &rValue) const
{
  // Two hits are identical if they have the same Id and originate from the same primary

  Bool_t rv = kFALSE ;

  if ( (fId == rValue.GetId()) && ( fTrack == rValue.GetPrimary() ) )
    rv = kTRUE;

  return rv;
}

//____________________________________________________________________________
AliPHOSHit AliPHOSHit::operator+(const AliPHOSHit &rValue)
{
  // Add the energy of the hit

  fELOS += rValue.GetEnergy() ;

  if(rValue.GetTime() < fTime)
    fTime = rValue.GetTime() ;

   return *this;

}

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

/* $Id$ */

//_________________________________________________________________________
//  Hits class for PHOS
//  A hit in PHOS is the sum of all hits in a single crystal
//*--
//*-- Author: Maxime Volkov (RRC KI) & Yves Schutz (SUBATECH) & Dmitri Peressounko (RRC KI & SUBATECH)

// --- ROOT system ---

// --- Standard library ---

// --- AliRoot header files ---
#include "AliPHOSHit.h"

ClassImp(AliPHOSHit)

  //____________________________________________________________________________
AliPHOSHit::AliPHOSHit(const AliPHOSHit & hit) :
  AliHit(hit),fId(0),fELOS(0),fTime(0)
{
  // copy ctor
  hit.Copy(*this);
}

//____________________________________________________________________________
AliPHOSHit::AliPHOSHit(Int_t shunt, Int_t track, Int_t id, Float_t *hits) :
  AliHit(shunt, track),fId(0),fELOS(0),fTime(0)
{
  //
  // Create a CPV hit object
  //

  fX          = hits[0] ;
  fY          = hits[1] ;
  fZ          = hits[2] ;
  fTime       = hits[3] ;
  fId         = id ;
  fELOS       = hits[4] ;
}
//____________________________________________________________________________
Bool_t AliPHOSHit::operator==(AliPHOSHit const &rValue) const
{
  // Two hits are identical if they have the same Id and originate from the same primary

  Bool_t rv = kFALSE ;

  if ( (fId == rValue.GetId()) && ( fTrack == rValue.GetPrimary() ) )
    rv = kTRUE;

  return rv;
}

//____________________________________________________________________________
AliPHOSHit AliPHOSHit::operator+(const AliPHOSHit &rValue)
{
  // Add the energy of the hit

  fELOS += rValue.GetEnergy() ;

  if(rValue.GetTime() < fTime)
    fTime = rValue.GetTime() ;

   return *this;

}

<|endoftext|>


<commit_before>#include "selectsignaldialog.h"
#include "ui_selectsignaldialog.h"

#include "signaldescription.h"
#include "signalhandler.h"
#include "jointnames.h"

#include <cstdio>
#include <cassert>

class SelectSignalDialog::Internal : public Ui::SelectSignalDialog
{
public:

  QList<QListWidget*> ArrayKeyWidgets;

};

SelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent)
{
  mInternal = new Internal;
  mInternal->setupUi(this);

  QStringList channels = SignalHandlerFactory::instance().channels();
  QStringList messageTypes = SignalHandlerFactory::instance().messageTypes();
  //QStringList messageFields;

  channels.sort();
  messageTypes.sort();

  mInternal->ChannelListBox->addItems(channels);
  mInternal->MessageTypeListBox->addItems(messageTypes);
  //mInternal->MessageFieldListBox->addItems(messageFields);

  mInternal->ChannelListBox->setCurrentRow(0);
  mInternal->MessageTypeListBox->setCurrentRow(0);
  //mInternal->MessageFieldListBox->setCurrentRow(0);

  this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged()));
  this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged()));
  this->onMessageTypeChanged();
}

void SelectSignalDialog::onMessageTypeChanged()
{
  if (!mInternal->MessageTypeListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();

  QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType);
  fieldNames.sort();

  mInternal->MessageFieldListBox->clear();
  mInternal->MessageFieldListBox->addItems(fieldNames);
  mInternal->MessageFieldListBox->setCurrentRow(0);
  this->onFieldNameChanged();
}

void SelectSignalDialog::onFieldNameChanged()
{
  if (!mInternal->MessageFieldListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString fieldName = mInternal->MessageFieldListBox->currentItem()->text();

  foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
  {
    delete listWidget;
  }
  mInternal->ArrayKeyWidgets.clear();

  const QList<QList<QString> >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName);

  bool useArrayKeys = !validArrayKeys.empty();
  mInternal->ArrayKeysLabel->setVisible(useArrayKeys);
  mInternal->ArrayKeysContainer->setVisible(useArrayKeys);

  foreach (const QList<QString> & keys, validArrayKeys)
  {
    assert(keys.size());
    QListWidget* listWidget = new QListWidget;
    listWidget->addItems(keys);
    listWidget->setCurrentRow(0);
    mInternal->ArrayKeyWidgets.append(listWidget);
    mInternal->ArrayKeysContainer->layout()->addWidget(listWidget);
  }

  if (mInternal->ArrayKeyWidgets.size())
  {
    mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection);
  }

}

SelectSignalDialog::~SelectSignalDialog()
{
  delete mInternal;
}

QList<SignalHandler*> SelectSignalDialog::createSignalHandlers() const
{
  QString channel = mInternal->ChannelListBox->currentItem()->text();
  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString messageField = mInternal->MessageFieldListBox->currentItem()->text();

  SignalDescription desc;
  desc.mChannel = channel;
  desc.mMessageType = messageType;
  desc.mFieldName = messageField;

  QList<SignalDescription> descriptions;

  if (mInternal->ArrayKeyWidgets.length())
  {
    foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
    {
      if (listWidget == mInternal->ArrayKeyWidgets.back())
      {
        foreach (QListWidgetItem*	selectedItem, listWidget->selectedItems())
        {
          QString arrayKey = selectedItem->text();
          SignalDescription descCopy(desc);
          descCopy.mArrayKeys.append(arrayKey);
          descriptions.append(descCopy);
        }
      }
      else
      {
        QString arrayKey = listWidget->currentItem()->text();
        desc.mArrayKeys.append(arrayKey);
      }
    }
  }
  else
  {
    descriptions.append(desc);
  }

  QList<SignalHandler*> signalHandlers;
  foreach (const SignalDescription& description, descriptions)
  {
    SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description);
    assert(signalHandler);
    signalHandlers.append(signalHandler);
  }

  return signalHandlers;
}

<commit_msg>fix a crash when the select signal dialog is empty<commit_after>#include "selectsignaldialog.h"
#include "ui_selectsignaldialog.h"

#include "signaldescription.h"
#include "signalhandler.h"
#include "jointnames.h"

#include <cstdio>
#include <cassert>

class SelectSignalDialog::Internal : public Ui::SelectSignalDialog
{
public:

  QList<QListWidget*> ArrayKeyWidgets;

};

SelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent)
{
  mInternal = new Internal;
  mInternal->setupUi(this);

  QStringList channels = SignalHandlerFactory::instance().channels();
  QStringList messageTypes = SignalHandlerFactory::instance().messageTypes();
  //QStringList messageFields;

  channels.sort();
  messageTypes.sort();

  mInternal->ChannelListBox->addItems(channels);
  mInternal->MessageTypeListBox->addItems(messageTypes);
  //mInternal->MessageFieldListBox->addItems(messageFields);

  mInternal->ChannelListBox->setCurrentRow(0);
  mInternal->MessageTypeListBox->setCurrentRow(0);
  //mInternal->MessageFieldListBox->setCurrentRow(0);

  this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged()));
  this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged()));
  this->onMessageTypeChanged();
}

void SelectSignalDialog::onMessageTypeChanged()
{
  if (!mInternal->MessageTypeListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();

  QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType);
  fieldNames.sort();

  mInternal->MessageFieldListBox->clear();
  mInternal->MessageFieldListBox->addItems(fieldNames);
  mInternal->MessageFieldListBox->setCurrentRow(0);
  this->onFieldNameChanged();
}

void SelectSignalDialog::onFieldNameChanged()
{
  if (!mInternal->MessageFieldListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString fieldName = mInternal->MessageFieldListBox->currentItem()->text();

  foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
  {
    delete listWidget;
  }
  mInternal->ArrayKeyWidgets.clear();

  const QList<QList<QString> >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName);

  bool useArrayKeys = !validArrayKeys.empty();
  mInternal->ArrayKeysLabel->setVisible(useArrayKeys);
  mInternal->ArrayKeysContainer->setVisible(useArrayKeys);

  foreach (const QList<QString> & keys, validArrayKeys)
  {
    assert(keys.size());
    QListWidget* listWidget = new QListWidget;
    listWidget->addItems(keys);
    listWidget->setCurrentRow(0);
    mInternal->ArrayKeyWidgets.append(listWidget);
    mInternal->ArrayKeysContainer->layout()->addWidget(listWidget);
  }

  if (mInternal->ArrayKeyWidgets.size())
  {
    mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection);
  }

}

SelectSignalDialog::~SelectSignalDialog()
{
  delete mInternal;
}

QList<SignalHandler*> SelectSignalDialog::createSignalHandlers() const
{
  if (!mInternal->ChannelListBox->currentItem()
      || !mInternal->MessageTypeListBox->currentItem()
      || !mInternal->MessageFieldListBox->currentItem())
    {
    return QList<SignalHandler*>();
    }

  QString channel = mInternal->ChannelListBox->currentItem()->text();
  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString messageField = mInternal->MessageFieldListBox->currentItem()->text();

  SignalDescription desc;
  desc.mChannel = channel;
  desc.mMessageType = messageType;
  desc.mFieldName = messageField;

  QList<SignalDescription> descriptions;

  if (mInternal->ArrayKeyWidgets.length())
  {
    foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
    {
      if (listWidget == mInternal->ArrayKeyWidgets.back())
      {
        foreach (QListWidgetItem*	selectedItem, listWidget->selectedItems())
        {
          QString arrayKey = selectedItem->text();
          SignalDescription descCopy(desc);
          descCopy.mArrayKeys.append(arrayKey);
          descriptions.append(descCopy);
        }
      }
      else
      {
        QString arrayKey = listWidget->currentItem()->text();
        desc.mArrayKeys.append(arrayKey);
      }
    }
  }
  else
  {
    descriptions.append(desc);
  }

  QList<SignalHandler*> signalHandlers;
  foreach (const SignalDescription& description, descriptions)
  {
    SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description);
    assert(signalHandler);
    signalHandlers.append(signalHandler);
  }

  return signalHandlers;
}

<|endoftext|>


<commit_before>#ifndef __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__
#define __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__

#include <limits>

#include <stan/math/boost_error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/math/error_handling.hpp>

#include <stan/math/matrix.hpp>

#include <boost/type_traits/common_type.hpp>

namespace stan {

  namespace math {

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_symmetric(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                                const char* name,
                                T_result* result = 0,
                                const Policy& = Policy()) {
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type size_type;
      size_type k = y.rows();
      if (k == 1)
        return true;

      for (size_type m = 0; m < k; ++m) {
        for (size_type n = m + 1; n < k; ++n) {
          if (fabs(y(m,n) - y(n,m)) > CONSTRAINT_TOLERANCE) {
            std::ostringstream message;
            message << name << " is not symmetric. "
                    << name << "[" << m << "," << n << "] is %1%, but "
                    << name << "[" << n << "," << m << "] element is " << y(n,m);
            T_result tmp = policies::raise_domain_error<T_y>(function,
                                                             message.str().c_str(),
                                                             y(m,n), Policy());
            if (result != 0)
              *result = tmp;
            return false;
          }

        }
      }
      return true;
    }

    /**
     * Return true if the specified matrix is symmetric
     *
     * NOTE: squareness is not checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is symmetric.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool symmetry_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      size_t k = y.rows();
      if (k == 1)
        return true;

      for (size_t m = 0; m < k; ++m) {
        for (size_t n = m + 1; n < k; ++n) {
          if (fabs(y(m,n) - y(n,m)) > CONSTRAINT_TOLERANCE)
            return false;
        }
      }
      return true;
    }

    /**
     * Return true if the specified matrix is positive definite
     *
     * NOTE: symmetry is NOT checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is positive definite.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool pd_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() == 1)
        return y(0,0) > CONSTRAINT_TOLERANCE;

      Eigen::LDLT< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > cholesky = y.ldlt();
      if( (cholesky.vectorD().array() > CONSTRAINT_TOLERANCE).all() )
        return true;

      return false;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be square,
     * symmetric, and positive definite.
     *
     * @param y Matrix to test.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() != y.cols() || y.rows() == 0)
        return false;

      if (!symmetry_validate(y))
        return false;

      if (!pd_validate(y))
        return false;

      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be symmetric
     * and positive definite.
     *
     * @param y Matrix to test.
     * @param err_msg Output stream for error messages.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y, std::ostream& err_msg) {
      if (y.rows() != y.cols() || y.rows() == 0) {
        err_msg << "Matrix is not square: [" << y.rows() << ", " << y.cols() << "]";
        return false;
      }

      if (!symmetry_validate(y)) {
        err_msg << "Matrix is not symmetric";
        return false;
      }

      if (!pd_validate(y)) {
        err_msg << "Matrix is not positive definite";
        return false;
      }

      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * correlation matrix.  A valid correlation matrix is symmetric,
     * has a unit diagonal (all 1 values), and has all values between
     * -1 and 1 (inclussive).
     *
     * @param y Matrix to test.
     * @return true if the specified matrix is a valid
     * correlation matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool corr_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (!cov_matrix_validate(y))
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::size_type k = 0; k < y.rows(); ++k) {
        if (fabs(y(k,k) - 1.0) > CONSTRAINT_TOLERANCE)
          return false;
      }
      return true;
    }

    /**
     * Return true if the specified vector is simplex.
     * To be a simplex, all values must be greater than or equal to 0
     * and the values must sum to 1.
     *
     *
The test that the values sum to 1 is done to within the
     * tolerance specified by CONSTRAINT_TOLERANCE.
     *
     * @param y Vector to test.
     * @return true if the vector is a simplex.
     */
    template <typename T>
    bool
    simplex_validate(const Eigen::Matrix<T,Eigen::Dynamic,1>& y) {
      if (y.size() == 0)
        return false;
      if (fabs(1.0 - y.sum()) > CONSTRAINT_TOLERANCE)
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,1>::size_type i = 0; i < y.size(); ++i) {
        if (!(y[i] >= 0.0))
          return false;
      }
      return true;
    }

    /**
     * Return true if the specified vector contains
     * only non-negative values and is sorted into increasing order.
     * There may be duplicate values.
     *
     * @param y Vector to test.
     * @return true if the vector has positive, ordered
     * values.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool pos_ordered_validate(const Eigen::Matrix<T,Eigen::Dynamic,1>& y) {
      if (y.size() == 0) return true;
      if (!(y[0] > 0.0)) return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,1>::size_type k = 1; k < y.size(); ++k) {
        if (!(y[k] > y[k-1]))
          return false;
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                              const char* name,
                              T_result* result = 0,
                              const Policy& = Policy()) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (boost::math::isnan(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must not be nan!";
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          message.str().c_str(),
                                                          y[i],
                                                          Policy());
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                              const char* name,
                              T_result* result = 0,
                              const Policy& = Policy()) {
      for (int i = 0; i < y.rows(); i++) {
        for (int j = 0; j < y.cols(); j++) {
          if (boost::math::isnan(y(i,j))) {
            std::ostringstream message;
            message << name << "[" << i << "," << j << "] is %1%, but must not be nan!";
            T_result tmp = policies::raise_domain_error<T_y>(function,
                                                             message.str().c_str(),
                                                             y(i,j), Policy());
            if (result != 0)
              *result = tmp;
            return false;
          }
        }
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_finite(const char* function,
                             const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                             const char* name,
                             T_result* result = 0,
                             const Policy& = Policy()) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (!boost::math::isfinite(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must be finite!";
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          message.str().c_str(),
                                                          y[i],
                                                          Policy());
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }

    template <typename T_covar, typename T_result = T_covar, class Policy = default_policy>
    inline bool check_cov_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result = 0,
                                 const Policy& = Policy()) {
      if (!cov_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid covariance matrix. "
               << "Sigma must be symmetric and positive semi-definite. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        T_result tmp = boost::math::policies::raise_domain_error<T_covar>(function,
                                                                          stream.str().c_str(),
                                                                          Sigma(0,0),
                                                                          Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }

    template <typename T_covar, typename T_result = T_covar, class Policy = default_policy>
    inline bool check_corr_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result = 0,
                                 const Policy& = Policy()) {
      if (!corr_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid correlation matrix."
               << "Sigma must be symmetric and positive semi-definite with ones on its diagonal. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        T_result tmp = policies::raise_domain_error<T_covar>(function,
                                                             stream.str().c_str(),
                                                             Sigma(0,0),
                                                             Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }

    template <typename T_size1, typename T_size2, typename T_result = T_size1, class Policy = default_policy>
    inline bool check_size_match(const char* function,
                                 T_size1 i,
                                 T_size2 j,
                                 T_result* result = 0,
                                 const Policy& = Policy()) {
      using stan::math::policies::raise_domain_error;
      typedef typename boost::common_type<T_size1,T_size2>::type common_type;
      if (static_cast<common_type>(i) != static_cast<common_type>(j)) {
        std::ostringstream msg;
        msg << "i and j must be same.  Found i=%1%, j=" << j;
        T_result tmp = raise_domain_error<T_result,T_size1>(function,
                                                            msg.str().c_str(),
                                                            i,
                                                            Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }

  }
}

#endif
<commit_msg>math/matrix_error_handling: added check_pos_definite()<commit_after>#ifndef __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__
#define __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__

#include <limits>

#include <stan/math/boost_error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/math/error_handling.hpp>

#include <stan/math/matrix.hpp>

#include <boost/type_traits/common_type.hpp>

namespace stan {

  namespace math {

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_symmetric(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                                const char* name,
                                T_result* result = 0,
                                const Policy& = Policy()) {
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type size_type;
      size_type k = y.rows();
      if (k == 1)
        return true;

      for (size_type m = 0; m < k; ++m) {
        for (size_type n = m + 1; n < k; ++n) {
          if (fabs(y(m,n) - y(n,m)) > CONSTRAINT_TOLERANCE) {
            std::ostringstream message;
            message << name << " is not symmetric. "
                    << name << "[" << m << "," << n << "] is %1%, but "
                    << name << "[" << n << "," << m << "] element is " << y(n,m);
            T_result tmp = policies::raise_domain_error<T_y>(function,
                                                             message.str().c_str(),
                                                             y(m,n), Policy());
            if (result != 0)
              *result = tmp;
            return false;
          }

        }
      }
      return true;
    }

    /**
     * Return true if the specified matrix is symmetric
     *
     * NOTE: squareness is not checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is symmetric.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool symmetry_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      size_t k = y.rows();
      if (k == 1)
        return true;

      for (size_t m = 0; m < k; ++m) {
        for (size_t n = m + 1; n < k; ++n) {
          if (fabs(y(m,n) - y(n,m)) > CONSTRAINT_TOLERANCE)
            return false;
        }
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_pos_definite(const char* function,
                                   const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                                   const char* name,
                                   T_result* result = 0,
                                   const Policy& = Policy()) {
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type size_type;
      if (y.rows() == 1 && y(0,0) <= CONSTRAINT_TOLERANCE) {
        std::ostringstream message;
        message << name << " is not positive definite. "
                << name << "(0,0) is %1%.";
        T_result tmp = policies::raise_domain_error<T_y>(function,
                                                         message.str().c_str(),
                                                         y(0,0), Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      Eigen::LDLT< Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic> > cholesky = y.ldlt();
      if((cholesky.vectorD().array() <= CONSTRAINT_TOLERANCE).any())  {
        std::ostringstream message;
        message << name << " is not positive definite. "
                << name << "(0,0) is %1%.";
        T_result tmp = policies::raise_domain_error<T_y>(function,
                                                         message.str().c_str(),
                                                         y(0,0), Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }
    /**
     * Return true if the specified matrix is positive definite
     *
     * NOTE: symmetry is NOT checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is positive definite.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool pd_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() == 1)
        return y(0,0) > CONSTRAINT_TOLERANCE;

      Eigen::LDLT< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > cholesky = y.ldlt();
      if( (cholesky.vectorD().array() > CONSTRAINT_TOLERANCE).all() )
        return true;

      return false;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be square,
     * symmetric, and positive definite.
     *
     * @param y Matrix to test.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() != y.cols() || y.rows() == 0)
        return false;

      if (!symmetry_validate(y))
        return false;

      if (!pd_validate(y))
        return false;

      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be symmetric
     * and positive definite.
     *
     * @param y Matrix to test.
     * @param err_msg Output stream for error messages.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y, std::ostream& err_msg) {
      if (y.rows() != y.cols() || y.rows() == 0) {
        err_msg << "Matrix is not square: [" << y.rows() << ", " << y.cols() << "]";
        return false;
      }

      if (!symmetry_validate(y)) {
        err_msg << "Matrix is not symmetric";
        return false;
      }

      if (!pd_validate(y)) {
        err_msg << "Matrix is not positive definite";
        return false;
      }

      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * correlation matrix.  A valid correlation matrix is symmetric,
     * has a unit diagonal (all 1 values), and has all values between
     * -1 and 1 (inclussive).
     *
     * @param y Matrix to test.
     * @return true if the specified matrix is a valid
     * correlation matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool corr_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (!cov_matrix_validate(y))
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::size_type k = 0; k < y.rows(); ++k) {
        if (fabs(y(k,k) - 1.0) > CONSTRAINT_TOLERANCE)
          return false;
      }
      return true;
    }

    /**
     * Return true if the specified vector is simplex.
     * To be a simplex, all values must be greater than or equal to 0
     * and the values must sum to 1.
     *
     *
The test that the values sum to 1 is done to within the
     * tolerance specified by CONSTRAINT_TOLERANCE.
     *
     * @param y Vector to test.
     * @return true if the vector is a simplex.
     */
    template <typename T>
    bool
    simplex_validate(const Eigen::Matrix<T,Eigen::Dynamic,1>& y) {
      if (y.size() == 0)
        return false;
      if (fabs(1.0 - y.sum()) > CONSTRAINT_TOLERANCE)
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,1>::size_type i = 0; i < y.size(); ++i) {
        if (!(y[i] >= 0.0))
          return false;
      }
      return true;
    }

    /**
     * Return true if the specified vector contains
     * only non-negative values and is sorted into increasing order.
     * There may be duplicate values.
     *
     * @param y Vector to test.
     * @return true if the vector has positive, ordered
     * values.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool pos_ordered_validate(const Eigen::Matrix<T,Eigen::Dynamic,1>& y) {
      if (y.size() == 0) return true;
      if (!(y[0] > 0.0)) return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,1>::size_type k = 1; k < y.size(); ++k) {
        if (!(y[k] > y[k-1]))
          return false;
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                              const char* name,
                              T_result* result = 0,
                              const Policy& = Policy()) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (boost::math::isnan(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must not be nan!";
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          message.str().c_str(),
                                                          y[i],
                                                          Policy());
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                              const char* name,
                              T_result* result = 0,
                              const Policy& = Policy()) {
      for (int i = 0; i < y.rows(); i++) {
        for (int j = 0; j < y.cols(); j++) {
          if (boost::math::isnan(y(i,j))) {
            std::ostringstream message;
            message << name << "[" << i << "," << j << "] is %1%, but must not be nan!";
            T_result tmp = policies::raise_domain_error<T_y>(function,
                                                             message.str().c_str(),
                                                             y(i,j), Policy());
            if (result != 0)
              *result = tmp;
            return false;
          }
        }
      }
      return true;
    }

    template <typename T_y, typename T_result = T_y, class Policy = default_policy>
    inline bool check_finite(const char* function,
                             const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                             const char* name,
                             T_result* result = 0,
                             const Policy& = Policy()) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (!boost::math::isfinite(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must be finite!";
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          message.str().c_str(),
                                                          y[i],
                                                          Policy());
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }

    template <typename T_covar, typename T_result = T_covar, class Policy = default_policy>
    inline bool check_cov_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result = 0,
                                 const Policy& = Policy()) {
      if (!cov_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid covariance matrix. "
               << "Sigma must be symmetric and positive semi-definite. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        T_result tmp = boost::math::policies::raise_domain_error<T_covar>(function,
                                                                          stream.str().c_str(),
                                                                          Sigma(0,0),
                                                                          Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }

    template <typename T_covar, typename T_result = T_covar, class Policy = default_policy>
    inline bool check_corr_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result = 0,
                                 const Policy& = Policy()) {
      if (!corr_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid correlation matrix."
               << "Sigma must be symmetric and positive semi-definite with ones on its diagonal. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        T_result tmp = policies::raise_domain_error<T_covar>(function,
                                                             stream.str().c_str(),
                                                             Sigma(0,0),
                                                             Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }

    template <typename T_size1, typename T_size2, typename T_result = T_size1, class Policy = default_policy>
    inline bool check_size_match(const char* function,
                                 T_size1 i,
                                 T_size2 j,
                                 T_result* result = 0,
                                 const Policy& = Policy()) {
      using stan::math::policies::raise_domain_error;
      typedef typename boost::common_type<T_size1,T_size2>::type common_type;
      if (static_cast<common_type>(i) != static_cast<common_type>(j)) {
        std::ostringstream msg;
        msg << "i and j must be same.  Found i=%1%, j=" << j;
        T_result tmp = raise_domain_error<T_result,T_size1>(function,
                                                            msg.str().c_str(),
                                                            i,
                                                            Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      return true;
    }

  }
}

#endif
<|endoftext|>


<commit_before>#ifndef __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__
#define __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__

#include <limits>

#include <stan/math/boost_error_handling.hpp>
#include <stan/math/special_functions.hpp>

#include <stan/math/matrix.hpp>

#include <boost/type_traits/common_type.hpp>

namespace stan {

  namespace math {
    /**
     * This is the tolerance for checking arithmetic bounds
     * in rank and in simplexes.  The current value is 1E-8.
     */
    const double CONSTRAINT_TOLERANCE = 1E-8;

    template <typename T_y, typename T_result, class Policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                              const char* name,
                              T_result* result,
                              const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (boost::math::isnan(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must not be nan!";
          *result = raise_domain_error<T_result,T_y>(function,
                                                     message.str().c_str(),
                                                     y[i],
                                                     Policy());
          return false;
        }
      }
      return true;
    }

    template <typename T_y, typename T_result, class Policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                              const char* name,
                              T_result* result,
                              const Policy& /*pol*/) {
      for (int i = 0; i < y.rows(); i++) {
        for (int j = 0; j < y.cols(); j++) {
          if (boost::math::isnan(y(i,j))) {
            std::ostringstream message;
            message << name << "[" << i << "," << j << "] is %1%, but must not be nan!";
            *result = policies::raise_domain_error<T_y>(function,
                                              message.str().c_str(),
                                              y(i,j), Policy());
            return false;
          }
        }
      }
      return true;
    }

    template <typename T_y, typename T_result, class Policy>
    inline bool check_finite(const char* function,
                             const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                             const char* name,
                             T_result* result,
                             const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (!boost::math::isfinite(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must be finite!";
          *result = raise_domain_error<T_result,T_y>(function,
                                                     message.str().c_str(),
                                                     y[i],
                                                     Policy());
          return false;
        }
      }
      return true;
    }

    template <typename T_covar, typename T_result, class Policy>
    inline bool check_cov_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result,
                                 const Policy& /*pol*/) {
      if (!cov_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid covariance matrix. "
               << "Sigma must be symmetric and positive semi-definite. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        *result = boost::math::policies::raise_domain_error<T_covar>(function,
                                                                     stream.str().c_str(),
                                                                     Sigma(0,0),
                                                                     Policy());
        return false;
      }
      return true;
    }

    template <typename T_covar, typename T_result, class Policy>
    inline bool check_corr_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result,
                                 const Policy& /*pol*/) {
      if (!corr_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid correlation matrix."
               << "Sigma must be symmetric and positive semi-definite with ones on its diagonal. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        *result = policies::raise_domain_error<T_covar>(function,
                                              stream.str().c_str(),
                                              Sigma(0,0),
                                              Policy());
        return false;
      }
      return true;
    }

    template <typename T_result, typename T_size1, typename T_size2, class Policy>
    inline bool check_size_match(const char* function,
                                 T_size1 i,
                                 T_size2 j,
                                 T_result* result,
                                 const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      typedef typename boost::common_type<T_size1,T_size2>::type common_type;
      if (static_cast<common_type>(i) != static_cast<common_type>(j)) {
        std::ostringstream msg;
        msg << "i and j must be same.  Found i=%1%, j=" << j;
        *result = raise_domain_error<T_result,T_size1>(function,
                                                       msg.str().c_str(),
                                                       i,
                                                       Policy());
        return false;
      }
      return true;
    }

    template <typename T_prob, typename T_result, class Policy>
    inline bool check_simplex(const char* function,
                              const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta,
                              const char* name,
                              T_result* result,
                              const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      if (!simplex_validate(theta)) {
        std::ostringstream stream;
        stream << name
               << "is not a valid simplex. The first element of the simplex is: %1%.";
        *result = raise_domain_error<T_result,T_prob>(function,
                                                      stream.str().c_str(),
                                                      theta(0),
                                                      Policy());
        return false;
      }
      return true;
    }

    // forward declaration for corr_matrix
    //template <typename T>
    //bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y);

    /**
     * Return true if the specified matrix is symmetric
     *
     * NOTE: squareness is not checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is symmetric.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool symmetry_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      size_t k = y.rows();
      if (k == 1)
        return true;

      for (size_t m = 0; m < k; ++m) {
        for (size_t n = m + 1; n < k; ++n) {
          if (fabs(y(m,n) - y(n,m)) > CONSTRAINT_TOLERANCE)
            return false;
        }
      }
      return true;
    }

    /**
     * Return true if the specified matrix is positive definite
     *
     * NOTE: symmetry is NOT checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is positive definite.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool pd_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() == 1)
        return y(0,0) > CONSTRAINT_TOLERANCE;

      Eigen::LDLT< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > cholesky = y.ldlt();
      if( (cholesky.vectorD().array() > CONSTRAINT_TOLERANCE).all() )
        return true;

      return false;
    }

    /**
     * Return true if the specified matrix is a valid
     * correlation matrix.  A valid correlation matrix is symmetric,
     * has a unit diagonal (all 1 values), and has all values between
     * -1 and 1 (inclussive).
     *
     * @param y Matrix to test.
     * @return true if the specified matrix is a valid
     * correlation matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool corr_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (!cov_matrix_validate(y))
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::size_type k = 0; k < y.rows(); ++k) {
        if (fabs(y(k,k) - 1.0) > CONSTRAINT_TOLERANCE)
          return false;
      }
      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be square,
     * symmetric, and positive definite.
     *
     * @param y Matrix to test.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() != y.cols() || y.rows() == 0)
        return false;

      if (!symmetry_validate(y))
        return false;

      if (!pd_validate(y))
        return false;

      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be symmetric
     * and positive definite.
     *
     * @param y Matrix to test.
     * @param err_msg Output stream for error messages.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y, std::ostream& err_msg) {
      if (y.rows() != y.cols() || y.rows() == 0) {
        err_msg << "Matrix is not square: [" << y.rows() << ", " << y.cols() << "]";
        return false;
      }

      if (!symmetry_validate(y)) {
        err_msg << "Matrix is not symmetric";
        return false;
      }

      if (!pd_validate(y)) {
        err_msg << "Matrix is not positive definite";
        return false;
      }

      return true;
    }

    /**
     * Return true if the specified vector is simplex.
     * To be a simplex, all values must be greater than or equal to 0
     * and the values must sum to 1.
     *
     *
The test that the values sum to 1 is done to within the
     * tolerance specified by CONSTRAINT_TOLERANCE.
     *
     * @param y Vector to test.
     * @return true if the vector is a simplex.
     */
    template <typename T>
    bool
    simplex_validate(const Eigen::Matrix<T,Eigen::Dynamic,1>& y) {
      if (y.size() == 0)
        return false;
      if (fabs(1.0 - y.sum()) > CONSTRAINT_TOLERANCE)
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,1>::size_type i = 0; i < y.size(); ++i) {
        if (!(y[i] >= 0.0))
          return false;
      }
      return true;
    }

  }
}

#endif
<commit_msg>removing forward declaration<commit_after>#ifndef __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__
#define __STAN__MATH__MATRIX_ERROR_HANDLING_HPP__

#include <limits>

#include <stan/math/boost_error_handling.hpp>
#include <stan/math/special_functions.hpp>

#include <stan/math/matrix.hpp>

#include <boost/type_traits/common_type.hpp>

namespace stan {

  namespace math {
    /**
     * This is the tolerance for checking arithmetic bounds
     * in rank and in simplexes.  The current value is 1E-8.
     */
    const double CONSTRAINT_TOLERANCE = 1E-8;

    template <typename T_y, typename T_result, class Policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                              const char* name,
                              T_result* result,
                              const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (boost::math::isnan(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must not be nan!";
          *result = raise_domain_error<T_result,T_y>(function,
                                                     message.str().c_str(),
                                                     y[i],
                                                     Policy());
          return false;
        }
      }
      return true;
    }

    template <typename T_y, typename T_result, class Policy>
    inline bool check_not_nan(const char* function,
                              const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                              const char* name,
                              T_result* result,
                              const Policy& /*pol*/) {
      for (int i = 0; i < y.rows(); i++) {
        for (int j = 0; j < y.cols(); j++) {
          if (boost::math::isnan(y(i,j))) {
            std::ostringstream message;
            message << name << "[" << i << "," << j << "] is %1%, but must not be nan!";
            *result = policies::raise_domain_error<T_y>(function,
                                              message.str().c_str(),
                                              y(i,j), Policy());
            return false;
          }
        }
      }
      return true;
    }

    template <typename T_y, typename T_result, class Policy>
    inline bool check_finite(const char* function,
                             const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                             const char* name,
                             T_result* result,
                             const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      for (int i = 0; i < y.rows(); i++) {
        if (!boost::math::isfinite(y[i])) {
          std::ostringstream message;
          message << name << "[" << i << "] is %1%, but must be finite!";
          *result = raise_domain_error<T_result,T_y>(function,
                                                     message.str().c_str(),
                                                     y[i],
                                                     Policy());
          return false;
        }
      }
      return true;
    }

    template <typename T_covar, typename T_result, class Policy>
    inline bool check_cov_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result,
                                 const Policy& /*pol*/) {
      if (!cov_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid covariance matrix. "
               << "Sigma must be symmetric and positive semi-definite. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        *result = boost::math::policies::raise_domain_error<T_covar>(function,
                                                                     stream.str().c_str(),
                                                                     Sigma(0,0),
                                                                     Policy());
        return false;
      }
      return true;
    }

    template <typename T_covar, typename T_result, class Policy>
    inline bool check_corr_matrix(const char* function,
                                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                                 T_result* result,
                                 const Policy& /*pol*/) {
      if (!corr_matrix_validate(Sigma)) {
        std::ostringstream stream;
        stream << "Sigma is not a valid correlation matrix."
               << "Sigma must be symmetric and positive semi-definite with ones on its diagonal. Sigma: \n"
               << Sigma
               << "\nSigma(0,0): %1%";
        *result = policies::raise_domain_error<T_covar>(function,
                                              stream.str().c_str(),
                                              Sigma(0,0),
                                              Policy());
        return false;
      }
      return true;
    }

    template <typename T_result, typename T_size1, typename T_size2, class Policy>
    inline bool check_size_match(const char* function,
                                 T_size1 i,
                                 T_size2 j,
                                 T_result* result,
                                 const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      typedef typename boost::common_type<T_size1,T_size2>::type common_type;
      if (static_cast<common_type>(i) != static_cast<common_type>(j)) {
        std::ostringstream msg;
        msg << "i and j must be same.  Found i=%1%, j=" << j;
        *result = raise_domain_error<T_result,T_size1>(function,
                                                       msg.str().c_str(),
                                                       i,
                                                       Policy());
        return false;
      }
      return true;
    }

    template <typename T_prob, typename T_result, class Policy>
    inline bool check_simplex(const char* function,
                              const Eigen::Matrix<T_prob,Eigen::Dynamic,1>& theta,
                              const char* name,
                              T_result* result,
                              const Policy& /*pol*/) {
      using stan::math::policies::raise_domain_error;
      if (!simplex_validate(theta)) {
        std::ostringstream stream;
        stream << name
               << "is not a valid simplex. The first element of the simplex is: %1%.";
        *result = raise_domain_error<T_result,T_prob>(function,
                                                      stream.str().c_str(),
                                                      theta(0),
                                                      Policy());
        return false;
      }
      return true;
    }

    /**
     * Return true if the specified matrix is symmetric
     *
     * NOTE: squareness is not checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is symmetric.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool symmetry_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      size_t k = y.rows();
      if (k == 1)
        return true;

      for (size_t m = 0; m < k; ++m) {
        for (size_t n = m + 1; n < k; ++n) {
          if (fabs(y(m,n) - y(n,m)) > CONSTRAINT_TOLERANCE)
            return false;
        }
      }
      return true;
    }

    /**
     * Return true if the specified matrix is positive definite
     *
     * NOTE: symmetry is NOT checked by this function
     *
     * @param y Matrix to test.
     * @return true if the matrix is positive definite.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool pd_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() == 1)
        return y(0,0) > CONSTRAINT_TOLERANCE;

      Eigen::LDLT< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > cholesky = y.ldlt();
      if( (cholesky.vectorD().array() > CONSTRAINT_TOLERANCE).all() )
        return true;

      return false;
    }

    /**
     * Return true if the specified matrix is a valid
     * correlation matrix.  A valid correlation matrix is symmetric,
     * has a unit diagonal (all 1 values), and has all values between
     * -1 and 1 (inclussive).
     *
     * @param y Matrix to test.
     * @return true if the specified matrix is a valid
     * correlation matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool corr_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (!cov_matrix_validate(y))
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>::size_type k = 0; k < y.rows(); ++k) {
        if (fabs(y(k,k) - 1.0) > CONSTRAINT_TOLERANCE)
          return false;
      }
      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be square,
     * symmetric, and positive definite.
     *
     * @param y Matrix to test.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y) {
      if (y.rows() != y.cols() || y.rows() == 0)
        return false;

      if (!symmetry_validate(y))
        return false;

      if (!pd_validate(y))
        return false;

      return true;
    }

    /**
     * Return true if the specified matrix is a valid
     * covariance matrix.  A valid covariance matrix must be symmetric
     * and positive definite.
     *
     * @param y Matrix to test.
     * @param err_msg Output stream for error messages.
     * @return true if the matrix is a valid covariance matrix.
     * @tparam T Type of scalar.
     */
    template <typename T>
    bool cov_matrix_validate(const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y, std::ostream& err_msg) {
      if (y.rows() != y.cols() || y.rows() == 0) {
        err_msg << "Matrix is not square: [" << y.rows() << ", " << y.cols() << "]";
        return false;
      }

      if (!symmetry_validate(y)) {
        err_msg << "Matrix is not symmetric";
        return false;
      }

      if (!pd_validate(y)) {
        err_msg << "Matrix is not positive definite";
        return false;
      }

      return true;
    }

    /**
     * Return true if the specified vector is simplex.
     * To be a simplex, all values must be greater than or equal to 0
     * and the values must sum to 1.
     *
     *
The test that the values sum to 1 is done to within the
     * tolerance specified by CONSTRAINT_TOLERANCE.
     *
     * @param y Vector to test.
     * @return true if the vector is a simplex.
     */
    template <typename T>
    bool
    simplex_validate(const Eigen::Matrix<T,Eigen::Dynamic,1>& y) {
      if (y.size() == 0)
        return false;
      if (fabs(1.0 - y.sum()) > CONSTRAINT_TOLERANCE)
        return false;
      for (typename Eigen::Matrix<T,Eigen::Dynamic,1>::size_type i = 0; i < y.size(); ++i) {
        if (!(y[i] >= 0.0))
          return false;
      }
      return true;
    }

  }
}

#endif
<|endoftext|>