<commit_before>/*
 Copyright (c) 2019, Ford Motor Company, Livio
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the the copyright holders nor the names of their
 contributors may be used to endorse or promote products derived from this
 software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "app_service_rpc_plugin/app_service_mobile_command_factory.h"

#include "application_manager/message.h"
#include "interfaces/MOBILE_API.h"

#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request.h"
#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request_to_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response.h"
#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response_from_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification.h"
#include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification_from_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request_to_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response_from_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/publish_app_service_request.h"
#include "app_service_rpc_plugin/commands/mobile/publish_app_service_response.h"

CREATE_LOGGERPTR_GLOBAL(logger_, "AppServiceRpcPlugin")

namespace app_service_rpc_plugin {
namespace strings = app_mngr::strings;

AppServiceMobileCommandFactory::AppServiceMobileCommandFactory(
    application_manager::ApplicationManager& application_manager,
    application_manager::rpc_service::RPCService& rpc_service,
    application_manager::HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handler)
    : application_manager_(application_manager)
    , rpc_service_(rpc_service)
    , hmi_capabilities_(hmi_capabilities)
    , policy_handler_(policy_handler) {
  LOG4CXX_AUTO_TRACE(logger_);
}

app_mngr::CommandSharedPtr AppServiceMobileCommandFactory::CreateCommand(
    const app_mngr::commands::MessageSharedPtr& message,
    app_mngr::commands::Command::CommandSource source) {
  UNUSED(source);

  const mobile_apis::FunctionID::eType function_id =
      static_cast<mobile_apis::FunctionID::eType>(
          (*message)[strings::params][strings::function_id].asInt());

  const mobile_apis::messageType::eType message_type =
      static_cast<mobile_apis::messageType::eType>(
          (*message)[strings::params][strings::message_type].asInt());

  auto message_type_str = "request";
  if (mobile_apis::messageType::response == message_type) {
    message_type_str = "response";
  } else if (mobile_apis::messageType::notification == message_type) {
    message_type_str = "notification";
  }

  UNUSED(message_type_str);
  LOG4CXX_DEBUG(logger_,
                "HMICommandFactory::CreateCommand function_id: "
                    << function_id << ", message type: " << message_type_str);

  return buildCommandCreator(function_id, message_type, source).create(message);
}

bool AppServiceMobileCommandFactory::IsAbleToProcess(
    const int32_t function_id,
    const app_mngr::commands::Command::CommandSource source) const {
  UNUSED(source);
  return buildCommandCreator(function_id,
                             mobile_apis::messageType::INVALID_ENUM,
                             source).CanBeCreated();
}

app_mngr::CommandCreator& AppServiceMobileCommandFactory::buildCommandCreator(
    const int32_t function_id,
    const int32_t message_type,
    const app_mngr::commands::Command::CommandSource source) const {
  auto factory = app_mngr::CommandCreatorFactory(
      application_manager_, rpc_service_, hmi_capabilities_, policy_handler_);

  switch (function_id) {
    case mobile_apis::FunctionID::PublishAppServiceID:
      if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<commands::PublishAppServiceRequest>()
                   : factory.GetCreator<commands::PublishAppServiceResponse>();
      }
      break;
    case mobile_apis::FunctionID::OnAppServiceDataID:
      return app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source
                 ? factory.GetCreator<
                       commands::OnAppServiceDataNotificationFromMobile>()
                 : factory.GetCreator<commands::OnAppServiceDataNotification>();
    case mobile_apis::FunctionID::GetAppServiceDataID:
      if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<commands::GetAppServiceDataRequest>()
                   : factory.GetCreator<
                         commands::GetAppServiceDataResponseFromMobile>();
      } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL ==
                 source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<
                         commands::GetAppServiceDataRequestToMobile>()
                   : factory.GetCreator<commands::GetAppServiceDataResponse>();
      }
      break;
    case mobile_apis::FunctionID::PerformAppServiceInteractionID:
      if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<
                         commands::PerformAppServiceInteractionRequest>()
                   : factory.GetCreator<
                         commands::
                             PerformAppServiceInteractionResponseFromMobile>();
      } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL ==
                 source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<
                         commands::
                             PerformAppServiceInteractionRequestToMobile>()
                   : factory.GetCreator<
                         commands::PerformAppServiceInteractionResponse>();
      }
      break;
    default:
      LOG4CXX_WARN(logger_, "Unsupported function_id: " << function_id);
  }
  return factory.GetCreator<app_mngr::InvalidCommand>();
}
}  // namespace vehicle_info_plugin
<commit_msg>Fix creation of PublishAppService command<commit_after>/*
 Copyright (c) 2019, Ford Motor Company, Livio
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the the copyright holders nor the names of their
 contributors may be used to endorse or promote products derived from this
 software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "app_service_rpc_plugin/app_service_mobile_command_factory.h"

#include "application_manager/message.h"
#include "interfaces/MOBILE_API.h"

#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request.h"
#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request_to_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response.h"
#include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response_from_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification.h"
#include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification_from_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request_to_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response.h"
#include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response_from_mobile.h"
#include "app_service_rpc_plugin/commands/mobile/publish_app_service_request.h"
#include "app_service_rpc_plugin/commands/mobile/publish_app_service_response.h"

CREATE_LOGGERPTR_GLOBAL(logger_, "AppServiceRpcPlugin")

namespace app_service_rpc_plugin {
namespace strings = app_mngr::strings;

AppServiceMobileCommandFactory::AppServiceMobileCommandFactory(
    application_manager::ApplicationManager& application_manager,
    application_manager::rpc_service::RPCService& rpc_service,
    application_manager::HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handler)
    : application_manager_(application_manager)
    , rpc_service_(rpc_service)
    , hmi_capabilities_(hmi_capabilities)
    , policy_handler_(policy_handler) {
  LOG4CXX_AUTO_TRACE(logger_);
}

app_mngr::CommandSharedPtr AppServiceMobileCommandFactory::CreateCommand(
    const app_mngr::commands::MessageSharedPtr& message,
    app_mngr::commands::Command::CommandSource source) {
  UNUSED(source);

  const mobile_apis::FunctionID::eType function_id =
      static_cast<mobile_apis::FunctionID::eType>(
          (*message)[strings::params][strings::function_id].asInt());

  const mobile_apis::messageType::eType message_type =
      static_cast<mobile_apis::messageType::eType>(
          (*message)[strings::params][strings::message_type].asInt());

  auto message_type_str = "request";
  if (mobile_apis::messageType::response == message_type) {
    message_type_str = "response";
  } else if (mobile_apis::messageType::notification == message_type) {
    message_type_str = "notification";
  }

  UNUSED(message_type_str);
  LOG4CXX_DEBUG(logger_,
                "HMICommandFactory::CreateCommand function_id: "
                    << function_id << ", message type: " << message_type_str);

  return buildCommandCreator(function_id, message_type, source).create(message);
}

bool AppServiceMobileCommandFactory::IsAbleToProcess(
    const int32_t function_id,
    const app_mngr::commands::Command::CommandSource source) const {
  UNUSED(source);
  return buildCommandCreator(function_id,
                             mobile_apis::messageType::INVALID_ENUM,
                             source).CanBeCreated();
}

app_mngr::CommandCreator& AppServiceMobileCommandFactory::buildCommandCreator(
    const int32_t function_id,
    const int32_t message_type,
    const app_mngr::commands::Command::CommandSource source) const {
  auto factory = app_mngr::CommandCreatorFactory(
      application_manager_, rpc_service_, hmi_capabilities_, policy_handler_);

  switch (function_id) {
    case mobile_apis::FunctionID::PublishAppServiceID:
      if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source &&
          mobile_apis::messageType::response != message_type) {
        return factory.GetCreator<commands::PublishAppServiceRequest>();
      } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL ==
                     source &&
                 mobile_apis::messageType::request != message_type) {
        return factory.GetCreator<commands::PublishAppServiceResponse>();
      }
      break;
    case mobile_apis::FunctionID::OnAppServiceDataID:
      return app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source
                 ? factory.GetCreator<
                       commands::OnAppServiceDataNotificationFromMobile>()
                 : factory.GetCreator<commands::OnAppServiceDataNotification>();
    case mobile_apis::FunctionID::GetAppServiceDataID:
      if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<commands::GetAppServiceDataRequest>()
                   : factory.GetCreator<
                         commands::GetAppServiceDataResponseFromMobile>();
      } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL ==
                 source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<
                         commands::GetAppServiceDataRequestToMobile>()
                   : factory.GetCreator<commands::GetAppServiceDataResponse>();
      }
      break;
    case mobile_apis::FunctionID::PerformAppServiceInteractionID:
      if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<
                         commands::PerformAppServiceInteractionRequest>()
                   : factory.GetCreator<
                         commands::
                             PerformAppServiceInteractionResponseFromMobile>();
      } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL ==
                 source) {
        return mobile_apis::messageType::request == message_type
                   ? factory.GetCreator<
                         commands::
                             PerformAppServiceInteractionRequestToMobile>()
                   : factory.GetCreator<
                         commands::PerformAppServiceInteractionResponse>();
      }
      break;
    default:
      LOG4CXX_WARN(logger_, "Unsupported function_id: " << function_id);
  }
  return factory.GetCreator<app_mngr::InvalidCommand>();
}
}  // namespace vehicle_info_plugin
<|endoftext|>


<commit_before>/**
 * @file version.cpp
 * @brief Print OpenCV build info
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include <stdio.h>
#include <opencv2/core/utility.hpp>

int main() {
	printf("OpenCV: %s", cv::getBuildInformation().c_str());
}
<commit_msg>opencv/version: Fix build<commit_after>/**
 * @file version.cpp
 * @brief Print OpenCV build info
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include <stdio.h>
#include <opencv2/core/utility.hpp>

int main() {
	printf("OpenCV: %s", cv::getBuildInformation().c_str());

	return 0;
}
<|endoftext|>


<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/InvocationOptions.h"
#include "cling/Interpreter/ClingOptions.h"

#include "clang/Driver/Options.h"

#include "llvm/ADT/OwningPtr.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/raw_ostream.h"

using namespace clang;
using namespace cling::driver::clingoptions;

using namespace llvm;
using namespace llvm::opt;

namespace {

#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)
#include "cling/Interpreter/ClingOptions.inc"
#undef OPTION
#undef PREFIX

  static const OptTable::Info ClingInfoTable[] = {
#define PREFIX(NAME, VALUE)
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
    FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "cling/Interpreter/ClingOptions.inc"
#undef OPTION
#undef PREFIX
  };

  class ClingOptTable : public OptTable {
  public:
    ClingOptTable()
      : OptTable(ClingInfoTable,
                 sizeof(ClingInfoTable) / sizeof(ClingInfoTable[0])) {}
  };

  static OptTable* CreateClingOptTable() {
    return new ClingOptTable();
  }

  static void ParseStartupOpts(cling::InvocationOptions& Opts,
                               InputArgList& Args /* , Diags */) {
    Opts.ErrorOut = Args.hasArg(OPT__errorout);
    Opts.NoLogo = Args.hasArg(OPT__nologo);
    Opts.ShowVersion = Args.hasArg(OPT_version);
    Opts.Verbose = Args.hasArg(OPT_v);
    Opts.Help = Args.hasArg(OPT_help);
    if (Args.hasArg(OPT__metastr, OPT__metastr_EQ)) {
      Arg* MetaStringArg = Args.getLastArg(OPT__metastr, OPT__metastr_EQ);
      Opts.MetaString = MetaStringArg->getValue();
      if (Opts.MetaString.length() == 0) {
        llvm::errs() << "ERROR: meta string must be non-empty! Defaulting to '.'.\n";
        Opts.MetaString = ".";
      }
    }
  }

  static void ParseLinkerOpts(cling::InvocationOptions& Opts,
                              InputArgList& Args /* , Diags */) {
    Opts.LibsToLoad = Args.getAllArgValues(OPT_l);
    std::vector<std::string> LibPaths = Args.getAllArgValues(OPT_L);
    for (size_t i = 0; i < LibPaths.size(); ++i)
      Opts.LibSearchPath.push_back(LibPaths[i]);
  }

  static void ParseInputs(cling::InvocationOptions& Opts,
                          int argc, const char* const argv[]) {
    if (argc <= 1) { return; }
    unsigned MissingArgIndex, MissingArgCount;
    llvm::OwningPtr<OptTable> OptsC1(clang::driver::createDriverOptTable());
    Opts.Inputs.clear();
    llvm::OwningPtr<InputArgList> Args(
        OptsC1->ParseArgs(argv+1, argv + argc, MissingArgIndex, MissingArgCount));
    for (ArgList::const_iterator it = Args->begin(),
           ie = Args->end(); it != ie; ++it) {
      if ( (*it)->getOption().getKind() == Option::InputClass ) {
          Opts.Inputs.push_back(std::string( (*it)->getValue() ) );
      }
    }
  }
}

