<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Common.h"

#include "Basics/directories.h"
#include "Basics/tri-strings.h"

#include "Actions/ActionFeature.h"
#include "Agency/AgencyFeature.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "ApplicationFeatures/EnvironmentFeature.h"
#include "ApplicationFeatures/GreetingsFeature.h"
#include "ApplicationFeatures/JemallocFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/NonceFeature.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "ApplicationFeatures/RocksDBOptionFeature.h"
#include "ApplicationFeatures/ShellColorsFeature.h"
#include "ApplicationFeatures/PrivilegeFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/SupervisorFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Cache/CacheManagerFeature.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LoggerBufferFeature.h"
#include "Logger/LoggerFeature.h"
#include "Pregel/PregelFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/BootstrapFeature.h"
#include "RestServer/CheckVersionFeature.h"
#include "RestServer/ConsoleFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/EndpointFeature.h"
#include "RestServer/FeatureCacheFeature.h"
#include "RestServer/FileDescriptorsFeature.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/InitDatabaseFeature.h"
#include "RestServer/LockfileFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ScriptFeature.h"
#include "RestServer/ServerFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "RestServer/TransactionManagerFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "RestServer/UnitTestsFeature.h"
#include "RestServer/UpgradeFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/WorkMonitorFeature.h"
#include "Scheduler/SchedulerFeature.h"
#include "Ssl/SslFeature.h"
#include "Ssl/SslServerFeature.h"
#include "Statistics/StatisticsFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/StorageEngineFeature.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"

#ifdef _WIN32
#include "ApplicationFeatures/WindowsServiceFeature.h"
#endif

#ifdef USE_ENTERPRISE
#include "Enterprise/RestServer/arangodEE.h"
#endif

// storage engines
#include "MMFiles/MMFilesEngine.h"
#include "RocksDBEngine/RocksDBEngine.h"

#ifdef _WIN32
#include <iostream>
#endif

using namespace arangodb;

static int runServer(int argc, char** argv, ArangoGlobalContext &context) {
  try {
    context.installSegv();
    context.runStartupChecks();

    usleep(5000000);

    std::string name = context.binaryName();

    auto options = std::make_shared<options::ProgramOptions>(
        argv[0], "Usage: " + name + " [<options>]", "For more information use:",
        SBIN_DIRECTORY);

    application_features::ApplicationServer server(options, SBIN_DIRECTORY);

    std::vector<std::string> nonServerFeatures = {
        "Action",        "Agency",
        "Cluster",       "Daemon",
        "FoxxQueues",    "GeneralServer",
        "Greetings",     "LoggerBufferFeature",
        "Server",        "SslServer",
        "Statistics",    "Supervisor"};

    int ret = EXIT_FAILURE;

    server.addFeature(new ActionFeature(&server));
    server.addFeature(new AgencyFeature(&server));
    server.addFeature(new aql::AqlFunctionFeature(&server));
    server.addFeature(new aql::OptimizerRulesFeature(&server));
    server.addFeature(new AuthenticationFeature(&server));
    server.addFeature(new AqlFeature(&server));
    server.addFeature(new BootstrapFeature(&server));
    server.addFeature(new CacheManagerFeature(&server));
    server.addFeature(
        new CheckVersionFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new ClusterFeature(&server));
    server.addFeature(new ConfigFeature(&server, name));
    server.addFeature(new ConsoleFeature(&server));
    server.addFeature(new DatabaseFeature(&server));
    server.addFeature(new DatabasePathFeature(&server));
    server.addFeature(new EndpointFeature(&server));
    server.addFeature(new EngineSelectorFeature(&server));
    server.addFeature(new EnvironmentFeature(&server));
    server.addFeature(new FeatureCacheFeature(&server));
    server.addFeature(new FileDescriptorsFeature(&server));
    server.addFeature(new FoxxQueuesFeature(&server));
    server.addFeature(new FrontendFeature(&server));
    server.addFeature(new GeneralServerFeature(&server));
    server.addFeature(new GreetingsFeature(&server));
    server.addFeature(new InitDatabaseFeature(&server, nonServerFeatures));
    server.addFeature(new JemallocFeature(&server));
    server.addFeature(new LanguageFeature(&server));
    server.addFeature(new LockfileFeature(&server));
    server.addFeature(new LoggerBufferFeature(&server));
    server.addFeature(new LoggerFeature(&server, true));
    server.addFeature(new NonceFeature(&server));
    server.addFeature(new PageSizeFeature(&server));
    server.addFeature(new pregel::PregelFeature(&server));
    server.addFeature(new PrivilegeFeature(&server));
    server.addFeature(new RandomFeature(&server));
    server.addFeature(new QueryRegistryFeature(&server));
    server.addFeature(new SchedulerFeature(&server));
    server.addFeature(new ScriptFeature(&server, &ret));
    server.addFeature(new ServerFeature(&server, &ret));
    server.addFeature(new ServerIdFeature(&server));
    server.addFeature(new ShellColorsFeature(&server));
    server.addFeature(new ShutdownFeature(&server, {"UnitTests", "Script"}));
    server.addFeature(new SslFeature(&server));
    server.addFeature(new StatisticsFeature(&server));
    server.addFeature(new StorageEngineFeature(&server));
    server.addFeature(new TempFeature(&server, name));
    server.addFeature(new TransactionManagerFeature(&server));
    server.addFeature(new TraverserEngineRegistryFeature(&server));
    server.addFeature(new UnitTestsFeature(&server, &ret));
    server.addFeature(new UpgradeFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new V8DealerFeature(&server));
    server.addFeature(new V8PlatformFeature(&server));
    server.addFeature(new VersionFeature(&server));
    server.addFeature(new ViewTypesFeature(&server));
    server.addFeature(new WorkMonitorFeature(&server));
    server.addFeature(new RocksDBOptionFeature(&server));

#ifdef ARANGODB_HAVE_FORK
    server.addFeature(new DaemonFeature(&server));
    server.addFeature(new SupervisorFeature(&server));
#endif

#ifdef _WIN32
    server.addFeature(new WindowsServiceFeature(&server));
#endif

#ifdef USE_ENTERPRISE
    setupServerEE(&server);
#else
    server.addFeature(new SslServerFeature(&server));
#endif

    // storage engines
    server.addFeature(new MMFilesEngine(&server));
    server.addFeature(new RocksDBEngine(&server));

    try {
      server.run(argc, argv);
      if (server.helpShown()) {
        // --help was displayed
        ret = EXIT_SUCCESS;
      }
    } catch (std::exception const& ex) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception: "
          << ex.what();
      ret = EXIT_FAILURE;
    } catch (...) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception of "
             "unknown type";
      ret = EXIT_FAILURE;
    }
    Logger::flush();
    return context.exit(ret);
  } catch (std::exception const& ex) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an exception: "
        << ex.what();
  } catch (...) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an xception of "
           "unknown type";
  }
  exit(EXIT_FAILURE);
}

#if _WIN32
static int ARGC;
static char** ARGV;

static void WINAPI ServiceMain(DWORD dwArgc, LPSTR* lpszArgv) {
  if (!TRI_InitWindowsEventLog()) {
    return;
  }
  // register the service ctrl handler,  lpszArgv[0] contains service name
  ServiceStatus =
      RegisterServiceCtrlHandlerA(lpszArgv[0], (LPHANDLER_FUNCTION)ServiceCtrl);

  // set start pending
  SetServiceStatus(SERVICE_START_PENDING, 0, 1, 10000, 0);

  ArangoGlobalContext context(ARGC, ARGV, SBIN_DIRECTORY);
  runServer(ARGC, ARGV, context);

  // service has stopped
  SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
  TRI_CloseWindowsEventlog();
}

#endif

