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

#include "Component.h"
#include "Input.h"
#include "CmakeRegen.h"
#include "Output.h"
#include "Analysis.h"
#include "Constants.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

/**
 * These variables contain the global lists of components and files.
 * They are globally accessible.
 */
std::unordered_map<std::string, Component *> components;
std::unordered_map<std::string, File> files;

// Variable to contain the root of the source tree.
static boost::filesystem::path root;

static bool CheckVersionFile() {
    const std::string currentVersion = CURRENT_VERSION;
    std::string version;
    boost::filesystem::ifstream in(root / VERSION_FILE);
    getline(in, version);
    return (version == currentVersion);
}

std::string targetFrom(const std::string &arg) {
    std::string target = arg;
    if (!target.empty() && target.back() == '/') {
        target.pop_back();
    }
    std::replace(target.begin(), target.end(), '.', '/');
    return target;
}

std::map<std::string, void (*)(int, char **)> functions = {
        {"--graph",        [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --graph <outputfile>\n", argv[0]);
            } else {
                FindCircularDependencies();
                OutputFlatDependencies(argv[2]);
            }
        }},
        {"--graph-cycles", [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --graph-cycles <outputfile>\n", argv[0]);
            } else {
                FindCircularDependencies();
                OutputCircularDependencies(argv[2]);
            }
        }},
        {"--graph-target", [](int argc, char **argv) {
            if (argc != 4) {
                printf("Usage: %s --graph-target <targetname> <outputfile>\n", argv[0]);
            } else {
                FindCircularDependencies();
                PrintGraphOnTarget(argv[3], components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--cycles",       [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --cycles <targetname>\n", argv[0]);
            } else {
                FindCircularDependencies();
                PrintCyclesForTarget(components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--stats",        [](int, char **) {
            std::size_t totalPublicLinks(0), totalPrivateLinks(0);
            for (const auto &c : components) {
                totalPublicLinks += c.second->pubDeps.size();
                totalPrivateLinks += c.second->privDeps.size();
            }
            fprintf(stderr, "%zu components with %zu public dependencies, %zu private dependencies\n",
                    components.size(), totalPublicLinks, totalPrivateLinks);
            FindCircularDependencies();
            fprintf(stderr, "Detected %zu nodes in cycles\n", NodesWithCycles());
        }},
        {"--inout",        [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --inout <targetname>\n", argv[0]);
            } else {
                PrintLinksForTarget(components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--shortest",     [](int argc, char **argv) {
            if (argc != 4) {
                printf("Usage: %s --shortest <targetname-from> <targetname-to>\n", argv[0]);
            } else {
                FindCircularDependencies();
                Component* from = components[std::string("./") + targetFrom(argv[2])],
                         * to = components[std::string("./") + targetFrom(argv[3])];
                if (!from) {
                    printf("No such component %s\n", argv[2]);
                } else if (!to) {
                    printf("No such component %s\n", argv[3]);
                } else {
                    FindSpecificLink(from, to);
                }
            }
        }},
        {"--info",         [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --info <targetname>\n", argv[0]);
            } else {
                PrintInfoOnTarget(components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--usedby",       [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --usedby <filename>\n", argv[0]);
            } else {
                auto f = &files[std::string("./") + argv[2]];
                for (auto &p : files) {
                    if (p.second.dependencies.find(f) != p.second.dependencies.end()) {
                        std::cout << p.second.path.string() << "\n";
                    }
                }
            }
        }},
        {"--regen",        [](int argc, char **argv) {
            boost::filesystem::current_path(root);
            if (argc >= 3) {
                for (int n = 2; n < argc; n++) {
                    if (components.find(targetFrom(argv[n])) != components.end()) {
                        RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], false);
                    } else {
                        std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n";
                    }
                }
            } else {
                for (auto &c : components) {
                    RegenerateCmakeFilesForComponent(c.second, false);
                }
            }
        }},
        {"--dryregen",     [](int argc, char **argv) {
            boost::filesystem::current_path(root);
            if (argc >= 3) {
                for (int n = 2; n < argc; n++) {
                    if (components.find(targetFrom(argv[n])) != components.end()) {
                        RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], true);
                    } else {
                        std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n";
                    }
                }
            } else {
                for (auto &c : components) {
                    RegenerateCmakeFilesForComponent(c.second, true);
                }
            }
        }},
        {"--outliers",       [](int, char**) {
            PrintAllComponents("Libraries with no links in:", [](const Component& c){
                return c.type == "library" &&
                    !c.files.empty() &&
                    c.pubLinks.empty() && c.privLinks.empty();
            });
            PrintAllComponents("Libraries with more than 30 outward links:", [](const Component& c){ return c.pubDeps.size() + c.privDeps.size() > 30; });
            PrintAllComponents("Libraries with less than 200 lines of code:", [](const Component& c) { return !c.files.empty() && c.loc() < 200; });
            PrintAllComponents("Libraries with more than 20000 lines of code:", [](const Component& c) { return c.loc() > 20000; });
            FindCircularDependencies();
            PrintAllComponents("Libraries that are part of a cycle:", [](const Component& c) { return !c.circulars.empty(); });
            PrintAllFiles("Files that are never used:", [](const File& f) { return !IsCompileableFile(f.path.extension().string()) && !f.hasInclude; });
            PrintAllFiles("Files with more than 2000 lines of code:", [](const File& f) { return f.loc > 2000; });
        }},
        {"--help",         [](int, char **argv) {
            printf("C++ Dependencies -- a tool to analyze large C++ code bases for #include dependency information\n");
            printf("Copyright (C) 2016, TomTom International BV\n");
            printf("\n");
            printf("  Usage:\n");
            printf("    %s [--dir <source-directory>] <command>\n", argv[0]);
            printf("    Source directory is assumed to be the current one if unspecified\n");
            printf("\n");
            printf("  Commands:\n");
            printf("  --help                        : Produce this help text\n");
            printf("\n");
            printf("  Extracting graphs:\n");
            printf("  --graph <output>              : Graph of all components with dependencies\n");
            printf("  --graph-cycles <output>       : Graph of components with cyclic dependencies on other components\n");
            printf("  --graph-for <output> <target> : Graph for all dependencies of a specific target\n");
            printf("\n");
            printf("  Getting information:\n");
            printf("  --stats                       : Info about code base size, complexity and cyclic dependency count\n");
            printf("  --cycles <targetname>         : Find all possible paths from this target back to itself\n");
            printf("  --shortest                    : Determine shortest path between components and its reason\n");
            printf("  --outliers                    : Finds all components and files that match a criterium for being out of the ordinary\n");
            printf("                                       - libraries that are not used\n");
            printf("                                       - components that use a lot of other components\n");
            printf("                                       - components with dependencies towards executables\n");
            printf("                                       - components with less than 200 LoC\n");
            printf("                                       - components with more than 20 kLoC\n");
            printf("                                       - components that are part of a cycle\n");
            printf("                                       - files that are more than 2000 LoC\n");
            printf("                                       - files that are not compiled and never included\n");
            printf("\n");
            printf("  Target information:\n");
            printf("  --info                        : Show all information on a given specific target\n");
            printf("  --usedby                      : Find all references to a specific header file\n");
            printf("  --inout                       : Find all incoming and outgoing links for a target\n");
            printf("  --ambiguous                   : Find all include statements that could refer to more than one header\n");
        }},
        // --ignore : Handled during input parsing as it is a pre-filter for CheckCycles instead.
};

