<commit_before>#include <blackhole/sink/elasticsearch.hpp>
#include <blackhole/utils/atomic.hpp>

#include "../global.hpp"

using namespace blackhole;

TEST(elasticsearch_t, Class) {
    using blackhole::sink::elasticsearch_t;
    elasticsearch_t sink;
    UNUSED(sink);
}

TEST(elasticsearch_t, Manual) {
    using blackhole::sink::elasticsearch_t;
    elasticsearch_t sink;
    std::string msg = "{}";
    boost::algorithm::replace_all(msg, "'", "\"");
    for (int i = 0; i < 200; ++i) {
        sink.consume(msg);
    }
}

using namespace elasticsearch;

namespace mock {

class response_t {
};

class action_t {
public:
    typedef response_t response_type;
    typedef result_t<response_type>::type result_type;

    static const request::method_t method_value = request::method_t::get;

    static const char* name() {
        return "mock.action";
    }

    std::string path() const {
        return "/";
    }
};

class connection_t {
public:
    typedef boost::asio::ip::tcp protocol_type;
    typedef protocol_type::endpoint endpoint_type;

    template<class... Args>
    connection_t(Args&&...) {}

    MOCK_CONST_METHOD0(endpoint, endpoint_type());

    MOCK_METHOD3(perform, void(
        actions::nodes_info_t,
        callback<actions::nodes_info_t>::type,
        long
    ));

    MOCK_METHOD3(perform, void(
        action_t,
        callback<action_t>::type,
        long
    ));
};

class pool_t {
public:
    typedef connection_t connection_type;
    typedef connection_type::endpoint_type endpoint_type;
    typedef std::unordered_map<
        endpoint_type,
        std::shared_ptr<connection_type>
    > pool_type;
    typedef pool_type::size_type size_type;
    typedef pool_type::iterator iterator;

    typedef std::mutex mutex_type;
    typedef pool_lock_t<pool_t> pool_lock_type;

    mutable std::mutex mutex;

    typedef std::pair<iterator, bool> pair_type;
    MOCK_METHOD2(insert, pair_type(
        const endpoint_type&,
        const std::shared_ptr<connection_type>&
    ));
    MOCK_METHOD1(remove, void(const endpoint_type&));

    //!@note: These methods are pure stubs, they shouldn't be called ever.
    MOCK_CONST_METHOD1(size, size_type(pool_lock_type&));
    MOCK_CONST_METHOD1(empty, bool(pool_lock_type&));
    MOCK_METHOD1(begin, iterator(pool_lock_type&));
    MOCK_METHOD1(end, iterator(pool_lock_type&));
};

class balancer : public balancing::strategy<pool_t> {
public:
    typedef pool_t pool_type;
    typedef pool_type::connection_type connection_type;

    MOCK_METHOD1(next, std::shared_ptr<connection_type>(pool_type& pool));
};

} // namespace mock

namespace elasticsearch {

template<>
struct extractor_t<mock::response_t> {
    static mock::response_t extract(const rapidjson::Value&) {
        return mock::response_t();
    }
};

} // namespace elasticsearch

class transport_t_SuccessfullyHandleMessage_Test;
class transport_t_HandleGenericError_Test;

namespace inspector {

//!@note: Helper class to easy ancestor's mock fields inspection.
template<class Connection, class Pool>
class http_transport_t : public elasticsearch::http_transport_t<Connection, Pool> {
    friend class ::transport_t_SuccessfullyHandleMessage_Test;
    friend class ::transport_t_HandleGenericError_Test;

public:
    template<typename... Args>
    http_transport_t(Args&&... args) :
        elasticsearch::http_transport_t<Connection, Pool>(std::forward<Args>(args)...)
    {}
};

} // namespace inspector

template<class Action>
struct event_t {
    std::atomic<int>& counter;

    void operator()(typename Action::result_type) {
        counter++;
    }
};

void post(boost::asio::io_service& loop,
          callback<mock::action_t>::type callback,
          result_t<mock::response_t>::type result) {
    loop.post(std::bind(callback, result));
}

namespace stub {

synchronized<logger_base_t> log(logger_factory_t::create());

} // namespace stub

TEST(transport_t, SuccessfullyHandleMessage) {
    boost::asio::io_service loop;

    std::unique_ptr<mock::balancer> balancer(new mock::balancer);
    std::shared_ptr<mock::connection_t> connection(new mock::connection_t);

    settings_t settings;

    inspector::http_transport_t<
        mock::connection_t,
        mock::pool_t
    > transport(settings, loop, stub::log);

    EXPECT_CALL(*balancer, next(_))
            .Times(1)
            .WillOnce(Return(connection));
    EXPECT_CALL(*connection, endpoint())
            .WillOnce(Return(mock::connection_t::endpoint_type()));
    EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
            .Times(1)
            .WillOnce(
                WithArg<1>(
                    Invoke(
                        std::bind(
                            &post,
                            std::ref(loop),
                            std::placeholders::_1,
                            mock::response_t()
                        )
                    )
                )
            );

    transport.balancer = std::move(balancer);

    std::atomic<int> counter(0);
    transport.perform(mock::action_t(), event_t<mock::action_t> { counter });
    loop.run_one();

    EXPECT_EQ(1, counter);
}

TEST(transport_t, HandleGenericError) {
    /*! After receiving the response with some elasticsearch error, a caller's
     *  callback must be called during the next event loop tick.
     */

    boost::asio::io_service loop;

    std::unique_ptr<mock::balancer> balancer(new mock::balancer);
    std::shared_ptr<mock::connection_t> connection(new mock::connection_t);

    settings_t settings;

    inspector::http_transport_t<
        mock::connection_t,
        mock::pool_t
    > transport(settings, loop, stub::log);

    EXPECT_CALL(*balancer, next(_))
            .Times(1)
            .WillOnce(Return(connection));
    EXPECT_CALL(*connection, endpoint())
            .WillOnce(Return(mock::connection_t::endpoint_type()));
    EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
            .Times(1)
            .WillOnce(
                WithArg<1>(
                    Invoke(
                        std::bind(
                            &post,
                            std::ref(loop),
                            std::placeholders::_1,
                            elasticsearch::error_t(generic_error_t("mock"))
                        )
                    )
                )
            );

    transport.balancer = std::move(balancer);

    std::atomic<int> counter(0);
    transport.perform(mock::action_t(), event_t<mock::action_t> { counter });
    loop.run_one();

    EXPECT_EQ(1, counter);
}
<commit_msg>[Unit Testing] Checking result type received.<commit_after>#include <blackhole/sink/elasticsearch.hpp>
#include <blackhole/utils/atomic.hpp>

#include "../global.hpp"

using namespace blackhole;

TEST(elasticsearch_t, Class) {
    using blackhole::sink::elasticsearch_t;
    elasticsearch_t sink;
    UNUSED(sink);
}

TEST(elasticsearch_t, Manual) {
    using blackhole::sink::elasticsearch_t;
    elasticsearch_t sink;
    std::string msg = "{}";
    boost::algorithm::replace_all(msg, "'", "\"");
    for (int i = 0; i < 200; ++i) {
        sink.consume(msg);
    }
}

using namespace elasticsearch;

namespace mock {

class response_t {
};

class action_t {
public:
    typedef response_t response_type;
    typedef result_t<response_type>::type result_type;

    static const request::method_t method_value = request::method_t::get;

    static const char* name() {
        return "mock.action";
    }

    std::string path() const {
        return "/";
    }
};

class connection_t {
public:
    typedef boost::asio::ip::tcp protocol_type;
    typedef protocol_type::endpoint endpoint_type;

    template<class... Args>
    connection_t(Args&&...) {}

    MOCK_CONST_METHOD0(endpoint, endpoint_type());

    MOCK_METHOD3(perform, void(
        actions::nodes_info_t,
        callback<actions::nodes_info_t>::type,
        long
    ));

    MOCK_METHOD3(perform, void(
        action_t,
        callback<action_t>::type,
        long
    ));
};

class pool_t {
public:
    typedef connection_t connection_type;
    typedef connection_type::endpoint_type endpoint_type;
    typedef std::unordered_map<
        endpoint_type,
        std::shared_ptr<connection_type>
    > pool_type;
    typedef pool_type::size_type size_type;
    typedef pool_type::iterator iterator;

    typedef std::mutex mutex_type;
    typedef pool_lock_t<pool_t> pool_lock_type;

    mutable std::mutex mutex;

    typedef std::pair<iterator, bool> pair_type;
    MOCK_METHOD2(insert, pair_type(
        const endpoint_type&,
        const std::shared_ptr<connection_type>&
    ));
    MOCK_METHOD1(remove, void(const endpoint_type&));

    //!@note: These methods are pure stubs, they shouldn't be called ever.
    MOCK_CONST_METHOD1(size, size_type(pool_lock_type&));
    MOCK_CONST_METHOD1(empty, bool(pool_lock_type&));
    MOCK_METHOD1(begin, iterator(pool_lock_type&));
    MOCK_METHOD1(end, iterator(pool_lock_type&));
};

class balancer : public balancing::strategy<pool_t> {
public:
    typedef pool_t pool_type;
    typedef pool_type::connection_type connection_type;

    MOCK_METHOD1(next, std::shared_ptr<connection_type>(pool_type& pool));
};

} // namespace mock

namespace elasticsearch {

template<>
struct extractor_t<mock::response_t> {
    static mock::response_t extract(const rapidjson::Value&) {
        return mock::response_t();
    }
};

} // namespace elasticsearch

class transport_t_SuccessfullyHandleMessage_Test;
class transport_t_HandleGenericError_Test;