int main(int argc, char* argv[]) {
#if _WIN32
  if (argc > 1 && TRI_EqualString("--start-service", argv[1])) {
    ARGC = argc;
    ARGV = argv;

    SERVICE_TABLE_ENTRY ste[] = {
      {TEXT(""), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {nullptr, nullptr}};

    if (!StartServiceCtrlDispatcher(ste)) {
      std::cerr << "FATAL: StartServiceCtrlDispatcher has failed with "
                << GetLastError() << std::endl;
      exit(EXIT_FAILURE);
    }
    return 0;
  }
#endif
  ArangoGlobalContext context(argc, argv, SBIN_DIRECTORY);
  return runServer(argc, argv, context);
}
<commit_msg>dont sleep at start (#3164)<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Common.h"

#include "Basics/directories.h"
#include "Basics/tri-strings.h"

#include "Actions/ActionFeature.h"
#include "Agency/AgencyFeature.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "ApplicationFeatures/EnvironmentFeature.h"
#include "ApplicationFeatures/GreetingsFeature.h"
#include "ApplicationFeatures/JemallocFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/NonceFeature.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "ApplicationFeatures/RocksDBOptionFeature.h"
#include "ApplicationFeatures/ShellColorsFeature.h"
#include "ApplicationFeatures/PrivilegeFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/SupervisorFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Cache/CacheManagerFeature.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LoggerBufferFeature.h"
#include "Logger/LoggerFeature.h"
#include "Pregel/PregelFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/BootstrapFeature.h"
#include "RestServer/CheckVersionFeature.h"
#include "RestServer/ConsoleFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/EndpointFeature.h"
#include "RestServer/FeatureCacheFeature.h"
#include "RestServer/FileDescriptorsFeature.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/InitDatabaseFeature.h"
#include "RestServer/LockfileFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ScriptFeature.h"
#include "RestServer/ServerFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "RestServer/TransactionManagerFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "RestServer/UnitTestsFeature.h"
#include "RestServer/UpgradeFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/WorkMonitorFeature.h"
#include "Scheduler/SchedulerFeature.h"
#include "Ssl/SslFeature.h"
#include "Ssl/SslServerFeature.h"
#include "Statistics/StatisticsFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/StorageEngineFeature.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"

#ifdef _WIN32
#include "ApplicationFeatures/WindowsServiceFeature.h"
#endif

#ifdef USE_ENTERPRISE
#include "Enterprise/RestServer/arangodEE.h"
#endif

// storage engines
#include "MMFiles/MMFilesEngine.h"
#include "RocksDBEngine/RocksDBEngine.h"

#ifdef _WIN32
#include <iostream>
#endif

using namespace arangodb;

static int runServer(int argc, char** argv, ArangoGlobalContext &context) {
  try {
    context.installSegv();
    context.runStartupChecks();

    std::string name = context.binaryName();

    auto options = std::make_shared<options::ProgramOptions>(
        argv[0], "Usage: " + name + " [<options>]", "For more information use:",
        SBIN_DIRECTORY);

    application_features::ApplicationServer server(options, SBIN_DIRECTORY);

    std::vector<std::string> nonServerFeatures = {
        "Action",        "Agency",
        "Cluster",       "Daemon",
        "FoxxQueues",    "GeneralServer",
        "Greetings",     "LoggerBufferFeature",
        "Server",        "SslServer",
        "Statistics",    "Supervisor"};

    int ret = EXIT_FAILURE;

    server.addFeature(new ActionFeature(&server));
    server.addFeature(new AgencyFeature(&server));
    server.addFeature(new aql::AqlFunctionFeature(&server));
    server.addFeature(new aql::OptimizerRulesFeature(&server));
    server.addFeature(new AuthenticationFeature(&server));
    server.addFeature(new AqlFeature(&server));
    server.addFeature(new BootstrapFeature(&server));
    server.addFeature(new CacheManagerFeature(&server));
    server.addFeature(
        new CheckVersionFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new ClusterFeature(&server));
    server.addFeature(new ConfigFeature(&server, name));
    server.addFeature(new ConsoleFeature(&server));
    server.addFeature(new DatabaseFeature(&server));
    server.addFeature(new DatabasePathFeature(&server));
    server.addFeature(new EndpointFeature(&server));
    server.addFeature(new EngineSelectorFeature(&server));
    server.addFeature(new EnvironmentFeature(&server));
    server.addFeature(new FeatureCacheFeature(&server));
    server.addFeature(new FileDescriptorsFeature(&server));
    server.addFeature(new FoxxQueuesFeature(&server));
    server.addFeature(new FrontendFeature(&server));
    server.addFeature(new GeneralServerFeature(&server));
    server.addFeature(new GreetingsFeature(&server));
    server.addFeature(new InitDatabaseFeature(&server, nonServerFeatures));
    server.addFeature(new JemallocFeature(&server));
    server.addFeature(new LanguageFeature(&server));
    server.addFeature(new LockfileFeature(&server));
    server.addFeature(new LoggerBufferFeature(&server));
    server.addFeature(new LoggerFeature(&server, true));
    server.addFeature(new NonceFeature(&server));
    server.addFeature(new PageSizeFeature(&server));
    server.addFeature(new pregel::PregelFeature(&server));
    server.addFeature(new PrivilegeFeature(&server));
    server.addFeature(new RandomFeature(&server));
    server.addFeature(new QueryRegistryFeature(&server));
    server.addFeature(new SchedulerFeature(&server));
    server.addFeature(new ScriptFeature(&server, &ret));
    server.addFeature(new ServerFeature(&server, &ret));
    server.addFeature(new ServerIdFeature(&server));
    server.addFeature(new ShellColorsFeature(&server));
    server.addFeature(new ShutdownFeature(&server, {"UnitTests", "Script"}));
    server.addFeature(new SslFeature(&server));
    server.addFeature(new StatisticsFeature(&server));
    server.addFeature(new StorageEngineFeature(&server));
    server.addFeature(new TempFeature(&server, name));
    server.addFeature(new TransactionManagerFeature(&server));
    server.addFeature(new TraverserEngineRegistryFeature(&server));
    server.addFeature(new UnitTestsFeature(&server, &ret));
    server.addFeature(new UpgradeFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new V8DealerFeature(&server));
    server.addFeature(new V8PlatformFeature(&server));
    server.addFeature(new VersionFeature(&server));
    server.addFeature(new ViewTypesFeature(&server));
    server.addFeature(new WorkMonitorFeature(&server));
    server.addFeature(new RocksDBOptionFeature(&server));

#ifdef ARANGODB_HAVE_FORK
    server.addFeature(new DaemonFeature(&server));
    server.addFeature(new SupervisorFeature(&server));
#endif

#ifdef _WIN32
    server.addFeature(new WindowsServiceFeature(&server));
#endif

#ifdef USE_ENTERPRISE
    setupServerEE(&server);
#else
    server.addFeature(new SslServerFeature(&server));
#endif

    // storage engines
    server.addFeature(new MMFilesEngine(&server));
    server.addFeature(new RocksDBEngine(&server));

    try {
      server.run(argc, argv);
      if (server.helpShown()) {
        // --help was displayed
        ret = EXIT_SUCCESS;
      }
    } catch (std::exception const& ex) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception: "
          << ex.what();
      ret = EXIT_FAILURE;
    } catch (...) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception of "
             "unknown type";
      ret = EXIT_FAILURE;
    }
    Logger::flush();
    return context.exit(ret);
  } catch (std::exception const& ex) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an exception: "
        << ex.what();
  } catch (...) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an xception of "
           "unknown type";
  }
  exit(EXIT_FAILURE);
}

#if _WIN32
static int ARGC;
static char** ARGV;

static void WINAPI ServiceMain(DWORD dwArgc, LPSTR* lpszArgv) {
  if (!TRI_InitWindowsEventLog()) {
    return;
  }
  // register the service ctrl handler,  lpszArgv[0] contains service name
  ServiceStatus =
      RegisterServiceCtrlHandlerA(lpszArgv[0], (LPHANDLER_FUNCTION)ServiceCtrl);

  // set start pending
  SetServiceStatus(SERVICE_START_PENDING, 0, 1, 10000, 0);

  ArangoGlobalContext context(ARGC, ARGV, SBIN_DIRECTORY);
  runServer(ARGC, ARGV, context);

  // service has stopped
  SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
  TRI_CloseWindowsEventlog();
}

#endif