int main(int argc, char **argv) {
    root = boost::filesystem::current_path();
    std::unordered_set<std::string> ignorefiles = {
            "unistd.h",
            "console.h",
            "stdint.h",
            "windows.h",
            "library.h",
            "endian.h",
            "rle.h",
    };
    if (argc > 1 && argv[1] == std::string("--dir")) {
        // Extract the root directory, reshuffle the other parameters.
        root = argv[2];
        argv[2] = argv[0];
        argv += 2;
        argc -= 2;
    }
    std::string command;
    if (argc > 1) {
        std::transform(argv[1], argv[1] + strlen(argv[1]), std::back_inserter(command), ::tolower);
    } else {
        command = "--help";
    }
    if (command == "--ignore") {
        for (int n = 2; n < argc; n++) {
            ignorefiles.insert(argv[n]);
        }
        argc = 1;
        command = "--stats";
    }
    if (command == "--regen" && !CheckVersionFile()) {
        fprintf(stderr,
                "Version of dependency checker not the same as the one used to generate the existing cmakelists. Refusing to regen\n"
                        "Please manually update " VERSION_FILE  " to version \"" CURRENT_VERSION "\" if you really want to do this.\n");
        command = "--dryregen";
    }

    LoadFileList(ignorefiles, root);
    {
        std::map<std::string, std::set<std::string>> collisions;
        std::unordered_map<std::string, std::string> includeLookup;
        CreateIncludeLookupTable(includeLookup, collisions);
        MapFilesToComponents();
        std::map<std::string, std::vector<std::string>> ambiguous;
        MapIncludesToDependencies(includeLookup, ambiguous);
        if (command == "--ambiguous") {
            printf("Found %zu ambiguous includes\n\n", ambiguous.size());
            for (auto &i : ambiguous) {
                printf("Include for %s\nFound in:\n", i.first.c_str());
                for (auto &s : i.second) {
                    printf("  included from %s\n", s.c_str());
                }
                printf("Options for file:\n");
                for (auto &c : collisions[i.first]) {
                    printf("  %s\n", c.c_str());
                }
                printf("\n");
            }
            exit(0);
        }

        for (auto &i : ambiguous) {
            for (auto &c : collisions[i.first]) {
                files[c].hasInclude = true; // There is at least one include that might end up here.
            }
        }
    }
    PropagateExternalIncludes();
    ExtractPublicDependencies();

    void (*function)(int, char **);
    function = functions[command];
    if (!function) {
        function = functions["--help"];
    }
    function(argc, argv);
    return 0;
}
<commit_msg>Added current version in help statement, closes #8<commit_after>/*
 * Copyright (C) 2012-2016. TomTom International BV (http://tomtom.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Component.h"
#include "Input.h"
#include "CmakeRegen.h"
#include "Output.h"
#include "Analysis.h"
#include "Constants.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

/**
 * These variables contain the global lists of components and files.
 * They are globally accessible.
 */
std::unordered_map<std::string, Component *> components;
std::unordered_map<std::string, File> files;

// Variable to contain the root of the source tree.
static boost::filesystem::path root;

static bool CheckVersionFile() {
    const std::string currentVersion = CURRENT_VERSION;
    std::string version;
    boost::filesystem::ifstream in(root / VERSION_FILE);
    getline(in, version);
    return (version == currentVersion);
}

std::string targetFrom(const std::string &arg) {
    std::string target = arg;
    if (!target.empty() && target.back() == '/') {
        target.pop_back();
    }
    std::replace(target.begin(), target.end(), '.', '/');
    return target;
}

std::map<std::string, void (*)(int, char **)> functions = {
        {"--graph",        [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --graph <outputfile>\n", argv[0]);
            } else {
                FindCircularDependencies();
                OutputFlatDependencies(argv[2]);
            }
        }},
        {"--graph-cycles", [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --graph-cycles <outputfile>\n", argv[0]);
            } else {
                FindCircularDependencies();
                OutputCircularDependencies(argv[2]);
            }
        }},
        {"--graph-target", [](int argc, char **argv) {
            if (argc != 4) {
                printf("Usage: %s --graph-target <targetname> <outputfile>\n", argv[0]);
            } else {
                FindCircularDependencies();
                PrintGraphOnTarget(argv[3], components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--cycles",       [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --cycles <targetname>\n", argv[0]);
            } else {
                FindCircularDependencies();
                PrintCyclesForTarget(components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--stats",        [](int, char **) {
            std::size_t totalPublicLinks(0), totalPrivateLinks(0);
            for (const auto &c : components) {
                totalPublicLinks += c.second->pubDeps.size();
                totalPrivateLinks += c.second->privDeps.size();
            }
            fprintf(stderr, "%zu components with %zu public dependencies, %zu private dependencies\n",
                    components.size(), totalPublicLinks, totalPrivateLinks);
            FindCircularDependencies();
            fprintf(stderr, "Detected %zu nodes in cycles\n", NodesWithCycles());
        }},
        {"--inout",        [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --inout <targetname>\n", argv[0]);
            } else {
                PrintLinksForTarget(components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--shortest",     [](int argc, char **argv) {
            if (argc != 4) {
                printf("Usage: %s --shortest <targetname-from> <targetname-to>\n", argv[0]);
            } else {
                FindCircularDependencies();
                Component* from = components[std::string("./") + targetFrom(argv[2])],
                         * to = components[std::string("./") + targetFrom(argv[3])];
                if (!from) {
                    printf("No such component %s\n", argv[2]);
                } else if (!to) {
                    printf("No such component %s\n", argv[3]);
                } else {
                    FindSpecificLink(from, to);
                }
            }
        }},
        {"--info",         [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --info <targetname>\n", argv[0]);
            } else {
                PrintInfoOnTarget(components[std::string("./") + targetFrom(argv[2])]);
            }
        }},
        {"--usedby",       [](int argc, char **argv) {
            if (argc != 3) {
                printf("Usage: %s --usedby <filename>\n", argv[0]);
            } else {
                auto f = &files[std::string("./") + argv[2]];
                for (auto &p : files) {
                    if (p.second.dependencies.find(f) != p.second.dependencies.end()) {
                        std::cout << p.second.path.string() << "\n";
                    }
                }
            }
        }},
        {"--regen",        [](int argc, char **argv) {
            boost::filesystem::current_path(root);
            if (argc >= 3) {
                for (int n = 2; n < argc; n++) {
                    if (components.find(targetFrom(argv[n])) != components.end()) {
                        RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], false);
                    } else {
                        std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n";
                    }
                }
            } else {
                for (auto &c : components) {
                    RegenerateCmakeFilesForComponent(c.second, false);
                }
            }
        }},
        {"--dryregen",     [](int argc, char **argv) {
            boost::filesystem::current_path(root);
            if (argc >= 3) {
                for (int n = 2; n < argc; n++) {
                    if (components.find(targetFrom(argv[n])) != components.end()) {
                        RegenerateCmakeFilesForComponent(components[targetFrom(argv[2])], true);
                    } else {
                        std::cout << "Target '" << targetFrom(argv[2]) << "' not found\n";
                    }
                }
            } else {
                for (auto &c : components) {
                    RegenerateCmakeFilesForComponent(c.second, true);
                }
            }
        }},
        {"--outliers",       [](int, char**) {
            PrintAllComponents("Libraries with no links in:", [](const Component& c){
                return c.type == "library" &&
                    !c.files.empty() &&
                    c.pubLinks.empty() && c.privLinks.empty();
            });
            PrintAllComponents("Libraries with more than 30 outward links:", [](const Component& c){ return c.pubDeps.size() + c.privDeps.size() > 30; });
            PrintAllComponents("Libraries with less than 200 lines of code:", [](const Component& c) { return !c.files.empty() && c.loc() < 200; });
            PrintAllComponents("Libraries with more than 20000 lines of code:", [](const Component& c) { return c.loc() > 20000; });
            FindCircularDependencies();
            PrintAllComponents("Libraries that are part of a cycle:", [](const Component& c) { return !c.circulars.empty(); });
            PrintAllFiles("Files that are never used:", [](const File& f) { return !IsCompileableFile(f.path.extension().string()) && !f.hasInclude; });
            PrintAllFiles("Files with more than 2000 lines of code:", [](const File& f) { return f.loc > 2000; });
        }},
        {"--help",         [](int, char **argv) {
            printf("C++ Dependencies -- a tool to analyze large C++ code bases for #include dependency information\n");
            printf("Copyright (C) 2016, TomTom International BV\n");
            printf("Version " CURRENT_VERSION "\n");
            printf("\n");
            printf("  Usage:\n");
            printf("    %s [--dir <source-directory>] <command>\n", argv[0]);
            printf("    Source directory is assumed to be the current one if unspecified\n");
            printf("\n");
            printf("  Commands:\n");
            printf("  --help                        : Produce this help text\n");
            printf("\n");
            printf("  Extracting graphs:\n");
            printf("  --graph <output>              : Graph of all components with dependencies\n");
            printf("  --graph-cycles <output>       : Graph of components with cyclic dependencies on other components\n");
            printf("  --graph-for <output> <target> : Graph for all dependencies of a specific target\n");
            printf("\n");
            printf("  Getting information:\n");
            printf("  --stats                       : Info about code base size, complexity and cyclic dependency count\n");
            printf("  --cycles <targetname>         : Find all possible paths from this target back to itself\n");
            printf("  --shortest                    : Determine shortest path between components and its reason\n");
            printf("  --outliers                    : Finds all components and files that match a criterium for being out of the ordinary\n");
            printf("                                       - libraries that are not used\n");
            printf("                                       - components that use a lot of other components\n");
            printf("                                       - components with dependencies towards executables\n");
            printf("                                       - components with less than 200 LoC\n");
            printf("                                       - components with more than 20 kLoC\n");
            printf("                                       - components that are part of a cycle\n");
            printf("                                       - files that are more than 2000 LoC\n");
            printf("                                       - files that are not compiled and never included\n");
            printf("\n");
            printf("  Target information:\n");
            printf("  --info                        : Show all information on a given specific target\n");
            printf("  --usedby                      : Find all references to a specific header file\n");
            printf("  --inout                       : Find all incoming and outgoing links for a target\n");
            printf("  --ambiguous                   : Find all include statements that could refer to more than one header\n");
        }},
        // --ignore : Handled during input parsing as it is a pre-filter for CheckCycles instead.
};