namespace inspector {

//!@note: Helper class to easy ancestor's mock fields inspection.
template<class Connection, class Pool>
class http_transport_t : public elasticsearch::http_transport_t<Connection, Pool> {
    friend class ::transport_t_SuccessfullyHandleMessage_Test;
    friend class ::transport_t_HandleGenericError_Test;

public:
    template<typename... Args>
    http_transport_t(Args&&... args) :
        elasticsearch::http_transport_t<Connection, Pool>(std::forward<Args>(args)...)
    {}
};

} // namespace inspector

template<class Action, class T>
struct event_t {
    std::atomic<int>& counter;

    void operator()(typename Action::result_type result) {
        counter++;
        EXPECT_TRUE(boost::get<T>(&result));
    }
};

void post(boost::asio::io_service& loop,
          callback<mock::action_t>::type callback,
          result_t<mock::response_t>::type result) {
    loop.post(std::bind(callback, result));
}

namespace stub {

synchronized<logger_base_t> log(logger_factory_t::create());

} // namespace stub

TEST(transport_t, SuccessfullyHandleMessage) {
    boost::asio::io_service loop;

    std::unique_ptr<mock::balancer> balancer(new mock::balancer);
    std::shared_ptr<mock::connection_t> connection(new mock::connection_t);

    settings_t settings;

    inspector::http_transport_t<
        mock::connection_t,
        mock::pool_t
    > transport(settings, loop, stub::log);

    EXPECT_CALL(*balancer, next(_))
            .Times(1)
            .WillOnce(Return(connection));
    EXPECT_CALL(*connection, endpoint())
            .WillOnce(Return(mock::connection_t::endpoint_type()));
    EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
            .Times(1)
            .WillOnce(
                WithArg<1>(
                    Invoke(
                        std::bind(
                            &post,
                            std::ref(loop),
                            std::placeholders::_1,
                            mock::response_t()
                        )
                    )
                )
            );

    transport.balancer = std::move(balancer);

    std::atomic<int> counter(0);
    transport.perform(
        mock::action_t(),
        event_t<mock::action_t, mock::response_t> { counter }
    );
    loop.run_one();

    EXPECT_EQ(1, counter);
}

TEST(transport_t, HandleGenericError) {
    /*! After receiving the response with some elasticsearch error, a caller's
     *  callback must be called during the next event loop tick.
     */

    boost::asio::io_service loop;

    std::unique_ptr<mock::balancer> balancer(new mock::balancer);
    std::shared_ptr<mock::connection_t> connection(new mock::connection_t);

    settings_t settings;

    inspector::http_transport_t<
        mock::connection_t,
        mock::pool_t
    > transport(settings, loop, stub::log);

    EXPECT_CALL(*balancer, next(_))
            .Times(1)
            .WillOnce(Return(connection));
    EXPECT_CALL(*connection, endpoint())
            .WillOnce(Return(mock::connection_t::endpoint_type()));
    EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
            .Times(1)
            .WillOnce(
                WithArg<1>(
                    Invoke(
                        std::bind(
                            &post,
                            std::ref(loop),
                            std::placeholders::_1,
                            elasticsearch::error_t(generic_error_t("mock"))
                        )
                    )
                )
            );

    transport.balancer = std::move(balancer);

    std::atomic<int> counter(0);
    transport.perform(
        mock::action_t(),
        event_t<mock::action_t, elasticsearch::error_t> { counter }
    );
    loop.run_one();

    EXPECT_EQ(1, counter);
}
<|endoftext|>


<commit_before>#include "Halide.h"
#include "wrapper_ger.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

#define MM 100
#define NN 200
#define alpha 3
int main(int, char **)
{
    Halide::Buffer<uint8_t> A_buf(NN, MM);
    Halide::Buffer<uint8_t> X_buf(MM);
    Halide::Buffer<uint8_t> Y_buf(NN);

    // Initialize matrix A with pseudorandom values:
    for (int i = 0; i < MM; i++) {
        for (int j = 0; j < NN; j++) {
            A_buf(j, i) = (i + 3) * (j + 1);
        }

    }
    // Initialize Vector X with pseudorandom values:
    for(int i=0 ; i<MM ;i++){
        X_buf(i) = (i + 1) ;

    }
    // Initialize Vector Y with pseudorandom values:
    for(int i=0 ; i<NN ;i++){
        Y_buf(i) = i ;

    }

    // Output buffer
    Halide::Buffer<uint8_t> C_buf(NN, MM);
    init_buffer(C_buf, (uint8_t)0);
    // TRAMISU CODE EXECUTION STARTS:
    auto start1 = std::chrono::high_resolution_clock::now();
    ger(A_buf.raw_buffer(), X_buf.raw_buffer(),Y_buf.raw_buffer(),C_buf.raw_buffer());
    auto end1 = std::chrono::high_resolution_clock::now();
    auto  duration1 =duration_cast<microseconds>(end1 - start1);
    // TRAMISU CODE EXECUTION ENDS.

    // REFERENCE Output buffer
    Halide::Buffer<uint8_t> C2_buf(NN, MM);
    init_buffer(C2_buf, (uint8_t)0);
    // REFERENCE C++ CODE EXECUTION STARTS:
    auto start2 = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < MM; i++) {
        for (int j = 0; j < NN; j++) {

                C2_buf(j, i) = A_buf(j, i) +(X_buf(i)*Y_buf(j))*alpha;
         }
    }
    auto end2 = std::chrono::high_resolution_clock::now();
    auto  duration2 =duration_cast<microseconds>(end2 - start2);
    // REFERENCE C++ CODE EXECUTION ENDS.

   //===== you can print MATRIX A =====
     //printf("\n MAT A  :");
     //print_buffer(A_buf);

   //===== you can print VECT X =====
     //printf("\n VECTEUR X  :");
     //print_buffer(X_buf);

   //===== you can print VECT Y =====
     //printf("\n VECTEUR Y  :");
     //print_buffer(Y_buf);

   //===== you can print MATRIX C =====
     //printf("\n SOL  :");
     //print_buffer(C_buf);

   //===== you can print MATRIX C_REF =====
     //printf("\n SOL_ref  :");
     //print_buffer(C2_buf);

   //===== printing REFERECE EXEC TIME: =====
    std::cout << "\n REF RESOLUTION TIME : " << duration2.count() << "microseconds";
   //===== printing TIRAMISU EXEC TIME: =====
    std::cout << "\n TIRAMISU RESOLUTION TIME : " << duration1.count() << "microseconds";
    printf("\n");

   //===== Verify if TIRAMISU output is correct: =====
    compare_buffers("ger", C_buf, C2_buf);

    printf("\n");

    return 0;
}
<commit_msg>deleting old version of ger<commit_after><|endoftext|>


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

#include "occa/mode.hpp"
#include "occa/device.hpp"

namespace occa {
  strToModeMap& modeMap() {
    static strToModeMap modeMap_;
    return modeMap_;
  }

  void registerMode(mode_v* mode) {
    modeMap()[mode->name()] = mode;
  }

  bool modeIsEnabled(const std::string &mode) {
    return (modeMap().find(mode) != modeMap().end());
  }

  mode_v* getMode(const occa::properties &props) {
    std::string mode = props["mode"].string();
    const bool noMode = !mode.size();
    if (noMode || !modeIsEnabled(mode)) {
      if (noMode) {
        std::cerr << "No OCCA mode given, defaulting to [Serial] mode\n";
      } else {
        std::cerr << "[" << mode << "] mode is not enabled, defaulting to [Serial] mode\n";
      }
      return modeMap()["Serial"];
    }
    return modeMap()[props["mode"]];
  }

  device_v* newModeDevice(const occa::properties &props) {
    return getMode(props)->newDevice(props);
  }

  modeInfo_v::modeInfo_v() {}

  styling::section& modeInfo_v::getDescription() {
    static styling::section section;
    return section;
  }

  std::string& mode_v::name() {
    return modeName;
  }
}
<commit_msg>[Mode] Cleaned up default case<commit_after>/* The MIT License (MIT)
 *
 * Copyright (c) 2014-2018 David Medina and Tim Warburton
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 */

#include "occa/mode.hpp"
#include "occa/device.hpp"

namespace occa {
  strToModeMap& modeMap() {
    static strToModeMap modeMap_;
    return modeMap_;
  }

  void registerMode(mode_v* mode) {
    modeMap()[mode->name()] = mode;
  }

  bool modeIsEnabled(const std::string &mode) {
    return (modeMap().find(mode) != modeMap().end());
  }

  mode_v* getMode(const occa::properties &props) {
    std::string mode = props["mode"].string();
    const bool noMode = !mode.size();
    if (noMode || !modeIsEnabled(mode)) {
      if (noMode) {
        std::cerr << "No OCCA mode given, defaulting to [Serial] mode\n";
      } else {
        std::cerr << "[" << mode << "] mode is not enabled, defaulting to [Serial] mode\n";
      }
      mode = "Serial";
    }
    return modeMap()[mode];
  }

  device_v* newModeDevice(const occa::properties &props) {
    return getMode(props)->newDevice(props);
  }

  modeInfo_v::modeInfo_v() {}

  styling::section& modeInfo_v::getDescription() {
    static styling::section section;
    return section;
  }

  std::string& mode_v::name() {
    return modeName;
  }
}
<|endoftext|>


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

#include "ninja.h"

#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#elif defined(linux)
#include <sys/sysinfo.h>
#endif

#include "browse.h"
#include "build.h"
#include "build_log.h"
#include "graph.h"
#include "graphviz.h"
#include "parsers.h"
#include "util.h"

option options[] = {
  { "help", no_argument, NULL, 'h' },
  { }
};