int main(int argc, char* argv[]) {
#if _WIN32
  if (argc > 1 && TRI_EqualString("--start-service", argv[1])) {
    ARGC = argc;
    ARGV = argv;

    SERVICE_TABLE_ENTRY ste[] = {
      {TEXT(""), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {nullptr, nullptr}};

    if (!StartServiceCtrlDispatcher(ste)) {
      std::cerr << "FATAL: StartServiceCtrlDispatcher has failed with "
                << GetLastError() << std::endl;
      exit(EXIT_FAILURE);
    }
    return 0;
  }
#endif
  ArangoGlobalContext context(argc, argv, SBIN_DIRECTORY);
  return runServer(argc, argv, context);
}
<|endoftext|>


<commit_before>#include <map>
#include <unistd.h>
#include <string.h>
#include "../src2/EventsWindow.h"

using namespace std;

void toString(vector<char> &output, const unique_ptr<EventsBucket> &bucket) {
    char timestr[256];
    char tmp[256];
    char *ptr = tmp;
    struct timeval tv;
    int64_t bucketStart = bucket->getBucketStart();
    int64_t bucketEnd = bucket->getBucketEnd();

    tv.tv_sec = bucketStart / 1000;
    tv.tv_usec = 0;
    struct tm tm;
    localtime_r(&tv.tv_sec, &tm);
    strftime(timestr, 128, "%r", &tm);
    // Report the stats for this time window and then reset
    int64_t width = bucketEnd - bucketStart;
    int count = snprintf(tmp, sizeof(tmp), "+++ Beacon counts for window(%ld): %s\n", width, timestr);
    output.insert(output.end(), ptr, ptr + count);
    map<int32_t, beacon_info>::const_iterator iter = bucket->begin();
    while (iter != bucket->end()) {
        output.push_back('\t');
        count = snprintf(tmp, sizeof(tmp), "+%2d(%s): %2d; ", iter->second.minor, iter->second.uuid,
                         iter->second.count);
        output.insert(output.end(), ptr, ptr + count);
        output.push_back('\n');
        iter++;
    }
    output.push_back('\n');
    output.push_back('\0');
}

void fullDump(const unique_ptr<EventsBucket> &bucket) {
    map<int32_t, beacon_info>::const_iterator iter = bucket->begin();
    while (iter != bucket->end()) {
        time_t infoTime = iter->second.time / 1000;
        printf("uuid=%s,isHeartbeat=%d,code=%d,manufacturer=%d,major=%d,minor=%d,power=%d,rssi=%d,count=%d,time=%lld(%s)\n",
               iter->second.uuid,
               iter->second.isHeartbeat,
               iter->second.code,
               iter->second.manufacturer,
               iter->second.major,
               iter->second.minor,
               iter->second.power,
               iter->second.rssi,
               iter->second.count,
               iter->second.time,
               ctime(&infoTime)
               );
        iter ++;
    }
}

int main() {
    EventsWindow window;

    window.reset(10);
    beacon_info info;
    memset(&info, 0, sizeof(info));
    info.rssi = 10;
    info.major = 1;
    info.manufacturer = 0xdead;
    info.code = 0xbeef;
    info.calibrated_power = -40;
    info.time = EventsWindow::currentMilliseconds();
    for (int n = 0; n < 60; n++) {
        int id = n % 5;
        int64_t nowMS = EventsWindow::currentMilliseconds();
        sprintf(info.uuid, "UUID-%.12d", id);
        info.rssi = 10;
        info.minor = id;
        info.time = nowMS;
        printf("n=%d, nowMS=%lld\n", n, nowMS);
        unique_ptr<EventsBucket> bucket = window.addEvent(info, false);
        if (bucket) {
            vector<char> tmp;
            toString(tmp, bucket);
            printf("%s\n", tmp.data());
            fullDump(bucket);
        }
        sleep(1);
    }
    fullDump(window.getCurrentBucket());
}
<commit_msg>int64_t requires %lld<commit_after>#include <map>
#include <unistd.h>
#include <string.h>
#include "../src2/EventsWindow.h"

using namespace std;

void toString(vector<char> &output, const unique_ptr<EventsBucket> &bucket) {
    char timestr[256];
    char tmp[256];
    char *ptr = tmp;
    struct timeval tv;
    int64_t bucketStart = bucket->getBucketStart();
    int64_t bucketEnd = bucket->getBucketEnd();

    tv.tv_sec = bucketStart / 1000;
    tv.tv_usec = 0;
    struct tm tm;
    localtime_r(&tv.tv_sec, &tm);
    strftime(timestr, 128, "%r", &tm);
    // Report the stats for this time window and then reset
    int64_t width = bucketEnd - bucketStart;
    int count = snprintf(tmp, sizeof(tmp), "+++ Beacon counts for window(%lld): %s\n", width, timestr);
    output.insert(output.end(), ptr, ptr + count);
    map<int32_t, beacon_info>::const_iterator iter = bucket->begin();
    while (iter != bucket->end()) {
        output.push_back('\t');
        count = snprintf(tmp, sizeof(tmp), "+%2d(%s): %2d; ", iter->second.minor, iter->second.uuid,
                         iter->second.count);
        output.insert(output.end(), ptr, ptr + count);
        output.push_back('\n');
        iter++;
    }
    output.push_back('\n');
    output.push_back('\0');
}

void fullDump(const unique_ptr<EventsBucket> &bucket) {
    map<int32_t, beacon_info>::const_iterator iter = bucket->begin();
    while (iter != bucket->end()) {
        time_t infoTime = iter->second.time / 1000;
        printf("uuid=%s,isHeartbeat=%d,code=%d,manufacturer=%d,major=%d,minor=%d,power=%d,rssi=%d,count=%d,time=%lld(%s)\n",
               iter->second.uuid,
               iter->second.isHeartbeat,
               iter->second.code,
               iter->second.manufacturer,
               iter->second.major,
               iter->second.minor,
               iter->second.power,
               iter->second.rssi,
               iter->second.count,
               iter->second.time,
               ctime(&infoTime)
               );
        iter ++;
    }
}

int main() {
    EventsWindow window;

    window.reset(10);
    beacon_info info;
    memset(&info, 0, sizeof(info));
    info.rssi = 10;
    info.major = 1;
    info.manufacturer = 0xdead;
    info.code = 0xbeef;
    info.calibrated_power = -40;
    info.time = EventsWindow::currentMilliseconds();

    // Test printing an empty bucket
    unique_ptr<EventsBucket> empty = window.getCurrentBucket();
    vector<char> tmp;
    empty->toString(tmp);
    printf("bucket.toString(): %s\n", tmp.data());

    for (int n = 0; n < 60; n++) {
        int id = n % 5;
        int64_t nowMS = EventsWindow::currentMilliseconds();
        sprintf(info.uuid, "UUID-%.12d", id);
        info.rssi = 10;
        info.minor = id;
        info.time = nowMS;
        printf("n=%d, nowMS=%lld\n", n, nowMS);
        unique_ptr<EventsBucket> bucket = window.addEvent(info, false);
        if (bucket) {
            toString(tmp, bucket);
            printf("%s\n", tmp.data());
            fullDump(bucket);
            bucket->toString(tmp);
            printf("bucket.toString(): %s\n", tmp.data());
        }
        sleep(1);
    }
    fullDump(window.getCurrentBucket());
}
<|endoftext|>


<commit_before>#include "util/completionmodel.hpp"

#include "application.hpp"
#include "common.hpp"
#include "debug/log.hpp"
#include "singletons/emotemanager.hpp"

#include <QtAlgorithms>

#include <utility>

namespace chatterino {

CompletionModel::CompletionModel(const QString &_channelName)
    : channelName(_channelName)
{
}

void CompletionModel::refresh()
{
    debug::Log("[CompletionModel:{}] Refreshing...]", this->channelName);

    auto app = getApp();

    // User-specific: Twitch Emotes
    // TODO: Fix this so it properly updates with the proper api. oauth token needs proper scope
    for (const auto &m : app->emotes->twitchAccountEmotes) {
        for (const auto &emoteName : m.second.emoteCodes) {
            // XXX: No way to discern between a twitch global emote and sub emote right now
            this->addString(emoteName, TaggedString::Type::TwitchGlobalEmote);
        }
    }

    // Global: BTTV Global Emotes
    std::vector<std::string> &bttvGlobalEmoteCodes = app->emotes->bttvGlobalEmoteCodes;
    for (const auto &m : bttvGlobalEmoteCodes) {
        this->addString(m, TaggedString::Type::BTTVGlobalEmote);
    }

    // Global: FFZ Global Emotes
    std::vector<std::string> &ffzGlobalEmoteCodes = app->emotes->ffzGlobalEmoteCodes;
    for (const auto &m : ffzGlobalEmoteCodes) {
        this->addString(m, TaggedString::Type::FFZGlobalEmote);
    }

    // Channel-specific: BTTV Channel Emotes
    std::vector<std::string> &bttvChannelEmoteCodes =
        app->emotes->bttvChannelEmoteCodes[this->channelName.toStdString()];
    for (const auto &m : bttvChannelEmoteCodes) {
        this->addString(m, TaggedString::Type::BTTVChannelEmote);
    }

    // Channel-specific: FFZ Channel Emotes
    std::vector<std::string> &ffzChannelEmoteCodes =
        app->emotes->ffzChannelEmoteCodes[this->channelName.toStdString()];
    for (const auto &m : ffzChannelEmoteCodes) {
        this->addString(m, TaggedString::Type::FFZChannelEmote);
    }

    // Global: Emojis
    const auto &emojiShortCodes = app->emotes->emojiShortCodes;
    for (const auto &m : emojiShortCodes) {
        this->addString(":" + m + ":", TaggedString::Type::Emoji);
    }

    // Channel-specific: Usernames
    // fourtf: only works with twitch chat
    //    auto c = singletons::ChannelManager::getInstance().getTwitchChannel(this->channelName);
    //    auto usernames = c->getUsernamesForCompletions();
    //    for (const auto &name : usernames) {
    //        assert(!name.displayName.isEmpty());
    //        this->addString(name.displayName);
    //        this->addString('@' + name.displayName);

    //        if (!name.localizedName.isEmpty()) {
    //            this->addString(name.localizedName);
    //            this->addString('@' + name.localizedName);
    //        }
    //    }
}

void CompletionModel::addString(const std::string &str, TaggedString::Type type)
{
    this->addString(qS(str), type);
}

void CompletionModel::addString(const QString &str, TaggedString::Type type)
{
    std::lock_guard<std::mutex> lock(this->emotesMutex);

    // Always add a space at the end of completions
    this->emotes.insert({str + " ", type});
}

void CompletionModel::addUser(const QString &str)
{
    auto ts = this->createUser(str + " ");
    // Always add a space at the end of completions
    std::pair<std::set<TaggedString>::iterator, bool> p = this->emotes.insert(ts);
    if (!p.second) {
        // No inseration was made, figure out if we need to replace the username.

        if (p.first->str > ts.str) {
            // Replace lowercase version of name with mixed-case version
            this->emotes.erase(p.first);
            auto result2 = this->emotes.insert(ts);
            assert(result2.second);
        } else {
            p.first->timeAdded = std::chrono::steady_clock::now();
        }
    }
}

void CompletionModel::ClearExpiredStrings()
{
    std::lock_guard<std::mutex> lock(this->emotesMutex);

    auto now = std::chrono::steady_clock::now();

    for (auto it = this->emotes.begin(); it != this->emotes.end();) {
        const auto &taggedString = *it;

        if (taggedString.HasExpired(now)) {
            // debug::Log("String {} expired", taggedString.str);
            it = this->emotes.erase(it);
        } else {
            ++it;
        }
    }
}

}  // namespace chatterino
<commit_msg>added username autocompletions with @<commit_after>#include "util/completionmodel.hpp"

#include "application.hpp"
#include "common.hpp"
#include "debug/log.hpp"
#include "singletons/emotemanager.hpp"

#include <QtAlgorithms>

#include <utility>

namespace chatterino {

CompletionModel::CompletionModel(const QString &_channelName)
    : channelName(_channelName)
{
}

void CompletionModel::refresh()
{
    debug::Log("[CompletionModel:{}] Refreshing...]", this->channelName);

    auto app = getApp();

    // User-specific: Twitch Emotes
    // TODO: Fix this so it properly updates with the proper api. oauth token needs proper scope
    for (const auto &m : app->emotes->twitchAccountEmotes) {
        for (const auto &emoteName : m.second.emoteCodes) {
            // XXX: No way to discern between a twitch global emote and sub emote right now
            this->addString(emoteName, TaggedString::Type::TwitchGlobalEmote);
        }
    }

    // Global: BTTV Global Emotes
    std::vector<std::string> &bttvGlobalEmoteCodes = app->emotes->bttvGlobalEmoteCodes;
    for (const auto &m : bttvGlobalEmoteCodes) {
        this->addString(m, TaggedString::Type::BTTVGlobalEmote);
    }

    // Global: FFZ Global Emotes
    std::vector<std::string> &ffzGlobalEmoteCodes = app->emotes->ffzGlobalEmoteCodes;
    for (const auto &m : ffzGlobalEmoteCodes) {
        this->addString(m, TaggedString::Type::FFZGlobalEmote);
    }

    // Channel-specific: BTTV Channel Emotes
    std::vector<std::string> &bttvChannelEmoteCodes =
        app->emotes->bttvChannelEmoteCodes[this->channelName.toStdString()];
    for (const auto &m : bttvChannelEmoteCodes) {
        this->addString(m, TaggedString::Type::BTTVChannelEmote);
    }

    // Channel-specific: FFZ Channel Emotes
    std::vector<std::string> &ffzChannelEmoteCodes =
        app->emotes->ffzChannelEmoteCodes[this->channelName.toStdString()];
    for (const auto &m : ffzChannelEmoteCodes) {
        this->addString(m, TaggedString::Type::FFZChannelEmote);
    }

    // Global: Emojis
    const auto &emojiShortCodes = app->emotes->emojiShortCodes;
    for (const auto &m : emojiShortCodes) {
        this->addString(":" + m + ":", TaggedString::Type::Emoji);
    }

    // Channel-specific: Usernames
    // fourtf: only works with twitch chat
    //    auto c = singletons::ChannelManager::getInstance().getTwitchChannel(this->channelName);
    //    auto usernames = c->getUsernamesForCompletions();
    //    for (const auto &name : usernames) {
    //        assert(!name.displayName.isEmpty());
    //        this->addString(name.displayName);
    //        this->addString('@' + name.displayName);

    //        if (!name.localizedName.isEmpty()) {
    //            this->addString(name.localizedName);
    //            this->addString('@' + name.localizedName);
    //        }
    //    }
}

void CompletionModel::addString(const std::string &str, TaggedString::Type type)
{
    this->addString(qS(str), type);
}

void CompletionModel::addString(const QString &str, TaggedString::Type type)
{
    std::lock_guard<std::mutex> lock(this->emotesMutex);

    // Always add a space at the end of completions
    this->emotes.insert({str + " ", type});
}

void CompletionModel::addUser(const QString &username)
{
    auto add = [this](const QString &str) {
        auto ts = this->createUser(str + " ");
        // Always add a space at the end of completions
        std::pair<std::set<TaggedString>::iterator, bool> p = this->emotes.insert(ts);
        if (!p.second) {
            // No inseration was made, figure out if we need to replace the username.

            if (p.first->str > ts.str) {
                // Replace lowercase version of name with mixed-case version
                this->emotes.erase(p.first);
                auto result2 = this->emotes.insert(ts);
                assert(result2.second);
            } else {
                p.first->timeAdded = std::chrono::steady_clock::now();
            }
        }
    };

    add(username);
    add("@" + username);
}

void CompletionModel::ClearExpiredStrings()
{
    std::lock_guard<std::mutex> lock(this->emotesMutex);

    auto now = std::chrono::steady_clock::now();

    for (auto it = this->emotes.begin(); it != this->emotes.end();) {
        const auto &taggedString = *it;

        if (taggedString.HasExpired(now)) {
            // debug::Log("String {} expired", taggedString.str);
            it = this->emotes.erase(it);
        } else {
            ++it;
        }
    }
}

}  // namespace chatterino
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_CUDAOBJDETECT_HPP__
#define __OPENCV_CUDAOBJDETECT_HPP__

#ifndef __cplusplus
#  error cudaobjdetect.hpp header must be compiled as C++
#endif

#include "opencv2/core/cuda.hpp"

/**
  @addtogroup cuda
  @{
      @defgroup cuda_objdetect Object Detection
  @}
 */

namespace cv { namespace cuda {

//! @addtogroup cuda_objdetect
//! @{

//
// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector
//

/** @brief The class implements Histogram of Oriented Gradients (@cite Dalal2005) object detector.

@note
    -   An example applying the HOG descriptor for people detection can be found at
        opencv_source_code/samples/cpp/peopledetect.cpp
    -   A CUDA example applying the HOG descriptor for people detection can be found at
        opencv_source_code/samples/gpu/hog.cpp
    -   (Python) An example applying the HOG descriptor for people detection can be found at
        opencv_source_code/samples/python2/peopledetect.py
 */
class CV_EXPORTS HOG : public Algorithm
{
public:
    enum
    {
        DESCR_FORMAT_ROW_BY_ROW,
        DESCR_FORMAT_COL_BY_COL
    };

    /** @brief Creates the HOG descriptor and detector.

    @param win_size Detection window size. Align to block size and block stride.
    @param block_size Block size in pixels. Align to cell size. Only (16,16) is supported for now.
    @param block_stride Block stride. It must be a multiple of cell size.
    @param cell_size Cell size. Only (8, 8) is supported for now.
    @param nbins Number of bins. Only 9 bins per cell are supported for now.
     */
    static Ptr<HOG> create(Size win_size = Size(64, 128),
                           Size block_size = Size(16, 16),
                           Size block_stride = Size(8, 8),
                           Size cell_size = Size(8, 8),
                           int nbins = 9);

    //! Gaussian smoothing window parameter.
    virtual void setWinSigma(double win_sigma) = 0;
    virtual double getWinSigma() const = 0;

    //! L2-Hys normalization method shrinkage.
    virtual void setL2HysThreshold(double threshold_L2hys) = 0;
    virtual double getL2HysThreshold() const = 0;

    //! Flag to specify whether the gamma correction preprocessing is required or not.
    virtual void setGammaCorrection(bool gamma_correction) = 0;
    virtual bool getGammaCorrection() const = 0;

    //! Maximum number of detection window increases.
    virtual void setNumLevels(int nlevels) = 0;
    virtual int getNumLevels() const = 0;

    //! Threshold for the distance between features and SVM classifying plane.
    //! Usually it is 0 and should be specfied in the detector coefficients (as the last free
    //! coefficient). But if the free coefficient is omitted (which is allowed), you can specify it
    //! manually here.
    virtual void setHitThreshold(double hit_threshold) = 0;
    virtual double getHitThreshold() const = 0;

    //! Window stride. It must be a multiple of block stride.
    virtual void setWinStride(Size win_stride) = 0;
    virtual Size getWinStride() const = 0;

    //! Coefficient of the detection window increase.
    virtual void setScaleFactor(double scale0) = 0;
    virtual double getScaleFactor() const = 0;

    //! Coefficient to regulate the similarity threshold. When detected, some
    //! objects can be covered by many rectangles. 0 means not to perform grouping.
    //! See groupRectangles.
    virtual void setGroupThreshold(int group_threshold) = 0;
    virtual int getGroupThreshold() const = 0;

    //! Descriptor storage format:
    //!   - **DESCR_FORMAT_ROW_BY_ROW** - Row-major order.
    //!   - **DESCR_FORMAT_COL_BY_COL** - Column-major order.
    virtual void setDescriptorFormat(int descr_format) = 0;
    virtual int getDescriptorFormat() const = 0;

    /** @brief Returns the number of coefficients required for the classification.
     */
    virtual size_t getDescriptorSize() const = 0;

    /** @brief Returns the block histogram size.
     */
    virtual size_t getBlockHistogramSize() const = 0;

    /** @brief Sets coefficients for the linear SVM classifier.
     */
    virtual void setSVMDetector(InputArray detector) = 0;

    /** @brief Returns coefficients of the classifier trained for people detection.
     */
    virtual Mat getDefaultPeopleDetector() const = 0;

    /** @brief Performs object detection without a multi-scale window.

    @param img Source image. CV_8UC1 and CV_8UC4 types are supported for now.
    @param found_locations Left-top corner points of detected objects boundaries.
    @param confidences Optional output array for confidences.
     */
    virtual void detect(InputArray img,
                        std::vector<Point>& found_locations,
                        std::vector<double>* confidences = NULL) = 0;

    /** @brief Performs object detection with a multi-scale window.

    @param img Source image. See cuda::HOGDescriptor::detect for type limitations.
    @param found_locations Detected objects boundaries.
    @param confidences Optional output array for confidences.
    @param hit_threshold Threshold for the distance between features and SVM classifying plane. See
    cuda::HOGDescriptor::detect for details.
    @param win_stride Window stride. It must be a multiple of block stride.
    @param padding Mock parameter to keep the CPU interface compatibility. It must be (0,0).
     */
    virtual void detectMultiScale(InputArray img,
                                  std::vector<Rect>& found_locations,
                                  std::vector<double>* confidences = NULL) = 0;

    /** @brief Returns block descriptors computed for the whole image.

    @param img Source image. See cuda::HOGDescriptor::detect for type limitations.
    @param descriptors 2D array of descriptors.
    @param stream CUDA stream.
     */
    virtual void compute(InputArray img,
                         OutputArray descriptors,
                         Stream& stream = Stream::Null()) = 0;
};

//
// CascadeClassifier
//

/** @brief Cascade classifier class used for object detection. Supports HAAR and LBP cascades. :

@note
   -   A cascade classifier example can be found at
        opencv_source_code/samples/gpu/cascadeclassifier.cpp
    -   A Nvidea API specific cascade classifier example can be found at
        opencv_source_code/samples/gpu/cascadeclassifier_nvidia_api.cpp
 */
class CV_EXPORTS CascadeClassifier : public Algorithm
{
public:
    /** @brief Loads the classifier from a file. Cascade type is detected automatically by constructor parameter.

    @param filename Name of the file from which the classifier is loaded. Only the old haar classifier
    (trained by the haar training application) and NVIDIA's nvbin are supported for HAAR and only new
    type of OpenCV XML cascade supported for LBP.
     */
    static Ptr<CascadeClassifier> create(const String& filename);
    /** @overload
     */
    static Ptr<CascadeClassifier> create(const FileStorage& file);

    //! Maximum possible object size. Objects larger than that are ignored. Used for
    //! second signature and supported only for LBP cascades.
    virtual void setMaxObjectSize(Size maxObjectSize) = 0;
    virtual Size getMaxObjectSize() const = 0;

    //! Minimum possible object size. Objects smaller than that are ignored.
    virtual void setMinObjectSize(Size minSize) = 0;
    virtual Size getMinObjectSize() const = 0;

    //! Parameter specifying how much the image size is reduced at each image scale.
    virtual void setScaleFactor(double scaleFactor) = 0;
    virtual double getScaleFactor() const = 0;

    //! Parameter specifying how many neighbors each candidate rectangle should have
    //! to retain it.
    virtual void setMinNeighbors(int minNeighbors) = 0;
    virtual int getMinNeighbors() const = 0;

    virtual void setFindLargestObject(bool findLargestObject) = 0;
    virtual bool getFindLargestObject() = 0;

    virtual void setMaxNumObjects(int maxNumObjects) = 0;
    virtual int getMaxNumObjects() const = 0;

    virtual Size getClassifierSize() const = 0;

    /** @brief Detects objects of different sizes in the input image.

    @param image Matrix of type CV_8U containing an image where objects should be detected.
    @param objects Buffer to store detected objects (rectangles).

    To get final array of detected objects use CascadeClassifier::convert method.

    @code
        Ptr<cuda::CascadeClassifier> cascade_gpu = cuda::CascadeClassifier::create(...);

        Mat image_cpu = imread(...)
        GpuMat image_gpu(image_cpu);

        GpuMat objbuf;
        cascade_gpu->detectMultiScale(image_gpu, objbuf);

        std::vector<Rect> faces;
        cascade_gpu->convert(objbuf, faces);

        for(int i = 0; i < detections_num; ++i)
           cv::rectangle(image_cpu, faces[i], Scalar(255));

        imshow("Faces", image_cpu);
    @endcode

    @sa CascadeClassifier::detectMultiScale
     */
    virtual void detectMultiScale(InputArray image,
                                  OutputArray objects,
                                  Stream& stream = Stream::Null()) = 0;

    /** @brief Converts objects array from internal representation to standard vector.

    @param gpu_objects Objects array in internal representation.
    @param objects Resulting array.
     */
    virtual void convert(OutputArray gpu_objects,
                         std::vector<Rect>& objects) = 0;
};

//! @}

}} // namespace cv { namespace cuda {

#endif /* __OPENCV_CUDAOBJDETECT_HPP__ */
<commit_msg>fix documentation warnings<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_CUDAOBJDETECT_HPP__
#define __OPENCV_CUDAOBJDETECT_HPP__

#ifndef __cplusplus
#  error cudaobjdetect.hpp header must be compiled as C++
#endif

#include "opencv2/core/cuda.hpp"

/**
  @addtogroup cuda
  @{
      @defgroup cudaobjdetect Object Detection
  @}
 */

namespace cv { namespace cuda {

//! @addtogroup cudaobjdetect
//! @{

//
// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector
//

/** @brief The class implements Histogram of Oriented Gradients (@cite Dalal2005) object detector.

@note
    -   An example applying the HOG descriptor for people detection can be found at
        opencv_source_code/samples/cpp/peopledetect.cpp
    -   A CUDA example applying the HOG descriptor for people detection can be found at
        opencv_source_code/samples/gpu/hog.cpp
    -   (Python) An example applying the HOG descriptor for people detection can be found at
        opencv_source_code/samples/python2/peopledetect.py
 */
class CV_EXPORTS HOG : public Algorithm
{
public:
    enum
    {
        DESCR_FORMAT_ROW_BY_ROW,
        DESCR_FORMAT_COL_BY_COL
    };

    /** @brief Creates the HOG descriptor and detector.

    @param win_size Detection window size. Align to block size and block stride.
    @param block_size Block size in pixels. Align to cell size. Only (16,16) is supported for now.
    @param block_stride Block stride. It must be a multiple of cell size.
    @param cell_size Cell size. Only (8, 8) is supported for now.
    @param nbins Number of bins. Only 9 bins per cell are supported for now.
     */
    static Ptr<HOG> create(Size win_size = Size(64, 128),
                           Size block_size = Size(16, 16),
                           Size block_stride = Size(8, 8),
                           Size cell_size = Size(8, 8),
                           int nbins = 9);

    //! Gaussian smoothing window parameter.
    virtual void setWinSigma(double win_sigma) = 0;
    virtual double getWinSigma() const = 0;

    //! L2-Hys normalization method shrinkage.
    virtual void setL2HysThreshold(double threshold_L2hys) = 0;
    virtual double getL2HysThreshold() const = 0;

    //! Flag to specify whether the gamma correction preprocessing is required or not.
    virtual void setGammaCorrection(bool gamma_correction) = 0;
    virtual bool getGammaCorrection() const = 0;

    //! Maximum number of detection window increases.
    virtual void setNumLevels(int nlevels) = 0;
    virtual int getNumLevels() const = 0;

    //! Threshold for the distance between features and SVM classifying plane.
    //! Usually it is 0 and should be specfied in the detector coefficients (as the last free
    //! coefficient). But if the free coefficient is omitted (which is allowed), you can specify it
    //! manually here.
    virtual void setHitThreshold(double hit_threshold) = 0;
    virtual double getHitThreshold() const = 0;

    //! Window stride. It must be a multiple of block stride.
    virtual void setWinStride(Size win_stride) = 0;
    virtual Size getWinStride() const = 0;

    //! Coefficient of the detection window increase.
    virtual void setScaleFactor(double scale0) = 0;
    virtual double getScaleFactor() const = 0;

    //! Coefficient to regulate the similarity threshold. When detected, some
    //! objects can be covered by many rectangles. 0 means not to perform grouping.
    //! See groupRectangles.
    virtual void setGroupThreshold(int group_threshold) = 0;
    virtual int getGroupThreshold() const = 0;

    //! Descriptor storage format:
    //!   - **DESCR_FORMAT_ROW_BY_ROW** - Row-major order.
    //!   - **DESCR_FORMAT_COL_BY_COL** - Column-major order.
    virtual void setDescriptorFormat(int descr_format) = 0;
    virtual int getDescriptorFormat() const = 0;

    /** @brief Returns the number of coefficients required for the classification.
     */
    virtual size_t getDescriptorSize() const = 0;

    /** @brief Returns the block histogram size.
     */
    virtual size_t getBlockHistogramSize() const = 0;

    /** @brief Sets coefficients for the linear SVM classifier.
     */
    virtual void setSVMDetector(InputArray detector) = 0;

    /** @brief Returns coefficients of the classifier trained for people detection.
     */
    virtual Mat getDefaultPeopleDetector() const = 0;

    /** @brief Performs object detection without a multi-scale window.

    @param img Source image. CV_8UC1 and CV_8UC4 types are supported for now.
    @param found_locations Left-top corner points of detected objects boundaries.
    @param confidences Optional output array for confidences.
     */
    virtual void detect(InputArray img,
                        std::vector<Point>& found_locations,
                        std::vector<double>* confidences = NULL) = 0;

    /** @brief Performs object detection with a multi-scale window.

    @param img Source image. See cuda::HOGDescriptor::detect for type limitations.
    @param found_locations Detected objects boundaries.
    @param confidences Optional output array for confidences.
     */
    virtual void detectMultiScale(InputArray img,
                                  std::vector<Rect>& found_locations,
                                  std::vector<double>* confidences = NULL) = 0;

    /** @brief Returns block descriptors computed for the whole image.

    @param img Source image. See cuda::HOGDescriptor::detect for type limitations.
    @param descriptors 2D array of descriptors.
    @param stream CUDA stream.
     */
    virtual void compute(InputArray img,
                         OutputArray descriptors,
                         Stream& stream = Stream::Null()) = 0;
};

//
// CascadeClassifier
//

/** @brief Cascade classifier class used for object detection. Supports HAAR and LBP cascades. :

@note
   -   A cascade classifier example can be found at
        opencv_source_code/samples/gpu/cascadeclassifier.cpp
    -   A Nvidea API specific cascade classifier example can be found at
        opencv_source_code/samples/gpu/cascadeclassifier_nvidia_api.cpp
 */
class CV_EXPORTS CascadeClassifier : public Algorithm
{
public:
    /** @brief Loads the classifier from a file. Cascade type is detected automatically by constructor parameter.

    @param filename Name of the file from which the classifier is loaded. Only the old haar classifier
    (trained by the haar training application) and NVIDIA's nvbin are supported for HAAR and only new
    type of OpenCV XML cascade supported for LBP.
     */
    static Ptr<CascadeClassifier> create(const String& filename);
    /** @overload
     */
    static Ptr<CascadeClassifier> create(const FileStorage& file);

    //! Maximum possible object size. Objects larger than that are ignored. Used for
    //! second signature and supported only for LBP cascades.
    virtual void setMaxObjectSize(Size maxObjectSize) = 0;
    virtual Size getMaxObjectSize() const = 0;

    //! Minimum possible object size. Objects smaller than that are ignored.
    virtual void setMinObjectSize(Size minSize) = 0;
    virtual Size getMinObjectSize() const = 0;

    //! Parameter specifying how much the image size is reduced at each image scale.
    virtual void setScaleFactor(double scaleFactor) = 0;
    virtual double getScaleFactor() const = 0;

    //! Parameter specifying how many neighbors each candidate rectangle should have
    //! to retain it.
    virtual void setMinNeighbors(int minNeighbors) = 0;
    virtual int getMinNeighbors() const = 0;

    virtual void setFindLargestObject(bool findLargestObject) = 0;
    virtual bool getFindLargestObject() = 0;

    virtual void setMaxNumObjects(int maxNumObjects) = 0;
    virtual int getMaxNumObjects() const = 0;

    virtual Size getClassifierSize() const = 0;

    /** @brief Detects objects of different sizes in the input image.

    @param image Matrix of type CV_8U containing an image where objects should be detected.
    @param objects Buffer to store detected objects (rectangles).
    @param stream CUDA stream.

    To get final array of detected objects use CascadeClassifier::convert method.

    @code
        Ptr<cuda::CascadeClassifier> cascade_gpu = cuda::CascadeClassifier::create(...);

        Mat image_cpu = imread(...)
        GpuMat image_gpu(image_cpu);

        GpuMat objbuf;
        cascade_gpu->detectMultiScale(image_gpu, objbuf);

        std::vector<Rect> faces;
        cascade_gpu->convert(objbuf, faces);

        for(int i = 0; i < detections_num; ++i)
           cv::rectangle(image_cpu, faces[i], Scalar(255));

        imshow("Faces", image_cpu);
    @endcode

    @sa CascadeClassifier::detectMultiScale
     */
    virtual void detectMultiScale(InputArray image,
                                  OutputArray objects,
                                  Stream& stream = Stream::Null()) = 0;

    /** @brief Converts objects array from internal representation to standard vector.

    @param gpu_objects Objects array in internal representation.
    @param objects Resulting array.
     */
    virtual void convert(OutputArray gpu_objects,
                         std::vector<Rect>& objects) = 0;
};

//! @}

}} // namespace cv { namespace cuda {

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


<commit_before>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 * Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse.
 *
 * metaverse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <metaverse/network/hosts.hpp>
#include <metaverse/macros_define.hpp>

#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
#include <metaverse/bitcoin.hpp>
#include <metaverse/bitcoin/utility/path.hpp>
#include <metaverse/bitcoin/math/limits.hpp>
#include <metaverse/network/settings.hpp>
#include <metaverse/network/channel.hpp>

namespace libbitcoin {
namespace network {

uint32_t timer_interval = 60 * 5; // 5 minutes

hosts::hosts(threadpool& pool, const settings& settings)
    : seed_count(settings.seeds.size())
    , host_pool_capacity_(std::max(settings.host_pool_capacity, 1u))
    , buffer_(host_pool_capacity_)
    , backup_(host_pool_capacity_)
    , inactive_(host_pool_capacity_ * 2)
    , seeds_()
    , stopped_(true)
    , file_path_(default_data_path() / settings.hosts_file)
    , disabled_(settings.host_pool_capacity == 0)
    , pool_(pool)
    , self_(settings.self)
{
}

// private
hosts::iterator hosts::find(const address& host)
{
    return find(buffer_, host);
}

hosts::iterator hosts::find(list& buffer, const address& host)
{
    const auto found = [&host](const address & entry)
    {
        return entry.port == host.port && entry.ip == host.ip;
    };
    return std::find_if(buffer.begin(), buffer.end(), found);
}

size_t hosts::count() const
{
    ///////////////////////////////////////////////////////////////////////////
    // Critical Section
    shared_lock lock(mutex_);

    return buffer_.size();
    ///////////////////////////////////////////////////////////////////////////
}

code hosts::fetch_seed(address& out, const config::authority::list& excluded_list)
{
    return fetch(seeds_, out, excluded_list);
}

code hosts::fetch(address& out, const config::authority::list& excluded_list)
{
    return fetch(buffer_, out, excluded_list);
}

template <typename T>
code hosts::fetch(T& buffer, address& out, const config::authority::list& excluded_list)
{
    if (disabled_) {
        return error::not_found;
    }

    // Critical Section
    shared_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    if (buffer.empty()) {
        return error::not_found;
    }

    auto match = [&excluded_list](address& addr) {
        auto auth = config::authority(addr);
        return std::find(excluded_list.begin(), excluded_list.end(), auth) == excluded_list.end();
    };

    std::vector<address> vec;
    std::copy_if(buffer.begin(), buffer.end(), std::back_inserter(vec), match);

    if (vec.empty()) {
        return error::not_found;
    }

    const auto index = pseudo_random(0, vec.size() - 1);
    out = vec[static_cast<size_t>(index)];

    return error::success;
}

hosts::address::list hosts::copy_seeds()
{
    if (disabled_)
        return address::list();

    shared_lock lock{mutex_};
    return seeds_;
}

hosts::address::list hosts::copy()
{
    if (disabled_)
        return address::list();

    shared_lock lock{mutex_};

    if (stopped_ || buffer_.empty())
        return address::list();

    // not copy all, but just 10% ~ 20% , at least one
    const auto out_count = std::max<size_t>(1,
        std::min<size_t>(1000, buffer_.size()) / pseudo_random(5, 10));

    const auto limit = buffer_.size();
    auto index = pseudo_random(0, limit - 1);

    address::list copy(out_count);

    for (size_t count = 0; count < out_count; ++count)
        copy.push_back(buffer_[index++ % limit]);

    pseudo_random::shuffle(copy);
    return copy;
}

bool hosts::store_cache(bool succeed_clear_buffer)
{
    if (!buffer_.empty()) {
        bc::ofstream file(file_path_.string());
        const auto file_error = file.bad();

        if (file_error) {
            log::error(LOG_NETWORK) << "hosts file (" << file_path_.string() << ") open failed" ;
            return false;
        }

        log::debug(LOG_NETWORK)
                << "sync hosts to file(" << file_path_.string()
                << "), inactive size is " << inactive_.size()
                << ", buffer size is " << buffer_.size();

        for (const auto& entry : buffer_) {
            // TODO: create full space-delimited network_address serialization.
            // Use to/from string format as opposed to wire serialization.
            if (!(channel::blacklisted(entry) || channel::manualbanned(entry))) {
                file << config::authority(entry) << std::endl;
            }
        }

        if (succeed_clear_buffer) {
            buffer_.clear();
        }
    }
    else {
        if (boost::filesystem::exists(file_path_.string())) {
            boost::filesystem::remove_all(file_path_.string());
        }
    }

    return true;
}

void hosts::handle_timer(const code& ec)
{
    if (disabled_) {
        return;
    }

    if (ec.value() != error::success) {
        return;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return;
    }

    {
        upgrade_to_unique_lock unq_lock(lock);

        if (!store_cache()) {
            return;
        }
    }

    snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));
}

// load
code hosts::start()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (!stopped_) {
        return error::operation_failed;
    }

    upgrade_to_unique_lock unq_lock(lock);
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    snap_timer_ = std::make_shared<deadline>(pool_, asio::seconds(timer_interval));
    snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));

    stopped_ = false;

    bc::ifstream file(file_path_.string());
    const auto file_error = file.bad();
    if (!file_error) {
        std::string line;
        while (std::getline(file, line)) {
            config::authority host(line);

            if (host.port() != 0) {
                auto network_address = host.to_network_address();
                if (network_address.is_routable()) {
                    buffer_.push_back(network_address);
                    if (buffer_.full()) {
                        break;
                    }
                }
                else {
                    log::debug(LOG_NETWORK) << "host start is not routable,"
                        << config::authority{network_address};
                }
            }
        }
    }

    if (file_error) {
        log::debug(LOG_NETWORK)
                << "Failed to save hosts file.";
        return error::file_system;
    }

    return error::success;
}