int main(int argc, char **argv) {
    root = boost::filesystem::current_path();
    std::unordered_set<std::string> ignorefiles = {
            "unistd.h",
            "console.h",
            "stdint.h",
            "windows.h",
            "library.h",
            "endian.h",
            "rle.h",
    };
    if (argc > 1 && argv[1] == std::string("--dir")) {
        // Extract the root directory, reshuffle the other parameters.
        root = argv[2];
        argv[2] = argv[0];
        argv += 2;
        argc -= 2;
    }
    std::string command;
    if (argc > 1) {
        std::transform(argv[1], argv[1] + strlen(argv[1]), std::back_inserter(command), ::tolower);
    } else {
        command = "--help";
    }
    if (command == "--ignore") {
        for (int n = 2; n < argc; n++) {
            ignorefiles.insert(argv[n]);
        }
        argc = 1;
        command = "--stats";
    }
    if (command == "--regen" && !CheckVersionFile()) {
        fprintf(stderr,
                "Version of dependency checker not the same as the one used to generate the existing cmakelists. Refusing to regen\n"
                        "Please manually update " VERSION_FILE  " to version \"" CURRENT_VERSION "\" if you really want to do this.\n");
        command = "--dryregen";
    }

    LoadFileList(ignorefiles, root);
    {
        std::map<std::string, std::set<std::string>> collisions;
        std::unordered_map<std::string, std::string> includeLookup;
        CreateIncludeLookupTable(includeLookup, collisions);
        MapFilesToComponents();
        std::map<std::string, std::vector<std::string>> ambiguous;
        MapIncludesToDependencies(includeLookup, ambiguous);
        if (command == "--ambiguous") {
            printf("Found %zu ambiguous includes\n\n", ambiguous.size());
            for (auto &i : ambiguous) {
                printf("Include for %s\nFound in:\n", i.first.c_str());
                for (auto &s : i.second) {
                    printf("  included from %s\n", s.c_str());
                }
                printf("Options for file:\n");
                for (auto &c : collisions[i.first]) {
                    printf("  %s\n", c.c_str());
                }
                printf("\n");
            }
            exit(0);
        }

        for (auto &i : ambiguous) {
            for (auto &c : collisions[i.first]) {
                files[c].hasInclude = true; // There is at least one include that might end up here.
            }
        }
    }
    PropagateExternalIncludes();
    ExtractPublicDependencies();

    void (*function)(int, char **);
    function = functions[command];
    if (!function) {
        function = functions["--help"];
    }
    function(argc, argv);
    return 0;
}
<|endoftext|>


<commit_before>#include "main.h"
#include "natives.h"
#include "CTeamspeak.h"
#include "CCallback.h"

extern void *pAMXFunctions;
logprintf_t logprintf;

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
	CCallback::Process();
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	logprintf = reinterpret_cast<logprintf_t>(ppData[PLUGIN_DATA_LOGPRINTF]);

	logprintf(" >> plugin.TSConnector: v0.6.1 loaded.");
	return 1;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
	CTeamspeak::Get()->Destroy();

	logprintf("plugin.TSConnector: Plugin unloaded.");
}

extern "C" const AMX_NATIVE_INFO native_list[] =
{
	AMX_DEFINE_NATIVE(TSC_Connect)
	AMX_DEFINE_NATIVE(TSC_Disconnect)
	AMX_DEFINE_NATIVE(TSC_Login)
	AMX_DEFINE_NATIVE(TSC_ChangeNickname)

	AMX_DEFINE_NATIVE(TSC_CreateChannel)
	AMX_DEFINE_NATIVE(TSC_DeleteChannel)
	AMX_DEFINE_NATIVE(TSC_SetChannelName)
	AMX_DEFINE_NATIVE(TSC_SetChannelDescription)
	AMX_DEFINE_NATIVE(TSC_SetChannelType)
	AMX_DEFINE_NATIVE(TSC_SetChannelPassword)
	AMX_DEFINE_NATIVE(TSC_SetChannelTalkPower)
	AMX_DEFINE_NATIVE(TSC_SetChannelUserLimit)
	AMX_DEFINE_NATIVE(TSC_SetChannelSubChannel)
	AMX_DEFINE_NATIVE(TSC_MoveChannelBelowChannel)

	AMX_DEFINE_NATIVE(TSC_KickClient)
	AMX_DEFINE_NATIVE(TSC_BanClient)
	AMX_DEFINE_NATIVE(TSC_MoveClient)

	AMX_DEFINE_NATIVE(TSC_SetClientChannelGroup)
	AMX_DEFINE_NATIVE(TSC_AddClientToServerGroup)
	AMX_DEFINE_NATIVE(TSC_RemoveClientFromServerGroup)
	AMX_DEFINE_NATIVE(TSC_ToggleClientTalkAbility)

	AMX_DEFINE_NATIVE(TSC_PokeClient)

	AMX_DEFINE_NATIVE(TSC_SendClientMessage)
	AMX_DEFINE_NATIVE(TSC_SendChannelMessage)
	AMX_DEFINE_NATIVE(TSC_SendServerMessage)

	{NULL, NULL}
};

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
	CCallback::AddAmxInstance(amx);
	return amx_Register(amx, native_list, -1);
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
	CCallback::RemoveAmxInstance(amx);
	return AMX_ERR_NONE;
}
<commit_msg>v0.6.2<commit_after>#include "main.h"
#include "natives.h"
#include "CTeamspeak.h"
#include "CCallback.h"

extern void *pAMXFunctions;
logprintf_t logprintf;

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
	CCallback::Process();
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	logprintf = reinterpret_cast<logprintf_t>(ppData[PLUGIN_DATA_LOGPRINTF]);

	logprintf(" >> plugin.TSConnector: v0.6.2 loaded.");
	return 1;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
	CTeamspeak::Get()->Destroy();

	logprintf("plugin.TSConnector: Plugin unloaded.");
}

extern "C" const AMX_NATIVE_INFO native_list[] =
{
	AMX_DEFINE_NATIVE(TSC_Connect)
	AMX_DEFINE_NATIVE(TSC_Disconnect)
	AMX_DEFINE_NATIVE(TSC_Login)
	AMX_DEFINE_NATIVE(TSC_ChangeNickname)

	AMX_DEFINE_NATIVE(TSC_CreateChannel)
	AMX_DEFINE_NATIVE(TSC_DeleteChannel)
	AMX_DEFINE_NATIVE(TSC_SetChannelName)
	AMX_DEFINE_NATIVE(TSC_SetChannelDescription)
	AMX_DEFINE_NATIVE(TSC_SetChannelType)
	AMX_DEFINE_NATIVE(TSC_SetChannelPassword)
	AMX_DEFINE_NATIVE(TSC_SetChannelTalkPower)
	AMX_DEFINE_NATIVE(TSC_SetChannelUserLimit)
	AMX_DEFINE_NATIVE(TSC_SetChannelSubChannel)
	AMX_DEFINE_NATIVE(TSC_MoveChannelBelowChannel)

	AMX_DEFINE_NATIVE(TSC_KickClient)
	AMX_DEFINE_NATIVE(TSC_BanClient)
	AMX_DEFINE_NATIVE(TSC_MoveClient)

	AMX_DEFINE_NATIVE(TSC_SetClientChannelGroup)
	AMX_DEFINE_NATIVE(TSC_AddClientToServerGroup)
	AMX_DEFINE_NATIVE(TSC_RemoveClientFromServerGroup)
	AMX_DEFINE_NATIVE(TSC_ToggleClientTalkAbility)

	AMX_DEFINE_NATIVE(TSC_PokeClient)

	AMX_DEFINE_NATIVE(TSC_SendClientMessage)
	AMX_DEFINE_NATIVE(TSC_SendChannelMessage)
	AMX_DEFINE_NATIVE(TSC_SendServerMessage)

	{NULL, NULL}
};

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
	CCallback::AddAmxInstance(amx);
	return amx_Register(amx, native_list, -1);
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
	CCallback::RemoveAmxInstance(amx);
	return AMX_ERR_NONE;
}
<|endoftext|>


<commit_before>/*
 * Blink
 * Turns on an LED on for one second,
 * then off for one second, repeatedly.
 */

#include "Arduino.h"

// Set LED_BUILTIN if it is not defined by Arduino framework
// #define LED_BUILTIN 13

void setup()
{
  // initialize LED digital pin as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, HIGH);
  // wait for a second
  delay(1000);
  // turn the LED off by making the voltage LOW
  digitalWrite(LED_BUILTIN, LOW);
   // wait for a second
  delay(1000);
}
<commit_msg>Turn light off :bulb:<commit_after>/*
 * Blink
 * Turns on an LED on for one second,
 * then off for one second, repeatedly.
 */

#include "Arduino.h"

// Set LED_BUILTIN if it is not defined by Arduino framework
// #define LED_BUILTIN 13

void setup()
{
  // initialize LED digital pin as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  // // turn the LED on (HIGH is the voltage level)
  // digitalWrite(LED_BUILTIN, HIGH);
  // // wait for a second
  // delay(1000);
  // turn the LED off by making the voltage LOW
  digitalWrite(LED_BUILTIN, LOW);
   // wait for a second
  delay(1000);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

class member {
  public:
  std::string username;
  std::string inventory[4000];
  int inventoryQuantities[4000];
  std::string gainedInventory[4000];
  int gainedQuantites[4000];
  int startCoins;
  public:
    void buy(std::string);
    void sell(std::string);
    void createItems(std::string);
    void destroyItems(std::string);
    void storeNewItem(std::string);

};
int answer;
int main()
{
  member mem1;
  member mem2;
  std::cout << "welcome to star Craft v0.0.1" << std::endl;
  std::cout << "1. Start a username" << std::endl;
  std::cout << "0. exit" << std::endl;
  std::cin >> answer;
  if(answer == 1)
  {
    std::cout << "What is your username to be?" << std::endl;
    std::cin >> mem1.username;
    std::cout << mem1.username << std::endl;

  }
  return 0;

}
<commit_msg>more knowledge more power<commit_after>#include <iostream>
#include <string>

class member {
  public:
  int starCoins;
  std::string username;
  std::string inventory[4000];
  int inventoryQuantities[4000];
  std::string gainedInventory[4000];
  int gainedQuantites[4000];
  public:
    void buy(std::string);
    void sell(std::string);
    void createItems(std::string);
    void destroyItems(std::string);
    void storeNewItem(std::string);
    void loadCoins(std::string)
    {
      starCoins = 10000;
    }
};

int answer;
int main()
{
  member mem1;
  member mem2;
  std::cout << "welcome to star Craft v0.0.1" << std::endl;
  std::cout << "1. Start a username" << std::endl;
  std::cout << "0. exit" << std::endl;
  std::cin >> answer;
  if(answer == 1)
  {
    std::cout << "What is your username to be?" << std::endl;
    std::cin >> mem1.username;
    std::cout << mem1.username << std::endl;
    mem1.loadCoins(mem1.username);
    std::cout << mem1.starCoins << std::endl;
  }
  std::cout << mem1.username << " you'll start off with " << mem1.startCoins << " startCoins, use them wisely"
    << std::endl;

  return 0;

}
<|endoftext|>


<commit_before>// sota.cpp : Defines the entry point for the console application.
//
#include <array>
#include <string>
#include <iostream>
#include <exception>

#include "ast.h"
#include "token.h"
#include "parser.h"
#include "grammar.h"

using namespace sota;

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

    std::string source = "1 + 2";

    auto parser = Parser(Type2Symbol);
    parser.Source = source;
    auto token = parser.Scan();

    return 0;
}
<commit_msg>demo of lookahead capabilities... -sai<commit_after>// sota.cpp : Defines the entry point for the console application.
//
#include <array>
#include <string>
#include <iostream>
#include <exception>