void usage(const BuildConfig& config) {
  fprintf(stderr,
"usage: ninja [options] target\n"
"\n"
"options:\n"
"  -f FILE  specify input build file [default=build.ninja]\n"
"  -j N     run N jobs in parallel [default=%d]\n"
"  -n       dry run (don't run commands but pretend they succeeded)\n"
"  -v       show all command lines\n"
"\n"
"  -t TOOL  run a subtool.  tools are:\n"
"             browse  browse dependency graph in a web browser\n"
"             graph   output graphviz dot file for targets\n"
"             query   show inputs/outputs for a path\n",
          config.parallelism);
}

int GuessParallelism() {
  int processors = 0;

#if defined(linux)
  processors = get_nprocs();
#elif defined(__APPLE__) || defined(__FreeBSD__)
  size_t processors_size = sizeof(processors);
  int name[] = {CTL_HW, HW_NCPU};
  if (sysctl(name, sizeof(name) / sizeof(int),
             &processors, &processors_size,
             NULL, 0) < 0) {
    processors = 1;
  }
#endif

  switch (processors) {
  case 0:
  case 1:
    return 2;
  case 2:
    return 3;
  default:
    return processors + 2;
  }
}

struct RealFileReader : public ManifestParser::FileReader {
  bool ReadFile(const string& path, string* content, string* err) {
    return ::ReadFile(path, content, err) == 0;
  }
};

int CmdGraph(State* state, int argc, char* argv[]) {
  GraphViz graph;
  graph.Start();
  for (int i = 0; i < argc; ++i)
    graph.AddTarget(state->GetNode(argv[i]));
  graph.Finish();
  return 0;
}

int CmdQuery(State* state, int argc, char* argv[]) {
  for (int i = 0; i < argc; ++i) {
    Node* node = state->GetNode(argv[i]);
    if (node) {
      printf("%s:\n", argv[i]);
      if (node->in_edge_) {
        printf("  input: %s\n", node->in_edge_->rule_->name_.c_str());
        for (vector<Node*>::iterator in = node->in_edge_->inputs_.begin();
             in != node->in_edge_->inputs_.end(); ++in) {
          printf("    %s\n", (*in)->file_->path_.c_str());
        }
      }
      for (vector<Edge*>::iterator edge = node->out_edges_.begin();
           edge != node->out_edges_.end(); ++edge) {
        printf("  output: %s\n", (*edge)->rule_->name_.c_str());
        for (vector<Node*>::iterator out = (*edge)->outputs_.begin();
             out != (*edge)->outputs_.end(); ++out) {
          printf("    %s\n", (*out)->file_->path_.c_str());
        }
      }
    } else {
      printf("%s unknown\n", argv[i]);
      return 1;
    }
  }
  return 0;
}

int CmdBrowse(State* state, int argc, char* argv[]) {
  RunBrowsePython(state, argv[0]);
  // If we get here, the browse failed.
  return 1;
}

int main(int argc, char** argv) {
  BuildConfig config;
  const char* input_file = "build.ninja";
  string tool;

  config.parallelism = GuessParallelism();

  int opt;
  while ((opt = getopt_long(argc, argv, "f:hj:nt:v", options, NULL)) != -1) {
    switch (opt) {
      case 'f':
        input_file = optarg;
        break;
      case 'j':
        config.parallelism = atoi(optarg);
        break;
      case 'n':
        config.dry_run = true;
        break;
      case 'v':
        config.verbosity = BuildConfig::VERBOSE;
        break;
      case 't':
        tool = optarg;
        break;
      case 'h':
      default:
        usage(config);
        return 1;
    }
  }
  if (optind >= argc) {
    Error("expected target to build");
    usage(config);
    return 1;
  }
  argv += optind;
  argc -= optind;

  char cwd[PATH_MAX];
  if (!getcwd(cwd, sizeof(cwd))) {
    perror("getcwd");
    return 1;
  }

  State state;
  RealFileReader file_reader;
  ManifestParser parser(&state, &file_reader);
  string err;
  if (!parser.Load(input_file, &err)) {
    Error("loading '%s': %s", input_file, err.c_str());
    return 1;
  }

  if (!tool.empty()) {
    if (tool == "graph")
      return CmdGraph(&state, argc, argv);
    if (tool == "query")
      return CmdQuery(&state, argc, argv);
    if (tool == "browse")
      return CmdBrowse(&state, argc, argv);
    Error("unknown tool '%s'", tool.c_str());
  }

  BuildLog build_log;
  build_log.SetConfig(&config);
  state.build_log_ = &build_log;

  const string build_dir = state.bindings_.LookupVariable("builddir");
  const char* kLogPath = ".ninja_log";
  string log_path = kLogPath;
  if (!build_dir.empty()) {
    if (mkdir(build_dir.c_str(), 0777) < 0 && errno != EEXIST) {
      Error("creating build directory %s: %s",
            build_dir.c_str(), strerror(errno));
      return 1;
    }
    log_path = build_dir + "/" + kLogPath;
  }

  if (!build_log.Load(log_path.c_str(), &err)) {
    Error("loading build log %s: %s",
          log_path.c_str(), err.c_str());
    return 1;
  }

  if (!build_log.OpenForWrite(log_path.c_str(), &err)) {
    Error("opening build log: %s", err.c_str());
    return 1;
  }

  Builder builder(&state, config);
  for (int i = 0; i < argc; ++i) {
    string path = argv[i];
    string err;
    if (!CanonicalizePath(&path, &err))
      Fatal("can't canonicalize '%s': %s", path.c_str(), err.c_str());

    if (!builder.AddTarget(path, &err)) {
      if (!err.empty()) {
        Error("%s", err.c_str());
        return 1;
      } else {
        // Added a target that is already up-to-date; not really
        // an error.
      }
    }
  }

  bool success = builder.Build(&err);
  if (!err.empty()) {
    printf("build stopped: %s.\n", err.c_str());
  }

  return success ? 0 : 1;
}
<commit_msg>[windows] get processor count using Windows API<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "ninja.h"

#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#elif defined(linux)
#include <sys/sysinfo.h>
#endif

#include "browse.h"
#include "build.h"
#include "build_log.h"
#include "graph.h"
#include "graphviz.h"
#include "parsers.h"
#include "util.h"

option options[] = {
  { "help", no_argument, NULL, 'h' },
  { }
};

void usage(const BuildConfig& config) {
  fprintf(stderr,
"usage: ninja [options] target\n"
"\n"
"options:\n"
"  -f FILE  specify input build file [default=build.ninja]\n"
"  -j N     run N jobs in parallel [default=%d]\n"
"  -n       dry run (don't run commands but pretend they succeeded)\n"
"  -v       show all command lines\n"
"\n"
"  -t TOOL  run a subtool.  tools are:\n"
"             browse  browse dependency graph in a web browser\n"
"             graph   output graphviz dot file for targets\n"
"             query   show inputs/outputs for a path\n",
          config.parallelism);
}

int GuessParallelism() {
  int processors = 0;

#if defined(linux)
  processors = get_nprocs();
#elif defined(__APPLE__) || defined(__FreeBSD__)
  size_t processors_size = sizeof(processors);
  int name[] = {CTL_HW, HW_NCPU};
  if (sysctl(name, sizeof(name) / sizeof(int),
             &processors, &processors_size,
             NULL, 0) < 0) {
    processors = 1;
  }
#elif defined(WIN32)
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  processors = info.dwNumberOfProcessors;
#endif

  switch (processors) {
  case 0:
  case 1:
    return 2;
  case 2:
    return 3;
  default:
    return processors + 2;
  }
}

struct RealFileReader : public ManifestParser::FileReader {
  bool ReadFile(const string& path, string* content, string* err) {
    return ::ReadFile(path, content, err) == 0;
  }
};

int CmdGraph(State* state, int argc, char* argv[]) {
  GraphViz graph;
  graph.Start();
  for (int i = 0; i < argc; ++i)
    graph.AddTarget(state->GetNode(argv[i]));
  graph.Finish();
  return 0;
}

int CmdQuery(State* state, int argc, char* argv[]) {
  for (int i = 0; i < argc; ++i) {
    Node* node = state->GetNode(argv[i]);
    if (node) {
      printf("%s:\n", argv[i]);
      if (node->in_edge_) {
        printf("  input: %s\n", node->in_edge_->rule_->name_.c_str());
        for (vector<Node*>::iterator in = node->in_edge_->inputs_.begin();
             in != node->in_edge_->inputs_.end(); ++in) {
          printf("    %s\n", (*in)->file_->path_.c_str());
        }
      }
      for (vector<Edge*>::iterator edge = node->out_edges_.begin();
           edge != node->out_edges_.end(); ++edge) {
        printf("  output: %s\n", (*edge)->rule_->name_.c_str());
        for (vector<Node*>::iterator out = (*edge)->outputs_.begin();
             out != (*edge)->outputs_.end(); ++out) {
          printf("    %s\n", (*out)->file_->path_.c_str());
        }
      }
    } else {
      printf("%s unknown\n", argv[i]);
      return 1;
    }
  }
  return 0;
}

int CmdBrowse(State* state, int argc, char* argv[]) {
  RunBrowsePython(state, argv[0]);
  // If we get here, the browse failed.
  return 1;
}