// load
code hosts::stop()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::success;
    }

    upgrade_to_unique_lock unq_lock(lock);

    // stop timer
    snap_timer_->stop();

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    stopped_ = true;

    if (!store_cache(true)) {
        return error::file_system;
    }

    return error::success;
}

code hosts::clear()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    if (!buffer_.empty()) {
        std::swap(backup_, buffer_);
        buffer_.clear();
    }

    return error::success;
}

code hosts::after_reseeding()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    //re-seeding failed and recover the buffer with backup one
    if (buffer_.size() <= seed_count) {
        log::debug(LOG_NETWORK)
                << "Reseeding finished, buffer size: " << buffer_.size()
                << ", less than seed count: " << seed_count
                << ", roll back the hosts cache.";

        if (!buffer_.full()) {
            for (auto& host : backup_) {
                if (find(host) == buffer_.end()) {
                    buffer_.push_back(host);

                    if (buffer_.full()) {
                        break;
                    }
                }
            }
        }
    }
    else {
        // filter inactive hosts
        for (auto &host : inactive_) {
            auto iter = find(host);
            if (iter != buffer_.end()) {
                buffer_.erase(iter);
            }
        }
    }

    // clear the backup
    backup_.clear();

    log::debug(LOG_NETWORK)
            << "Reseeding finished, buffer size: " << buffer_.size();

    return error::success;
}