#include "ast.h"
#include "token.h"
#include "parser.h"
#include "grammar.h"

using namespace sota;

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

    std::string source = "1 + 2";

    auto parser = Parser(Type2Symbol);
    parser.Source = source;
    auto token = parser.LookAhead(5);
    std::cout << token << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2015-2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "sync.h"

#include "util.h"
#include "utilstrencodings.h"

#include <boost/thread/tss.hpp> // for boost::thread_specific_ptr
#include <stdio.h>
#include <thread>

#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char *pszName, const char *pszFile, unsigned int nLine)
{
    LOGA("LOCKCONTENTION: %s\n", pszName);
    LOGA("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */

void EnterCritical(const char *pszName, const char *pszFile, unsigned int nLine, void *cs, bool fTry)
{
}
void LeaveCritical()
{
}
void DeleteCritical(const void *cs)
{
}

void AssertLockHeldInternal(const char *pszName, const char *pszFile, unsigned int nLine, void *cs)
{

}

void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, unsigned int nLine, void *cs)
{

}

void AssertWriteLockHeldInternal(const char *pszName,
    const char *pszFile,
    unsigned int nLine,
    CSharedCriticalSection *cs)
{
    if (cs->try_lock()) // It would be better to check that this thread has the lock
    {
        fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine,
            LocksHeld().c_str());
        fflush(stderr);
        abort();
    }
}

void AssertRecursiveWriteLockHeldInternal(const char *pszName,
    const char *pszFile,
    unsigned int nLine,
    CRecursiveSharedCriticalSection *cs)
{
    if (cs->try_lock()) // It would be better to check that this thread has the lock
    {
        fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine,
            LocksHeld().c_str());
        fflush(stderr);
        abort();
    }
}

// BU normally CCriticalSection is a typedef, but when lockorder debugging is on we need to delete the critical
// section from the lockorder map
#ifdef DEBUG_LOCKORDER
CCriticalSection::CCriticalSection() : name(nullptr) {}
CCriticalSection::CCriticalSection(const char *n) : name(n)
{
// print the address of named critical sections so they can be found in the mutrace output
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("CCriticalSection %s at %p\n", name, this);
        fflush(stdout);
    }
#endif
}

CCriticalSection::~CCriticalSection()
{
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("Destructing %s\n", name);
        fflush(stdout);
    }
#endif
    DeleteCritical((void *)this);
}
#endif

// BU normally CSharedCriticalSection is a typedef, but when lockorder debugging is on we need to delete the critical
// section from the lockorder map
#ifdef DEBUG_LOCKORDER
CSharedCriticalSection::CSharedCriticalSection() : name(nullptr) {}
CSharedCriticalSection::CSharedCriticalSection(const char *n) : name(n)
{
// print the address of named critical sections so they can be found in the mutrace output
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("CSharedCriticalSection %s at %p\n", name, this);
        fflush(stdout);
    }
#endif
}

CSharedCriticalSection::~CSharedCriticalSection()
{
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("Destructing CSharedCriticalSection %s\n", name);
        fflush(stdout);
    }
#endif
    DeleteCritical((void *)this);
}
#endif

CRecursiveSharedCriticalSection::CRecursiveSharedCriticalSection() : name(nullptr) {}
CRecursiveSharedCriticalSection::CRecursiveSharedCriticalSection(const char *n) : name(n)
{
// print the address of named critical sections so they can be found in the mutrace output
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("CRecursiveSharedCriticalSection %s at %p\n", name, this);
        fflush(stdout);
    }
#endif
}

CRecursiveSharedCriticalSection::~CRecursiveSharedCriticalSection()
{
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("Destructing CRecursiveSharedCriticalSection %s\n", name);
        fflush(stdout);
    }
#endif
    DeleteCritical((void *)this);
}

#endif /* DEBUG_LOCKORDER */
<commit_msg>fix needless ifdefs to a single ifdef for DEBUG_LOCKORDER for the file<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2015-2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "sync.h"

#include "util.h"
#include "utilstrencodings.h"

#include <boost/thread/tss.hpp> // for boost::thread_specific_ptr
#include <stdio.h>
#include <thread>

#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char *pszName, const char *pszFile, unsigned int nLine)
{
    LOGA("LOCKCONTENTION: %s\n", pszName);
    LOGA("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */

#ifdef DEBUG_LOCKORDER // this ifdef covers the rest of the file

void EnterCritical(const char *pszName, const char *pszFile, unsigned int nLine, void *cs, bool fTry)
{
}
void LeaveCritical()
{
}
void DeleteCritical(const void *cs)
{
}

void AssertLockHeldInternal(const char *pszName, const char *pszFile, unsigned int nLine, void *cs)
{

}

void AssertLockNotHeldInternal(const char *pszName, const char *pszFile, unsigned int nLine, void *cs)
{

}

void AssertWriteLockHeldInternal(const char *pszName,
    const char *pszFile,
    unsigned int nLine,
    CSharedCriticalSection *cs)
{
    if (cs->try_lock()) // It would be better to check that this thread has the lock
    {
        fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine,
            LocksHeld().c_str());
        fflush(stderr);
        abort();
    }
}

void AssertRecursiveWriteLockHeldInternal(const char *pszName,
    const char *pszFile,
    unsigned int nLine,
    CRecursiveSharedCriticalSection *cs)
{
    if (cs->try_lock()) // It would be better to check that this thread has the lock
    {
        fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine,
            LocksHeld().c_str());
        fflush(stderr);
        abort();
    }
}

// BU normally CCriticalSection is a typedef, but when lockorder debugging is on we need to delete the critical
// section from the lockorder map
CCriticalSection::CCriticalSection() : name(nullptr) {}
CCriticalSection::CCriticalSection(const char *n) : name(n)
{
// print the address of named critical sections so they can be found in the mutrace output
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("CCriticalSection %s at %p\n", name, this);
        fflush(stdout);
    }
#endif
}

CCriticalSection::~CCriticalSection()
{
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("Destructing %s\n", name);
        fflush(stdout);
    }
#endif
    DeleteCritical((void *)this);
}

// BU normally CSharedCriticalSection is a typedef, but when lockorder debugging is on we need to delete the critical
// section from the lockorder map
CSharedCriticalSection::CSharedCriticalSection() : name(nullptr) {}
CSharedCriticalSection::CSharedCriticalSection(const char *n) : name(n)
{
// print the address of named critical sections so they can be found in the mutrace output
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("CSharedCriticalSection %s at %p\n", name, this);
        fflush(stdout);
    }
#endif
}

CSharedCriticalSection::~CSharedCriticalSection()
{
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("Destructing CSharedCriticalSection %s\n", name);
        fflush(stdout);
    }
#endif
    DeleteCritical((void *)this);
}

CRecursiveSharedCriticalSection::CRecursiveSharedCriticalSection() : name(nullptr) {}
CRecursiveSharedCriticalSection::CRecursiveSharedCriticalSection(const char *n) : name(n)
{
// print the address of named critical sections so they can be found in the mutrace output
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("CRecursiveSharedCriticalSection %s at %p\n", name, this);
        fflush(stdout);
    }
#endif
}

CRecursiveSharedCriticalSection::~CRecursiveSharedCriticalSection()
{
#ifdef ENABLE_MUTRACE
    if (name)
    {
        printf("Destructing CRecursiveSharedCriticalSection %s\n", name);
        fflush(stdout);
    }
#endif
    DeleteCritical((void *)this);
}

#endif /* DEBUG_LOCKORDER */
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * X testing environment - Google Test environment feat. dummy x server
 *
 * Copyright (C) 2011, 2012 Canonical Ltd.
 * Copyright © 2012 Red Hat, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 ******************************************************************************/

#include "xorg/gtest/xorg-gtest-test.h"

#include <stdexcept>

#include <X11/Xlib.h>

struct xorg::testing::Test::Private {
  ::Display* display;
  std::string display_string;
};

xorg::testing::Test::Test() : d_(new Private) {
  d_->display = NULL;
}

xorg::testing::Test::~Test() {}

void xorg::testing::Test::SetUp() {
  const char *dpy = NULL;

  if (!d_->display_string.empty())
    dpy = d_->display_string.c_str();

  d_->display = XOpenDisplay(dpy);
  if (!d_->display)
    throw std::runtime_error("Failed to open connection to display");
}