int main(int argc, char** argv) {
  BuildConfig config;
  const char* input_file = "build.ninja";
  string tool;

  config.parallelism = GuessParallelism();

  int opt;
  while ((opt = getopt_long(argc, argv, "f:hj:nt:v", options, NULL)) != -1) {
    switch (opt) {
      case 'f':
        input_file = optarg;
        break;
      case 'j':
        config.parallelism = atoi(optarg);
        break;
      case 'n':
        config.dry_run = true;
        break;
      case 'v':
        config.verbosity = BuildConfig::VERBOSE;
        break;
      case 't':
        tool = optarg;
        break;
      case 'h':
      default:
        usage(config);
        return 1;
    }
  }
  if (optind >= argc) {
    Error("expected target to build");
    usage(config);
    return 1;
  }
  argv += optind;
  argc -= optind;

  char cwd[PATH_MAX];
  if (!getcwd(cwd, sizeof(cwd))) {
    perror("getcwd");
    return 1;
  }

  State state;
  RealFileReader file_reader;
  ManifestParser parser(&state, &file_reader);
  string err;
  if (!parser.Load(input_file, &err)) {
    Error("loading '%s': %s", input_file, err.c_str());
    return 1;
  }

  if (!tool.empty()) {
    if (tool == "graph")
      return CmdGraph(&state, argc, argv);
    if (tool == "query")
      return CmdQuery(&state, argc, argv);
    if (tool == "browse")
      return CmdBrowse(&state, argc, argv);
    Error("unknown tool '%s'", tool.c_str());
  }

  BuildLog build_log;
  build_log.SetConfig(&config);
  state.build_log_ = &build_log;

  const string build_dir = state.bindings_.LookupVariable("builddir");
  const char* kLogPath = ".ninja_log";
  string log_path = kLogPath;
  if (!build_dir.empty()) {
    if (mkdir(build_dir.c_str(), 0777) < 0 && errno != EEXIST) {
      Error("creating build directory %s: %s",
            build_dir.c_str(), strerror(errno));
      return 1;
    }
    log_path = build_dir + "/" + kLogPath;
  }

  if (!build_log.Load(log_path.c_str(), &err)) {
    Error("loading build log %s: %s",
          log_path.c_str(), err.c_str());
    return 1;
  }

  if (!build_log.OpenForWrite(log_path.c_str(), &err)) {
    Error("opening build log: %s", err.c_str());
    return 1;
  }

  Builder builder(&state, config);
  for (int i = 0; i < argc; ++i) {
    string path = argv[i];
    string err;
    if (!CanonicalizePath(&path, &err))
      Fatal("can't canonicalize '%s': %s", path.c_str(), err.c_str());

    if (!builder.AddTarget(path, &err)) {
      if (!err.empty()) {
        Error("%s", err.c_str());
        return 1;
      } else {
        // Added a target that is already up-to-date; not really
        // an error.
      }
    }
  }

  bool success = builder.Build(&err);
  if (!err.empty()) {
    printf("build stopped: %s.\n", err.c_str());
  }

  return success ? 0 : 1;
}
<|endoftext|>


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

#include "ros/ros.h"
#include <iostream>
#include <pcl/point_types.h>
#include "sensor_msgs/PointCloud2.h"
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/io/pcd_io.h>
#include <neo/neo.hpp>

#include <dynamic_reconfigure/server.h>
#include <neo_ros_pc2/FilterConfig.h>
#include <neo_ros_pc2/neo_filter.h>

typedef dynamic_reconfigure::Server<neo_ros_pc2::FilterConfig> FilterConfigServer;

neo_filter::Config filter_config;

void callback(neo_ros_pc2::FilterConfig &config, uint32_t level) {
    filter_config.MedianFilter = config.median_filter_;
    filter_config.MedianFilterWindowsSize = config.median_filter_windows_size_;
    filter_config.ClosedPointFilter = config.close_point_filter_;
    filter_config.ClosePointDistance = config.close_point_distance_;

    ROS_DEBUG("Reconfigure Request:");
    ROS_DEBUG("  median_filter: %s", config.median_filter_ ? "True" : "False");
    ROS_DEBUG("  median_filter_windows_size_: %d", config.median_filter_windows_size_);
    ROS_DEBUG("  close_point_filter: %s", config.close_point_filter_ ? "True" : "False");
    ROS_DEBUG("  close_point_distance: %d", config.close_point_distance_);

}

void median_filter(pcl::PointCloud<pcl::PointXYZ> *pointcloud) {
    ROS_DEBUG("median filter");

}

void publish_scan(ros::Publisher *pub,
                  const neo::scan *scan, std::string frame_id)
{
    pcl::PointCloud <pcl::PointXYZ> cloud;
    pcl::PointCloud <pcl::PointXYZ> cloud_polar;
    sensor_msgs::PointCloud2 cloud_msg;

    float angle;
    int32_t range;
    float x;
    float y;
    int i = 0;

    cloud.height = 1;
    cloud.width = scan->samples.size();
    cloud.points.resize(cloud.width * cloud.height);

    cloud_polar.height = 1;
    cloud_polar.width = cloud.width;
    cloud_polar.resize(cloud_polar.width * cloud_polar.height);

    for (const neo::sample& sample : scan->samples)
    {
        range = sample.distance;
        if (filter_config.ClosedPointFilter) {
            if (range < filter_config.ClosePointDistance)
                continue;
        }
        angle = ((float)sample.angle / 1000); //millidegrees to degrees

        //Polar to Cartesian Conversion
        x = (range * cos(DEG2RAD(angle))) / 100;
        y = (range * sin(DEG2RAD(angle))) / 100;

        cloud.points[i].x = x;
        cloud.points[i].y = y;

        cloud_polar.points[i].x = float(range);
        cloud_polar.points[i].y = angle;
        i++;
    }
    cloud.width = i;
    cloud_polar.width = i;
    cloud.points.resize(i * cloud.height);
    cloud_polar.points.resize(i * cloud_polar.height);
    if (filter_config.MedianFilter)
        median_filter(&cloud_polar);

    //Convert pcl PC to ROS PC2
    pcl::toROSMsg(cloud, cloud_msg);
    cloud_msg.header.frame_id = frame_id;

    ROS_DEBUG("Publishing a full scan");
    ROS_DEBUG("Scan number: %d", i);
    pub->publish(cloud_msg);
}