code hosts::remove(const address& host)
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    auto it = find(host);
    if (it != buffer_.end()) {
        buffer_.erase(it);
    }

    if (find(inactive_, host) == inactive_.end()) {
        inactive_.push_back(host);
    }

    return error::success;
}

code hosts::store_seed(const address& host)
{
    // don't store blacklist and banned address
    if (channel::blacklisted(host) || channel::manualbanned(host)) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    auto iter = std::find_if(seeds_.begin(), seeds_.end(),
        [&host](const address& item){
            return host.ip == item.ip && host.port == item.port;
        });

    if (iter == seeds_.end()) {
        constexpr size_t max_seeds = 8;
        constexpr size_t half_pos = max_seeds >> 1;
        upgrade_to_unique_lock unq_lock(lock);
        if (seeds_.size() == max_seeds) { // full
            std::copy(seeds_.begin()+half_pos+1, seeds_.end(), seeds_.begin()+half_pos);
            seeds_.back() = host;
        }
        else {
            seeds_.push_back(host);
        }
#ifdef PRIVATE_CHAIN
        log::info(LOG_NETWORK) << "store seed " << config::authority(host).to_string();
#endif
    }

    return error::success;
}

code hosts::remove_seed(const address& host)
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    auto iter = std::find_if(seeds_.begin(), seeds_.end(),
        [&host](const address& item){
            return host.ip == item.ip && host.port == item.port;
        });

    if (iter != seeds_.end()) {
        upgrade_to_unique_lock unq_lock(lock);
        seeds_.erase(iter);

#ifdef PRIVATE_CHAIN
        log::info(LOG_NETWORK) << "remove seed " << config::authority(host).to_string();
#endif
    }

    return error::success;
}