void xorg::testing::Test::TearDown() {
  if (d_->display)
    XCloseDisplay(d_->display);
  d_->display = NULL;
}

::Display* xorg::testing::Test::Display() const {
  return d_->display;
}

void xorg::testing::Test::SetDisplayString(const std::string &display) {
  d_->display_string = display;
}
<commit_msg>Expand on the default 'failed to open connection to display' error<commit_after>/*******************************************************************************
 *
 * X testing environment - Google Test environment feat. dummy x server
 *
 * Copyright (C) 2011, 2012 Canonical Ltd.
 * Copyright © 2012 Red Hat, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 ******************************************************************************/

#include "xorg/gtest/xorg-gtest-test.h"

#include <stdexcept>

#include <X11/Xlib.h>

struct xorg::testing::Test::Private {
  ::Display* display;
  std::string display_string;
};

xorg::testing::Test::Test() : d_(new Private) {
  d_->display = NULL;
}

xorg::testing::Test::~Test() {}

void xorg::testing::Test::SetUp() {
  const char *dpy = NULL;

  if (!d_->display_string.empty())
    dpy = d_->display_string.c_str();

  d_->display = XOpenDisplay(dpy);
  if (!d_->display) {
    std::stringstream ss;
    ss << "Failed to open connection to display";
    if (dpy != NULL) ss << " " << dpy;
    ss << ".\nThis usually means that your X server did not start properly.\n";
    ss << "Check the log file, or set XORG_GTEST_CHILD_STDOUT to see the server's\n"
          "error messages when starting.";
    throw std::runtime_error(ss.str());
  }
}

void xorg::testing::Test::TearDown() {
  if (d_->display)
    XCloseDisplay(d_->display);
  d_->display = NULL;
}

::Display* xorg::testing::Test::Display() const {
  return d_->display;
}

void xorg::testing::Test::SetDisplayString(const std::string &display) {
  d_->display_string = display;
}
<|endoftext|>


<commit_before>#include "BehaviorTree.h"

using namespace BT;

int main(int argc, char **argv)
{
    try
    {
        int TickPeriod_milliseconds = 1000;

        ActionTestNode* test1 = new ActionTestNode("A1");
        ActionTestNode* test2 = new ActionTestNode("A2");
        ActionTestNode* test3 = new ActionTestNode("A3");
        ActionTestNode* test4 = new ActionTestNode("A4");

        SequenceStarNode* sequence1 = new SequenceStarNode("seq1");
        SelectorStarNode* selector1 = new SelectorStarNode("sel1");
        SelectorStarNode* selector2 = new SelectorStarNode("sel12");

        SequenceStarNode* root = new SequenceStarNode("root");

        test1->SetBehavior(Success);
        test1->SetTime(3);
        test2->SetBehavior(Success);
        test2->SetTime(2);
        test3->SetBehavior(Failure);
        test4->SetBehavior(Success);

        selector1->AddChild(test1);
        selector1->AddChild(test2);

        selector2->AddChild(test3);
        selector2->AddChild(test4);

        root->AddChild(selector1);
        root->AddChild(selector2);

        Execute(root, TickPeriod_milliseconds);//from BehaviorTree.cpp
}
    catch (BehaviorTreeException& Exception)
    {
        std::cout << Exception.what() << std::endl;
    }

return 0;
}

<commit_msg>Update test.cpp<commit_after>#include "BehaviorTree.h"

using namespace BT;

int main(int argc, char **argv)
{
    try
    {
        int TickPeriod_milliseconds = 1000;

        ActionTestNode* test1 = new ActionTestNode("A1");
        ActionTestNode* test2 = new ActionTestNode("A2");
        ActionTestNode* test3 = new ActionTestNode("A3");
        ActionTestNode* test4 = new ActionTestNode("A4");

        SequenceStarNode* sequence1 = new SequenceStarNode("seq1");
        SelectorStarNode* selector1 = new SelectorStarNode("sel1");
        SelectorStarNode* selector2 = new SelectorStarNode("sel12");

        SequenceStarNode* root = new SequenceStarNode("root");

        test1->SetBehavior(Success);
        test1->SetTime(3);
        test2->SetBehavior(Success);
        test2->SetTime(2);
        test3->SetBehavior(Failure);
        test4->SetBehavior(Success);
        test4->SetTime(5);

        selector1->AddChild(test1);
        selector1->AddChild(test2);

        selector2->AddChild(test3);
        selector2->AddChild(test4);

        root->AddChild(selector1);
        root->AddChild(selector2);

        Execute(root, TickPeriod_milliseconds);//from BehaviorTree.cpp
}
    catch (BehaviorTreeException& Exception)
    {
        std::cout << Exception.what() << std::endl;
    }

return 0;
}

<|endoftext|>


<commit_before>#include "opml.h"

#include <cassert>
#include <cstring>

namespace newsboat {

xmlDocPtr OPML::generate_opml(const FeedContainer& feedcontainer)
{
	xmlDocPtr root = xmlNewDoc((const xmlChar*)"1.0");
	xmlNodePtr opml_node =
		xmlNewDocNode(root, nullptr, (const xmlChar*)"opml", nullptr);
	xmlSetProp(opml_node, (const xmlChar*)"version", (const xmlChar*)"1.0");
	xmlDocSetRootElement(root, opml_node);

	xmlNodePtr head = xmlNewTextChild(
		opml_node, nullptr, (const xmlChar*)"head", nullptr);
	xmlNewTextChild(head,
		nullptr,
		(const xmlChar*)"title",
		(const xmlChar*)PROGRAM_NAME " - Exported Feeds");
	xmlNodePtr body = xmlNewTextChild(
		opml_node, nullptr, (const xmlChar*)"body", nullptr);

	for (const auto& feed : feedcontainer.feeds) {
		if (!utils::is_special_url(feed->rssurl())) {
			std::string rssurl = feed->rssurl();
			std::string link = feed->link();
			std::string title = feed->title();

			xmlNodePtr outline = xmlNewTextChild(body,
				nullptr,
				(const xmlChar*)"outline",
				nullptr);
			xmlSetProp(outline,
				(const xmlChar*)"type",
				(const xmlChar*)"rss");
			xmlSetProp(outline,
				(const xmlChar*)"xmlUrl",
				(const xmlChar*)rssurl.c_str());
			xmlSetProp(outline,
				(const xmlChar*)"htmlUrl",
				(const xmlChar*)link.c_str());
			xmlSetProp(outline,
				(const xmlChar*)"title",
				(const xmlChar*)title.c_str());
		}
	}

	return root;
}

void rec_find_rss_outlines(
		urlreader* urlcfg,
		xmlNode* node,
		std::string tag)
{
	while (node) {
		std::string newtag = tag;

		if (strcmp((const char*)node->name, "outline") == 0) {
			char* url = (char*)xmlGetProp(
				node, (const xmlChar*)"xmlUrl");
			if (!url) {
				url = (char*)xmlGetProp(
					node, (const xmlChar*)"url");
			}

			if (url) {
				LOG(level::DEBUG,
					"OPML::import: found RSS outline with "
					"url = "
					"%s",
					url);

				std::string nurl = std::string(url);

				// Liferea uses a pipe to signal feeds read from
				// the output of a program in its OPMLs. Convert
				// them to our syntax.
				if (*url == '|') {
					nurl = strprintf::fmt(
						"exec:%s", url + 1);
					LOG(level::DEBUG,
						"OPML::import: liferea-style "
						"url %s "
						"converted to %s",
						url,
						nurl);
				}

				// Handle OPML filters.
				char* filtercmd = (char*)xmlGetProp(
					node, (const xmlChar*)"filtercmd");
				if (filtercmd) {
					LOG(level::DEBUG,
						"OPML::import: adding filter "
						"command %s to url %s",
						filtercmd,
						nurl);
					nurl.insert(0,
						strprintf::fmt("filter:%s:",
							filtercmd));
					xmlFree(filtercmd);
				}

				xmlFree(url);
				// Filters and scripts may have arguments, so,
				// quote them when needed.
				// TODO: get rid of xmlStrdup, it's useless
				url = (char*)xmlStrdup(
					(const xmlChar*)
						utils::quote_if_necessary(nurl)
							.c_str());
				assert(url);

				bool found = false;

				LOG(level::DEBUG,
					"OPML::import: size = %u",
					urlcfg->get_urls().size());
				// TODO: replace with algorithm::any or something
				if (urlcfg->get_urls().size() > 0) {
					for (const auto& u :
						urlcfg->get_urls()) {
						if (u == url) {
							found = true;
						}
					}
				}

				if (!found) {
					LOG(level::DEBUG,
						"OPML::import: added url = %s",
						url);
					urlcfg->get_urls().push_back(
						std::string(url));
					if (tag.length() > 0) {
						LOG(level::DEBUG,
							"OPML::import: "
							"appending "
							"tag %s to url %s",
							tag,
							url);
						urlcfg->get_tags(url).push_back(
							tag);
					}
				} else {
					LOG(level::DEBUG,
						"OPML::import: url = %s is "
						"already "
						"in list",
						url);
				}
				xmlFree(url);
			} else {
				char* text = (char*)xmlGetProp(
					node, (const xmlChar*)"text");
				if (!text)
					text = (char*)xmlGetProp(
						node, (const xmlChar*)"title");
				if (text) {
					if (newtag.length() > 0) {
						newtag.append("/");
					}
					newtag.append(text);
					xmlFree(text);
				}
			}
		}
		rec_find_rss_outlines(urlcfg, node->children, newtag);

		node = node->next;
	}
}

bool OPML::import(
		const std::string& filename,
		urlreader* urlcfg)
{
	xmlDoc* doc = xmlReadFile(filename.c_str(), nullptr, 0);
	if (doc == nullptr) {
		return false;
	}

	xmlNode* root = xmlDocGetRootElement(doc);

	for (xmlNode* node = root->children; node != nullptr;
		node = node->next) {
		if (strcmp((const char*)node->name, "body") == 0) {
			LOG(level::DEBUG, "OPML::import: found body");
			rec_find_rss_outlines(urlcfg, node->children, "");
			urlcfg->write_config();
		}
	}

	xmlFreeDoc(doc);

	return true;
}

} // namespace newsboat
<commit_msg>opml.cpp: always use curly braces around `if` blocks<commit_after>#include "opml.h"