int main(int argc, char *argv[]) try
{
    //Initialize Node and handles
    ros::init(argc, argv, "neo_node");
    ros::NodeHandle nh;
    ros::NodeHandle nh_private("~");

    //Get Serial Parameters
    std::string serial_port;
    nh_private.param<std::string>("serial_port", serial_port, "/dev/ttyUSB0");
    int serial_baudrate;
    nh_private.param<int>("serial_baudrate", serial_baudrate, 115200);

    //Get Scanner Parameters
    int rotation_speed;
    nh_private.param<int>("rotation_speed", rotation_speed, 5);

    //Get frame id Parameters
    std::string frame_id;
    nh_private.param<std::string>("frame_id", frame_id, "laser_frame");

    //Setup Publisher
    ros::Publisher scan_pub = nh.advertise<sensor_msgs::PointCloud2>("pc2", 1000);

    //Create Neo Driver Object
    neo::neo device{serial_port.c_str()};
    ROS_INFO("Device connect successful!");

    //Send Rotation Speed
    device.set_motor_speed(rotation_speed);

    ROS_INFO("expected rotation frequency: %d (Hz)", rotation_speed);

    //Start Scan
    device.start_scanning();

    // dynamic_reconfigure server
    FilterConfigServer server;
    FilterConfigServer::CallbackType f;
    f = boost::bind(&callback, _1, _2);
    server.setCallback(f);

    while (ros::ok())
    {
        //Grab Full Scan
        const neo::scan scan = device.get_scan();

        publish_scan(&scan_pub, &scan, frame_id);

        ros::spinOnce();
    }

    //Stop Scanning & Destroy Driver
    device.stop_scanning();
    device.set_motor_speed(0);
} catch (const neo::device_error& e) {
      ROS_ERROR_STREAM("Error: " << e.what() << std::endl);
}
<commit_msg>fix(TimeStamp): adding TimeStamp to pc2 header.<commit_after>
/*The MIT License (MIT)
 *
 * Copyright (c) 2017, Scanse, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "ros/ros.h"
#include <iostream>
#include <pcl/point_types.h>
#include "sensor_msgs/PointCloud2.h"
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/io/pcd_io.h>
#include <neo/neo.hpp>

#include <dynamic_reconfigure/server.h>
#include <neo_ros_pc2/FilterConfig.h>
#include <neo_ros_pc2/neo_filter.h>

typedef dynamic_reconfigure::Server<neo_ros_pc2::FilterConfig> FilterConfigServer;

neo_filter::Config filter_config;

void callback(neo_ros_pc2::FilterConfig &config, uint32_t level) {
    filter_config.MedianFilter = config.median_filter_;
    filter_config.MedianFilterWindowsSize = config.median_filter_windows_size_;
    filter_config.ClosedPointFilter = config.close_point_filter_;
    filter_config.ClosePointDistance = config.close_point_distance_;

    ROS_DEBUG("Reconfigure Request:");
    ROS_DEBUG("  median_filter: %s", config.median_filter_ ? "True" : "False");
    ROS_DEBUG("  median_filter_windows_size_: %d", config.median_filter_windows_size_);
    ROS_DEBUG("  close_point_filter: %s", config.close_point_filter_ ? "True" : "False");
    ROS_DEBUG("  close_point_distance: %d", config.close_point_distance_);

}

void median_filter(pcl::PointCloud<pcl::PointXYZ> *pointcloud) {
    ROS_DEBUG("median filter");

}

void publish_scan(ros::Publisher *pub,
                  const neo::scan *scan, std::string frame_id)
{
    pcl::PointCloud <pcl::PointXYZ> cloud;
    pcl::PointCloud <pcl::PointXYZ> cloud_polar;
    sensor_msgs::PointCloud2 cloud_msg;
    ros::Time ros_time_now = ros::Time::now();

    float angle;
    int32_t range;
    float x;
    float y;
    int i = 0;

    cloud.height = 1;
    cloud.width = scan->samples.size();
    cloud.points.resize(cloud.width * cloud.height);

    cloud_polar.height = 1;
    cloud_polar.width = cloud.width;
    cloud_polar.resize(cloud_polar.width * cloud_polar.height);

    for (const neo::sample& sample : scan->samples)
    {
        range = sample.distance;
        if (filter_config.ClosedPointFilter) {
            if (range < filter_config.ClosePointDistance)
                continue;
        }
        angle = ((float)sample.angle / 1000); //millidegrees to degrees

        //Polar to Cartesian Conversion
        x = (range * cos(DEG2RAD(angle))) / 100;
        y = (range * sin(DEG2RAD(angle))) / 100;

        cloud.points[i].x = x;
        cloud.points[i].y = y;

        cloud_polar.points[i].x = float(range);
        cloud_polar.points[i].y = angle;
        i++;
    }
    cloud.width = i;
    cloud_polar.width = i;
    cloud.points.resize(i * cloud.height);
    cloud_polar.points.resize(i * cloud_polar.height);
    if (filter_config.MedianFilter)
        median_filter(&cloud_polar);

    //Convert pcl PC to ROS PC2
    pcl::toROSMsg(cloud, cloud_msg);
    cloud_msg.header.frame_id = frame_id;
    cloud_msg.header.stamp = ros_time_now;

    ROS_DEBUG("Publishing a full scan");
    ROS_DEBUG("Scan number: %d", i);
    pub->publish(cloud_msg);
}

int main(int argc, char *argv[]) try
{
    //Initialize Node and handles
    ros::init(argc, argv, "neo_node");
    ros::NodeHandle nh;
    ros::NodeHandle nh_private("~");

    //Get Serial Parameters
    std::string serial_port;
    nh_private.param<std::string>("serial_port", serial_port, "/dev/ttyUSB0");
    int serial_baudrate;
    nh_private.param<int>("serial_baudrate", serial_baudrate, 115200);

    //Get Scanner Parameters
    int rotation_speed;
    nh_private.param<int>("rotation_speed", rotation_speed, 5);

    //Get frame id Parameters
    std::string frame_id;
    nh_private.param<std::string>("frame_id", frame_id, "laser_frame");

    //Setup Publisher
    ros::Publisher scan_pub = nh.advertise<sensor_msgs::PointCloud2>("pc2", 1000);

    //Create Neo Driver Object
    neo::neo device{serial_port.c_str()};
    ROS_INFO("Device connect successful!");

    //Send Rotation Speed
    device.set_motor_speed(rotation_speed);

    ROS_INFO("expected rotation frequency: %d (Hz)", rotation_speed);

    //Start Scan
    device.start_scanning();

    // dynamic_reconfigure server
    FilterConfigServer server;
    FilterConfigServer::CallbackType f;
    f = boost::bind(&callback, _1, _2);
    server.setCallback(f);

    while (ros::ok())
    {
        //Grab Full Scan
        const neo::scan scan = device.get_scan();

        publish_scan(&scan_pub, &scan, frame_id);

        ros::spinOnce();
    }

    //Stop Scanning & Destroy Driver
    device.stop_scanning();
    device.set_motor_speed(0);
} catch (const neo::device_error& e) {
      ROS_ERROR_STREAM("Error: " << e.what() << std::endl);
}
<|endoftext|>


<commit_before>/*
   This file is part of the clang-lazy static checker.

  Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  Copyright (C) 2015 Sergio Martins <smartins@kde.org>

  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.

  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 General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "Utils.h"
#include "StringUtils.h"

#include "checkbase.h"
#include "checkmanager.h"

#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/AST/ParentMap.h"

#include <stdio.h>
#include <sstream>
#include <iostream>

using namespace clang;
using namespace std;

namespace {

class MyFixItOptions : public FixItOptions
{
public:
    MyFixItOptions(bool inplace)
    {
        InPlace = inplace;
        FixWhatYouCan = true;
        FixOnlyWarnings = true;
        Silent = false;
    }

    std::string RewriteFilename(const std::string &filename, int &fd) override
    {
        fd = -1;
        return InPlace ? filename : filename + "_fixed.cpp";
    }

#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6
    bool InPlace;
#endif
};

static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
    if (!s)
        return;

    auto it = s->child_begin();
    auto e = s->child_end();
    for (; it != e; ++it) {
        llvm::errs() << "Patching " << (*it)->getStmtClassName() << "\n";
        map->setParent(*it, s);
        manuallyPopulateParentMap(map, *it);
    }
}

class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>
{
public:
    LazyASTConsumer(CompilerInstance &ci, const vector<string> &requestedChecks, bool inplaceFixits)
        : m_ci(ci)
        , m_rewriter(nullptr)
        , m_parentMap(nullptr)
        , m_checkManager(CheckManager::instance())
    {
        m_checkManager->setCompilerInstance(&m_ci);
        m_checkManager->createChecks(requestedChecks);
        if (m_checkManager->fixitsEnabled())
            m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));
    }

    ~LazyASTConsumer()
    {
        if (m_rewriter != nullptr) {
            m_rewriter->WriteFixedFiles();
            delete m_rewriter;
        }
    }

    void setParentMap(ParentMap *map)
    {
        delete m_parentMap;
        m_parentMap = map;
        auto &createdChecks = m_checkManager->createdChecks();
        for (auto &check : createdChecks)
            check->setParentMap(map);
    }

    bool VisitDecl(Decl *decl)
    {
        auto &createdChecks = m_checkManager->createdChecks();
        for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) {
            (*it)->VisitDeclaration(decl);
        }

        return true;
    }

    bool VisitStmt(Stmt *stm)
    {
        static Stmt *lastStm = nullptr;
        // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
        if (lastStm && isa<CXXCatchStmt>(lastStm) && m_parentMap && !m_parentMap->hasParent(stm)) {
            m_parentMap->setParent(stm, lastStm);
            manuallyPopulateParentMap(m_parentMap, stm);
        }

        lastStm = stm;

        // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
        // So re-set a parent map each time we go into a different hieararchy
        if (m_parentMap == nullptr || !m_parentMap->hasParent(stm)) {
            assert(stm != nullptr);
            setParentMap(new ParentMap(stm));
        }

        auto &createdChecks = m_checkManager->createdChecks();
        for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) {
            (*it)->VisitStatement(stm);
        }

        return true;
    }

    void HandleTranslationUnit(ASTContext &ctx) override
    {
        TraverseDecl(ctx.getTranslationUnitDecl());
    }

    CompilerInstance &m_ci;
    FixItRewriter *m_rewriter;
    ParentMap *m_parentMap;
    CheckManager *m_checkManager;
};

//------------------------------------------------------------------------------

static bool parseArgument(const string &arg, vector<string> &args)
{
    auto it = std::find(args.begin(), args.end(), arg);
    if (it != args.end()) {
        args.erase(it, it + 1);
        return true;
    }

    return false;
}

static int parseLevel(vector<std::string> &args)
{
    static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
    const int numLevels = levels.size();
    for (int i = 0; i < numLevels; ++i) {
        if (parseArgument(levels.at(i), args)) {
            return i;
        }
    }

    return -1;
}

class LazyASTAction : public PluginASTAction {
protected:
    std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override
    {
        return llvm::make_unique<LazyASTConsumer>(ci, m_checks, m_inplaceFixits);
    }

    bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override
    {
        std::vector<std::string> args = args_;

        if (parseArgument("help", args)) {
            llvm::errs() << "Help:\n";
            PrintHelp(llvm::errs());
            return false;
        }

        if (parseArgument("no-inplace-fixits", args)) {
            // Unit-tests don't use inplace fixits
            m_inplaceFixits = false;
        }

        auto checkManager = CheckManager::instance();
        const int requestedLevel = parseLevel(/*by-ref*/args);
        if (requestedLevel != -1) {
            checkManager->setRequestedLevel(requestedLevel);
        }

        if (parseArgument("enable-all-fixits", args)) {
            // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
            CheckManager::instance()->enableAllFixIts();
        }

        if (args.size() > 1) {
            // Too many arguments.
            llvm::errs() << "Too many arguments: ";
            for (const std::string &a : args)
                llvm::errs() << a << " ";
            llvm::errs() << "\n";

            PrintHelp(llvm::errs());
            return false;
        } else if (args.size() == 1) {
            m_checks = CheckManager::instance()->checkNamesForCommaSeparatedString(args[0]);
            if (m_checks.empty()) {
                llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
                PrintHelp(llvm::errs());
                return false;
            }
        }

        return true;
    }

    void PrintHelp(llvm::raw_ostream &ros)
    {
        const vector<string> &names = CheckManager::instance()->availableCheckNames(false);

        ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
        ros << "export CLAZY_CHECKS=\"reserve-candidates,qstring-uneeded-heap-allocations\"\n\n";
        ros << "or pass as compiler arguments, for example:\n";
        ros << "-Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-uneeded-heap-allocations\n";
        ros << "\n";
        ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
        ros << "export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
        ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\n\n";

        ros << "Available checks and FixIts:\n\n";
        for (uint i = 1; i < names.size(); ++i) {
            auto padded = names[i];
            padded.insert(padded.end(), 39 - padded.size(), ' ');
            ros << names[i];
            auto fixits = CheckManager::instance()->availableFixIts(names[i]);
            if (!fixits.empty()) {
                ros << "    (";
                bool isFirst = true;
                for (auto fixit : fixits) {
                    if (isFirst) {
                        isFirst = false;
                    } else {
                        ros << ",";
                    }

                    ros << fixit.name;
                }
                ros << ")";
            }
            ros << "\n";
        }

        exit(-2);
    }

private:
    vector<string> m_checks;
    bool m_inplaceFixits = true;
};

}

static FrontendPluginRegistry::Add<LazyASTAction>
X("clang-lazy", "clang lazy plugin");
<commit_msg>Don't break getting checks from env-variable<commit_after>/*
   This file is part of the clang-lazy static checker.

  Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  Copyright (C) 2015 Sergio Martins <smartins@kde.org>

  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.

  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 General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "Utils.h"