code hosts::store(const address& host)
{
    if (disabled_) {
        return error::success;
    }

    if (!host.is_routable()) {
        // We don't treat invalid address as an error, just log it.
        return error::success;
    }

    // don't store self address
    auto authority = config::authority{host};
    if (authority == self_ || authority.port() == 0) {
        return error::success;
    }

    // don't store blacklist and banned address
    if (channel::blacklisted(host) || channel::manualbanned(host)) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    if (find(host) == buffer_.end()) {
        buffer_.push_back(host);
    }

    auto iter = find(inactive_, host);
    if (iter != inactive_.end()) {
        inactive_.erase(iter);
    }

    return error::success;
}

// The handler is invoked once all calls to do_store are completed.
// We disperse here to allow other addresses messages to interleave hosts.
void hosts::store(const address::list& hosts, result_handler handler)
{
    if (disabled_ || hosts.empty()) {
        handler(error::success);
        return;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        handler(error::service_stopped);
        return;
    }

    // Accept between 1 and all of this peer's addresses up to capacity.
    const auto capacity = host_pool_capacity_;
    size_t host_size = hosts.size();
    const size_t usable = std::min(host_size, capacity);
    const size_t random = static_cast<size_t>(pseudo_random(1, usable));

    // But always accept at least the amount we are short if available.
    const size_t gap = capacity - buffer_.size();
    const size_t accept = std::max(gap, random);

    // Convert minimum desired to step for iteration, no less than 1.
    const auto step = std::max(usable / accept, size_t(1));
    size_t accepted = 0;

    {
        upgrade_to_unique_lock unq_lock(lock);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        for (size_t index = 0; index < usable; index = ceiling_add(index, step)) {
            const auto& host = hosts[index];

            // Do not treat invalid address as an error, just log it.
            if (!host.is_valid()) {
                log::debug(LOG_NETWORK)
                        << "Invalid host address from peer.";
                continue;
            }

            if (channel::blacklisted(host) || channel::manualbanned(host)) {
                continue;
            }

            // Do not allow duplicates in the host cache.
            if (find(host) == buffer_.end()
                    && find(inactive_, host) == inactive_.end()) {
                ++accepted;
                buffer_.push_back(host);
            }
        }

        log::debug(LOG_NETWORK)
                << "Accepted (" << accepted << " of " << hosts.size()
                << ") host addresses from peer."
                << " inactive size is " << inactive_.size()
                << ", buffer size is " << buffer_.size();
    }

    // Notice: don't unique lock this handler
    handler(error::success);
}

} // namespace network
} // namespace libbitcoin
<commit_msg>do not use swap on boost::circular_buffer<commit_after>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 * Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse.
 *
 * metaverse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <metaverse/network/hosts.hpp>