#include <cassert>
#include <cstring>

namespace newsboat {

xmlDocPtr OPML::generate_opml(const FeedContainer& feedcontainer)
{
	xmlDocPtr root = xmlNewDoc((const xmlChar*)"1.0");
	xmlNodePtr opml_node =
		xmlNewDocNode(root, nullptr, (const xmlChar*)"opml", nullptr);
	xmlSetProp(opml_node, (const xmlChar*)"version", (const xmlChar*)"1.0");
	xmlDocSetRootElement(root, opml_node);

	xmlNodePtr head = xmlNewTextChild(
		opml_node, nullptr, (const xmlChar*)"head", nullptr);
	xmlNewTextChild(head,
		nullptr,
		(const xmlChar*)"title",
		(const xmlChar*)PROGRAM_NAME " - Exported Feeds");
	xmlNodePtr body = xmlNewTextChild(
		opml_node, nullptr, (const xmlChar*)"body", nullptr);

	for (const auto& feed : feedcontainer.feeds) {
		if (!utils::is_special_url(feed->rssurl())) {
			std::string rssurl = feed->rssurl();
			std::string link = feed->link();
			std::string title = feed->title();

			xmlNodePtr outline = xmlNewTextChild(body,
				nullptr,
				(const xmlChar*)"outline",
				nullptr);
			xmlSetProp(outline,
				(const xmlChar*)"type",
				(const xmlChar*)"rss");
			xmlSetProp(outline,
				(const xmlChar*)"xmlUrl",
				(const xmlChar*)rssurl.c_str());
			xmlSetProp(outline,
				(const xmlChar*)"htmlUrl",
				(const xmlChar*)link.c_str());
			xmlSetProp(outline,
				(const xmlChar*)"title",
				(const xmlChar*)title.c_str());
		}
	}

	return root;
}

void rec_find_rss_outlines(
		urlreader* urlcfg,
		xmlNode* node,
		std::string tag)
{
	while (node) {
		std::string newtag = tag;

		if (strcmp((const char*)node->name, "outline") == 0) {
			char* url = (char*)xmlGetProp(
				node, (const xmlChar*)"xmlUrl");
			if (!url) {
				url = (char*)xmlGetProp(
					node, (const xmlChar*)"url");
			}

			if (url) {
				LOG(level::DEBUG,
					"OPML::import: found RSS outline with "
					"url = "
					"%s",
					url);

				std::string nurl = std::string(url);

				// Liferea uses a pipe to signal feeds read from
				// the output of a program in its OPMLs. Convert
				// them to our syntax.
				if (*url == '|') {
					nurl = strprintf::fmt(
						"exec:%s", url + 1);
					LOG(level::DEBUG,
						"OPML::import: liferea-style "
						"url %s "
						"converted to %s",
						url,
						nurl);
				}

				// Handle OPML filters.
				char* filtercmd = (char*)xmlGetProp(
					node, (const xmlChar*)"filtercmd");
				if (filtercmd) {
					LOG(level::DEBUG,
						"OPML::import: adding filter "
						"command %s to url %s",
						filtercmd,
						nurl);
					nurl.insert(0,
						strprintf::fmt("filter:%s:",
							filtercmd));
					xmlFree(filtercmd);
				}

				xmlFree(url);
				// Filters and scripts may have arguments, so,
				// quote them when needed.
				// TODO: get rid of xmlStrdup, it's useless
				url = (char*)xmlStrdup(
					(const xmlChar*)
						utils::quote_if_necessary(nurl)
							.c_str());
				assert(url);

				bool found = false;

				LOG(level::DEBUG,
					"OPML::import: size = %u",
					urlcfg->get_urls().size());
				// TODO: replace with algorithm::any or something
				if (urlcfg->get_urls().size() > 0) {
					for (const auto& u :
						urlcfg->get_urls()) {
						if (u == url) {
							found = true;
						}
					}
				}

				if (!found) {
					LOG(level::DEBUG,
						"OPML::import: added url = %s",
						url);
					urlcfg->get_urls().push_back(
						std::string(url));
					if (tag.length() > 0) {
						LOG(level::DEBUG,
							"OPML::import: "
							"appending "
							"tag %s to url %s",
							tag,
							url);
						urlcfg->get_tags(url).push_back(
							tag);
					}
				} else {
					LOG(level::DEBUG,
						"OPML::import: url = %s is "
						"already "
						"in list",
						url);
				}
				xmlFree(url);
			} else {
				char* text = (char*)xmlGetProp(
					node, (const xmlChar*)"text");
				if (!text) {
					text = (char*)xmlGetProp(
						node, (const xmlChar*)"title");
				}
				if (text) {
					if (newtag.length() > 0) {
						newtag.append("/");
					}
					newtag.append(text);
					xmlFree(text);
				}
			}
		}
		rec_find_rss_outlines(urlcfg, node->children, newtag);

		node = node->next;
	}
}

bool OPML::import(
		const std::string& filename,
		urlreader* urlcfg)
{
	xmlDoc* doc = xmlReadFile(filename.c_str(), nullptr, 0);
	if (doc == nullptr) {
		return false;
	}

	xmlNode* root = xmlDocGetRootElement(doc);

	for (xmlNode* node = root->children; node != nullptr;
		node = node->next) {
		if (strcmp((const char*)node->name, "body") == 0) {
			LOG(level::DEBUG, "OPML::import: found body");
			rec_find_rss_outlines(urlcfg, node->children, "");
			urlcfg->write_config();
		}
	}

	xmlFreeDoc(doc);

	return true;
}

} // namespace newsboat
<|endoftext|>


<commit_before>#include <iostream>
#include <json.hpp>

using namespace std;

int main() {
	JSON::Object<
		JSON::Field<int, 'a'>,
		JSON::Field<double, 'b'>,
		JSON::Field<string, 'c'>,
		JSON::Field<JSON::Object<
			JSON::Field<bool, 'f'>
		>, 'o'>,
		JSON::Field<vector<vector<JSON::Object<
			JSON::Field<double, 'x'>,
			JSON::Field<double, 'y'>
		>>>, 'x'>
	> o;

	o.Get<'a'>();
	o.Get<'x'>();
	o.Get<'o'>().Get<'f'>();

	JSON::Object<JSON::Field<bool, 'f'>>().Get<'f'>();

	JSON::Field<bool, UNPACK("hello")>();

	return 0;
}
<commit_msg>Tests<commit_after>#include <iostream>
#include <json.hpp>

using namespace std;

int main() {
	JSON::Object<
		JSON::Field<int, UNPACK("hello")>,
		JSON::Field<double, 'b'>,
		JSON::Field<string, 'c'>,
		JSON::Field<JSON::Object<
			JSON::Field<bool, 'f'>
		>, 'o'>,
		JSON::Field<vector<vector<JSON::Object<
			JSON::Field<double, 'x'>,
			JSON::Field<double, 'y'>
		>>>, 'x'>
	> o;

	o.Get<UNPACK("hello")>();
	o.Get<'x'>();
	o.Get<'o'>().Get<'f'>();

	JSON::Object<JSON::Field<bool, 'f'>>().Get<'f'>();

	cout << JSON::Field<bool, UNPACK("hello")>::s_szName << endl;

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "txdb.h"

#include "core.h"
#include "uint256.h"
#include "auxpow.h"

#include <stdint.h>

using namespace std;

void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
    if (coins.IsPruned())
        batch.Erase(make_pair('c', hash));
    else
        batch.Write(make_pair('c', hash), coins);
}

void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
    batch.Write('B', hash);
}

CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}

bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
    return db.Read(make_pair('c', txid), coins);
}

bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
    CLevelDBBatch batch;
    BatchWriteCoins(batch, txid, coins);
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
    return db.Exists(make_pair('c', txid));
}

uint256 CCoinsViewDB::GetBestBlock() {
    uint256 hashBestChain;
    if (!db.Read('B', hashBestChain))
        return uint256(0);
    return hashBestChain;
}

bool CCoinsViewDB::SetBestBlock(const uint256 &hashBlock) {
    CLevelDBBatch batch;
    BatchWriteHashBestChain(batch, hashBlock);
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock) {
    LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());

    CLevelDBBatch batch;
    for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
        BatchWriteCoins(batch, it->first, it->second);
    if (hashBlock != uint256(0))
        BatchWriteHashBestChain(batch, hashBlock);

    return db.WriteBatch(batch);
}

CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}