#include "StringUtils.h"

#include "checkbase.h"
#include "checkmanager.h"

#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Lex/Lexer.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/AST/ParentMap.h"

#include <stdio.h>
#include <sstream>
#include <iostream>

using namespace clang;
using namespace std;

namespace {

class MyFixItOptions : public FixItOptions
{
public:
    MyFixItOptions(bool inplace)
    {
        InPlace = inplace;
        FixWhatYouCan = true;
        FixOnlyWarnings = true;
        Silent = false;
    }

    std::string RewriteFilename(const std::string &filename, int &fd) override
    {
        fd = -1;
        return InPlace ? filename : filename + "_fixed.cpp";
    }

#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6
    bool InPlace;
#endif
};

static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
    if (!s)
        return;

    auto it = s->child_begin();
    auto e = s->child_end();
    for (; it != e; ++it) {
        llvm::errs() << "Patching " << (*it)->getStmtClassName() << "\n";
        map->setParent(*it, s);
        manuallyPopulateParentMap(map, *it);
    }
}

class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>
{
public:
    LazyASTConsumer(CompilerInstance &ci, const vector<string> &requestedChecks, bool inplaceFixits)
        : m_ci(ci)
        , m_rewriter(nullptr)
        , m_parentMap(nullptr)
        , m_checkManager(CheckManager::instance())
    {
        m_checkManager->setCompilerInstance(&m_ci);
        m_checkManager->createChecks(requestedChecks);
        if (m_checkManager->fixitsEnabled())
            m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));
    }

    ~LazyASTConsumer()
    {
        if (m_rewriter != nullptr) {
            m_rewriter->WriteFixedFiles();
            delete m_rewriter;
        }
    }

    void setParentMap(ParentMap *map)
    {
        delete m_parentMap;
        m_parentMap = map;
        auto &createdChecks = m_checkManager->createdChecks();
        for (auto &check : createdChecks)
            check->setParentMap(map);
    }

    bool VisitDecl(Decl *decl)
    {
        auto &createdChecks = m_checkManager->createdChecks();
        for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) {
            (*it)->VisitDeclaration(decl);
        }

        return true;
    }

    bool VisitStmt(Stmt *stm)
    {
        static Stmt *lastStm = nullptr;
        // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
        if (lastStm && isa<CXXCatchStmt>(lastStm) && m_parentMap && !m_parentMap->hasParent(stm)) {
            m_parentMap->setParent(stm, lastStm);
            manuallyPopulateParentMap(m_parentMap, stm);
        }

        lastStm = stm;

        // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
        // So re-set a parent map each time we go into a different hieararchy
        if (m_parentMap == nullptr || !m_parentMap->hasParent(stm)) {
            assert(stm != nullptr);
            setParentMap(new ParentMap(stm));
        }

        auto &createdChecks = m_checkManager->createdChecks();
        for (auto it = createdChecks.cbegin(), end = createdChecks.cend(); it != end; ++it) {
            (*it)->VisitStatement(stm);
        }

        return true;
    }

    void HandleTranslationUnit(ASTContext &ctx) override
    {
        TraverseDecl(ctx.getTranslationUnitDecl());
    }

    CompilerInstance &m_ci;
    FixItRewriter *m_rewriter;
    ParentMap *m_parentMap;
    CheckManager *m_checkManager;
};

//------------------------------------------------------------------------------

static bool parseArgument(const string &arg, vector<string> &args)
{
    auto it = std::find(args.begin(), args.end(), arg);
    if (it != args.end()) {
        args.erase(it, it + 1);
        return true;
    }

    return false;
}

static int parseLevel(vector<std::string> &args)
{
    static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
    const int numLevels = levels.size();
    for (int i = 0; i < numLevels; ++i) {
        if (parseArgument(levels.at(i), args)) {
            return i;
        }
    }

    return -1;
}

class LazyASTAction : public PluginASTAction {
protected:
    std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override
    {
        return llvm::make_unique<LazyASTConsumer>(ci, m_checks, m_inplaceFixits);
    }

    bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override
    {
        std::vector<std::string> args = args_;

        if (parseArgument("help", args)) {
            llvm::errs() << "Help:\n";
            PrintHelp(llvm::errs());
            return false;
        }

        if (parseArgument("no-inplace-fixits", args)) {
            // Unit-tests don't use inplace fixits
            m_inplaceFixits = false;
        }

        auto checkManager = CheckManager::instance();
        const int requestedLevel = parseLevel(/*by-ref*/args);
        if (requestedLevel != -1) {
            checkManager->setRequestedLevel(requestedLevel);
        }

        if (parseArgument("enable-all-fixits", args)) {
            // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
            CheckManager::instance()->enableAllFixIts();
        }

        if (args.empty()) {
            m_checks = CheckManager::instance()->requestedCheckNamesThroughEnv();
        } if (args.size() > 1) {
            // Too many arguments.
            llvm::errs() << "Too many arguments: ";
            for (const std::string &a : args)
                llvm::errs() << a << " ";
            llvm::errs() << "\n";

            PrintHelp(llvm::errs());
            return false;
        } else if (args.size() == 1) {
            m_checks = CheckManager::instance()->checkNamesForCommaSeparatedString(args[0]);
            if (m_checks.empty()) {
                llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
                PrintHelp(llvm::errs());
                return false;
            }
        }

        return true;
    }

    void PrintHelp(llvm::raw_ostream &ros)
    {
        const vector<string> &names = CheckManager::instance()->availableCheckNames(false);

        ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
        ros << "export CLAZY_CHECKS=\"reserve-candidates,qstring-uneeded-heap-allocations\"\n\n";
        ros << "or pass as compiler arguments, for example:\n";
        ros << "-Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-uneeded-heap-allocations\n";
        ros << "\n";
        ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
        ros << "export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
        ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\n\n";

        ros << "Available checks and FixIts:\n\n";
        for (uint i = 1; i < names.size(); ++i) {
            auto padded = names[i];
            padded.insert(padded.end(), 39 - padded.size(), ' ');
            ros << names[i];
            auto fixits = CheckManager::instance()->availableFixIts(names[i]);
            if (!fixits.empty()) {
                ros << "    (";
                bool isFirst = true;
                for (auto fixit : fixits) {
                    if (isFirst) {
                        isFirst = false;
                    } else {
                        ros << ",";
                    }

                    ros << fixit.name;
                }
                ros << ")";
            }
            ros << "\n";
        }

        exit(-2);
    }

private:
    vector<string> m_checks;
    bool m_inplaceFixits = true;
};

}

static FrontendPluginRegistry::Add<LazyASTAction>
X("clang-lazy", "clang lazy plugin");
<|endoftext|>


<commit_before>#include <Internal/VirtualConsoleImpl.hpp>
#include <Windows.h>
#include <string>
#include <thread>
#include <Internal/VA_LISTHelper.hpp>
#include <iostream>
#include <Utility/DebugLog/Include/Internal/ThreadPool.hpp>
#include <string>

namespace Utility
{
    namespace DebugLog
    {

        struct LoggingData // TODORT, maybe move to .cpp?
        {
            std::string function;
            size_t line;
            LogTag tag;
            LogLevel vLevel;
            std::string p_message;
            // TODORT Ideally I would like the conversion to happen on the threads, however,
            // I did not manage to fully use the VA_LIST correctly thus some values were copied between threads.
            //    std::string format;
            //    va_list args;
        };

        VirtualConsoleImpl::VirtualConsoleImpl(const std::string& p_pipeName, ctpl::thread_pool& p_threadPool)
            : m_pipeName(p_pipeName), m_threadPool(p_threadPool)
        {
        }

        void VirtualConsoleImpl::Initialize(bool p_writeToConsole, bool p_writeToFile, const ConsoleColor& p_textColor, const ConsoleColor& p_backgroundColor)
        {
            if(!p_writeToConsole && !p_writeToFile)
            {
                throw std::runtime_error("Not both outputs can be offline."); // TODORT better message ?
            }

            SECURITY_ATTRIBUTES sa;
            sa.nLength = sizeof(SECURITY_ATTRIBUTES);
            sa.bInheritHandle = 1;
            sa.lpSecurityDescriptor = 0;

            if(!CreatePipe(&m_farEnd, &m_nearEnd, &sa, 0))
            {
                throw std::runtime_error("Creating shared memory failed.");
                return;
            }
            SetHandleInformation(m_nearEnd, HANDLE_FLAG_INHERIT, 0);
            PROCESS_INFORMATION pi;
            STARTUPINFO si;
            ZeroMemory(&pi, sizeof(pi));
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(STARTUPINFO);
            si.hStdInput = this->m_farEnd;
            si.dwFlags |= STARTF_USESTDHANDLES;

            HMODULE hModule = GetModuleHandleW(NULL);
            WCHAR path[MAX_PATH];
            GetModuleFileNameW(hModule, path, MAX_PATH);
            std::wstring tmpPath = std::wstring(path);
            tmpPath = std::wstring(tmpPath.begin(), tmpPath.end() - 10); // TODORT, better solution
            tmpPath.append(L"ConsoleApplication.exe");

            WCHAR arguments[100];
#ifndef UNICODE
            sprintf(arguments, "%d", color);
#else
            std::wstring wPipeName(m_pipeName.begin(), m_pipeName.end()); // I fucking hate windows
            DWORD color = p_textColor.stateValue | p_backgroundColor.stateValue; // I fucking hate windows
            swprintf(arguments, L"0, %s %d %d %d", wPipeName.c_str(), color, p_writeToConsole, p_writeToFile); // I fucking hate windows
#endif
            if(!CreateProcess(tmpPath.c_str(), arguments, 0, 0, 1, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, 0, 0, &si, &pi))
            {
                throw std::runtime_error("Creating virtualConsole failed.");
            }
            m_process = pi.hProcess;
            CloseHandle(pi.hThread);
        }