#include <metaverse/macros_define.hpp>

#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
#include <metaverse/bitcoin.hpp>
#include <metaverse/bitcoin/utility/path.hpp>
#include <metaverse/bitcoin/math/limits.hpp>
#include <metaverse/network/settings.hpp>
#include <metaverse/network/channel.hpp>

namespace libbitcoin {
namespace network {

uint32_t timer_interval = 60 * 5; // 5 minutes

hosts::hosts(threadpool& pool, const settings& settings)
    : seed_count(settings.seeds.size())
    , host_pool_capacity_(std::max(settings.host_pool_capacity, 1u))
    , buffer_(host_pool_capacity_)
    , backup_(host_pool_capacity_)
    , inactive_(host_pool_capacity_ * 2)
    , seeds_()
    , stopped_(true)
    , file_path_(default_data_path() / settings.hosts_file)
    , disabled_(settings.host_pool_capacity == 0)
    , pool_(pool)
    , self_(settings.self)
{
}

// private
hosts::iterator hosts::find(const address& host)
{
    return find(buffer_, host);
}

hosts::iterator hosts::find(list& buffer, const address& host)
{
    const auto found = [&host](const address & entry)
    {
        return entry.port == host.port && entry.ip == host.ip;
    };
    return std::find_if(buffer.begin(), buffer.end(), found);
}

size_t hosts::count() const
{
    ///////////////////////////////////////////////////////////////////////////
    // Critical Section
    shared_lock lock(mutex_);

    return buffer_.size();
    ///////////////////////////////////////////////////////////////////////////
}

code hosts::fetch_seed(address& out, const config::authority::list& excluded_list)
{
    return fetch(seeds_, out, excluded_list);
}

code hosts::fetch(address& out, const config::authority::list& excluded_list)
{
    return fetch(buffer_, out, excluded_list);
}

template <typename T>
code hosts::fetch(T& buffer, address& out, const config::authority::list& excluded_list)
{
    if (disabled_) {
        return error::not_found;
    }

    // Critical Section
    shared_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    if (buffer.empty()) {
        return error::not_found;
    }

    auto match = [&excluded_list](address& addr) {
        auto auth = config::authority(addr);
        return std::find(excluded_list.begin(), excluded_list.end(), auth) == excluded_list.end();
    };

    std::vector<address> vec;
    std::copy_if(buffer.begin(), buffer.end(), std::back_inserter(vec), match);

    if (vec.empty()) {
        return error::not_found;
    }

    const auto index = pseudo_random(0, vec.size() - 1);
    out = vec[static_cast<size_t>(index)];

    return error::success;
}

hosts::address::list hosts::copy_seeds()
{
    if (disabled_)
        return address::list();

    shared_lock lock{mutex_};
    return seeds_;
}

hosts::address::list hosts::copy()
{
    if (disabled_)
        return address::list();

    shared_lock lock{mutex_};

    if (stopped_ || buffer_.empty())
        return address::list();

    // not copy all, but just 10% ~ 20% , at least one
    const auto out_count = std::max<size_t>(1,
        std::min<size_t>(1000, buffer_.size()) / pseudo_random(5, 10));

    const auto limit = buffer_.size();
    auto index = pseudo_random(0, limit - 1);

    address::list copy(out_count);

    for (size_t count = 0; count < out_count; ++count)
        copy.push_back(buffer_[index++ % limit]);

    pseudo_random::shuffle(copy);
    return copy;
}

bool hosts::store_cache(bool succeed_clear_buffer)
{
    if (!buffer_.empty()) {
        bc::ofstream file(file_path_.string());
        const auto file_error = file.bad();

        if (file_error) {
            log::error(LOG_NETWORK) << "hosts file (" << file_path_.string() << ") open failed" ;
            return false;
        }

        log::debug(LOG_NETWORK)
                << "sync hosts to file(" << file_path_.string()
                << "), inactive size is " << inactive_.size()
                << ", buffer size is " << buffer_.size();

        for (const auto& entry : buffer_) {
            // TODO: create full space-delimited network_address serialization.
            // Use to/from string format as opposed to wire serialization.
            if (!(channel::blacklisted(entry) || channel::manualbanned(entry))) {
                file << config::authority(entry) << std::endl;
            }
        }

        if (succeed_clear_buffer) {
            buffer_.clear();
        }
    }
    else {
        if (boost::filesystem::exists(file_path_.string())) {
            boost::filesystem::remove_all(file_path_.string());
        }
    }

    return true;
}

void hosts::handle_timer(const code& ec)
{
    if (disabled_) {
        return;
    }

    if (ec.value() != error::success) {
        return;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return;
    }

    {
        upgrade_to_unique_lock unq_lock(lock);

        if (!store_cache()) {
            return;
        }
    }

    snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));
}

// load
code hosts::start()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (!stopped_) {
        return error::operation_failed;
    }

    upgrade_to_unique_lock unq_lock(lock);
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    snap_timer_ = std::make_shared<deadline>(pool_, asio::seconds(timer_interval));
    snap_timer_->start(std::bind(&hosts::handle_timer, shared_from_this(), std::placeholders::_1));

    stopped_ = false;

    bc::ifstream file(file_path_.string());
    const auto file_error = file.bad();
    if (!file_error) {
        std::string line;
        while (std::getline(file, line)) {
            config::authority host(line);

            if (host.port() != 0) {
                auto network_address = host.to_network_address();
                if (network_address.is_routable()) {
                    buffer_.push_back(network_address);
                    if (buffer_.full()) {
                        break;
                    }
                }
                else {
                    log::debug(LOG_NETWORK) << "host start is not routable,"
                        << config::authority{network_address};
                }
            }
        }
    }

    if (file_error) {
        log::debug(LOG_NETWORK)
                << "Failed to save hosts file.";
        return error::file_system;
    }

    return error::success;
}

// load
code hosts::stop()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::success;
    }

    upgrade_to_unique_lock unq_lock(lock);

    // stop timer
    snap_timer_->stop();

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    stopped_ = true;

    if (!store_cache(true)) {
        return error::file_system;
    }

    return error::success;
}

code hosts::clear()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    if (!buffer_.empty()) {
        backup_.clear();
        std::copy(buffer_.begin(), buffer_.end(), std::back_inserter(backup_));
        buffer_.clear();
    }

    return error::success;
}

code hosts::after_reseeding()
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    //re-seeding failed and recover the buffer with backup one
    if (buffer_.size() <= seed_count) {
        log::debug(LOG_NETWORK)
                << "Reseeding finished, buffer size: " << buffer_.size()
                << ", less than seed count: " << seed_count
                << ", roll back the hosts cache.";

        if (!buffer_.full()) {
            for (auto& host : backup_) {
                if (find(host) == buffer_.end()) {
                    buffer_.push_back(host);

                    if (buffer_.full()) {
                        break;
                    }
                }
            }
        }
    }
    else {
        // filter inactive hosts
        for (auto &host : inactive_) {
            auto iter = find(host);
            if (iter != buffer_.end()) {
                buffer_.erase(iter);
            }
        }
    }

    // clear the backup
    backup_.clear();

    log::debug(LOG_NETWORK)
            << "Reseeding finished, buffer size: " << buffer_.size();

    return error::success;
}