bool CBlockTreeDB::WriteDiskBlockIndex(const CDiskBlockIndex& diskblockindex)
{
    return Write(boost::tuples::make_tuple('b', *diskblockindex.phashBlock, 'a'), diskblockindex);
}

bool CBlockTreeDB::WriteBlockIndex(const CBlockIndex& blockindex)
{
    return Write(boost::tuples::make_tuple('b', blockindex.GetBlockHash(), 'b'), blockindex);
}

bool CBlockTreeDB::ReadDiskBlockIndex(const uint256 &blkid, CDiskBlockIndex &diskblockindex)
{
    return Read(boost::tuples::make_tuple('b', blkid, 'a'), diskblockindex);
}

bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
{
    // Obsolete; only written for backward compatibility.
    return Write('I', bnBestInvalidWork);
}

bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
    return Write(make_pair('f', nFile), info);
}

bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
    return Read(make_pair('f', nFile), info);
}

bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
    return Write('l', nFile);
}

bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
    if (fReindexing)
        return Write('R', '1');
    else
        return Erase('R');
}

bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
    fReindexing = Exists('R');
    return true;
}

bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
    return Read('l', nFile);
}

bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
    leveldb::Iterator *pcursor = db.NewIterator();
    pcursor->SeekToFirst();

    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
    stats.hashBlock = GetBestBlock();
    ss << stats.hashBlock;
    int64_t nTotalAmount = 0;
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'c') {
                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CCoins coins;
                ssValue >> coins;
                uint256 txhash;
                ssKey >> txhash;
                ss << txhash;
                ss << VARINT(coins.nVersion);
                ss << (coins.fCoinBase ? 'c' : 'n');
                ss << VARINT(coins.nHeight);
                stats.nTransactions++;
                for (unsigned int i=0; i<coins.vout.size(); i++) {
                    const CTxOut &out = coins.vout[i];
                    if (!out.IsNull()) {
                        stats.nTransactionOutputs++;
                        ss << VARINT(i+1);
                        ss << out;
                        nTotalAmount += out.nValue;
                    }
                }
                stats.nSerializedSize += 32 + slValue.size();
                ss << VARINT(0);
            }
            pcursor->Next();
        } catch (std::exception &e) {
            return error("%s : Deserialize or I/O error - %s", __func__, e.what());
        }
    }
    delete pcursor;
    stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
    stats.hashSerialized = ss.GetHash();
    stats.nTotalAmount = nTotalAmount;
    return true;
}

bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
    return Read(make_pair('t', txid), pos);
}

bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
    CLevelDBBatch batch;
    for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
        batch.Write(make_pair('t', it->first), it->second);
    return WriteBatch(batch);
}

bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
    return Write(std::make_pair('F', name), fValue ? '1' : '0');
}

bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
    char ch;
    if (!Read(std::make_pair('F', name), ch))
        return false;
    fValue = ch == '1';
    return true;
}

bool CBlockTreeDB::LoadBlockIndexGuts()
{
    leveldb::Iterator *pcursor = NewIterator();

    CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
    uint256 hash;
    ssKeySet << boost::tuples::make_tuple('b', uint256(0), 'a'); // 'b' is the prefix for BlockIndex, 'a' sigifies the first part
    pcursor->Seek(ssKeySet.str());

    // Load mapBlockIndex
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'b') {
                ssKey >> hash;

                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue_immutable(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CDiskBlockIndex diskindex;
                ssValue_immutable >> diskindex; // read all immutable data

                // Construct immutable parts of block index objecty
                CBlockIndex* pindexNew = InsertBlockIndex(hash);
                assert(diskindex.GetBlockHash() == *pindexNew->phashBlock); // paranoia check

                pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
                pindexNew->nHeight        = diskindex.nHeight;
                pindexNew->nFile          = diskindex.nFile;
                pindexNew->nDataPos       = diskindex.nDataPos;
                pindexNew->nUndoPos       = diskindex.nUndoPos;
                pindexNew->nVersion       = diskindex.nVersion;
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
                pindexNew->nTime          = diskindex.nTime;
                pindexNew->nBits          = diskindex.nBits;
                pindexNew->nNonce         = diskindex.nNonce;
                pindexNew->nStatus        = diskindex.nStatus;
                pindexNew->nTx            = diskindex.nTx;

                // CheckIndex need phashBlock to be set
                diskindex.phashBlock = pindexNew->phashBlock;
                if (!diskindex.CheckIndex())
                    return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString());

                pcursor->Next(); // now we should be on the 'b' subkey

                assert(pcursor->Valid());

                slValue = pcursor->value();
                CDataStream ssValue_mutable(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                ssValue_mutable >> *pindexNew;      // read all mutable data

                pcursor->Next();
            } else {
                break; // if shutdown requested or finished loading block index
            }
        } catch (std::exception &e) {
            return error("%s : Deserialize or I/O error - %s", __func__, e.what());
        }
    }
    delete pcursor;

    return true;
}
<commit_msg>Added explicit check for key length when loading blocks from disk, to catch 1.7/1.8 change. This avoids the problem where mis-loaded blocks later cause an assertion error.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "txdb.h"

#include "core.h"
#include "uint256.h"
#include "auxpow.h"

#include <stdint.h>

using namespace std;

void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
    if (coins.IsPruned())
        batch.Erase(make_pair('c', hash));
    else
        batch.Write(make_pair('c', hash), coins);
}

void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
    batch.Write('B', hash);
}

CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}

bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
    return db.Read(make_pair('c', txid), coins);
}

bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
    CLevelDBBatch batch;
    BatchWriteCoins(batch, txid, coins);
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
    return db.Exists(make_pair('c', txid));
}

uint256 CCoinsViewDB::GetBestBlock() {
    uint256 hashBestChain;
    if (!db.Read('B', hashBestChain))
        return uint256(0);
    return hashBestChain;
}

bool CCoinsViewDB::SetBestBlock(const uint256 &hashBlock) {
    CLevelDBBatch batch;
    BatchWriteHashBestChain(batch, hashBlock);
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock) {
    LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());

    CLevelDBBatch batch;
    for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
        BatchWriteCoins(batch, it->first, it->second);
    if (hashBlock != uint256(0))
        BatchWriteHashBestChain(batch, hashBlock);

    return db.WriteBatch(batch);
}

CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}

bool CBlockTreeDB::WriteDiskBlockIndex(const CDiskBlockIndex& diskblockindex)
{
    return Write(boost::tuples::make_tuple('b', *diskblockindex.phashBlock, 'a'), diskblockindex);
}

bool CBlockTreeDB::WriteBlockIndex(const CBlockIndex& blockindex)
{
    return Write(boost::tuples::make_tuple('b', blockindex.GetBlockHash(), 'b'), blockindex);
}

bool CBlockTreeDB::ReadDiskBlockIndex(const uint256 &blkid, CDiskBlockIndex &diskblockindex)
{
    return Read(boost::tuples::make_tuple('b', blkid, 'a'), diskblockindex);
}

bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
{
    // Obsolete; only written for backward compatibility.
    return Write('I', bnBestInvalidWork);
}

bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
    return Write(make_pair('f', nFile), info);
}

bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
    return Read(make_pair('f', nFile), info);
}

bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
    return Write('l', nFile);
}

bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
    if (fReindexing)
        return Write('R', '1');
    else
        return Erase('R');
}

bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
    fReindexing = Exists('R');
    return true;
}

bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
    return Read('l', nFile);
}

bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
    leveldb::Iterator *pcursor = db.NewIterator();
    pcursor->SeekToFirst();

    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
    stats.hashBlock = GetBestBlock();
    ss << stats.hashBlock;
    int64_t nTotalAmount = 0;
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'c') {
                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CCoins coins;
                ssValue >> coins;
                uint256 txhash;
                ssKey >> txhash;
                ss << txhash;
                ss << VARINT(coins.nVersion);
                ss << (coins.fCoinBase ? 'c' : 'n');
                ss << VARINT(coins.nHeight);
                stats.nTransactions++;
                for (unsigned int i=0; i<coins.vout.size(); i++) {
                    const CTxOut &out = coins.vout[i];
                    if (!out.IsNull()) {
                        stats.nTransactionOutputs++;
                        ss << VARINT(i+1);
                        ss << out;
                        nTotalAmount += out.nValue;
                    }
                }
                stats.nSerializedSize += 32 + slValue.size();
                ss << VARINT(0);
            }
            pcursor->Next();
        } catch (std::exception &e) {
            return error("%s : Deserialize or I/O error - %s", __func__, e.what());
        }
    }
    delete pcursor;
    stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
    stats.hashSerialized = ss.GetHash();
    stats.nTotalAmount = nTotalAmount;
    return true;
}

bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
    return Read(make_pair('t', txid), pos);
}

bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
    CLevelDBBatch batch;
    for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
        batch.Write(make_pair('t', it->first), it->second);
    return WriteBatch(batch);
}

bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
    return Write(std::make_pair('F', name), fValue ? '1' : '0');
}

bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
    char ch;
    if (!Read(std::make_pair('F', name), ch))
        return false;
    fValue = ch == '1';
    return true;
}