cling::InvocationOptions
cling::InvocationOptions::CreateFromArgs(int argc, const char* const argv[],
                                         std::vector<unsigned>& leftoverArgs
                                         /* , Diagnostic &Diags */) {
  InvocationOptions ClingOpts;
  llvm::OwningPtr<OptTable> Opts(CreateClingOptTable());
  unsigned MissingArgIndex, MissingArgCount;
  llvm::OwningPtr<InputArgList> Args(
    Opts->ParseArgs(argv, argv + argc, MissingArgIndex, MissingArgCount));

  //if (MissingArgCount)
  //  Diags.Report(diag::err_drv_missing_argument)
  //    << Args->getArgString(MissingArgIndex) << MissingArgCount;

  // Forward unknown arguments.
  for (ArgList::const_iterator it = Args->begin(),
         ie = Args->end(); it != ie; ++it) {
    if ((*it)->getOption().getKind() == Option::UnknownClass
        ||(*it)->getOption().getKind() == Option::InputClass) {
      leftoverArgs.push_back((*it)->getIndex());
    }
  }
  ParseStartupOpts(ClingOpts, *Args /* , Diags */);
  ParseLinkerOpts(ClingOpts, *Args /* , Diags */);
  ParseInputs(ClingOpts, argc, argv);
  return ClingOpts;
}

void cling::InvocationOptions::PrintHelp() {
  llvm::OwningPtr<OptTable> Opts(CreateClingOptTable());

  Opts->PrintHelp(llvm::outs(), "cling",
                  "cling: LLVM/clang C++ Interpreter: http://cern.ch/cling");

  llvm::OwningPtr<OptTable> OptsC1(clang::driver::createDriverOptTable());
  OptsC1->PrintHelp(llvm::outs(), "clang -cc1",
                    "LLVM 'Clang' Compiler: http://clang.llvm.org");

}
<commit_msg>Insert extra lines, makes the output prettier.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/InvocationOptions.h"
#include "cling/Interpreter/ClingOptions.h"

#include "clang/Driver/Options.h"

#include "llvm/ADT/OwningPtr.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/raw_ostream.h"

using namespace clang;
using namespace cling::driver::clingoptions;

using namespace llvm;
using namespace llvm::opt;

namespace {

#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)
#include "cling/Interpreter/ClingOptions.inc"
#undef OPTION
#undef PREFIX

  static const OptTable::Info ClingInfoTable[] = {
#define PREFIX(NAME, VALUE)
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
    FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "cling/Interpreter/ClingOptions.inc"
#undef OPTION
#undef PREFIX
  };

  class ClingOptTable : public OptTable {
  public:
    ClingOptTable()
      : OptTable(ClingInfoTable,
                 sizeof(ClingInfoTable) / sizeof(ClingInfoTable[0])) {}
  };

  static OptTable* CreateClingOptTable() {
    return new ClingOptTable();
  }

  static void ParseStartupOpts(cling::InvocationOptions& Opts,
                               InputArgList& Args /* , Diags */) {
    Opts.ErrorOut = Args.hasArg(OPT__errorout);
    Opts.NoLogo = Args.hasArg(OPT__nologo);
    Opts.ShowVersion = Args.hasArg(OPT_version);
    Opts.Verbose = Args.hasArg(OPT_v);
    Opts.Help = Args.hasArg(OPT_help);
    if (Args.hasArg(OPT__metastr, OPT__metastr_EQ)) {
      Arg* MetaStringArg = Args.getLastArg(OPT__metastr, OPT__metastr_EQ);
      Opts.MetaString = MetaStringArg->getValue();
      if (Opts.MetaString.length() == 0) {
        llvm::errs() << "ERROR: meta string must be non-empty! Defaulting to '.'.\n";
        Opts.MetaString = ".";
      }
    }
  }

  static void ParseLinkerOpts(cling::InvocationOptions& Opts,
                              InputArgList& Args /* , Diags */) {
    Opts.LibsToLoad = Args.getAllArgValues(OPT_l);
    std::vector<std::string> LibPaths = Args.getAllArgValues(OPT_L);
    for (size_t i = 0; i < LibPaths.size(); ++i)
      Opts.LibSearchPath.push_back(LibPaths[i]);
  }