        VirtualConsoleImpl::~VirtualConsoleImpl()
        {
            if(m_nearEnd != INVALID_HANDLE_VALUE)
            {
                if(m_nearEnd != INVALID_HANDLE_VALUE)
                {
                    TerminateProcess(m_process, 0); // TODORT Graceful shutdown may be ok?
                    CloseHandle(m_process);
                }
                CloseHandle(m_nearEnd);
                CloseHandle(m_farEnd);
            }
        }

        void AsynchronousLogText(int id, VirtualConsoleImpl* const p_console, LoggingData* p_data)
        {
            p_console->WriteToSharedMemory(*p_data);
            delete p_data;
        }

        void VirtualConsoleImpl::LT(const std::string& p_function, const size_t& p_line, const LogTag& p_tag, const LogLevel& p_vLevel, const char* p_format, ...)
        {
            va_list args;
            va_start(args, p_format);
            LoggingData* threadData = new LoggingData();
            threadData->function = p_function;
            threadData->line = p_line;
            threadData->tag = p_tag;
            threadData->vLevel = p_vLevel;
            toString(threadData->p_message, p_format, args);
            m_threadPool.push(AsynchronousLogText, this, threadData);
            va_end(args);
        }

        void VirtualConsoleImpl::WriteToSharedMemory(const LoggingData& p_loggingData)
        {
            DWORD l;
            // TODORT better format
            std::string out = std::string("[" + p_loggingData.function + ":" + std::to_string(p_loggingData.line) + "]" + "\t" + p_loggingData.p_message + "\n");
            WriteFile(m_nearEnd, out.c_str(), out.size(), &l, 0);
        }
    }
}<commit_msg>Fixed faulty logic for building console colors.<commit_after>#include <Internal/VirtualConsoleImpl.hpp>
#include <Windows.h>
#include <string>
#include <thread>
#include <Internal/VA_LISTHelper.hpp>
#include <iostream>
#include <Utility/DebugLog/Include/Internal/ThreadPool.hpp>
#include <string>

namespace Utility
{
    namespace DebugLog
    {

        struct LoggingData // TODORT, maybe move to .cpp?
        {
            std::string function;
            size_t line;
            LogTag tag;
            LogLevel vLevel;
            std::string p_message;
            // TODORT Ideally I would like the conversion to happen on the threads, however,
            // I did not manage to fully use the VA_LIST correctly thus some values were copied between threads.
            //    std::string format;
            //    va_list args;
        };

        VirtualConsoleImpl::VirtualConsoleImpl(const std::string& p_pipeName, ctpl::thread_pool& p_threadPool)
            : m_pipeName(p_pipeName), m_threadPool(p_threadPool)
        {
        }

        void VirtualConsoleImpl::Initialize(bool p_writeToConsole, bool p_writeToFile, const ConsoleColor& p_textColor, const ConsoleColor& p_backgroundColor)
        {
            if(!p_writeToConsole && !p_writeToFile)
            {
                throw std::runtime_error("Not both outputs can be offline."); // TODORT better message ?
            }

            SECURITY_ATTRIBUTES sa;
            sa.nLength = sizeof(SECURITY_ATTRIBUTES);
            sa.bInheritHandle = 1;
            sa.lpSecurityDescriptor = 0;

            if(!CreatePipe(&m_farEnd, &m_nearEnd, &sa, 0))
            {
                throw std::runtime_error("Creating shared memory failed.");
                return;
            }
            SetHandleInformation(m_nearEnd, HANDLE_FLAG_INHERIT, 0);
            PROCESS_INFORMATION pi;
            STARTUPINFO si;
            ZeroMemory(&pi, sizeof(pi));
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(STARTUPINFO);
            si.hStdInput = this->m_farEnd;
            si.dwFlags |= STARTF_USESTDHANDLES;

            HMODULE hModule = GetModuleHandleW(NULL);
            WCHAR path[MAX_PATH];
            GetModuleFileNameW(hModule, path, MAX_PATH);
            std::wstring tmpPath = std::wstring(path);
            tmpPath = std::wstring(tmpPath.begin(), tmpPath.end() - 10); // TODORT, better solution
            tmpPath.append(L"ConsoleApplication.exe");

            WCHAR arguments[100];
#ifndef UNICODE
            sprintf(arguments, "%d", color);
#else
            std::wstring wPipeName(m_pipeName.begin(), m_pipeName.end()); // I fucking hate windows
            DWORD color = p_textColor.stateValue + p_backgroundColor.stateValue; // I fucking hate windows
            swprintf(arguments, L"0, %s %d %d %d", wPipeName.c_str(), color, p_writeToConsole, p_writeToFile); // I fucking hate windows
#endif
            if(!CreateProcess(tmpPath.c_str(), arguments, 0, 0, 1, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, 0, 0, &si, &pi))
            {
                throw std::runtime_error("Creating virtualConsole failed.");
            }
            m_process = pi.hProcess;
            CloseHandle(pi.hThread);
        }

        VirtualConsoleImpl::~VirtualConsoleImpl()
        {
            if(m_nearEnd != INVALID_HANDLE_VALUE)
            {
                if(m_nearEnd != INVALID_HANDLE_VALUE)
                {
                    TerminateProcess(m_process, 0); // TODORT Graceful shutdown may be ok?
                    CloseHandle(m_process);
                }
                CloseHandle(m_nearEnd);
                CloseHandle(m_farEnd);
            }
        }

        void AsynchronousLogText(int id, VirtualConsoleImpl* const p_console, LoggingData* p_data)
        {
            p_console->WriteToSharedMemory(*p_data);
            delete p_data;
        }

        void VirtualConsoleImpl::LT(const std::string& p_function, const size_t& p_line, const LogTag& p_tag, const LogLevel& p_vLevel, const char* p_format, ...)
        {
            va_list args;
            va_start(args, p_format);
            LoggingData* threadData = new LoggingData();
            threadData->function = p_function;
            threadData->line = p_line;
            threadData->tag = p_tag;
            threadData->vLevel = p_vLevel;
            toString(threadData->p_message, p_format, args);
            m_threadPool.push(AsynchronousLogText, this, threadData);
            va_end(args);
        }

        void VirtualConsoleImpl::WriteToSharedMemory(const LoggingData& p_loggingData)
        {
            DWORD l;
            // TODORT better format
            std::string out = std::string("[" + p_loggingData.function + ":" + std::to_string(p_loggingData.line) + "]" + "\t" + p_loggingData.p_message + "\n");
            WriteFile(m_nearEnd, out.c_str(), out.size(), &l, 0);
        }
    }
}<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file main.cpp
 */

#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>
#include <JPetTaskLoader/JPetTaskLoader.h>
#include "TaskA.h"
#include "SignalFinder.h"
#include "PhysicalDescriptor.h"
#include "HitFinder.h"
#include "TimeCalibLoader.h"
#include "TaskC.h"
#include "TaskD.h"
#include "TaskE.h"

using namespace std;

int main(int argc, char* argv[])
{
  DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
  JPetManager& manager = JPetManager::getManager();
  manager.parseCmdLine(argc, argv);

  // Here create all analysis modules to be used:

  manager.registerTask([]() {
    return new JPetTaskLoader("hld",
                              "tslot.raw",
                              new TaskA("TaskA: Unp to Timewindow",
                                        "Process unpacked HLD file into a tree of JPetTimeWindow objects")
                             );
  });

  manager.registerTask([]() {
    return new JPetTaskLoader("tslot.raw", "tslot.raw",
                              new TimeCalibLoader("Apply time corrections from prepared calibrations",
                                  "Apply time corrections from prepared calibrations"));
  });
  manager.registerTask([]() {
    return new JPetTaskLoader("tslot.raw",
                              "raw.sig",
                              new SignalFinder("SignalFinder: Create Raw Sigs",
                                  "Create Raw Signals, optionallh draw TOTs per THR",
                                  true)
                             );
  });

  manager.registerTask([]() {
    return new JPetTaskLoader("phys_sig", "hits",
                              new HitFinder("Module: Pair signals",
                                            "Create hits from physical signals from both ends of scintilators"));
  });

  //manager.registerTask([]() {
  //return new JPetTaskLoader("raw.sig", "phys.hit",
  //new TaskC("Module C: Pair signals",
  //"Create hits from pairs of signals"));
  //});

  // manager.registerTask([](){
  //     return new JPetTaskLoader("phys.hit", "phys.hit.means",
  // 				new TaskD("Module D: Make histograms for hits",
  // 					  "Only make timeDiff histos and produce mean timeDiff value for each threshold and slot to be used by the next module"));
  //   });

  // manager.registerTask([](){
  //     return new JPetTaskLoader("phys.hit.means", "phys.hit.coincplots",
  // 				new TaskE("Module E: Filter hits",
  // 					  "Pass only hits with time diffrerence close to the peak"));
  //   });

  manager.run();
}
<commit_msg>Correct comments in main.cpp<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file main.cpp
 */

#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>
#include <JPetTaskLoader/JPetTaskLoader.h>
#include "TaskA.h"
#include "SignalFinder.h"
#include "PhysicalDescriptor.h"
#include "HitFinder.h"
#include "TimeCalibLoader.h"
#include "TaskC.h"
#include "TaskD.h"
#include "TaskE.h"

using namespace std;