bool CBlockTreeDB::LoadBlockIndexGuts()
{
    leveldb::Iterator *pcursor = NewIterator();

    CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
    uint256 hash;
    ssKeySet << boost::tuples::make_tuple('b', uint256(0), 'a'); // 'b' is the prefix for BlockIndex, 'a' signifies the first part
    pcursor->Seek(ssKeySet.str());

    // Load mapBlockIndex
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'b') {
                // Detect pre-1.8 keys in the database and abort if found
                if (slKey.size() < ssKeySet.size()) {
                    return error("Database key size is %d expected %d, require reindex to upgrade.", slKey.size(), ssKeySet.size());
                }

                ssKey >> hash;

                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue_immutable(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CDiskBlockIndex diskindex;
                ssValue_immutable >> diskindex; // read all immutable data

                // Construct immutable parts of block index objecty
                CBlockIndex* pindexNew = InsertBlockIndex(hash);
                assert(diskindex.GetBlockHash() == *pindexNew->phashBlock); // paranoia check

                pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
                pindexNew->nHeight        = diskindex.nHeight;
                pindexNew->nFile          = diskindex.nFile;
                pindexNew->nDataPos       = diskindex.nDataPos;
                pindexNew->nUndoPos       = diskindex.nUndoPos;
                pindexNew->nVersion       = diskindex.nVersion;
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
                pindexNew->nTime          = diskindex.nTime;
                pindexNew->nBits          = diskindex.nBits;
                pindexNew->nNonce         = diskindex.nNonce;
                pindexNew->nStatus        = diskindex.nStatus;
                pindexNew->nTx            = diskindex.nTx;

                // CheckIndex need phashBlock to be set
                diskindex.phashBlock = pindexNew->phashBlock;
                if (!diskindex.CheckIndex())
                    return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString());

                pcursor->Next(); // now we should be on the 'b' subkey

                assert(pcursor->Valid());

                slValue = pcursor->value();
                CDataStream ssValue_mutable(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                ssValue_mutable >> *pindexNew;      // read all mutable data

                pcursor->Next();
            } else {
                break; // if shutdown requested or finished loading block index
            }
        } catch (std::exception &e) {
            return error("%s : Deserialize or I/O error - %s", __func__, e.what());
        }
    }
    delete pcursor;

    return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include "sdklayout.hpp"
#include "filesystem.hpp"

#include <qi/application.hpp>
#include <qi/path.hpp>
#include <qi/os.hpp>
#include <qi/qi.hpp>
#include <qi/log.hpp>

#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

qiLogCategory("qi.path");

namespace qi
{
  SDKLayout* gInstance = NULL;
  SDKLayout* getInstance();

  //only needed to make valgrind happy.
  static void cleanupSdkLayout() {
    if (!qi::os::getenv("VALGRIND").empty()) {
      delete gInstance;
      gInstance = 0;
    }
  }

  QI_AT_EXIT(&cleanupSdkLayout);

  namespace path
  {

    boost::filesystem::path absPath(const std::string &pathString)
    {
      boost::filesystem::path path(pathString, qi::unicodeFacet());
      return boost::filesystem::system_complete(path).make_preferred();
    }

    namespace detail {

      void addOptionalSdkPrefix(const char *prefix)
      {
        return getInstance()->addOptionalSdkPrefix(prefix);
      }

      void clearOptionalSdkPrefix()
      {
        return getInstance()->clearOptionalSdkPrefix();
      }

      std::vector<std::string> getSdkPrefixes()
      {
        return getInstance()->getSdkPrefixes();
      }
    }

    std::string sdkPrefix()
    {
      return getInstance()->sdkPrefix();
    }

    std::string findBin(const std::string &name)
    {
      return getInstance()->findBin(name);
    }

    std::string findLib(const std::string &name)
    {
      return getInstance()->findLib(name);
    }

    std::string findConf(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findConf(applicationName, filename);
    }

    std::string findData(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findData(applicationName, filename);
    }

    std::vector<std::string> listData(const std::string &applicationName,
                                      const std::string &pattern)
    {
      return getInstance()->listData(applicationName, pattern);
    }

    std::vector<std::string> confPaths(const std::string &applicationName)
    {
      return getInstance()->confPaths(applicationName);
    }

    std::vector<std::string> dataPaths(const std::string &applicationName)
    {
      return getInstance()->dataPaths(applicationName);
    }

    std::vector<std::string> binPaths()
    {
      return getInstance()->binPaths();
    }

    std::vector<std::string> libPaths()
    {
      return getInstance()->libPaths();
    }

    void setWritablePath(const std::string &path)
    {
      qiLogVerbose() << "Writable path set to " << path;
      getInstance()->setWritablePath(path);
    }

    std::string userWritableDataPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return getInstance()->userWritableDataPath(applicationName, filename);
    }

    std::string userWritableConfPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return qi::getInstance()->userWritableConfPath(applicationName, filename);
    }
  };

  SDKLayout* getInstance()
  {
    if (gInstance == NULL) {
      std::string prefix;
      std::string mode;
      const char *program = qi::Application::program();

      if (!program || !boost::filesystem::exists(program)) {
        mode = "error";
      }
      else {
        boost::filesystem::path execPath(program, qi::unicodeFacet());
        execPath = boost::filesystem::system_complete(execPath).make_preferred();
        prefix = execPath.parent_path().parent_path().string(qi::unicodeFacet());
        if (execPath.parent_path().filename().string(qi::unicodeFacet()) != "bin")
          mode = execPath.parent_path().filename().string(qi::unicodeFacet());
        else
          mode = "";
      }
      gInstance = new SDKLayout(prefix, mode);
    }

    return gInstance;
  }

  namespace {
    _QI_COMMAND_LINE_OPTIONS(
      "Chrooting",
      ("writable-path", value<std::string>()->notifier(&qi::path::setWritablePath), "Set the writable path.")
      )
  }
}
<commit_msg>Fix initialization of SDK path for applications in UTF-8 path (fix bug #18146)<commit_after>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include "sdklayout.hpp"
#include "filesystem.hpp"

#include <qi/application.hpp>
#include <qi/path.hpp>
#include <qi/os.hpp>
#include <qi/qi.hpp>
#include <qi/log.hpp>

#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

qiLogCategory("qi.path");

namespace qi
{
  SDKLayout* gInstance = NULL;
  SDKLayout* getInstance();

  //only needed to make valgrind happy.
  static void cleanupSdkLayout() {
    if (!qi::os::getenv("VALGRIND").empty()) {
      delete gInstance;
      gInstance = 0;
    }
  }

  QI_AT_EXIT(&cleanupSdkLayout);

  namespace path
  {

    boost::filesystem::path absPath(const std::string &pathString)
    {
      boost::filesystem::path path(pathString, qi::unicodeFacet());
      return boost::filesystem::system_complete(path).make_preferred();
    }

    namespace detail {

      void addOptionalSdkPrefix(const char *prefix)
      {
        return getInstance()->addOptionalSdkPrefix(prefix);
      }

      void clearOptionalSdkPrefix()
      {
        return getInstance()->clearOptionalSdkPrefix();
      }

      std::vector<std::string> getSdkPrefixes()
      {
        return getInstance()->getSdkPrefixes();
      }
    }

    std::string sdkPrefix()
    {
      return getInstance()->sdkPrefix();
    }

    std::string findBin(const std::string &name)
    {
      return getInstance()->findBin(name);
    }

    std::string findLib(const std::string &name)
    {
      return getInstance()->findLib(name);
    }

    std::string findConf(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findConf(applicationName, filename);
    }

    std::string findData(const std::string &applicationName,
                         const std::string &filename)
    {
      if(filename == "") {
        qiLogError() << "Filename cannot be empty!";
        return std::string();
      }
      return getInstance()->findData(applicationName, filename);
    }

    std::vector<std::string> listData(const std::string &applicationName,
                                      const std::string &pattern)
    {
      return getInstance()->listData(applicationName, pattern);
    }

    std::vector<std::string> confPaths(const std::string &applicationName)
    {
      return getInstance()->confPaths(applicationName);
    }

    std::vector<std::string> dataPaths(const std::string &applicationName)
    {
      return getInstance()->dataPaths(applicationName);
    }

    std::vector<std::string> binPaths()
    {
      return getInstance()->binPaths();
    }

    std::vector<std::string> libPaths()
    {
      return getInstance()->libPaths();
    }

    void setWritablePath(const std::string &path)
    {
      qiLogVerbose() << "Writable path set to " << path;
      getInstance()->setWritablePath(path);
    }

    std::string userWritableDataPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return getInstance()->userWritableDataPath(applicationName, filename);
    }

    std::string userWritableConfPath(const std::string &applicationName,
                                     const std::string &filename)
    {
      return qi::getInstance()->userWritableConfPath(applicationName, filename);
    }
  };

  SDKLayout* getInstance()
  {
    if (gInstance == NULL) {
      std::string prefix;
      std::string mode;
      const char *program = qi::Application::program();

      if (!program) {
        mode = "error";
      }
      else {
        boost::filesystem::path execPath(program, qi::unicodeFacet());
        if(!boost::filesystem::exists(execPath)) {
          mode = "error";
        }
        else {
          execPath = boost::filesystem::system_complete(execPath).make_preferred();
          prefix = execPath.parent_path().parent_path().string(qi::unicodeFacet());
          if (execPath.parent_path().filename().string(qi::unicodeFacet()) != "bin")
            mode = execPath.parent_path().filename().string(qi::unicodeFacet());
          else
            mode = "";
        }
      }
      gInstance = new SDKLayout(prefix, mode);
    }

    return gInstance;
  }

  namespace {
    _QI_COMMAND_LINE_OPTIONS(
      "Chrooting",
      ("writable-path", value<std::string>()->notifier(&qi::path::setWritablePath), "Set the writable path.")
      )
  }
}
<|endoftext|>