  static void ParseInputs(cling::InvocationOptions& Opts,
                          int argc, const char* const argv[]) {
    if (argc <= 1) { return; }
    unsigned MissingArgIndex, MissingArgCount;
    llvm::OwningPtr<OptTable> OptsC1(clang::driver::createDriverOptTable());
    Opts.Inputs.clear();
    llvm::OwningPtr<InputArgList> Args(
        OptsC1->ParseArgs(argv+1, argv + argc, MissingArgIndex, MissingArgCount));
    for (ArgList::const_iterator it = Args->begin(),
           ie = Args->end(); it != ie; ++it) {
      if ( (*it)->getOption().getKind() == Option::InputClass ) {
          Opts.Inputs.push_back(std::string( (*it)->getValue() ) );
      }
    }
  }
}

cling::InvocationOptions
cling::InvocationOptions::CreateFromArgs(int argc, const char* const argv[],
                                         std::vector<unsigned>& leftoverArgs
                                         /* , Diagnostic &Diags */) {
  InvocationOptions ClingOpts;
  llvm::OwningPtr<OptTable> Opts(CreateClingOptTable());
  unsigned MissingArgIndex, MissingArgCount;
  llvm::OwningPtr<InputArgList> Args(
    Opts->ParseArgs(argv, argv + argc, MissingArgIndex, MissingArgCount));

  //if (MissingArgCount)
  //  Diags.Report(diag::err_drv_missing_argument)
  //    << Args->getArgString(MissingArgIndex) << MissingArgCount;

  // Forward unknown arguments.
  for (ArgList::const_iterator it = Args->begin(),
         ie = Args->end(); it != ie; ++it) {
    if ((*it)->getOption().getKind() == Option::UnknownClass
        ||(*it)->getOption().getKind() == Option::InputClass) {
      leftoverArgs.push_back((*it)->getIndex());
    }
  }
  ParseStartupOpts(ClingOpts, *Args /* , Diags */);
  ParseLinkerOpts(ClingOpts, *Args /* , Diags */);
  ParseInputs(ClingOpts, argc, argv);
  return ClingOpts;
}

void cling::InvocationOptions::PrintHelp() {
  llvm::OwningPtr<OptTable> Opts(CreateClingOptTable());

  Opts->PrintHelp(llvm::outs(), "cling",
                  "cling: LLVM/clang C++ Interpreter: http://cern.ch/cling");

  llvm::outs() << "\n\n";

  llvm::OwningPtr<OptTable> OptsC1(clang::driver::createDriverOptTable());
  OptsC1->PrintHelp(llvm::outs(), "clang -cc1",
                    "LLVM 'Clang' Compiler: http://clang.llvm.org");

}
<|endoftext|>


<commit_before>/* ******************************************************************************
 *
 *
 * This program and the accompanying materials are made available under the
 * terms of the Apache License, Version 2.0 which is available at
 * https://www.apache.org/licenses/LICENSE-2.0.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 ******************************************************************************/

//
// @author raver119@gmail.com
// @author Yurii Shyrma (iuriish@yahoo.com)
//
#include <array/DataBuffer.h>
#include <array/DataTypeUtils.h>
#if defined(HAVE_VEDA)
#include <ops/declarable/platform/vednn/veda_helper.h>
#endif