int main(int argc, char* argv[])
{
  DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
  JPetManager& manager = JPetManager::getManager();
  manager.parseCmdLine(argc, argv);

  // Here create all analysis modules to be used:

  manager.registerTask([]() {
    return new JPetTaskLoader("hld",
                              "tslot.raw",
                              new TaskA("TaskA: Unp to Timewindow",
                                        "Process unpacked HLD file into a tree of JPetTimeWindow objects")
                             );
  });

  manager.registerTask([]() {
    return new JPetTaskLoader("tslot.raw", "tslot.raw",
                              new TimeCalibLoader("Apply time corrections from prepared calibrations",
                                  "Apply time corrections from prepared calibrations"));
  });
  manager.registerTask([]() {
    return new JPetTaskLoader("tslot.raw",
                              "raw.sig",
                              new SignalFinder("SignalFinder: Create Raw Sigs",
                                  "Create Raw Signals, optional  draw TOTs per THR",
                                  true)
                             );
  });

  manager.registerTask([]() {
    return new JPetTaskLoader("phys_sig", "hits",
                              new HitFinder("Module: Pair signals",
                                            "Create hits from physical signals from both ends of scintilators"));
  });

  //manager.registerTask([]() {
  //return new JPetTaskLoader("raw.sig", "phys.hit",
  //new TaskC("Module C: Pair signals",
  //"Create hits from pairs of signals"));
  //});

  // manager.registerTask([](){
  //     return new JPetTaskLoader("phys.hit", "phys.hit.means",
  // 				new TaskD("Module D: Make histograms for hits",
  // 					  "Only make timeDiff histos and produce mean timeDiff value for each threshold and slot to be used by the next module"));
  //   });

  // manager.registerTask([](){
  //     return new JPetTaskLoader("phys.hit.means", "phys.hit.coincplots",
  // 				new TaskE("Module E: Filter hits",
  // 					  "Pass only hits with time diffrerence close to the peak"));
  //   });

  manager.run();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: prgsbar.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2004-01-06 19:19:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PRGSBAR_HXX
#define _PRGSBAR_HXX

#ifndef _WINDOW_HXX
#include <vcl/window.hxx>
#endif

/*************************************************************************

Beschreibung
============

class ProgressBar

Diese Klasse dient zur Anzeige einer Progress-Anzeige.

--------------------------------------------------------------------------

WinBits

WB_BORDER           Border um das Fenster
WB_3DLOOK           3D-Darstellung

--------------------------------------------------------------------------

Methoden

Mit SetValue() setzt man einen Prozent-Wert zwischen 0 und 100. Wenn Werte
groesser 100 gesetzt werden, faengt das letzte Rechteck an zu blinken.

*************************************************************************/

// -----------
// - WinBits -
// -----------

#define WB_STDPROGRESSBAR       WB_BORDER

// ---------------
// - ProgressBar -
// ---------------

class ProgressBar : public Window
{
private:
    Point               maPos;
    long                mnPrgsWidth;
    long                mnPrgsHeight;
    USHORT              mnPercent;
    USHORT              mnPercentCount;
    BOOL                mbCalcNew;

#ifdef _SV_PRGSBAR_CXX
    void                ImplInit();
    void                ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
    void                ImplDrawProgress( USHORT nOldPerc, USHORT nNewPerc );
#endif

public:
                        ProgressBar( Window* pParent, WinBits nWinBits = WB_STDPROGRESSBAR );
                        ProgressBar( Window* pParent, const ResId& rResId );
                        ~ProgressBar();

    virtual void        Paint( const Rectangle& rRect );
    virtual void        Resize();
    virtual void        StateChanged( StateChangedType nStateChange );
    virtual void        DataChanged( const DataChangedEvent& rDCEvt );

    void                SetValue( USHORT nNewPercent );
    USHORT              GetValue() const { return mnPercent; }
};

#endif  // _PRGSBAR_HXX
<commit_msg>INTEGRATION: CWS visibility03 (1.2.482); FILE MERGED 2005/03/24 14:13:54 mhu 1.2.482.1: #i45006# Include svtools/(svl|svt)dllapi.h, declare symbol visibility with (SVL|SVT)_DLL(PUBLIC|PRIVATE) as appropriate; partial cleanup.<commit_after>/*************************************************************************
 *
 *  $RCSfile: prgsbar.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 10:25:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PRGSBAR_HXX
#define _PRGSBAR_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _WINDOW_HXX
#include <vcl/window.hxx>
#endif

/*************************************************************************

Beschreibung
============

class ProgressBar

Diese Klasse dient zur Anzeige einer Progress-Anzeige.

--------------------------------------------------------------------------

WinBits

WB_BORDER           Border um das Fenster
WB_3DLOOK           3D-Darstellung

--------------------------------------------------------------------------

Methoden

Mit SetValue() setzt man einen Prozent-Wert zwischen 0 und 100. Wenn Werte
groesser 100 gesetzt werden, faengt das letzte Rechteck an zu blinken.

*************************************************************************/

// -----------
// - WinBits -
// -----------

#define WB_STDPROGRESSBAR       WB_BORDER

// ---------------
// - ProgressBar -
// ---------------

class SVT_DLLPUBLIC ProgressBar : public Window
{
private:
    Point               maPos;
    long                mnPrgsWidth;
    long                mnPrgsHeight;
    USHORT              mnPercent;
    USHORT              mnPercentCount;
    BOOL                mbCalcNew;

#ifdef _SV_PRGSBAR_CXX
    SVT_DLLPRIVATE void             ImplInit();
    SVT_DLLPRIVATE void             ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
    SVT_DLLPRIVATE void             ImplDrawProgress( USHORT nOldPerc, USHORT nNewPerc );
#endif

public:
                        ProgressBar( Window* pParent, WinBits nWinBits = WB_STDPROGRESSBAR );
                        ProgressBar( Window* pParent, const ResId& rResId );
                        ~ProgressBar();

    virtual void        Paint( const Rectangle& rRect );
    virtual void        Resize();
    virtual void        StateChanged( StateChangedType nStateChange );
    virtual void        DataChanged( const DataChangedEvent& rDCEvt );

    void                SetValue( USHORT nNewPercent );
    USHORT              GetValue() const { return mnPercent; }
};

#endif  // _PRGSBAR_HXX
<|endoftext|>


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

#include "jrt.h"
#include "jrt-bit-fields.h"

/**
 * Extract a bit-field from the integer.
 *
 * @return bit-field's value
 */
uint64_t __attr_const___
jrt_extract_bit_field (uint64_t container, /**< container to extract bit-field from */
                       uint32_t lsb, /**< least significant bit of the value
                                      *   to be extracted */
                       uint32_t width) /**< width of the bit-field to be extracted */
{
  JERRY_ASSERT (lsb < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT (width < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT ((lsb + width) <= JERRY_BITSINBYTE * sizeof (uint64_t));

  uint64_t shifted_value = container >> lsb;
  uint64_t bit_field_mask = (1ull << width) - 1;

  return (shifted_value & bit_field_mask);
} /* jrt_extract_bit_field */

/**
 * Extract a bit-field from the integer.
 *
 * @return bit-field's value
 */
uint64_t __attr_const___
jrt_set_bit_field_value (uint64_t container, /**< container to insert bit-field to */
                         uint64_t new_bit_field_value, /**< value of bit-field to insert */
                         uint32_t lsb, /**< least significant bit of the value
                                        *   to be extracted */
                         uint32_t width) /**< width of the bit-field to be extracted */
{
  JERRY_ASSERT (lsb < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT (width < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT ((lsb + width) <= JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT (new_bit_field_value <= (1ull << width));

  uint64_t bit_field_mask = (1ull << width) - 1;
  uint64_t shifted_bit_field_mask = bit_field_mask << lsb;
  uint64_t shifted_new_bit_field_value = new_bit_field_value << lsb;

  return (container & ~shifted_bit_field_mask) | shifted_new_bit_field_value;
} /* jrt_set_bit_field_value */
<commit_msg>Fixing assertion in jrt_set_bit_field_value.<commit_after>/* Copyright 2014-2015 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "jrt.h"
#include "jrt-bit-fields.h"

/**
 * Extract a bit-field from the integer.
 *
 * @return bit-field's value
 */
uint64_t __attr_const___
jrt_extract_bit_field (uint64_t container, /**< container to extract bit-field from */
                       uint32_t lsb, /**< least significant bit of the value
                                      *   to be extracted */
                       uint32_t width) /**< width of the bit-field to be extracted */
{
  JERRY_ASSERT (lsb < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT (width < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT ((lsb + width) <= JERRY_BITSINBYTE * sizeof (uint64_t));

  uint64_t shifted_value = container >> lsb;
  uint64_t bit_field_mask = (1ull << width) - 1;

  return (shifted_value & bit_field_mask);
} /* jrt_extract_bit_field */

/**
 * Extract a bit-field from the integer.
 *
 * @return bit-field's value
 */
uint64_t __attr_const___
jrt_set_bit_field_value (uint64_t container, /**< container to insert bit-field to */
                         uint64_t new_bit_field_value, /**< value of bit-field to insert */
                         uint32_t lsb, /**< least significant bit of the value
                                        *   to be extracted */
                         uint32_t width) /**< width of the bit-field to be extracted */
{
  JERRY_ASSERT (lsb < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT (width < JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT ((lsb + width) <= JERRY_BITSINBYTE * sizeof (uint64_t));
  JERRY_ASSERT (new_bit_field_value < (1ull << width));

  uint64_t bit_field_mask = (1ull << width) - 1;
  uint64_t shifted_bit_field_mask = bit_field_mask << lsb;
  uint64_t shifted_new_bit_field_value = new_bit_field_value << lsb;

  return (container & ~shifted_bit_field_mask) | shifted_new_bit_field_value;
} /* jrt_set_bit_field_value */
<|endoftext|>


<commit_before><commit_msg>Remove FastLoader optimization<commit_after><|endoftext|>