code hosts::remove(const address& host)
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    auto it = find(host);
    if (it != buffer_.end()) {
        buffer_.erase(it);
    }

    if (find(inactive_, host) == inactive_.end()) {
        inactive_.push_back(host);
    }

    return error::success;
}

code hosts::store_seed(const address& host)
{
    // don't store blacklist and banned address
    if (channel::blacklisted(host) || channel::manualbanned(host)) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    auto iter = std::find_if(seeds_.begin(), seeds_.end(),
        [&host](const address& item){
            return host.ip == item.ip && host.port == item.port;
        });

    if (iter == seeds_.end()) {
        constexpr size_t max_seeds = 8;
        constexpr size_t half_pos = max_seeds >> 1;
        upgrade_to_unique_lock unq_lock(lock);
        if (seeds_.size() == max_seeds) { // full
            std::copy(seeds_.begin()+half_pos+1, seeds_.end(), seeds_.begin()+half_pos);
            seeds_.back() = host;
        }
        else {
            seeds_.push_back(host);
        }
#ifdef PRIVATE_CHAIN
        log::info(LOG_NETWORK) << "store seed " << config::authority(host).to_string();
#endif
    }

    return error::success;
}

code hosts::remove_seed(const address& host)
{
    if (disabled_) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    auto iter = std::find_if(seeds_.begin(), seeds_.end(),
        [&host](const address& item){
            return host.ip == item.ip && host.port == item.port;
        });

    if (iter != seeds_.end()) {
        upgrade_to_unique_lock unq_lock(lock);
        seeds_.erase(iter);

#ifdef PRIVATE_CHAIN
        log::info(LOG_NETWORK) << "remove seed " << config::authority(host).to_string();
#endif
    }

    return error::success;
}

code hosts::store(const address& host)
{
    if (disabled_) {
        return error::success;
    }

    if (!host.is_routable()) {
        // We don't treat invalid address as an error, just log it.
        return error::success;
    }

    // don't store self address
    auto authority = config::authority{host};
    if (authority == self_ || authority.port() == 0) {
        return error::success;
    }

    // don't store blacklist and banned address
    if (channel::blacklisted(host) || channel::manualbanned(host)) {
        return error::success;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        return error::service_stopped;
    }

    upgrade_to_unique_lock unq_lock(lock);

    if (find(host) == buffer_.end()) {
        buffer_.push_back(host);
    }

    auto iter = find(inactive_, host);
    if (iter != inactive_.end()) {
        inactive_.erase(iter);
    }

    return error::success;
}

// The handler is invoked once all calls to do_store are completed.
// We disperse here to allow other addresses messages to interleave hosts.
void hosts::store(const address::list& hosts, result_handler handler)
{
    if (disabled_ || hosts.empty()) {
        handler(error::success);
        return;
    }

    // Critical Section
    upgrade_lock lock(mutex_);

    if (stopped_) {
        handler(error::service_stopped);
        return;
    }

    // Accept between 1 and all of this peer's addresses up to capacity.
    const auto capacity = host_pool_capacity_;
    size_t host_size = hosts.size();
    const size_t usable = std::min(host_size, capacity);
    const size_t random = static_cast<size_t>(pseudo_random(1, usable));

    // But always accept at least the amount we are short if available.
    const size_t gap = capacity - buffer_.size();
    const size_t accept = std::max(gap, random);

    // Convert minimum desired to step for iteration, no less than 1.
    const auto step = std::max(usable / accept, size_t(1));
    size_t accepted = 0;

    {
        upgrade_to_unique_lock unq_lock(lock);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        for (size_t index = 0; index < usable; index = ceiling_add(index, step)) {
            const auto& host = hosts[index];

            // Do not treat invalid address as an error, just log it.
            if (!host.is_valid()) {
                log::debug(LOG_NETWORK)
                        << "Invalid host address from peer.";
                continue;
            }

            if (channel::blacklisted(host) || channel::manualbanned(host)) {
                continue;
            }

            // Do not allow duplicates in the host cache.
            if (find(host) == buffer_.end()
                    && find(inactive_, host) == inactive_.end()) {
                ++accepted;
                buffer_.push_back(host);
            }
        }

        log::debug(LOG_NETWORK)
                << "Accepted (" << accepted << " of " << hosts.size()
                << ") host addresses from peer."
                << " inactive size is " << inactive_.size()
                << ", buffer size is " << buffer_.size();
    }

    // Notice: don't unique lock this handler
    handler(error::success);
}

} // namespace network
} // namespace libbitcoin
<|endoftext|>


<commit_before><commit_msg>Planning : reduce the error frequency for multi-thread error in open space planner<commit_after><|endoftext|>


<commit_before><commit_msg>Perception: use EnsureDirectory to create directory at lane_camera_perception (#8094)<commit_after><|endoftext|>


<commit_before>#pragma once

#include <cstddef>
#include <cstdlib>
#include <type_traits>
#include <utility>
#include <cmath>
#include <iostream>

#include <typefu/traits.hpp>
#include <typefu/gen.hpp>

#include <typefu/restrict.hpp>
#include <typefu/promote.hpp>

#include <typefu/components.hpp>
#include <typefu/range.hpp>

#include <vec/vecType.hpp>
#include <swizzle/swizzle.hpp>
#include <swizzle/swizzle1.hpp>
#include <vec/tvec.hpp>
#include <vec/tvec2.hpp>
#include <mat/tmat.hpp>
#include <mat/tmat2.hpp>

#include <vec/opr/asig.hpp>
#include <vec/opr/enum.hpp>
#include <vec/opr/num.hpp>
#include <vec/opr/comp.hpp>
#include <vec/opr/io.hpp>

#include <vec/func/trig.hpp>
#include <vec/func/exp.hpp>
#include <vec/func/common.hpp>
#include <vec/func/geo.hpp>
#include <vec/func/rel.hpp>
#include <vec/func/reduct.hpp>
#include <vec/func/io.hpp>

#include <mat/opr/asig.hpp>
#include <mat/opr/num.hpp>
#include <mat/opr/comp.hpp>
#include <mat/opr/io.hpp>

#include <mat/func/reduct.hpp>
#include <mat/func/mat.hpp>
#include <mat/func/io.hpp>

#include <vec/vecType.tpp>
#include <swizzle/swizzle.tpp>
#include <swizzle/swizzle1.tpp>
#include <vec/tvec.tpp>
#include <vec/tvec2.tpp>
#include <mat/tmat.tpp>
#include <mat/tmat2.tpp>

#include <vec/opr/asig.tpp>
#include <vec/opr/enum.tpp>
#include <vec/opr/num.tpp>
#include <vec/opr/comp.tpp>
#include <vec/opr/io.tpp>

#include <vec/func/trig.tpp>
#include <vec/func/exp.tpp>
#include <vec/func/common.tpp>
#include <vec/func/geo.tpp>
#include <vec/func/rel.tpp>
#include <vec/func/reduct.tpp>
#include <vec/func/io.tpp>

#include <mat/opr/asig.tpp>
#include <mat/opr/num.tpp>
#include <mat/opr/comp.tpp>
#include <mat/opr/io.tpp>

#include <mat/func/reduct.tpp>
#include <mat/func/mat.tpp>
#include <mat/func/io.tpp>

#include <types.hpp>
<commit_msg>namespace wrapper<commit_after>#pragma once

#include <cstddef>
#include <cstdlib>
#include <type_traits>
#include <utility>
#include <cmath>
#include <iostream>

namespace mmm {

#include <typefu/traits.hpp>
#include <typefu/gen.hpp>

#include <typefu/restrict.hpp>
#include <typefu/promote.hpp>

#include <typefu/components.hpp>
#include <typefu/range.hpp>

#include <vec/vecType.hpp>
#include <swizzle/swizzle.hpp>
#include <swizzle/swizzle1.hpp>
#include <vec/tvec.hpp>
#include <vec/tvec2.hpp>
#include <mat/tmat.hpp>
#include <mat/tmat2.hpp>

#include <vec/opr/asig.hpp>
#include <vec/opr/enum.hpp>
#include <vec/opr/num.hpp>
#include <vec/opr/comp.hpp>
#include <vec/opr/io.hpp>

#include <vec/func/trig.hpp>
#include <vec/func/exp.hpp>
#include <vec/func/common.hpp>
#include <vec/func/geo.hpp>
#include <vec/func/rel.hpp>
#include <vec/func/reduct.hpp>
#include <vec/func/io.hpp>

#include <mat/opr/asig.hpp>
#include <mat/opr/num.hpp>
#include <mat/opr/comp.hpp>
#include <mat/opr/io.hpp>

#include <mat/func/reduct.hpp>
#include <mat/func/mat.hpp>
#include <mat/func/io.hpp>

#include <vec/vecType.tpp>
#include <swizzle/swizzle.tpp>
#include <swizzle/swizzle1.tpp>
#include <vec/tvec.tpp>
#include <vec/tvec2.tpp>
#include <mat/tmat.tpp>
#include <mat/tmat2.tpp>

#include <vec/opr/asig.tpp>
#include <vec/opr/enum.tpp>
#include <vec/opr/num.tpp>
#include <vec/opr/comp.tpp>
#include <vec/opr/io.tpp>

#include <vec/func/trig.tpp>
#include <vec/func/exp.tpp>
#include <vec/func/common.tpp>
#include <vec/func/geo.tpp>
#include <vec/func/rel.tpp>
#include <vec/func/reduct.tpp>
#include <vec/func/io.tpp>

#include <mat/opr/asig.tpp>
#include <mat/opr/num.tpp>
#include <mat/opr/comp.tpp>
#include <mat/opr/io.tpp>

#include <mat/func/reduct.tpp>
#include <mat/func/mat.tpp>
#include <mat/func/io.tpp>

#include <types.hpp>

}
<|endoftext|>