namespace sd {
void DataBuffer::expand(const uint64_t size) {
  if (size > _lenInBytes) {
    // allocate new buffer
    int8_t* newBuffer = nullptr;
    ALLOCATE(newBuffer, _workspace, size, int8_t);

    // copy data from existing buffer
    std::memcpy(newBuffer, _primaryBuffer, _lenInBytes);

    if (_isOwnerPrimary) {
      RELEASE(reinterpret_cast<int8_t*>(_primaryBuffer), _workspace);
    }

    _primaryBuffer = newBuffer;
    _lenInBytes = size;
    _isOwnerPrimary = true;
  }
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::allocateBuffers(const bool allocBoth) {  // always allocate primary buffer only (cpu case)

  allocatePrimary();
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyBufferFrom(const DataBuffer& other, size_t sizeToCopyinBytes, const sd::LongType offsetThis,
                                const sd::LongType offsetOther) {
  if (sizeToCopyinBytes == 0) sizeToCopyinBytes = other.getLenInBytes();
  if (sizeToCopyinBytes == 0) return;

  if (other._primaryBuffer != nullptr)
    std::memcpy(
        static_cast<int8_t*>(_primaryBuffer) + offsetThis * DataTypeUtils::sizeOfElement(_dataType),
        static_cast<const int8_t*>(other._primaryBuffer) + offsetOther * DataTypeUtils::sizeOfElement(other._dataType),
        sizeToCopyinBytes);
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyBufferFromHost(const void* hostBuffer, size_t sizeToCopyinBytes, const sd::LongType offsetThis,
                                    const sd::LongType offsetHostBuffer) {
  if (sizeToCopyinBytes == 0) sizeToCopyinBytes = getLenInBytes();
  if (sizeToCopyinBytes == 0) return;

  if (hostBuffer != nullptr)
    std::memcpy(static_cast<int8_t*>(_primaryBuffer) + offsetThis * DataTypeUtils::sizeOfElement(_dataType),
                static_cast<const int8_t*>(hostBuffer) + offsetHostBuffer * DataTypeUtils::sizeOfElement(_dataType),
                sizeToCopyinBytes);
}

/////////////////////////
void DataBuffer::memcpy(const DataBuffer& dst, const DataBuffer& src) {
  if (src._lenInBytes > dst._lenInBytes)
    throw std::runtime_error("DataBuffer::memcpy: Source data buffer is larger than destination");

  std::memcpy(dst._primaryBuffer, src._primaryBuffer, src._lenInBytes);
  dst.readPrimary();
}

////////////////////////////////////////////////////////////////////////

#if defined(HAVE_VEDA)
////////////////////////////////////////////////////////////////////////
void DataBuffer::deleteSpecial() {
  // device id for now is 0
  if (_specialBuffer) {
#if defined(DEBUG_VEDA_LOGS)
    sd_debug("%s \n", "remove Veda Buffer");
#endif
    VEDAdeviceptr v = (VEDAdeviceptr)_specialBuffer;
    VEDA_HANDLE& handle = VEDA::getInstance().getVEDA_HANDLE(0);
    SCOPED_VEDA_CONTEXT scopedContext(handle.getDevice());
    VEDA_CALL_THROW(vedaMemFreeAsync(v, 0));
    // sync here
    // scopedContext.sync();
    _specialBuffer = nullptr;
  }
}

////////////////////////////////////////////////////////////////////////
void** DataBuffer::getPtrToSpecial() const { return (void**)&_specialBuffer; }

void DataBuffer::showBufferLimited() {
#if defined(DEBUG_VEDA_LOGS)
  float* x = (float*)_primaryBuffer;
  size_t size = getLenInBytes();
  size = size > 80 ? 80 : 0;
  sd_debug("cpu: %p\n", (void*)x);
  for (int i = 0; i < size / sizeof(float); i++) sd_debug("%f, ", x[i]);
  sd_debug("%s", "\n");
#endif
}
////////////////////////////////////////////////////////////////////////
void DataBuffer::syncToPrimary(const LaunchContext* context, const bool forceSync) {
  if (isPrimaryActual() && !forceSync) {
    return;
  }
  // do it if we have _specialBuffer otherwise escape this as no op
  if (_specialBuffer) {
    allocatePrimary();
    // lets copy from _specialBuffer and sync it back
    // we will take device 0 as usual and sync on it
    sd_debug("%s \n", "syncToPrimary Veda Buffer");
#if defined(DEBUG_VEDA_LOGS)
    sd_debug("syncToPrimary--%p ---%p---{\n", _primaryBuffer, _specialBuffer);
    showBufferLimited();
#endif
    VEDA_HANDLE& handle = VEDA::getInstance().getVEDA_HANDLE(0);
    SCOPED_VEDA_CONTEXT scopedContext(handle.getDevice());
    VEDA_CALL_THROW(vedaMemcpyDtoHAsync(_primaryBuffer, (VEDAdeviceptr)_specialBuffer, getLenInBytes(), 0));
    // sync ops here to read completed result
    scopedContext.sync();
    readPrimary();
#if defined(DEBUG_VEDA_LOGS)
    if (sd::Environment::getInstance().isDebug() && sd::Environment::getInstance().isVerbose()) {
      auto fshow = handle.getFunctionByConstPtrName("showBufferVe");
      VEDA_CALL_THROW(vedaLaunchKernel(fshow, 0, (VEDAdeviceptr)_specialBuffer));
      scopedContext.sync();
    }
    sd_debug("%s", "----after---\n");
    // show buffer
    showBufferLimited();
    sd_debug("%s", "----}\n");
#endif
  }
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::setCountersToZero() {
  _counter.store(0L);
  _writePrimary.store(0L);
  _writeSpecial.store(0L);
  _readPrimary.store(0L);
  _readSpecial.store(0L);
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyCounters(const DataBuffer& other) {
  _counter.store(other._counter);
  _writePrimary.store(other._writePrimary);
  _writeSpecial.store(other._writeSpecial);
  _readPrimary.store(other._readPrimary);
  _readSpecial.store(other._readSpecial);
}

void DataBuffer::writePrimary() const { _writePrimary = ++_counter; }
void DataBuffer::writeSpecial() const { _writeSpecial = ++_counter; }
void DataBuffer::readPrimary() const { _readPrimary = ++_counter; }
void DataBuffer::readSpecial() const { _readSpecial = ++_counter; }
bool DataBuffer::isPrimaryActual() const {
  return (_writePrimary.load() > _writeSpecial.load() || _readPrimary.load() > _writeSpecial.load());
}
bool DataBuffer::isSpecialActual() const {
  return (_writeSpecial.load() > _writePrimary.load() || _readSpecial.load() > _writePrimary.load());
}

void DataBuffer::allocVeda(){

        if (!isSpecialActual() && !special()) {
          auto length = getLenInBytes();
          if (primary() && length > 0) {
#if defined(DEBUG_VEDA_LOGS)
            sd_debug("allocVeda: store result in %p\n", (void *)getPtrToSpecial());
#endif
            VEDA_CALL_THROW(vedaMemAllocAsync((VEDAdeviceptr *)getPtrToSpecial(), length, 0));
          } else {
#if defined(DEBUG_VEDA_LOGS)
            sd_debug("allocVeda: %s\n", "as the length is 0, its not important");
#endif
          }
        }
}

void DataBuffer::asyncToVeda(){
        if (!isSpecialActual()) {
          if (special()) {
            auto hostPtr = primary();
            auto length = getLenInBytes();
#if defined(DEBUG_VEDA_LOGS)
            sd_debug("asyncCopyToVeda: primary %p to special %p\n", hostPtr, special());
#endif
            VEDA_CALL_THROW(vedaMemcpyHtoDAsync((VEDAdeviceptr)special(), hostPtr, length, 0));
          }
          readSpecial();
        }
}
#else

////////////////////////////////////////////////////////////////////////
void DataBuffer::deleteSpecial() {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::syncToPrimary(const LaunchContext* context, const bool forceSync) {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::setCountersToZero() {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyCounters(const DataBuffer& other) {}

void DataBuffer::writePrimary() const {}
void DataBuffer::writeSpecial() const {}
void DataBuffer::readPrimary() const {}
void DataBuffer::readSpecial() const {}
bool DataBuffer::isPrimaryActual() const { return true; }
bool DataBuffer::isSpecialActual() const { return false; }
#endif

////////////////////////////////////////////////////////////////////////
void DataBuffer::setSpecial(void* special, const bool isOwnerSpecail) {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::setToZeroBuffers(const bool both) { memset(primary(), 0, getLenInBytes()); }

////////////////////////////////////////////////////////////////////////
void DataBuffer::syncToSpecial(const bool forceSync) {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::allocateSpecial() {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::migrate() {}

void DataBuffer::showCounters(const char* msg1, const char* msg2) {
#if defined(HAVE_VEDA) && defined(DEBUG_VEDA_LOGS)
  sd_debug("%s %s || primary %p special %p :: wP: %d wS: %d rP: %d rS: %d\n", msg1, msg2, _primaryBuffer,
           _specialBuffer, (int)_writePrimary.load(), (int)_writeSpecial.load(), (int)_readPrimary.load(),
           (int)_readSpecial.load());
#endif
}

}  // namespace sd
<commit_msg>typo (#9708)<commit_after>/* ******************************************************************************
 *
 *
 * This program and the accompanying materials are made available under the
 * terms of the Apache License, Version 2.0 which is available at
 * https://www.apache.org/licenses/LICENSE-2.0.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 ******************************************************************************/

//
// @author raver119@gmail.com
// @author Yurii Shyrma (iuriish@yahoo.com)
//
#include <array/DataBuffer.h>
#include <array/DataTypeUtils.h>
#if defined(HAVE_VEDA)
#include <ops/declarable/platform/vednn/veda_helper.h>
#endif

namespace sd {
void DataBuffer::expand(const uint64_t size) {
  if (size > _lenInBytes) {
    // allocate new buffer
    int8_t* newBuffer = nullptr;
    ALLOCATE(newBuffer, _workspace, size, int8_t);

    // copy data from existing buffer
    std::memcpy(newBuffer, _primaryBuffer, _lenInBytes);

    if (_isOwnerPrimary) {
      RELEASE(reinterpret_cast<int8_t*>(_primaryBuffer), _workspace);
    }

    _primaryBuffer = newBuffer;
    _lenInBytes = size;
    _isOwnerPrimary = true;
  }
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::allocateBuffers(const bool allocBoth) {  // always allocate primary buffer only (cpu case)

  allocatePrimary();
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyBufferFrom(const DataBuffer& other, size_t sizeToCopyinBytes, const sd::LongType offsetThis,
                                const sd::LongType offsetOther) {
  if (sizeToCopyinBytes == 0) sizeToCopyinBytes = other.getLenInBytes();
  if (sizeToCopyinBytes == 0) return;

  if (other._primaryBuffer != nullptr)
    std::memcpy(
        static_cast<int8_t*>(_primaryBuffer) + offsetThis * DataTypeUtils::sizeOfElement(_dataType),
        static_cast<const int8_t*>(other._primaryBuffer) + offsetOther * DataTypeUtils::sizeOfElement(other._dataType),
        sizeToCopyinBytes);
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyBufferFromHost(const void* hostBuffer, size_t sizeToCopyinBytes, const sd::LongType offsetThis,
                                    const sd::LongType offsetHostBuffer) {
  if (sizeToCopyinBytes == 0) sizeToCopyinBytes = getLenInBytes();
  if (sizeToCopyinBytes == 0) return;

  if (hostBuffer != nullptr)
    std::memcpy(static_cast<int8_t*>(_primaryBuffer) + offsetThis * DataTypeUtils::sizeOfElement(_dataType),
                static_cast<const int8_t*>(hostBuffer) + offsetHostBuffer * DataTypeUtils::sizeOfElement(_dataType),
                sizeToCopyinBytes);
}

/////////////////////////
void DataBuffer::memcpy(const DataBuffer& dst, const DataBuffer& src) {
  if (src._lenInBytes > dst._lenInBytes)
    throw std::runtime_error("DataBuffer::memcpy: Source data buffer is larger than destination");

  std::memcpy(dst._primaryBuffer, src._primaryBuffer, src._lenInBytes);
  dst.readPrimary();
}

////////////////////////////////////////////////////////////////////////

#if defined(HAVE_VEDA)
////////////////////////////////////////////////////////////////////////
void DataBuffer::deleteSpecial() {
  // device id for now is 0
  if (_specialBuffer) {
#if defined(DEBUG_VEDA_LOGS)
    sd_debug("%s \n", "remove Veda Buffer");
#endif
    VEDAdeviceptr v = (VEDAdeviceptr)_specialBuffer;
    VEDA_HANDLE& handle = VEDA::getInstance().getVEDA_HANDLE(0);
    SCOPED_VEDA_CONTEXT scopedContext(handle.getDevice());
    VEDA_CALL_THROW(vedaMemFreeAsync(v, 0));
    // sync here
    // scopedContext.sync();
    _specialBuffer = nullptr;
  }
}

////////////////////////////////////////////////////////////////////////
void** DataBuffer::getPtrToSpecial() const { return (void**)&_specialBuffer; }

void DataBuffer::showBufferLimited() {
#if defined(DEBUG_VEDA_LOGS)
  float* x = (float*)_primaryBuffer;
  size_t size = getLenInBytes();
  size = size > 80 ? 80 : 0;
  sd_debug("cpu: %p\n", (void*)x);
  for (int i = 0; i < size / sizeof(float); i++) sd_debug("%f, ", x[i]);
  sd_debug("%s", "\n");
#endif
}
////////////////////////////////////////////////////////////////////////
void DataBuffer::syncToPrimary(const LaunchContext* context, const bool forceSync) {
  if (isPrimaryActual() && !forceSync) {
    return;
  }
  // do it if we have _specialBuffer otherwise escape this as no op
  if (_specialBuffer) {
    allocatePrimary();
    // lets copy from _specialBuffer and sync it back
    // we will take device 0 as usual and sync on it
    sd_debug("%s \n", "syncToPrimary Veda Buffer");
#if defined(DEBUG_VEDA_LOGS)
    sd_debug("syncToPrimary--%p ---%p---{\n", _primaryBuffer, _specialBuffer);
    showBufferLimited();
#endif
    VEDA_HANDLE& handle = VEDA::getInstance().getVEDA_HANDLE(0);
    SCOPED_VEDA_CONTEXT scopedContext(handle.getDevice());
    VEDA_CALL_THROW(vedaMemcpyDtoHAsync(_primaryBuffer, (VEDAdeviceptr)_specialBuffer, getLenInBytes(), 0));
    // sync ops here to read completed result
    scopedContext.sync();
    readPrimary();
#if defined(DEBUG_VEDA_LOGS)
    if (sd::Environment::getInstance().isDebug() && sd::Environment::getInstance().isVerbose()) {
      auto fshow = handle.getFunctionByConstPtrName("showBufferVe");
      VEDA_CALL_THROW(vedaLaunchKernel(fshow, 0, (VEDAdeviceptr)_specialBuffer));
      scopedContext.sync();
    }
    sd_debug("%s", "----after---\n");
    // show buffer
    showBufferLimited();
    sd_debug("%s", "----}\n");
#endif
  }
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::setCountersToZero() {
  _counter.store(0L);
  _writePrimary.store(0L);
  _writeSpecial.store(0L);
  _readPrimary.store(0L);
  _readSpecial.store(0L);
}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyCounters(const DataBuffer& other) {
  _counter.store(other._counter);
  _writePrimary.store(other._writePrimary);
  _writeSpecial.store(other._writeSpecial);
  _readPrimary.store(other._readPrimary);
  _readSpecial.store(other._readSpecial);
}

void DataBuffer::writePrimary() const { _writePrimary = ++_counter; }
void DataBuffer::writeSpecial() const { _writeSpecial = ++_counter; }
void DataBuffer::readPrimary() const { _readPrimary = ++_counter; }
void DataBuffer::readSpecial() const { _readSpecial = ++_counter; }
bool DataBuffer::isPrimaryActual() const {
  return (_writePrimary.load() > _writeSpecial.load() || _readPrimary.load() > _writeSpecial.load());
}
bool DataBuffer::isSpecialActual() const {
  return (_writeSpecial.load() > _writePrimary.load() || _readSpecial.load() > _writePrimary.load());
}

void DataBuffer::allocVeda(){

        if (!isSpecialActual() && !special()) {
          auto length = getLenInBytes();
          if (primary() && length > 0) {
#if defined(DEBUG_VEDA_LOGS)
            sd_debug("allocVeda: store result in %p\n", (void *)getPtrToSpecial());
#endif
            VEDA_CALL_THROW(vedaMemAllocAsync((VEDAdeviceptr *)getPtrToSpecial(), length, 0));
          } else {
#if defined(DEBUG_VEDA_LOGS)
            sd_debug("allocVeda: %s\n", "as the length is 0, its not important");
#endif
          }
        }
}

void DataBuffer::asyncToVeda(){
        if (!isSpecialActual()) {
          if (special()) {
            auto hostPtr = primary();
            auto length = getLenInBytes();
#if defined(DEBUG_VEDA_LOGS)
            sd_debug("asyncCopyToVeda: primary %p to special %p\n", hostPtr, special());
#endif
            VEDA_CALL_THROW(vedaMemcpyHtoDAsync((VEDAdeviceptr)special(), hostPtr, length, 0));
          }
          readSpecial();
        }
}
#else

////////////////////////////////////////////////////////////////////////
void DataBuffer::deleteSpecial() {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::syncToPrimary(const LaunchContext* context, const bool forceSync) {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::setCountersToZero() {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::copyCounters(const DataBuffer& other) {}

void DataBuffer::writePrimary() const {}
void DataBuffer::writeSpecial() const {}
void DataBuffer::readPrimary() const {}
void DataBuffer::readSpecial() const {}
bool DataBuffer::isPrimaryActual() const { return true; }
bool DataBuffer::isSpecialActual() const { return false; }
void DataBuffer::showBufferLimited() {}
#endif

////////////////////////////////////////////////////////////////////////
void DataBuffer::setSpecial(void* special, const bool isOwnerSpecail) {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::setToZeroBuffers(const bool both) { memset(primary(), 0, getLenInBytes()); }

////////////////////////////////////////////////////////////////////////
void DataBuffer::syncToSpecial(const bool forceSync) {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::allocateSpecial() {}

////////////////////////////////////////////////////////////////////////
void DataBuffer::migrate() {}

void DataBuffer::showCounters(const char* msg1, const char* msg2) {
#if defined(HAVE_VEDA) && defined(DEBUG_VEDA_LOGS)
  sd_debug("%s %s || primary %p special %p :: wP: %d wS: %d rP: %d rS: %d\n", msg1, msg2, _primaryBuffer,
           _specialBuffer, (int)_writePrimary.load(), (int)_writeSpecial.load(), (int)_readPrimary.load(),
           (int)_readSpecial.load());
#endif
}

}  // namespace sd
<|endoftext|>


<commit_before>#include "Logging.hpp"

#include "common/logger/XmlLoggerSink.hpp"

#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/spdlog.h>

const std::string SpdLogger = "logger";

std::shared_ptr<spdlog::logger> Log::logger()
{
    static auto logger = spdlog::get(SpdLogger);
    return logger;
}

std::vector<spdlog::sink_ptr> createLoggerSinks()
{
    std::vector<spdlog::sink_ptr> sinks;

    sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
    sinks.push_back(std::make_shared<LoggerXmlSinkMt>(XmlLogsRepo::get()));

    return sinks;
}

std::shared_ptr<spdlog::logger> Log::create()
{
    return create(createLoggerSinks());
}

std::shared_ptr<spdlog::logger> Log::create(const std::vector<spdlog::sink_ptr>& sinks)
{
    auto logger = std::make_shared<spdlog::logger>(SpdLogger, sinks.begin(), sinks.end());
    logger->set_level(spdlog::level::debug);
    logger->set_pattern("[%H:%M:%S.%e] [%t] [%l]: %v");
    spdlog::register_logger(logger);
    return logger;
}

void Log::setLevel(const std::string& level)
{
    if (level == "trace")
        logger()->set_level(spdlog::level::trace);
    else if (level == "debug")
        logger()->set_level(spdlog::level::debug);
    else if (level == "info")
        logger()->set_level(spdlog::level::info);
    else if (level == "error")
        logger()->set_level(spdlog::level::err);
}
<commit_msg>fix: audit support for old CMS<commit_after>#include "Logging.hpp"

#include "common/logger/XmlLoggerSink.hpp"

#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/spdlog.h>

const std::string SpdLogger = "logger";

std::shared_ptr<spdlog::logger> Log::logger()
{
    static auto logger = spdlog::get(SpdLogger);
    return logger;
}

std::vector<spdlog::sink_ptr> createLoggerSinks()
{
    std::vector<spdlog::sink_ptr> sinks;

    sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
    sinks.push_back(std::make_shared<LoggerXmlSinkMt>(XmlLogsRepo::get()));

    return sinks;
}

std::shared_ptr<spdlog::logger> Log::create()
{
    return create(createLoggerSinks());
}

std::shared_ptr<spdlog::logger> Log::create(const std::vector<spdlog::sink_ptr>& sinks)
{
    auto logger = std::make_shared<spdlog::logger>(SpdLogger, sinks.begin(), sinks.end());
    logger->set_level(spdlog::level::debug);
    logger->set_pattern("[%H:%M:%S.%e] [%t] [%l]: %v");
    spdlog::register_logger(logger);
    return logger;
}

void Log::setLevel(const std::string& level)
{
    if (level == "trace" || level == "audit")
        logger()->set_level(spdlog::level::trace);
    else if (level == "debug")
        logger()->set_level(spdlog::level::debug);
    else if (level == "info")
        logger()->set_level(spdlog::level::info);
    else if (level == "error")
        logger()->set_level(spdlog::level::err);
}
<|endoftext|>


<commit_before>/***************************************************************************
                          Kopete Instant Messenger
							 kopetewindows.cpp
                            -------------------
				(C) 2001-2002 by Duncan Mac-Vicar P. <duncan@kde.org>
				(C) 2001-2002 by Stefan Gehn <sgehn@gmx.net>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kopetewindow.h"
#include "kopetewindow.moc"

#include "contactlist.h"
#include "kopetecontact.h"
#include "kopete.h"
#include "kopeteballoon.h"
#include "systemtray.h"

#include <qlayout.h>

#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstdaction.h>

KopeteWindow::KopeteWindow(QWidget *parent, const char *name ): KMainWindow(parent,name)
{
	kdDebug() << "[KopeteWindow] KopeteWindow()" << endl;

	/* -------------------------------------------------------------------------------- */
	initView();
	initActions();
	initSystray();
	/* -------------------------------------------------------------------------------- */

	loadOptions();

	// we always show our statusbar
	// it's important because it shows the protocol-icons
	statusBar()->show();

	// for now systemtray is also always shown
	// TODO: make the configurable
	tray->show();
}

void KopeteWindow::initView ( void )
{
	mainwidget = new QWidget(this);
	setCentralWidget(mainwidget);

	QBoxLayout *layout = new QBoxLayout(mainwidget,QBoxLayout::TopToBottom);
	contactlist = new ContactList(mainwidget);

	layout->insertWidget ( -1, contactlist );
	connect( contactlist, SIGNAL(executed(QListViewItem *)), this, SLOT(slotExecuted(QListViewItem *)) );
}

void KopeteWindow::initActions ( void )
{
	actionAddContact = new KAction( i18n("&Add contact"),"bookmark_add", 0 ,
							kopeteapp, SLOT(slotAddContact()),
							actionCollection(), "AddContact" );

	actionConnect = new KAction( i18n("&Connect All"),"connect_creating", 0 ,
							kopeteapp, SLOT(slotConnectAll()),
							actionCollection(), "Connect" );

	actionDisconnect = new KAction( i18n("&Disconnect All"),"connect_no", 0 ,
							kopeteapp, SLOT(slotDisconnectAll()),
							actionCollection(), "Disconnect" );

	actionConnectionMenu = new KActionMenu( i18n("Connection"),"connect_established",
							actionCollection(), "Connection" );

	actionConnectionMenu->insert(actionConnect);
	actionConnectionMenu->insert(actionDisconnect);

	actionSetAway = new KAction( i18n("&Set away globally"), "away", 0 ,
							kopeteapp, SLOT(slotSetAwayAll()),
							actionCollection(), "SetAway" );

	actionSetAvailable = new KAction( i18n("Set availa&ble globally"), "available", 0 ,
							kopeteapp, SLOT(slotSetAvailableAll()),
							actionCollection(), "SetAvailable" );

	actionAwayMenu = new KActionMenu( i18n("Status"),"awaymenu",
							actionCollection(), "Status" );
	actionAwayMenu->insert(actionSetAvailable);
	actionAwayMenu->insert(actionSetAway);

	actionPrefs = KStdAction::preferences(kopeteapp, SLOT(slotPreferences()), actionCollection());

//	actionQuit = KStdAction::quit(kopeteapp, SLOT(slotExit()), actionCollection());
	KStdAction::quit(kopeteapp, SLOT(quit()), actionCollection());

	toolbarAction = KStdAction::showToolbar(this, SLOT(showToolbar()), actionCollection());

	createGUI ( "kopeteui.rc" );
}

void KopeteWindow::initSystray ( void )
{
	tray = new KopeteSystemTray(this, "KopeteSystemTray");
	KPopupMenu *tm = tray->getContextMenu();

	tm->insertSeparator();
	actionAddContact->plug( tm );
	tm->insertSeparator();
//	actionConnect->plug( tm );
//	actionDisconnect->plug( tm );
	actionConnectionMenu->plug ( tm );
	actionAwayMenu->plug( tm );
	tm->insertSeparator();
	actionPrefs->plug( tm );
//	tm->insertSeparator();
}

KopeteWindow::~KopeteWindow()
{
//	delete tray;
	kdDebug() << "[KopeteWindow] ~KopeteWindow()" << endl;
}

bool KopeteWindow::queryExit()
{
	kdDebug() << "[KopeteWindow] queryExit()" << endl;
	saveOptions();
	return true;
}

void KopeteWindow::loadOptions(void)
{
	KConfig *config = KGlobal::config();

	toolBar("mainToolBar")->applySettings( config, "ToolBar Settings" );

	applyMainWindowSettings ( config, "General Options" );

	QPoint pos = config->readPointEntry("Position");
	move(pos);

	QSize size = config->readSizeEntry("Geometry");
	if(!size.isEmpty())
	{
		resize(size);
	}

	QString tmp = config->readEntry("State", "Shown");
	if ( tmp == "Minimized" )
	{
		showMinimized();
	}
	else if ( tmp == "Hidden" )
	{
		hide();
	}
	else
	{
		KConfig *config = KGlobal::config();
		config->setGroup("Appearance");
		if ( !config->readBoolEntry("StartDocked", false) )
			show();
	}

	toolbarAction->setChecked( !toolBar("mainToolBar")->isHidden() );
}

void KopeteWindow::saveOptions(void)
{
	KConfig *config = KGlobal::config();

	toolBar("mainToolBar")->saveSettings ( config, "ToolBar Settings" );

	saveMainWindowSettings( config, "General Options" );

	config->setGroup("General Options");
	config->writeEntry("Position", pos());
	config->writeEntry("Geometry", size());

	if(isMinimized())
	{
		config->writeEntry("State", "Minimized");
	}
	else if(isHidden())
	{
		config->writeEntry("State", "Hidden");
	}
	else
	{
		config->writeEntry("State", "Shown");
	}

	config->sync();
}

void KopeteWindow::showToolbar(void)
{
	if( toolbarAction->isChecked() )
		toolBar("mainToolBar")->show();
	else
		toolBar("mainToolBar")->hide();
}

void KopeteWindow::slotExecuted( QListViewItem *item )
{
	KopeteContactViewItem *contactvi = dynamic_cast<KopeteContactViewItem *>(item);
	if ( contactvi )
		contactvi->contact()->execute();
}

// vim: set noet sw=4 ts=4 sts=4:

<commit_msg>Captialization<commit_after>/***************************************************************************
                          Kopete Instant Messenger
							 kopetewindows.cpp
                            -------------------
				(C) 2001-2002 by Duncan Mac-Vicar P. <duncan@kde.org>
				(C) 2001-2002 by Stefan Gehn <sgehn@gmx.net>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kopetewindow.h"
#include "kopetewindow.moc"

#include "contactlist.h"
#include "kopetecontact.h"
#include "kopete.h"
#include "kopeteballoon.h"
#include "systemtray.h"

#include <qlayout.h>

#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstdaction.h>

KopeteWindow::KopeteWindow(QWidget *parent, const char *name ): KMainWindow(parent,name)
{
	kdDebug() << "[KopeteWindow] KopeteWindow()" << endl;

	/* -------------------------------------------------------------------------------- */
	initView();
	initActions();
	initSystray();
	/* -------------------------------------------------------------------------------- */

	loadOptions();

	// we always show our statusbar
	// it's important because it shows the protocol-icons
	statusBar()->show();

	// for now systemtray is also always shown
	// TODO: make the configurable
	tray->show();
}

void KopeteWindow::initView ( void )
{
	mainwidget = new QWidget(this);
	setCentralWidget(mainwidget);

	QBoxLayout *layout = new QBoxLayout(mainwidget,QBoxLayout::TopToBottom);
	contactlist = new ContactList(mainwidget);

	layout->insertWidget ( -1, contactlist );
	connect( contactlist, SIGNAL(executed(QListViewItem *)), this, SLOT(slotExecuted(QListViewItem *)) );
}

void KopeteWindow::initActions ( void )
{
	actionAddContact = new KAction( i18n("&Add contact"),"bookmark_add", 0 ,
							kopeteapp, SLOT(slotAddContact()),
							actionCollection(), "AddContact" );

	actionConnect = new KAction( i18n("&Connect All"),"connect_creating", 0 ,
							kopeteapp, SLOT(slotConnectAll()),
							actionCollection(), "Connect" );

	actionDisconnect = new KAction( i18n("&Disconnect All"),"connect_no", 0 ,
							kopeteapp, SLOT(slotDisconnectAll()),
							actionCollection(), "Disconnect" );

	actionConnectionMenu = new KActionMenu( i18n("Connection"),"connect_established",
							actionCollection(), "Connection" );

	actionConnectionMenu->insert(actionConnect);
	actionConnectionMenu->insert(actionDisconnect);

	actionSetAway = new KAction( i18n("&Set Away Globally"), "away", 0 ,
							kopeteapp, SLOT(slotSetAwayAll()),
							actionCollection(), "SetAway" );

	actionSetAvailable = new KAction( i18n("Set Availa&ble Globally"), "available", 0 ,
							kopeteapp, SLOT(slotSetAvailableAll()),
							actionCollection(), "SetAvailable" );

	actionAwayMenu = new KActionMenu( i18n("Status"),"awaymenu",
							actionCollection(), "Status" );
	actionAwayMenu->insert(actionSetAvailable);
	actionAwayMenu->insert(actionSetAway);

	actionPrefs = KStdAction::preferences(kopeteapp, SLOT(slotPreferences()), actionCollection());

//	actionQuit = KStdAction::quit(kopeteapp, SLOT(slotExit()), actionCollection());
	KStdAction::quit(kopeteapp, SLOT(quit()), actionCollection());

	toolbarAction = KStdAction::showToolbar(this, SLOT(showToolbar()), actionCollection());

	createGUI ( "kopeteui.rc" );
}

void KopeteWindow::initSystray ( void )
{
	tray = new KopeteSystemTray(this, "KopeteSystemTray");
	KPopupMenu *tm = tray->getContextMenu();

	tm->insertSeparator();
	actionAddContact->plug( tm );
	tm->insertSeparator();
//	actionConnect->plug( tm );
//	actionDisconnect->plug( tm );
	actionConnectionMenu->plug ( tm );
	actionAwayMenu->plug( tm );
	tm->insertSeparator();
	actionPrefs->plug( tm );
//	tm->insertSeparator();
}

KopeteWindow::~KopeteWindow()
{
//	delete tray;
	kdDebug() << "[KopeteWindow] ~KopeteWindow()" << endl;
}

bool KopeteWindow::queryExit()
{
	kdDebug() << "[KopeteWindow] queryExit()" << endl;
	saveOptions();
	return true;
}

void KopeteWindow::loadOptions(void)
{
	KConfig *config = KGlobal::config();

	toolBar("mainToolBar")->applySettings( config, "ToolBar Settings" );

	applyMainWindowSettings ( config, "General Options" );

	QPoint pos = config->readPointEntry("Position");
	move(pos);

	QSize size = config->readSizeEntry("Geometry");
	if(!size.isEmpty())
	{
		resize(size);
	}

	QString tmp = config->readEntry("State", "Shown");
	if ( tmp == "Minimized" )
	{
		showMinimized();
	}
	else if ( tmp == "Hidden" )
	{
		hide();
	}
	else
	{
		KConfig *config = KGlobal::config();
		config->setGroup("Appearance");
		if ( !config->readBoolEntry("StartDocked", false) )
			show();
	}

	toolbarAction->setChecked( !toolBar("mainToolBar")->isHidden() );
}

void KopeteWindow::saveOptions(void)
{
	KConfig *config = KGlobal::config();

	toolBar("mainToolBar")->saveSettings ( config, "ToolBar Settings" );

	saveMainWindowSettings( config, "General Options" );

	config->setGroup("General Options");
	config->writeEntry("Position", pos());
	config->writeEntry("Geometry", size());

	if(isMinimized())
	{
		config->writeEntry("State", "Minimized");
	}
	else if(isHidden())
	{
		config->writeEntry("State", "Hidden");
	}
	else
	{
		config->writeEntry("State", "Shown");
	}

	config->sync();
}

void KopeteWindow::showToolbar(void)
{
	if( toolbarAction->isChecked() )
		toolBar("mainToolBar")->show();
	else
		toolBar("mainToolBar")->hide();
}

void KopeteWindow::slotExecuted( QListViewItem *item )
{
	KopeteContactViewItem *contactvi = dynamic_cast<KopeteContactViewItem *>(item);
	if ( contactvi )
		contactvi->contact()->execute();
}

// vim: set noet sw=4 ts=4 sts=4:

<|endoftext|>


<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#include "sections.hpp"

#include <iostream>
#include <iterator>

#include <hadesmem/pelib/section.hpp>
#include <hadesmem/pelib/section_list.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/process.hpp>

void DumpSections(hadesmem::Process const& process,
                  hadesmem::PeFile const& pe_file)
{
  // TODO: Detect when a file has no sections.
  // TODO: Detect when a file has more than 96 sections (allowed on Vista+, but
  // technically outside of the spec).
  hadesmem::SectionList sections(process, pe_file);

  if (std::begin(sections) != std::end(sections))
  {
    std::wcout << "\n\tSections:\n";
  }

  for (auto const& s : sections)
  {
    std::wcout << "\n";
    std::wcout << "\t\tName: " << s.GetName().c_str() << "\n";
    std::wcout << "\t\tVirtualAddress: " << std::hex << s.GetVirtualAddress()
               << std::dec << "\n";
    std::wcout << "\t\tVirtualSize: " << std::hex << s.GetVirtualSize()
               << std::dec << "\n";
    std::wcout << "\t\tPointerToRawData: " << std::hex
               << s.GetPointerToRawData() << std::dec << "\n";
    std::wcout << "\t\tSizeOfRawData: " << std::hex << s.GetSizeOfRawData()
               << std::dec << "\n";
    std::wcout << "\t\tPointerToRelocations: " << std::hex
               << s.GetPointerToRelocations() << std::dec << "\n";
    std::wcout << "\t\tPointerToLinenumbers: " << std::hex
               << s.GetPointerToLinenumbers() << std::dec << "\n";
    std::wcout << "\t\tNumberOfRelocations: " << std::hex
               << s.GetNumberOfRelocations() << std::dec << "\n";
    std::wcout << "\t\tNumberOfLinenumbers: " << std::hex
               << s.GetNumberOfLinenumbers() << std::dec << "\n";
    std::wcout << "\t\tCharacteristics: " << std::hex << s.GetCharacteristics()
               << std::dec << "\n";
  }
}
<commit_msg>* [Dump] Fix for previous commit. (Moved the comments but forgot to hit save.)<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#include "sections.hpp"

#include <iostream>
#include <iterator>

#include <hadesmem/pelib/section.hpp>
#include <hadesmem/pelib/section_list.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/process.hpp>

// TODO: Detect when a file has no sections.

// TODO: Detect when a file has more than 96 sections (allowed on Vista+, but
// technically outside of the spec).

void DumpSections(hadesmem::Process const& process,
                  hadesmem::PeFile const& pe_file)
{
  hadesmem::SectionList sections(process, pe_file);

  if (std::begin(sections) != std::end(sections))
  {
    std::wcout << "\n\tSections:\n";
  }

  for (auto const& s : sections)
  {
    std::wcout << "\n";
    std::wcout << "\t\tName: " << s.GetName().c_str() << "\n";
    std::wcout << "\t\tVirtualAddress: " << std::hex << s.GetVirtualAddress()
               << std::dec << "\n";
    std::wcout << "\t\tVirtualSize: " << std::hex << s.GetVirtualSize()
               << std::dec << "\n";
    std::wcout << "\t\tPointerToRawData: " << std::hex
               << s.GetPointerToRawData() << std::dec << "\n";
    std::wcout << "\t\tSizeOfRawData: " << std::hex << s.GetSizeOfRawData()
               << std::dec << "\n";
    std::wcout << "\t\tPointerToRelocations: " << std::hex
               << s.GetPointerToRelocations() << std::dec << "\n";
    std::wcout << "\t\tPointerToLinenumbers: " << std::hex
               << s.GetPointerToLinenumbers() << std::dec << "\n";
    std::wcout << "\t\tNumberOfRelocations: " << std::hex
               << s.GetNumberOfRelocations() << std::dec << "\n";
    std::wcout << "\t\tNumberOfLinenumbers: " << std::hex
               << s.GetNumberOfLinenumbers() << std::dec << "\n";
    std::wcout << "\t\tCharacteristics: " << std::hex << s.GetCharacteristics()
               << std::dec << "\n";
  }
}
<|endoftext|>


<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#include "EchoIndicationWrapper.h"
#include "EchoRequestProxy.h"
#include "GeneratedTypes.h"
#include "SwallowProxy.h"

#define LOOP_COUNT 5 //1000
#define SEPARATE_EVENT_THREAD
//#define USE_MUTEX_SYNC

EchoRequestProxy *echoRequestProxy = 0;

#ifndef SEPARATE_EVENT_THREAD
typedef int SEM_TYPE;
#define SEMPOST(A) (*(A))++
#define SEMWAIT pthread_worker
#elif defined(USE_MUTEX_SYNC)
typedef pthread_mutex_t SEM_TYPE;
#define SEMINIT(A) pthread_mutex_lock(A);
#define SEMWAIT(A) pthread_mutex_lock(A);
#define SEMPOST(A) pthread_mutex_unlock(A);
#else // use semaphores
typedef sem_t SEM_TYPE;
#define SEMINIT(A) sem_init(A, 0, 0);
#define SEMWAIT(A) sem_wait(A);
#define SEMPOST(A) sem_post(A)
#endif

#ifdef SEPARATE_EVENT_THREAD
#define PREPAREWAIT(A)
#define CHECKSEM(A) 1
#else // use inline sync
#define PREPAREWAIT(A) (A) = 0
#define CHECKSEM(A) (!(A))
#endif

static SEM_TYPE sem_heard2;

PortalPoller *poller = 0;

static void *pthread_worker(void *p)
{
    void *rc = NULL;
    while (CHECKSEM(sem_heard2) && !rc && !poller->stopping)
        rc = poller->portalExec_event(poller->portalExec_timeout);
    return rc;
}
static void init_thread()
{
#ifdef SEPARATE_EVENT_THREAD
    pthread_t threaddata;
    SEMINIT(&sem_heard2);
    pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller);
#endif
}

class EchoIndication : public EchoIndicationWrapper
{
public:
    virtual void heard(uint32_t v) {
        fprintf(stderr, "heard an echo: %d\n", v);
	echoRequestProxy->say2(v, 2*v);
    }
    virtual void heard2(uint32_t a, uint32_t b) {
        catch_timer(20);
        SEMPOST(&sem_heard2);
        //fprintf(stderr, "heard an echo2: %ld %ld\n", a, b);
        //catch_timer(25);
    }
    EchoIndication(unsigned int id, PortalPoller *poller) : EchoIndicationWrapper(id, poller) {}
};

static void call_say(int v)
{
    printf("[%s:%d] %d\n", __FUNCTION__, __LINE__, v);
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    echoRequestProxy->say(v);
    SEMWAIT(&sem_heard2);
    printf("call_say: elapsed %zd\n", lap_timer(0));
}

static void call_say2(int v, int v2)
{
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    catch_timer(0);
    echoRequestProxy->say2(v, v2);
    catch_timer(19);
    SEMWAIT(&sem_heard2);
    catch_timer(30);
}

int main(int argc, const char **argv)
{
    poller = new PortalPoller();
    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, poller);
    // these use the default poller
    SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow);
    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);

    poller->portalExec_init();
    init_thread();
    portalExec_start();

    int v = 42;
    fprintf(stderr, "Saying %d\n", v);
    call_say(v);
    call_say(v*5);
    call_say(v*17);
    call_say(v*93);
    printf("[%s:%d] run %d loops\n\n", __FUNCTION__, __LINE__, LOOP_COUNT);
    init_timer();
    start_timer(1);
printf("[%s:%d] sleep2\n", __FUNCTION__, __LINE__); sleep(2);
    for (int i = 0; i < LOOP_COUNT; i++)
        call_say2(v, v*3);
uint64_t elapsed = lap_timer(1);
    printf("TEST TYPE: "
#ifndef SEPARATE_EVENT_THREAD
       "INLINE"
#elif defined(USE_MUTEX_SYNC)
       "MUTEX"
#else
       "SEM"
#endif
       "\n");
    print_timer(LOOP_COUNT);
    printf("call_say: elapsed %zd average %zd\n", elapsed, elapsed/LOOP_COUNT);
    echoRequestProxy->setLeds(9);
    poller->portalExec_end();
    portalExec_end();
    return 0;
}
<commit_msg>timing in floating point<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#include "EchoIndicationWrapper.h"
#include "EchoRequestProxy.h"
#include "GeneratedTypes.h"
#include "SwallowProxy.h"

#define LOOP_COUNT 50 //1000
#define SEPARATE_EVENT_THREAD
//#define USE_MUTEX_SYNC

EchoRequestProxy *echoRequestProxy = 0;

#ifndef SEPARATE_EVENT_THREAD
typedef int SEM_TYPE;
#define SEMPOST(A) (*(A))++
#define SEMWAIT pthread_worker
#elif defined(USE_MUTEX_SYNC)
typedef pthread_mutex_t SEM_TYPE;
#define SEMINIT(A) pthread_mutex_lock(A);
#define SEMWAIT(A) pthread_mutex_lock(A);
#define SEMPOST(A) pthread_mutex_unlock(A);
#else // use semaphores
typedef sem_t SEM_TYPE;
#define SEMINIT(A) sem_init(A, 0, 0);
#define SEMWAIT(A) sem_wait(A);
#define SEMPOST(A) sem_post(A)
#endif

#ifdef SEPARATE_EVENT_THREAD
#define PREPAREWAIT(A)
#define CHECKSEM(A) 1
#else // use inline sync
#define PREPAREWAIT(A) (A) = 0
#define CHECKSEM(A) (!(A))
#endif

static SEM_TYPE sem_heard2;

PortalPoller *poller = 0;

static void *pthread_worker(void *p)
{
    void *rc = NULL;
    while (CHECKSEM(sem_heard2) && !rc && !poller->stopping)
        rc = poller->portalExec_event(poller->portalExec_timeout);
    return rc;
}
static void init_thread()
{
#ifdef SEPARATE_EVENT_THREAD
    pthread_t threaddata;
    SEMINIT(&sem_heard2);
    pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller);
#endif
}

class EchoIndication : public EchoIndicationWrapper
{
public:
    virtual void heard(uint32_t v) {
        fprintf(stderr, "heard an echo: %d\n", v);
	echoRequestProxy->say2(v, 2*v);
    }
    virtual void heard2(uint32_t a, uint32_t b) {
        catch_timer(20);
        SEMPOST(&sem_heard2);
        //fprintf(stderr, "heard an echo2: %ld %ld\n", a, b);
        //catch_timer(25);
    }
    EchoIndication(unsigned int id, PortalPoller *poller) : EchoIndicationWrapper(id, poller) {}
};

static void call_say(int v)
{
    printf("[%s:%d] %d\n", __FUNCTION__, __LINE__, v);
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    echoRequestProxy->say(v);
    SEMWAIT(&sem_heard2);
    printf("call_say: elapsed %zd\n", lap_timer(0));
}

static void call_say2(int v, int v2)
{
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    catch_timer(0);
    echoRequestProxy->say2(v, v2);
    catch_timer(19);
    SEMWAIT(&sem_heard2);
    catch_timer(30);
}

int main(int argc, const char **argv)
{
    poller = new PortalPoller();
    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, poller);
    // these use the default poller
    SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow);
    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);

    poller->portalExec_init();
    init_thread();
    portalExec_start();

    int v = 42;
    fprintf(stderr, "Saying %d\n", v);
    call_say(v);
    call_say(v*5);
    call_say(v*17);
    call_say(v*93);
    printf("[%s:%d] run %d loops\n\n", __FUNCTION__, __LINE__, LOOP_COUNT);
    init_timer();
    start_timer(1);
printf("[%s:%d] sleep2\n", __FUNCTION__, __LINE__); sleep(2);
    for (int i = 0; i < LOOP_COUNT; i++)
        call_say2(v, v*3);
uint64_t elapsed = lap_timer(1);
    printf("TEST TYPE: "
#ifndef SEPARATE_EVENT_THREAD
       "INLINE"
#elif defined(USE_MUTEX_SYNC)
       "MUTEX"
#else
       "SEM"
#endif
       "\n");
    print_timer(LOOP_COUNT);
    printf("call_say: elapsed %g average %g\n", (double) elapsed, (double) elapsed/ (double) LOOP_COUNT);
    echoRequestProxy->setLeds(9);
    poller->portalExec_end();
    portalExec_end();
    return 0;
}
<|endoftext|>


<commit_before>/**
 * 3.2.2 string字符串上的操作：string的empty和size操作
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/7/18
 */

#include <string>
#include <iostream>

using std::string;

using std::cin;
using std::cout; using std::endl;

int main() {
  string line;
  while (getline(cin, line)) {
    if (line.empty()) { // 判断数据是否为空：
      cout << "此行数据为空" << endl;
    } else {
      unsigned long size = line.size(); // 注意，其实 size 函数返回的确切类型是 string::size_type，但不管怎样，是一个无符号整型数
      // 或者可以直接使用auto进行类型自动推断 auto size = line.size()
      cout << "此行数据长度为：" << size << endl;
      if (size > 3) { // 输出字符长度大于3的字符串
        cout << "此行数据内容为：" << line << endl;
      }
    }
  }
  return 0;
}

<commit_msg>3.2.2 string字符串上的操作：string的empty和size操作<commit_after>/**
 * 3.2.2 string字符串上的操作：string的empty和size操作
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/7/18
 */

#include <string>
#include <iostream>

using std::string;

using std::cin;
using std::cout; using std::endl;

int main() {
  // 基本知识点
  string s1;
  string s2 = "";
  string s3("hello workd!");

  cout << "s1默认初始值是否为空：" << s1.empty() << endl;  // 默认初始值 empty 为真
  cout << "s2空字符串是否为空：" << s2.empty() << endl;    // 空字符串 empty 也为真
  cout << "s3字符串长度：" << s3.size() << endl;

  // 读取输入信息范例
  string line;
  while (getline(cin, line)) {
    if (line.empty()) { // 判断数据是否为空：
      cout << "此行数据为空" << endl;
    } else {
      unsigned long size = line.size(); // 注意，其实 size 函数返回的确切类型是 string::size_type，但不管怎样，是一个无符号整型数
      // 或者可以直接使用auto进行类型自动推断 auto size = line.size()
      cout << "此行数据长度为：" << size << endl;
      if (size > 3) { // 输出字符长度大于3的字符串
        cout << "此行数据内容为：" << line << endl;
      }
    }
  }
  return 0;
}

<|endoftext|>