<commit_before>// This is a regression test on debug info to make sure that we can get a
// meaningful stack trace from a C++ program.
// RUN: %llvmgcc -S -O0 -g %s -o - | llvm-as | llc --disable-fp-elim -o %t.s -f
// RUN: %compile_c %t.s -o %t.o
// RUN: %link %t.o -o %t.exe
// RUN: echo {break DeepStack::deepest\nrun 17\nwhere\n} > %t.in
// RUN: gdb -q -batch -n -x %t.in %t.exe | tee %t.out | \
// RUN:   grep {#0  DeepStack::deepest.*(this=.*,.*x=33)}
// RUN: gdb -q -batch -n -x %t.in %t.exe | \
// RUN:   grep {#7  0x.* in main.*(argc=\[12\],.*argv=.*)}

// Only works on ppc, x86 and x86_64.  Should generalize?
// XFAIL: alpha|ia64|arm

// FIXME: Un-XFAIL this test when debug stuff is working again.
// XFAIL: *

#include <stdlib.h>

class DeepStack {
  int seedVal;
public:
  DeepStack(int seed) : seedVal(seed) {}

  int shallowest( int x ) { return shallower(x + 1); }
  int shallower ( int x ) { return shallow(x + 2); }
  int shallow   ( int x ) { return deep(x + 3); }
  int deep      ( int x ) { return deeper(x + 4); }
  int deeper    ( int x ) { return deepest(x + 6); }
  int deepest   ( int x ) { return x + 7; }

  int runit() { return shallowest(seedVal); }
};

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

  DeepStack DS9( (argc > 1 ? atoi(argv[1]) : 0) );
  return DS9.runit();
}
<commit_msg>This test works again for Darwin because a patch was reverted.<commit_after>// This is a regression test on debug info to make sure that we can get a
// meaningful stack trace from a C++ program.
// RUN: %llvmgcc -S -O0 -g %s -o - | llvm-as | llc --disable-fp-elim -o %t.s -f
// RUN: %compile_c %t.s -o %t.o
// RUN: %link %t.o -o %t.exe
// RUN: echo {break DeepStack::deepest\nrun 17\nwhere\n} > %t.in
// RUN: gdb -q -batch -n -x %t.in %t.exe | tee %t.out | \
// RUN:   grep {#0  DeepStack::deepest.*(this=.*,.*x=33)}
// RUN: gdb -q -batch -n -x %t.in %t.exe | \
// RUN:   grep {#7  0x.* in main.*(argc=\[12\],.*argv=.*)}

// Only works on ppc, x86 and x86_64.  Should generalize?
// FIXME: Un-XFAIL this test for Linux when debug stuff is working again.
// XFAIL: alpha|ia64|arm|linux

#include <stdlib.h>

class DeepStack {
  int seedVal;
public:
  DeepStack(int seed) : seedVal(seed) {}

  int shallowest( int x ) { return shallower(x + 1); }
  int shallower ( int x ) { return shallow(x + 2); }
  int shallow   ( int x ) { return deep(x + 3); }
  int deep      ( int x ) { return deeper(x + 4); }
  int deeper    ( int x ) { return deepest(x + 6); }
  int deepest   ( int x ) { return x + 7; }

  int runit() { return shallowest(seedVal); }
};

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

  DeepStack DS9( (argc > 1 ? atoi(argv[1]) : 0) );
  return DS9.runit();
}
<|endoftext|>


<commit_before>#include <cassert>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <unordered_map>
#include "configuration.h"
#include "bf.h"

using namespace util;
using namespace bf;

trial<nothing> run(config const& cfg)
{
  auto k = *cfg.as<size_t>("hash-functions");
  auto cells = *cfg.as<size_t>("cells");
  auto seed = *cfg.as<size_t>("seed");
  auto fpr = *cfg.as<double>("fp-rate");
  auto capacity = *cfg.as<size_t>("capacity");
  auto width = *cfg.as<size_t>("width");
  auto part = *cfg.as<bool>("partition");
  auto double_hashing = *cfg.as<bool>("double-hashing");
  auto d = *cfg.as<size_t>("evict");

  auto k2 = *cfg.as<size_t>("hash-functions-2nd");
  auto cells2 = *cfg.as<size_t>("cells-2nd");
  auto seed2 = *cfg.as<size_t>("seed-2nd");
  auto width2 = *cfg.as<size_t>("width-2nd");
  auto double_hashing2 = *cfg.as<bool>("double-hashing-2nd");

  auto const& type = *cfg.as<std::string>("type");
  std::unique_ptr<bloom_filter> bf;

  if (type == "basic")
  {
    if (fpr == 0 || capacity == 0)
    {
      if (cells == 0)
        return error{"need non-zero cells"};
      if (k == 0)
        return error{"need non-zero k"};

      auto h = make_hasher(k, seed, double_hashing);
      bf.reset(new basic_bloom_filter(std::move(h), cells, part));
    }
    else
    {
      assert(fpr != 0 && capacity != 0);
      bf.reset(new basic_bloom_filter(fpr, capacity, seed, part));
    }
  }
  else if (type == "counting")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (width == 0)
      return error{"need non-zero cell width"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h = make_hasher(k, seed, double_hashing);
    bf.reset(new counting_bloom_filter(std::move(h), cells, width, part));
  }
  else if (type == "spectral-mi")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (width == 0)
      return error{"need non-zero cell width"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h = make_hasher(k, seed, double_hashing);
    bf.reset(new spectral_mi_bloom_filter(std::move(h), cells, width, part));
  }
  else if (type == "spectral-rm")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (width == 0)
      return error{"need non-zero cell width"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h1 = make_hasher(k, seed, double_hashing);
    auto h2 = make_hasher(k2, seed2, double_hashing2);
    bf.reset(new spectral_rm_bloom_filter(std::move(h1), cells, width,
                                          std::move(h2), cells2, width2,
                                          part));
  }
  else if (type == "bitwise")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (k == 0)
      return error{"need non-zero k"};

    bf.reset(new bitwise_bloom_filter(k, cells, seed));
  }
  else if (type == "a2")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (capacity == 0)
      return error{"need non-zero capacity"};
    if (k == 0)
      return error{"need non-zero k"};

    bf.reset(new a2_bloom_filter(k, cells, capacity, seed, seed2));
  }
  else if (type == "stable")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h = make_hasher(k, seed, double_hashing);
    bf.reset(new stable_bloom_filter(std::move(h), cells, seed, d));
  }
  else
  {
    return error{"invalid bloom filter type"};
  }

  std::string line;
  auto input_file = *cfg.as<std::string>("input");
  std::ifstream in{input_file};
  if (! in)
    return error{"cannot read " + input_file};

  in >> std::noskipws;

  while (std::getline(in, line))
  {
    if (line.empty())
      continue;

    auto p = line.data();
    while (*p)
      if (*p == ' ' || *p == '\t')
        return error{"whitespace in input not supported"};
      else
        ++p;

    bf->add(line);
  }

  size_t tn = 0, tp = 0, fp = 0, fn = 0;
  size_t ground_truth;
  std::string element;
  auto query_file = *cfg.as<std::string>("query");
  std::ifstream query{query_file};
  if (! query)
    return error{"cannot read " + query_file};

  std::cout << "TN TP FP FN G C E" << std::endl;
  while (query >> ground_truth >> element)  // uniq -c
  {
    auto count = bf->lookup(line);
    if (count == 0 && ground_truth == 0)
      ++tn;
    else if (count == ground_truth)
      ++tp;
    else if (count > ground_truth)
      ++fp;
    else
      ++fn;

    std::cout
      << tn << ' ' << tp << ' ' << fp << ' ' << fn << ' '
      << ground_truth << ' ' << count << ' ' << element << std::endl;
  }

  return nil;
}

int main(int argc, char* argv[])
{
  auto cfg = config::parse(argc, argv);
  if (! cfg)
  {
    std::cerr << cfg.failure().msg() << ", try -h or --help" << std::endl;
    return 1;
  }

  if (argc < 2 || cfg->check("help") || cfg->check("advanced"))
  {
    cfg->usage(std::cerr, cfg->check("advanced"));
    return 0;
  }

  if (! cfg->check("type"))
  {
    std::cerr << "missing bloom filter type" << std::endl;
    return 1;
  }

  if (! cfg->check("input"))
  {
    std::cerr << "missing input file" << std::endl;
    return 1;
  }

  if (! cfg->check("query"))
  {
    std::cerr << "missing query file" << std::endl;
    return 1;
  }

  auto t = run(*cfg);
  if (! t)
  {
    std::cerr << t.failure().msg() << std::endl;
    return 1;
  }

  return 0;
}
<commit_msg>Fix bug that caused false evaluation results.<commit_after>#include <cassert>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <unordered_map>
#include "configuration.h"
#include "bf.h"

using namespace util;
using namespace bf;

trial<nothing> run(config const& cfg)
{
  auto k = *cfg.as<size_t>("hash-functions");
  auto cells = *cfg.as<size_t>("cells");
  auto seed = *cfg.as<size_t>("seed");
  auto fpr = *cfg.as<double>("fp-rate");
  auto capacity = *cfg.as<size_t>("capacity");
  auto width = *cfg.as<size_t>("width");
  auto part = *cfg.as<bool>("partition");
  auto double_hashing = *cfg.as<bool>("double-hashing");
  auto d = *cfg.as<size_t>("evict");

  auto k2 = *cfg.as<size_t>("hash-functions-2nd");
  auto cells2 = *cfg.as<size_t>("cells-2nd");
  auto seed2 = *cfg.as<size_t>("seed-2nd");
  auto width2 = *cfg.as<size_t>("width-2nd");
  auto double_hashing2 = *cfg.as<bool>("double-hashing-2nd");

  auto const& type = *cfg.as<std::string>("type");
  std::unique_ptr<bloom_filter> bf;

  if (type == "basic")
  {
    if (fpr == 0 || capacity == 0)
    {
      if (cells == 0)
        return error{"need non-zero cells"};
      if (k == 0)
        return error{"need non-zero k"};

      auto h = make_hasher(k, seed, double_hashing);
      bf.reset(new basic_bloom_filter(std::move(h), cells, part));
    }
    else
    {
      assert(fpr != 0 && capacity != 0);
      bf.reset(new basic_bloom_filter(fpr, capacity, seed, part));
    }
  }
  else if (type == "counting")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (width == 0)
      return error{"need non-zero cell width"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h = make_hasher(k, seed, double_hashing);
    bf.reset(new counting_bloom_filter(std::move(h), cells, width, part));
  }
  else if (type == "spectral-mi")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (width == 0)
      return error{"need non-zero cell width"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h = make_hasher(k, seed, double_hashing);
    bf.reset(new spectral_mi_bloom_filter(std::move(h), cells, width, part));
  }
  else if (type == "spectral-rm")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (width == 0)
      return error{"need non-zero cell width"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h1 = make_hasher(k, seed, double_hashing);
    auto h2 = make_hasher(k2, seed2, double_hashing2);
    bf.reset(new spectral_rm_bloom_filter(std::move(h1), cells, width,
                                          std::move(h2), cells2, width2,
                                          part));
  }
  else if (type == "bitwise")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (k == 0)
      return error{"need non-zero k"};

    bf.reset(new bitwise_bloom_filter(k, cells, seed));
  }
  else if (type == "a2")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (capacity == 0)
      return error{"need non-zero capacity"};
    if (k == 0)
      return error{"need non-zero k"};

    bf.reset(new a2_bloom_filter(k, cells, capacity, seed, seed2));
  }
  else if (type == "stable")
  {
    if (cells == 0)
      return error{"need non-zero cells"};
    if (k == 0)
      return error{"need non-zero k"};

    auto h = make_hasher(k, seed, double_hashing);
    bf.reset(new stable_bloom_filter(std::move(h), cells, seed, d));
  }
  else
  {
    return error{"invalid bloom filter type"};
  }

  std::string line;
  auto input_file = *cfg.as<std::string>("input");
  std::ifstream in{input_file};
  if (! in)
    return error{"cannot read " + input_file};

  in >> std::noskipws;

  while (std::getline(in, line))
  {
    if (line.empty())
      continue;

    auto p = line.data();
    while (*p)
      if (*p == ' ' || *p == '\t')
        return error{"whitespace in input not supported"};
      else
        ++p;

    bf->add(line);
  }

  size_t tn = 0, tp = 0, fp = 0, fn = 0;
  size_t ground_truth;
  std::string element;
  auto query_file = *cfg.as<std::string>("query");
  std::ifstream query{query_file};
  if (! query)
    return error{"cannot read " + query_file};

  std::cout << "TN TP FP FN G C E" << std::endl;
  while (query >> ground_truth >> element)  // uniq -c
  {
    auto count = bf->lookup(element);
    if (count == 0 && ground_truth == 0)
      ++tn;
    else if (count == ground_truth)
      ++tp;
    else if (count > ground_truth)
      ++fp;
    else
      ++fn;

    std::cout
      << tn << ' ' << tp << ' ' << fp << ' ' << fn << ' '
      << ground_truth << ' ' << count << ' ' << element << std::endl;
  }

  return nil;
}

int main(int argc, char* argv[])
{
  auto cfg = config::parse(argc, argv);
  if (! cfg)
  {
    std::cerr << cfg.failure().msg() << ", try -h or --help" << std::endl;
    return 1;
  }

  if (argc < 2 || cfg->check("help") || cfg->check("advanced"))
  {
    cfg->usage(std::cerr, cfg->check("advanced"));
    return 0;
  }

  if (! cfg->check("type"))
  {
    std::cerr << "missing bloom filter type" << std::endl;
    return 1;
  }

  if (! cfg->check("input"))
  {
    std::cerr << "missing input file" << std::endl;
    return 1;
  }

  if (! cfg->check("query"))
  {
    std::cerr << "missing query file" << std::endl;
    return 1;
  }

  auto t = run(*cfg);
  if (! t)
  {
    std::cerr << t.failure().msg() << std::endl;
    return 1;
  }

  return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3460
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3460 to 3461<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3461
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3157
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3157 to 3158<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3158
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3180
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3180 to 3181<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3181
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>// Copyright Ingo Proff 2017.
// https://github.com/CrikeeIP/Stopwatch
// Distributed under the MIT Software License (X11 license).
// (See accompanying file LICENSE)

#include <iostream>
#include <string>
#include "../include/Stopwatch.hpp"

int main()
{
   //Namespace alias
   namespace sw = stopwatch;

   //Create and start a stopwatch
   sw::Stopwatch my_watch;
   my_watch.start();

   //Do something time-consuming
   for(std::size_t i = 1; i <= 500000; i++){
      if( i%10 == 0){
         std::cout << i << std::endl;
      }
      if( i % 100000 == 0){
          my_watch.lap();
      }
   }

   //Get elapsed time..
   // .. in nanoseconds
   std::uint64_t elapsed_ns = my_watch.elapsed<sw::nanoseconds>();
   // .. in microseconds
   std::uint64_t elapsed_mus = my_watch.elapsed<sw::microseconds>();
   // .. in milliseconds (default template argument, therefore not needed)
   std::uint64_t elapsed_ms = my_watch.elapsed();
   // .. in seconds
   std::uint64_t elapsed_s = my_watch.elapsed<sw::seconds>();

   //Get lap times
   auto laps = my_watch.elapsed_laps();

   //Print to screen
   std::cout << "---------------" << std::endl;
   std::cout << elapsed_ns << " ns" << std::endl;
   std::cout << elapsed_mus << " mus" << std::endl;
   std::cout << elapsed_ms << " ms" << std::endl;
   std::cout << elapsed_s << " s" << std::endl;

   std::cout << "---------------" << std::endl;
   std::cout << "Laps Total: " << laps.first << std::endl;
   auto rounds = laps.second;
   std::cout << "Lap Times: " << sw::show_times(rounds);

   return 0;
}
<commit_msg>Lap timing tests<commit_after>// Copyright Ingo Proff 2017.
// https://github.com/CrikeeIP/Stopwatch
// Distributed under the MIT Software License (X11 license).
// (See accompanying file LICENSE)

#include <iostream>
#include <string>
#include "../include/Stopwatch.hpp"

int main()
{
   //Namespace alias
   namespace sw = stopwatch;

   //Create and start a stopwatch
   sw::Stopwatch my_watch;
   my_watch.start();

   //Do something time-consuming
   for(std::size_t i = 1; i <= 500000; i++){
      if( i%10 == 0){
         std::cout << i << std::endl;
      }
      if( i % 100000 == 0){
          my_watch.lap();
      }
   }

   //Get elapsed time..
   // .. in nanoseconds
   std::uint64_t elapsed_ns = my_watch.elapsed<sw::nanoseconds>();
   // .. in microseconds
   std::uint64_t elapsed_mus = my_watch.elapsed<sw::microseconds>();
   // .. in milliseconds (default template argument, therefore not needed)
   std::uint64_t elapsed_ms = my_watch.elapsed();
   // .. in seconds
   std::uint64_t elapsed_s = my_watch.elapsed<sw::seconds>();

   //Get lap times
   auto laps = my_watch.elapsed_laps();

   //Print to screen
   std::cout << "---------------" << std::endl;
   std::cout << elapsed_ns << " ns" << std::endl;
   std::cout << elapsed_mus << " mus" << std::endl;
   std::cout << elapsed_ms << " ms" << std::endl;
   std::cout << elapsed_s << " s" << std::endl;

   std::cout << "---------------" << std::endl;
   std::cout << "Laps Total: " << laps.first << std::endl;
   auto lap_times = laps.second;
   std::cout << "Lap Times: " << sw::show_times(lap_times);

   return 0;
}
<|endoftext|>


<commit_before>//==============================================================================
// Main source file
//==============================================================================

#include <QCoreApplication>
#include <QDir>
#include <QMap>
#include <QProcess>
#include <QString>

//==============================================================================

#include <iostream>

//==============================================================================

typedef QMap<QString, QStringList> Tests;

//==============================================================================

int main(int pArgc, char *pArgv[])
{
    // Retrieve the different arguments that were passed

    QStringList args = QStringList();

    for (int i = 1; i < pArgc; ++i)
        args << pArgv[i];

    // The different tests that are  to be run

    Tests tests;

    tests["Compiler"] = QStringList() << "test";

    // Run the different tests

    QString exePath = QCoreApplication(pArgc, pArgv).applicationDirPath();
    QStringList failedTests = QStringList();
    int res = 0;

    Tests::const_iterator iter = tests.constBegin();

    while (iter != tests.constEnd()) {
        if (iter != tests.constBegin()) {
            std::cout << std::endl;
            std::cout << std::endl;
            std::cout << std::endl;
        }

        std::cout << "********* " << qPrintable(iter.key()) << " *********" << std::endl;
        std::cout << std::endl;

        foreach (const QString &test, iter.value()) {
            QString testName = QString("%1_%2").arg(iter.key(), test);

            // Go to the parent directory of the directory that contains the
            // test, so that we can load plugins without any problem

            QDir::setCurrent(exePath+"/..");

            // Execute the test itself

            int testRes = QProcess::execute(QString("%1/%2").arg(exePath, testName), args);

            if (testRes)
                failedTests << testName;

            res = res?res:testRes;

            std::cout << std::endl;
        }

        std::cout << qPrintable(QString("*").repeated(9+1+iter.key().count()+1+9)) << std::endl;

        ++iter;
    }

    // Reporting

    std::cout << std::endl;
    std::cout << std::endl;
    std::cout << std::endl;
    std::cout << "********* Reporting *********" << std::endl;
    std::cout << std::endl;

    if (failedTests.isEmpty()) {
        std::cout << "All the tests passed!" << std::endl;
    } else {
        if (failedTests.count() == 1)
            std::cout << "The following test failed:" << std::endl;
        else
            std::cout << "The following tests failed:" << std::endl;

        foreach (const QString &failedTest, failedTests)
            std::cout << " - " << qPrintable(failedTest) << std::endl;
    }

    std::cout << std::endl;
    std::cout << "*****************************" << std::endl;

    // Return the overall outcome of the tests

    return res;
}

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor refactoring to respect our coding style.<commit_after>//==============================================================================
// Main source file
//==============================================================================

#include <QCoreApplication>
#include <QDir>
#include <QMap>
#include <QProcess>
#include <QString>

//==============================================================================

#include <iostream>

//==============================================================================

typedef QMap<QString, QStringList> Tests;

//==============================================================================

int main(int pArgc, char *pArgv[])
{
    // Retrieve the different arguments that were passed

    QStringList args = QStringList();

    for (int i = 1; i < pArgc; ++i)
        args << pArgv[i];

    // The different tests that are  to be run

    Tests tests;

    tests["Compiler"] = QStringList() << "test";

    // Run the different tests

    QString exePath = QCoreApplication(pArgc, pArgv).applicationDirPath();
    QStringList failedTests = QStringList();
    int res = 0;

    Tests::const_iterator iterBegin = tests.constBegin();
    Tests::const_iterator iterEnd   = tests.constEnd();

    Tests::const_iterator iter = iterBegin;

    while (iter != iterEnd) {
        if (iter != iterBegin) {
            std::cout << std::endl;
            std::cout << std::endl;
            std::cout << std::endl;
        }

        std::cout << "********* " << qPrintable(iter.key()) << " *********" << std::endl;
        std::cout << std::endl;

        foreach (const QString &test, iter.value()) {
            QString testName = QString("%1_%2").arg(iter.key(), test);

            // Go to the parent directory of the directory that contains the
            // test, so that we can load plugins without any problem

            QDir::setCurrent(exePath+"/..");

            // Execute the test itself

            int testRes = QProcess::execute(QString("%1/%2").arg(exePath, testName), args);

            if (testRes)
                failedTests << testName;

            res = res?res:testRes;

            std::cout << std::endl;
        }

        std::cout << qPrintable(QString("*").repeated(9+1+iter.key().count()+1+9)) << std::endl;

        ++iter;
    }

    // Reporting

    std::cout << std::endl;
    std::cout << std::endl;
    std::cout << std::endl;
    std::cout << "********* Reporting *********" << std::endl;
    std::cout << std::endl;

    if (failedTests.isEmpty()) {
        std::cout << "All the tests passed!" << std::endl;
    } else {
        if (failedTests.count() == 1)
            std::cout << "The following test failed:" << std::endl;
        else
            std::cout << "The following tests failed:" << std::endl;

        foreach (const QString &failedTest, failedTests)
            std::cout << " - " << qPrintable(failedTest) << std::endl;
    }

    std::cout << std::endl;
    std::cout << "*****************************" << std::endl;

    // Return the overall outcome of the tests

    return res;
}

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "fakevimhandler.h"

#include <QApplication>
#include <QFontMetrics>
#include <QMainWindow>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextEdit>

#define EDITOR(editor, call) \
    if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \
        (ed->call); \
    } else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \
        (ed->call); \
    }

using namespace FakeVim::Internal;

typedef QLatin1String _;

/**
 * Simple editor widget.
 * @tparam TextEdit QTextEdit or QPlainTextEdit as base class
 */
template <typename TextEdit>
class Editor : public TextEdit
{
public:
    Editor(QWidget *parent = 0) : TextEdit(parent)
    {
        TextEdit::setCursorWidth(0);
    }

    void paintEvent(QPaintEvent *e)
    {
        TextEdit::paintEvent(e);

        if ( !m_cursorRect.isNull() && e->rect().intersects(m_cursorRect) ) {
            QRect rect = m_cursorRect;
            m_cursorRect = QRect();
            TextEdit::update(rect);
        }

        // Draw text cursor.
        QRect rect = TextEdit::cursorRect();
        if ( e->rect().intersects(rect) ) {
            QPainter painter(TextEdit::viewport());

            if ( TextEdit::overwriteMode() ) {
                QFontMetrics fm(TextEdit::font());
                const int position = TextEdit::textCursor().position();
                const QChar c = TextEdit::document()->characterAt(position);
                rect.setWidth(fm.width(c));
                painter.setPen(Qt::NoPen);
                painter.setBrush(TextEdit::palette().color(QPalette::Base));
                painter.setCompositionMode(QPainter::CompositionMode_Difference);
            } else {
                rect.setWidth(TextEdit::cursorWidth());
                painter.setPen(TextEdit::palette().color(QPalette::Text));
            }

            painter.drawRect(rect);
            m_cursorRect = rect;
        }
    }

private:
    QRect m_cursorRect;
};

class Proxy : public QObject
{
    Q_OBJECT

public:
    Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
      : QObject(parent), m_widget(widget), m_mainWindow(mw)
    {}

public slots:
    void changeSelection(const QList<QTextEdit::ExtraSelection> &s)
    {
        EDITOR(m_widget, setExtraSelections(s));
    }

    void changeStatusData(const QString &info)
    {
        m_statusData = info;
        updateStatusBar();
    }

    void highlightMatches(const QString &pattern)
    {
        QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
        if (!ed)
            return;

        // Clear previous highlights.
        ed->selectAll();
        QTextCursor cur = ed->textCursor();

        QTextEdit::ExtraSelection selection;
        selection.format.setBackground(Qt::yellow);

        // Highlight matches.
        QTextDocument *doc = ed->document();
        QRegExp re(pattern);
        cur = doc->find(re);

        QList<QTextEdit::ExtraSelection> selections;

        int a = cur.position();
        while ( !cur.isNull() ) {
            if ( cur.hasSelection() ) {
                selection.cursor = cur;
                selections.append(selection);
            } else {
                cur.movePosition(QTextCursor::NextCharacter);
            }
            cur = doc->find(re, cur);
            int b = cur.position();
            if (a == b) {
                cur.movePosition(QTextCursor::NextCharacter);
                cur = doc->find(re, cur);
                b = cur.position();
                if (a == b) break;
            }
            a = b;
        }

        ed->setExtraSelections(selections);
    }

    void changeStatusMessage(const QString &contents, int cursorPos)
    {
        m_statusMessage = cursorPos == -1 ? contents
            : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
        updateStatusBar();
    }

    void changeExtraInformation(const QString &info)
    {
        QMessageBox::information(m_widget, tr("Information"), info);
    }

    void updateStatusBar()
    {
        int slack = 80 - m_statusMessage.size() - m_statusData.size();
        QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
        m_mainWindow->statusBar()->showMessage(msg);
    }

    void handleExCommand(bool *handled, const ExCommand &cmd)
    {
        if (cmd.matches(_("q"), _("quit")) || cmd.matches(_("qa"), _("qall"))) {
            QApplication::quit();
        } else {
            *handled = false;
            return;
        }

        *handled = true;
    }

private:
    QWidget *m_widget;
    QMainWindow *m_mainWindow;
    QString m_statusMessage;
    QString m_statusData;
};

QWidget *createEditorWidget(bool usePlainTextEdit)
{
    QWidget *editor = 0;
    if (usePlainTextEdit) {
        Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>;
        w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        editor = w;
    } else {
        Editor<QTextEdit> *w = new Editor<QTextEdit>;
        w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        editor = w;
    }
    editor->setObjectName(_("Editor"));
    editor->setFocus();

    return editor;
}

void initHandler(FakeVimHandler &handler)
{
    // Set some Vim options.
    handler.handleCommand(_("set expandtab"));
    handler.handleCommand(_("set shiftwidth=8"));
    handler.handleCommand(_("set tabstop=16"));
    handler.handleCommand(_("set autoindent"));

    // Try to source file "fakevimrc" from current directory.
    handler.handleCommand(_("source fakevimrc"));

    handler.installEventFilter();
    handler.setupWidget();
}

void initMainWindow(QMainWindow &mainWindow, QWidget *centralWidget, const QString &title)
{
    mainWindow.setWindowTitle(QString(_("FakeVim (%1)")).arg(title));
    mainWindow.setCentralWidget(centralWidget);
    mainWindow.resize(600, 650);
    mainWindow.move(0, 0);
    mainWindow.show();

    // Set monospace font for editor and status bar.
    QFont font = QApplication::font();
    font.setFamily(_("Monospace"));
    centralWidget->setFont(font);
    mainWindow.statusBar()->setFont(font);
}

void readFile(FakeVimHandler &handler, const QString &editFileName)
{
    handler.handleCommand(QString(_("r %1")).arg(editFileName));
}

void clearUndoRedo(QWidget *editor)
{
    EDITOR(editor, setUndoRedoEnabled(false));
    EDITOR(editor, setUndoRedoEnabled(true));
}

void connectSignals(FakeVimHandler &handler, Proxy &proxy)
{
    QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)),
        &proxy, SLOT(changeStatusMessage(QString,int)));
    QObject::connect(&handler,
        SIGNAL(selectionChanged(QList<QTextEdit::ExtraSelection>)),
        &proxy, SLOT(changeSelection(QList<QTextEdit::ExtraSelection>)));
    QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)),
        &proxy, SLOT(changeExtraInformation(QString)));
    QObject::connect(&handler, SIGNAL(statusDataChanged(QString)),
        &proxy, SLOT(changeStatusData(QString)));
    QObject::connect(&handler, SIGNAL(highlightMatches(QString)),
        &proxy, SLOT(highlightMatches(QString)));
    QObject::connect(&handler, SIGNAL(handleExCommandRequested(bool*,ExCommand)),
        &proxy, SLOT(handleExCommand(bool*,ExCommand)));
}

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

    QStringList args = app.arguments();

    // If first argument is present use QPlainTextEdit instead on QTextEdit;
    bool usePlainTextEdit = args.size() > 1;
    // Second argument is path to file to edit.
    const QString editFileName = args.value(2, QString(_("/usr/share/vim/vim74/tutor/tutor")));

    // Create editor widget.
    QWidget *editor = createEditorWidget(usePlainTextEdit);

    // Create FakeVimHandler instance which will emulate Vim behavior in editor widget.
    FakeVimHandler handler(editor, 0);

    // Create main window.
    QMainWindow mainWindow;
    initMainWindow(mainWindow, editor, usePlainTextEdit ? _("QPlainTextEdit") : _("QTextEdit"));

    // Connect slots to FakeVimHandler signals.
    Proxy proxy(editor, &mainWindow);
    connectSignals(handler, proxy);

    // Initialize FakeVimHandler.
    initHandler(handler);

    // Read file content to editor.
    readFile(handler, editFileName);

    // Clear undo and redo queues.
    clearUndoRedo(editor);

    return app.exec();
}

#include "main.moc"
<commit_msg>Example works with visual block mode<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "fakevimhandler.h"

#include <QApplication>
#include <QFontMetrics>
#include <QMainWindow>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextBlock>
#include <QTextEdit>

#define EDITOR(editor, call) \
    if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \
        (ed->call); \
    } else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \
        (ed->call); \
    }

using namespace FakeVim::Internal;

typedef QLatin1String _;

/**
 * Simple editor widget.
 * @tparam TextEdit QTextEdit or QPlainTextEdit as base class
 */
template <typename TextEdit>
class Editor : public TextEdit
{
public:
    Editor(QWidget *parent = 0) : TextEdit(parent)
    {
        TextEdit::setCursorWidth(0);
    }

    void paintEvent(QPaintEvent *e)
    {
        TextEdit::paintEvent(e);

        if ( !m_cursorRect.isNull() && e->rect().intersects(m_cursorRect) ) {
            QRect rect = m_cursorRect;
            m_cursorRect = QRect();
            TextEdit::update(rect);
        }

        // Draw text cursor.
        QRect rect = TextEdit::cursorRect();
        if ( e->rect().intersects(rect) ) {
            QPainter painter(TextEdit::viewport());

            if ( TextEdit::overwriteMode() ) {
                QFontMetrics fm(TextEdit::font());
                const int position = TextEdit::textCursor().position();
                const QChar c = TextEdit::document()->characterAt(position);
                rect.setWidth(fm.width(c));
                painter.setPen(Qt::NoPen);
                painter.setBrush(TextEdit::palette().color(QPalette::Base));
                painter.setCompositionMode(QPainter::CompositionMode_Difference);
            } else {
                rect.setWidth(TextEdit::cursorWidth());
                painter.setPen(TextEdit::palette().color(QPalette::Text));
            }

            painter.drawRect(rect);
            m_cursorRect = rect;
        }
    }

private:
    QRect m_cursorRect;
};

class Proxy : public QObject
{
    Q_OBJECT

public:
    Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
      : QObject(parent), m_widget(widget), m_mainWindow(mw)
    {}

public slots:
    void changeStatusData(const QString &info)
    {
        m_statusData = info;
        updateStatusBar();
    }

    void highlightMatches(const QString &pattern)
    {
        QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
        if (!ed)
            return;

        QTextCursor cur = ed->textCursor();

        QTextEdit::ExtraSelection selection;
        selection.format.setBackground(Qt::yellow);
        selection.format.setForeground(Qt::black);

        // Highlight matches.
        QTextDocument *doc = ed->document();
        QRegExp re(pattern);
        cur = doc->find(re);

        m_searchSelection.clear();

        int a = cur.position();
        while ( !cur.isNull() ) {
            if ( cur.hasSelection() ) {
                selection.cursor = cur;
                m_searchSelection.append(selection);
            } else {
                cur.movePosition(QTextCursor::NextCharacter);
            }
            cur = doc->find(re, cur);
            int b = cur.position();
            if (a == b) {
                cur.movePosition(QTextCursor::NextCharacter);
                cur = doc->find(re, cur);
                b = cur.position();
                if (a == b) break;
            }
            a = b;
        }

        updateExtraSelections();
    }

    void changeStatusMessage(const QString &contents, int cursorPos)
    {
        m_statusMessage = cursorPos == -1 ? contents
            : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
        updateStatusBar();
    }

    void changeExtraInformation(const QString &info)
    {
        QMessageBox::information(m_widget, tr("Information"), info);
    }

    void updateStatusBar()
    {
        int slack = 80 - m_statusMessage.size() - m_statusData.size();
        QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
        m_mainWindow->statusBar()->showMessage(msg);
    }

    void handleExCommand(bool *handled, const ExCommand &cmd)
    {
        if (cmd.matches(_("q"), _("quit")) || cmd.matches(_("qa"), _("qall"))) {
            QApplication::quit();
        } else {
            *handled = false;
            return;
        }

        *handled = true;
    }

    void requestSetBlockSelection(bool on = false)
    {
        QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
        if (!ed)
            return;

        QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette()
                                                  : QApplication::palette();

        m_blockSelection.clear();
        m_clearSelection.clear();

        if (on) {
            QTextCursor cur = ed->textCursor();

            QTextEdit::ExtraSelection selection;
            selection.format.setBackground( pal.color(QPalette::Base) );
            selection.format.setForeground( pal.color(QPalette::Text) );
            selection.cursor = cur;
            m_clearSelection.append(selection);

            selection.format.setBackground( pal.color(QPalette::Highlight) );
            selection.format.setForeground( pal.color(QPalette::HighlightedText) );

            int from = cur.positionInBlock();
            int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position();
            const int min = qMin(cur.position(), cur.anchor());
            const int max = qMax(cur.position(), cur.anchor());
            for ( QTextBlock block = cur.document()->findBlock(min);
                  block.isValid() && block.position() < max; block = block.next() ) {
                cur.setPosition( block.position() + qMin(from, block.length()) );
                cur.setPosition( block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor );
                selection.cursor = cur;
                m_blockSelection.append(selection);
            }

            connect( ed, SIGNAL(selectionChanged()),
                     SLOT(requestSetBlockSelection()), Qt::UniqueConnection );

            QPalette pal2 = ed->palette();
            pal2.setColor(QPalette::Highlight, Qt::transparent);
            pal2.setColor(QPalette::HighlightedText, Qt::transparent);
            ed->setPalette(pal2);

        } else {
            ed->setPalette(pal);

            disconnect( ed, SIGNAL(selectionChanged()),
                        this, SLOT(requestSetBlockSelection()) );
        }

        updateExtraSelections();
    }

    void requestHasBlockSelection(bool *on)
    {
        *on = !m_blockSelection.isEmpty();
    }

private:
    void updateExtraSelections()
    {
        QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
        if (ed)
            ed->setExtraSelections(m_clearSelection + m_searchSelection + m_blockSelection);
    }

    QWidget *m_widget;
    QMainWindow *m_mainWindow;
    QString m_statusMessage;
    QString m_statusData;

    QList<QTextEdit::ExtraSelection> m_searchSelection;
    QList<QTextEdit::ExtraSelection> m_clearSelection;
    QList<QTextEdit::ExtraSelection> m_blockSelection;
};

QWidget *createEditorWidget(bool usePlainTextEdit)
{
    QWidget *editor = 0;
    if (usePlainTextEdit) {
        Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>;
        w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        editor = w;
    } else {
        Editor<QTextEdit> *w = new Editor<QTextEdit>;
        w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        editor = w;
    }
    editor->setObjectName(_("Editor"));
    editor->setFocus();

    return editor;
}

void initHandler(FakeVimHandler &handler)
{
    // Set some Vim options.
    handler.handleCommand(_("set expandtab"));
    handler.handleCommand(_("set shiftwidth=8"));
    handler.handleCommand(_("set tabstop=16"));
    handler.handleCommand(_("set autoindent"));

    // Try to source file "fakevimrc" from current directory.
    handler.handleCommand(_("source fakevimrc"));

    handler.installEventFilter();
    handler.setupWidget();
}

void initMainWindow(QMainWindow &mainWindow, QWidget *centralWidget, const QString &title)
{
    mainWindow.setWindowTitle(QString(_("FakeVim (%1)")).arg(title));
    mainWindow.setCentralWidget(centralWidget);
    mainWindow.resize(600, 650);
    mainWindow.move(0, 0);
    mainWindow.show();

    // Set monospace font for editor and status bar.
    QFont font = QApplication::font();
    font.setFamily(_("Monospace"));
    centralWidget->setFont(font);
    mainWindow.statusBar()->setFont(font);
}

void readFile(FakeVimHandler &handler, const QString &editFileName)
{
    handler.handleCommand(QString(_("r %1")).arg(editFileName));
}

void clearUndoRedo(QWidget *editor)
{
    EDITOR(editor, setUndoRedoEnabled(false));
    EDITOR(editor, setUndoRedoEnabled(true));
}

void connectSignals(FakeVimHandler &handler, Proxy &proxy)
{
    QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)),
        &proxy, SLOT(changeStatusMessage(QString,int)));
    QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)),
        &proxy, SLOT(changeExtraInformation(QString)));
    QObject::connect(&handler, SIGNAL(statusDataChanged(QString)),
        &proxy, SLOT(changeStatusData(QString)));
    QObject::connect(&handler, SIGNAL(highlightMatches(QString)),
        &proxy, SLOT(highlightMatches(QString)));
    QObject::connect(&handler, SIGNAL(handleExCommandRequested(bool*,ExCommand)),
        &proxy, SLOT(handleExCommand(bool*,ExCommand)));
    QObject::connect(&handler, SIGNAL(requestSetBlockSelection(bool)),
        &proxy, SLOT(requestSetBlockSelection(bool)));
    QObject::connect(&handler, SIGNAL(requestHasBlockSelection(bool*)),
        &proxy, SLOT(requestHasBlockSelection(bool*)));
}

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

    QStringList args = app.arguments();

    // If first argument is present use QPlainTextEdit instead on QTextEdit;
    bool usePlainTextEdit = args.size() > 1;
    // Second argument is path to file to edit.
    const QString editFileName = args.value(2, QString(_("/usr/share/vim/vim74/tutor/tutor")));

    // Create editor widget.
    QWidget *editor = createEditorWidget(usePlainTextEdit);

    // Create FakeVimHandler instance which will emulate Vim behavior in editor widget.
    FakeVimHandler handler(editor, 0);

    // Create main window.
    QMainWindow mainWindow;
    initMainWindow(mainWindow, editor, usePlainTextEdit ? _("QPlainTextEdit") : _("QTextEdit"));

    // Connect slots to FakeVimHandler signals.
    Proxy proxy(editor, &mainWindow);
    connectSignals(handler, proxy);

    // Initialize FakeVimHandler.
    initHandler(handler);

    // Read file content to editor.
    readFile(handler, editFileName);

    // Clear undo and redo queues.
    clearUndoRedo(editor);

    return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>/******************************************************************************
** Copyright (c) 2015, Intel Corporation                                     **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ******************************************************************************/
/* Narayanan Sundaram (Intel Corp.), Michael Anderson (Intel Corp.)
 * ******************************************************************************/

#include <iostream>
#include "catch.hpp"
#include "generator.hpp"
#include <algorithm>

template<typename T>
bool edge_compare(const GraphPad::edge_t<T> &e1,
                  const GraphPad::edge_t<T> &e2)
{
        if( (e1.src < e2.src) ||
            ((e1.src == e2.src) && (e1.dst < e2.dst)) ||
            ((e1.src == e2.src) && (e1.dst == e2.dst) && (e1.val < e2.val)) )
        {
                return true;
        }
        return false;
}

template <typename EDGE_T>
void collect_edges(const GraphPad::edgelist_t<EDGE_T>& in_edges, GraphPad::edgelist_t<EDGE_T>& out_edges) {

    REQUIRE(sizeof(EDGE_T)%sizeof(int) == 0);
    int T_by_int = sizeof(in_edges.edges[0])/sizeof(int);

    int* OERecvCount = new int[GraphPad::get_global_nrank()];
    MPI_Allgather(&in_edges.nnz, 1, MPI_INT, OERecvCount, 1, MPI_INT, MPI_COMM_WORLD);

    int* OERecvOffset = new int[GraphPad::get_global_nrank()];
    int* OERecvCountInt = new int[GraphPad::get_global_nrank()];
    OERecvOffset[0] = 0;
    for (int i = 1; i < GraphPad::get_global_nrank(); i++) {
      OERecvOffset[i] = OERecvOffset[i-1] + T_by_int*OERecvCount[i-1];
    }
    for (int i = 0; i < GraphPad::get_global_nrank(); i++) {
      OERecvCountInt[i] = T_by_int*OERecvCount[i];
    }

    int nnz = 0;
    for (int i = 0; i < GraphPad::get_global_nrank(); i++) {
      nnz += OERecvCount[i];
    }
    out_edges = GraphPad::edgelist_t<EDGE_T>(in_edges.m, in_edges.n, nnz);

    MPI_Allgatherv(in_edges.edges, in_edges.nnz*T_by_int, MPI_INT, out_edges.edges, OERecvCountInt, OERecvOffset, MPI_INT, MPI_COMM_WORLD);

    delete [] OERecvCount;
    delete [] OERecvCountInt;
    delete [] OERecvOffset;
}

template <typename TILE_T, typename EDGE_T>
void matrix_test(GraphPad::edgelist_t<EDGE_T> E)
{
    std::sort(E.edges, E.edges + E.nnz, edge_compare<EDGE_T>);

  // Create identity matrix from generator
    GraphPad::SpMat<TILE_T> A;
    GraphPad::AssignSpMat(E, &A, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);

    //collect all edges
    GraphPad::edgelist_t<EDGE_T> EAll;
    collect_edges(E, EAll);
    std::sort(EAll.edges, EAll.edges + EAll.nnz, edge_compare<EDGE_T>);

    REQUIRE(A.getNNZ() == EAll.nnz);
    REQUIRE(A.m == E.m);
    REQUIRE(A.n == E.n);
    REQUIRE(A.empty == false);

    // Get new edgelist from matrix
    GraphPad::edgelist_t<EDGE_T> OE;
    A.get_edges(&OE);

    //collect all edges
    GraphPad::edgelist_t<EDGE_T> OEAll;
    collect_edges(OE, OEAll);
    std::sort(OEAll.edges, OEAll.edges + OEAll.nnz, edge_compare<EDGE_T>);

    REQUIRE(EAll.nnz == OEAll.nnz);
    REQUIRE(EAll.m == OEAll.m);
    REQUIRE(EAll.n == OEAll.n);
    for(int i = 0 ; i < EAll.nnz ; i++)
    {
            REQUIRE(EAll.edges[i].src == OEAll.edges[i].src);
            REQUIRE(EAll.edges[i].dst == OEAll.edges[i].dst);
            REQUIRE(EAll.edges[i].val == OEAll.edges[i].val);
    }

    // Test transpose
    GraphPad::SpMat<TILE_T> AT;
    GraphPad::Transpose(A, &AT, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);
    REQUIRE(AT.getNNZ() == EAll.nnz);
    REQUIRE(AT.m == E.n);
    REQUIRE(AT.n == E.m);
    REQUIRE(AT.empty == false);

    GraphPad::SpMat<TILE_T> ATT;
    GraphPad::Transpose(AT, &ATT, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);
    REQUIRE(ATT.getNNZ() == EAll.nnz);
    REQUIRE(ATT.m == E.m);
    REQUIRE(ATT.n == E.n);
    REQUIRE(ATT.empty == false);

    GraphPad::edgelist_t<EDGE_T> OET;
    ATT.get_edges(&OET);

    //collect edges
    GraphPad::edgelist_t<EDGE_T> OETAll;
    collect_edges(OET, OETAll);
    std::sort(OETAll.edges, OETAll.edges + OETAll.nnz, edge_compare<EDGE_T>);

    REQUIRE(EAll.nnz == OETAll.nnz);
    REQUIRE(E.m == OET.m);
    REQUIRE(E.n == OET.n);
    for(int i = 0 ; i < EAll.nnz ; i++)
    {
            REQUIRE(EAll.edges[i].src == OETAll.edges[i].src);
            REQUIRE(EAll.edges[i].dst == OETAll.edges[i].dst);
            REQUIRE(EAll.edges[i].val == OETAll.edges[i].val);
    }
}

template <typename TILE_T, typename EDGE_T>
void create_matrix_test(int N)
{
  auto E = generate_identity_edgelist<EDGE_T>(N);
  matrix_test<TILE_T, EDGE_T>(E);

  auto R = generate_random_edgelist<EDGE_T>(N, 16);
  matrix_test<TILE_T, EDGE_T>(R);
}

TEST_CASE("matrix_nnz", "matrix_nnz")
{
  SECTION(" CSRTile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::CSRTile<int>, int>(5);
        create_matrix_test<GraphPad::CSRTile<int>, int>(500);
  }
  SECTION(" DCSCTile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::DCSCTile<int>, int>(5);
        create_matrix_test<GraphPad::DCSCTile<int>, int>(500);
  }
  SECTION(" COOTile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::COOTile<int>, int>(5);
        create_matrix_test<GraphPad::COOTile<int>, int>(500);
  }
  SECTION(" COOSIMD32Tile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::COOSIMD32Tile<int>, int>(5);
        create_matrix_test<GraphPad::COOSIMD32Tile<int>, int>(500);
  }
}

template <typename T>
void mul(T a, T b, T * c, void* vsp) {*c = a*b;}

template <typename T>
void add(T a, T b, T * c, void* vsp) {*c = a+b;}

template <typename TILE_T, typename EDGE_T>
void spgemm_IxI_test(GraphPad::edgelist_t<EDGE_T> E,
                     GraphPad::edgelist_t<EDGE_T> R)
{
    GraphPad::SpMat<TILE_T> A;
    GraphPad::AssignSpMat(E, &A, 1, 1, GraphPad::partition_fn_1d);

    GraphPad::SpMat<TILE_T> B;
    GraphPad::AssignSpMat(R, &B, 1, 1, GraphPad::partition_fn_1d);

    GraphPad::SpMat<TILE_T> C;
    GraphPad::SpGEMM(A, B, &C, mul, add);

    GraphPad::edgelist_t<EDGE_T> OE;
    C.get_edges(&OE);
    REQUIRE(E.nnz == OE.nnz);
    REQUIRE(E.m == OE.m);
    REQUIRE(E.n == OE.n);

    std::sort(OE.edges, OE.edges + OE.nnz, edge_compare<EDGE_T>);
    std::sort(E.edges, E.edges + E.nnz, edge_compare<EDGE_T>);

    for(int i = 0 ; i < OE.nnz ; i++)
    {
      REQUIRE(OE.edges[i].src == OE.edges[i].dst);
      REQUIRE(OE.edges[i].val == Approx(E.edges[i].val * E.edges[i].val));
    }
}

template <typename TILE_T, typename EDGE_T>
void create_spgemm_test(int N)
{
  auto E1 = generate_identity_edgelist<EDGE_T>(N);
  auto E2 = generate_identity_edgelist<EDGE_T>(N);
  spgemm_IxI_test<TILE_T, EDGE_T>(E1, E2);

}

TEST_CASE("spgemm", "spgemm")
{
  SECTION(" CSR SpGEMM", "CSR SpGEMM") {
    create_spgemm_test<GraphPad::CSRTile<double>, double>(50);
  }
}

template <typename TILE_T, typename EDGE_T>
void create_spmv_identity_test(int N) {
    auto E1 = generate_identity_edgelist<EDGE_T>(N);
    GraphPad::SpMat<TILE_T> A;
    GraphPad::AssignSpMat(E1, &A, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);

    auto E2 = generate_random_vector_edgelist<EDGE_T>(N, N/10);
    GraphPad::SpVec<GraphPad::DenseSegment<EDGE_T> > x;
    x.AllocatePartitioned(N, GraphPad::get_global_nrank(), GraphPad::vector_partition_fn);
    x.ingestEdgelist(E2);

    GraphPad::SpVec<GraphPad::DenseSegment<EDGE_T> > y;
    y.AllocatePartitioned(N, GraphPad::get_global_nrank(), GraphPad::vector_partition_fn);
    GraphPad::Clear(&y);

    GraphPad::SpMSpV(A, x, &y, mul, add, NULL);

    REQUIRE(x.getNNZ() == y.getNNZ());

    GraphPad::edgelist_t<EDGE_T> E3;
    GraphPad::edgelist_t<EDGE_T> E4;
    y.get_edges(&E3);
    collect_edges(E3, E4);
    std::sort(E4.edges, E4.edges + E4.nnz, edge_compare<EDGE_T>);
    for (int i = 0; i < E3.nnz; i++) {
      printf("%d %d %lf\n", E3.edges[i].src, E3.edges[i].dst, E3.edges[i].val);
    }

    GraphPad::edgelist_t<EDGE_T> E5;
    collect_edges(E2, E5);
    std::sort(E5.edges, E5.edges + E5.nnz, edge_compare<EDGE_T>);
    for (int i = 0; i < E5.nnz; i++) {
      printf("%d %d %lf\n", E5.edges[i].src, E5.edges[i].dst, E5.edges[i].val);
    }
    for (int i = 0; i < E2.nnz; i++) {
      printf("%d %d %lf\n", E2.edges[i].src, E2.edges[i].dst, E2.edges[i].val);
    }

    REQUIRE(E4.nnz == E5.nnz);
    for (int i = 0; i < E4.nnz; i++) {
      REQUIRE(E5.edges[i].dst == E4.edges[i].dst);
      REQUIRE(E5.edges[i].src == E4.edges[i].src);
      REQUIRE(E5.edges[i].val == E4.edges[i].val);
    }
}

TEST_CASE("spmv", "spmv")
{
  SECTION("CSR mvm") {
    create_spmv_identity_test<GraphPad::CSRTile<double>, double>(100);
  }
}
<commit_msg>spmv test v2<commit_after>/******************************************************************************
** Copyright (c) 2015, Intel Corporation                                     **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ******************************************************************************/
/* Narayanan Sundaram (Intel Corp.), Michael Anderson (Intel Corp.)
 * ******************************************************************************/

#include <iostream>
#include "catch.hpp"
#include "generator.hpp"
#include <algorithm>

template<typename T>
bool edge_compare(const GraphPad::edge_t<T> &e1,
                  const GraphPad::edge_t<T> &e2)
{
        if( (e1.src < e2.src) ||
            ((e1.src == e2.src) && (e1.dst < e2.dst)) ||
            ((e1.src == e2.src) && (e1.dst == e2.dst) && (e1.val < e2.val)) )
        {
                return true;
        }
        return false;
}

template <typename EDGE_T>
void collect_edges(const GraphPad::edgelist_t<EDGE_T>& in_edges, GraphPad::edgelist_t<EDGE_T>& out_edges) {

    REQUIRE(sizeof(EDGE_T)%sizeof(int) == 0);
    int T_by_int = sizeof(in_edges.edges[0])/sizeof(int);

    int* OERecvCount = new int[GraphPad::get_global_nrank()];
    MPI_Allgather(&in_edges.nnz, 1, MPI_INT, OERecvCount, 1, MPI_INT, MPI_COMM_WORLD);

    int* OERecvOffset = new int[GraphPad::get_global_nrank()];
    int* OERecvCountInt = new int[GraphPad::get_global_nrank()];
    OERecvOffset[0] = 0;
    for (int i = 1; i < GraphPad::get_global_nrank(); i++) {
      OERecvOffset[i] = OERecvOffset[i-1] + T_by_int*OERecvCount[i-1];
    }
    for (int i = 0; i < GraphPad::get_global_nrank(); i++) {
      OERecvCountInt[i] = T_by_int*OERecvCount[i];
    }

    int nnz = 0;
    for (int i = 0; i < GraphPad::get_global_nrank(); i++) {
      nnz += OERecvCount[i];
    }
    out_edges = GraphPad::edgelist_t<EDGE_T>(in_edges.m, in_edges.n, nnz);

    MPI_Allgatherv(in_edges.edges, in_edges.nnz*T_by_int, MPI_INT, out_edges.edges, OERecvCountInt, OERecvOffset, MPI_INT, MPI_COMM_WORLD);

    delete [] OERecvCount;
    delete [] OERecvCountInt;
    delete [] OERecvOffset;
}

template <typename TILE_T, typename EDGE_T>
void matrix_test(GraphPad::edgelist_t<EDGE_T> E)
{
    std::sort(E.edges, E.edges + E.nnz, edge_compare<EDGE_T>);

  // Create identity matrix from generator
    GraphPad::SpMat<TILE_T> A;
    GraphPad::AssignSpMat(E, &A, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);

    //collect all edges
    GraphPad::edgelist_t<EDGE_T> EAll;
    collect_edges(E, EAll);
    std::sort(EAll.edges, EAll.edges + EAll.nnz, edge_compare<EDGE_T>);

    REQUIRE(A.getNNZ() == EAll.nnz);
    REQUIRE(A.m == E.m);
    REQUIRE(A.n == E.n);
    REQUIRE(A.empty == false);

    // Get new edgelist from matrix
    GraphPad::edgelist_t<EDGE_T> OE;
    A.get_edges(&OE);

    //collect all edges
    GraphPad::edgelist_t<EDGE_T> OEAll;
    collect_edges(OE, OEAll);
    std::sort(OEAll.edges, OEAll.edges + OEAll.nnz, edge_compare<EDGE_T>);

    REQUIRE(EAll.nnz == OEAll.nnz);
    REQUIRE(EAll.m == OEAll.m);
    REQUIRE(EAll.n == OEAll.n);
    for(int i = 0 ; i < EAll.nnz ; i++)
    {
            REQUIRE(EAll.edges[i].src == OEAll.edges[i].src);
            REQUIRE(EAll.edges[i].dst == OEAll.edges[i].dst);
            REQUIRE(EAll.edges[i].val == OEAll.edges[i].val);
    }

    // Test transpose
    GraphPad::SpMat<TILE_T> AT;
    GraphPad::Transpose(A, &AT, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);
    REQUIRE(AT.getNNZ() == EAll.nnz);
    REQUIRE(AT.m == E.n);
    REQUIRE(AT.n == E.m);
    REQUIRE(AT.empty == false);

    GraphPad::SpMat<TILE_T> ATT;
    GraphPad::Transpose(AT, &ATT, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);
    REQUIRE(ATT.getNNZ() == EAll.nnz);
    REQUIRE(ATT.m == E.m);
    REQUIRE(ATT.n == E.n);
    REQUIRE(ATT.empty == false);

    GraphPad::edgelist_t<EDGE_T> OET;
    ATT.get_edges(&OET);

    //collect edges
    GraphPad::edgelist_t<EDGE_T> OETAll;
    collect_edges(OET, OETAll);
    std::sort(OETAll.edges, OETAll.edges + OETAll.nnz, edge_compare<EDGE_T>);

    REQUIRE(EAll.nnz == OETAll.nnz);
    REQUIRE(E.m == OET.m);
    REQUIRE(E.n == OET.n);
    for(int i = 0 ; i < EAll.nnz ; i++)
    {
            REQUIRE(EAll.edges[i].src == OETAll.edges[i].src);
            REQUIRE(EAll.edges[i].dst == OETAll.edges[i].dst);
            REQUIRE(EAll.edges[i].val == OETAll.edges[i].val);
    }
}

template <typename TILE_T, typename EDGE_T>
void create_matrix_test(int N)
{
  auto E = generate_identity_edgelist<EDGE_T>(N);
  matrix_test<TILE_T, EDGE_T>(E);

  auto R = generate_random_edgelist<EDGE_T>(N, 16);
  matrix_test<TILE_T, EDGE_T>(R);
}

TEST_CASE("matrix_nnz", "matrix_nnz")
{
  SECTION(" CSRTile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::CSRTile<int>, int>(5);
        create_matrix_test<GraphPad::CSRTile<int>, int>(500);
  }
  SECTION(" DCSCTile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::DCSCTile<int>, int>(5);
        create_matrix_test<GraphPad::DCSCTile<int>, int>(500);
  }
  SECTION(" COOTile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::COOTile<int>, int>(5);
        create_matrix_test<GraphPad::COOTile<int>, int>(500);
  }
  SECTION(" COOSIMD32Tile basic tests ", "CSRTile basic tests") {
        create_matrix_test<GraphPad::COOSIMD32Tile<int>, int>(5);
        create_matrix_test<GraphPad::COOSIMD32Tile<int>, int>(500);
  }
}

template <typename T>
void mul(T a, T b, T * c, void* vsp) {*c = a*b;}

template <typename T>
void add(T a, T b, T * c, void* vsp) {*c = a+b;}

template <typename TILE_T, typename EDGE_T>
void spgemm_IxI_test(GraphPad::edgelist_t<EDGE_T> E,
                     GraphPad::edgelist_t<EDGE_T> R)
{
    GraphPad::SpMat<TILE_T> A;
    GraphPad::AssignSpMat(E, &A, 1, 1, GraphPad::partition_fn_1d);

    GraphPad::SpMat<TILE_T> B;
    GraphPad::AssignSpMat(R, &B, 1, 1, GraphPad::partition_fn_1d);

    GraphPad::SpMat<TILE_T> C;
    GraphPad::SpGEMM(A, B, &C, mul, add);

    GraphPad::edgelist_t<EDGE_T> OE;
    C.get_edges(&OE);
    REQUIRE(E.nnz == OE.nnz);
    REQUIRE(E.m == OE.m);
    REQUIRE(E.n == OE.n);

    std::sort(OE.edges, OE.edges + OE.nnz, edge_compare<EDGE_T>);
    std::sort(E.edges, E.edges + E.nnz, edge_compare<EDGE_T>);

    for(int i = 0 ; i < OE.nnz ; i++)
    {
      REQUIRE(OE.edges[i].src == OE.edges[i].dst);
      REQUIRE(OE.edges[i].val == Approx(E.edges[i].val * E.edges[i].val));
    }
}

template <typename TILE_T, typename EDGE_T>
void create_spgemm_test(int N)
{
  auto E1 = generate_identity_edgelist<EDGE_T>(N);
  auto E2 = generate_identity_edgelist<EDGE_T>(N);
  spgemm_IxI_test<TILE_T, EDGE_T>(E1, E2);

}

TEST_CASE("spgemm", "spgemm")
{
  SECTION(" CSR SpGEMM", "CSR SpGEMM") {
    create_spgemm_test<GraphPad::CSRTile<double>, double>(50);
  }
}

template <typename TILE_T, typename EDGE_T>
void create_spmv_identity_test(int N) {
    auto E1 = generate_identity_edgelist<EDGE_T>(N);
    GraphPad::SpMat<TILE_T> A;
    GraphPad::AssignSpMat(E1, &A, GraphPad::get_global_nrank(), GraphPad::get_global_nrank(), GraphPad::partition_fn_1d);

    auto E2 = generate_random_vector_edgelist<EDGE_T>(N, N/10);
    GraphPad::SpVec<GraphPad::DenseSegment<EDGE_T> > x;
    x.AllocatePartitioned(N, GraphPad::get_global_nrank(), GraphPad::vector_partition_fn);
    x.ingestEdgelist(E2);

    GraphPad::SpVec<GraphPad::DenseSegment<EDGE_T> > y;
    y.AllocatePartitioned(N, GraphPad::get_global_nrank(), GraphPad::vector_partition_fn);
    GraphPad::Clear(&y);

    GraphPad::SpMSpV(A, x, &y, mul, add, NULL);

    REQUIRE(x.getNNZ() == y.getNNZ());

    GraphPad::edgelist_t<EDGE_T> E3;
    GraphPad::edgelist_t<EDGE_T> E4;
    y.get_edges(&E3);
    collect_edges(E3, E4);
    std::sort(E4.edges, E4.edges + E4.nnz, edge_compare<EDGE_T>);

    GraphPad::edgelist_t<EDGE_T> E5;
    collect_edges(E2, E5);
    std::sort(E5.edges, E5.edges + E5.nnz, edge_compare<EDGE_T>);

    REQUIRE(E4.nnz == E5.nnz);
    for (int i = 0; i < E4.nnz; i++) {
      REQUIRE(E5.edges[i].dst == E4.edges[i].dst);
      REQUIRE(E5.edges[i].src == E4.edges[i].src);
      REQUIRE(E5.edges[i].val == E4.edges[i].val);
    }
}

TEST_CASE("spmv", "spmv")
{
  SECTION("CSR mvm") {
    create_spmv_identity_test<GraphPad::CSRTile<double>, double>(5000);
    create_spmv_identity_test<GraphPad::CSRTile<double>, double>(10);
  }
}
<|endoftext|>


<commit_before>
#include "../src/richkware.h"
#include <assert.h>
#include <iostream>

// Global variables
std::vector<std::string> strings = {"qwerty", "343wbt3wv3", "23v45.c-55,.v32c", "43344545tbv45v2c5223v4234", "34",
                                    "- - ", ".-,", "&",
                                    "123om12jo3m12oj3c123cxo1kimxo12i3c12kcm4xi1op23m4cp1m4p12i4n1p2i4xm4po12mxm4p1o2mxpm4p21om4xpm4xp14m1po2xm41po4mxp1om4p1o2xm41po4m1p4mp12m4p1m4p1mx4x1po2m4cxp1o2m4xp12om4xp121v"};
const char *appName = "Richk";
const char *defaultEncryptionKey = "richktest"; // pre-shared key with RMS, to enable encryption before receiving a server-side generated key
const char *serverAddress = "127.0.0.1"; // Richkware-Manager-Server IP address
const char *port = "8080"; // Richkware-Manager-Server TCP port
const char *associatedUser = "richk@richk.me"; // account in RMS which is linked to
int timeoutUploadInfo = 5000;
const char *serverPort = "6000"; // Richkware Server port for CommandResponse protocol

void TEST_Crypto();

void TEST_ReverseCommand();

void TEST_Network();

void test(std::string s1, std::string s2);

void test(bool b);

int main() {
    //ShowWindow(GetConsoleWindow(), 1);
    std::cout << "Init test phase..." << std::endl << std::endl;

    try {
        TEST_Crypto();
        TEST_Network();
        TEST_ReverseCommand();
    }
    catch (std::string e) {
        std::cout << "TEST Exception: " << e << std::endl;
    }

    std::cout << std::endl << "Tests done successfully." << std::endl;
    system("pause");
    return 0;

}

void test(std::string s1, std::string s2) {
    if (s1 == s2) {
        return;
    } else {
        throw s1 + " != " + s2;
    }
}

void test(bool b) {
    if (b) {
        return;
    } else {
        throw "boolean false";
    }
}

void test(int expected, int actual) {
    if (expected == actual) {
        return;
    } else {
        std::stringstream ss1;
        std::stringstream ss2;
        ss1 << actual;
        std::string stringActual = ss1.str();
        ss2 << expected;
        std::string stringExpected = ss2.str();
        throw "actual value different from expected: " + stringActual + " != " + stringExpected;
    }
}

void testContains(std::string expected, std::string actual) {
    if (actual.find(expected) != std::string::npos) {
        return;
    } else {
        throw "expected string " + expected + " not found in tested string";
    }
}

void testTrue(bool actual) {
    if (actual) {
        return;
    } else {
        throw "actual result is false";
    }
}

void testFalse(bool actual) {
    if (!actual) {
        return;
    } else {
        throw "actual result is false";
    }
}

void TEST_ReverseCommand() {
    const char *appName = "Richk";
    const char *defaultEncryptionKey = "richktest"; // pre-shared key with RMS, to enable encryption before receiving a server-side generated key
    const char *serverAddress = "172.24.9.142"; // Richkware-Manager-Server IP address
    const char *port = "8080"; // Richkware-Manager-Server TCP port
    const char *associatedUser = "richk@i.it"; // account in RMS which is linked to

    std::cout << "Initializing richkware..." << std::endl;

    Richkware richkware(appName, defaultEncryptionKey, serverAddress, port, associatedUser);

    //the agent connects to server and retrieves a 3-command-long string
    std::cout << "TEST 1: getCommands()" << std::endl;
    test(50, richkware.getCommands().size());

    std::cout << "TEST 2: executeCommands()" << std::endl;
    testContains("KO", richkware.executeCommand("echo OK"));

    Network network(serverAddress, port, associatedUser, defaultEncryptionKey);

    std::cout << "TEST 3: fetchCommands()" << std::endl;
    test("YzNSaGNuUT0jI2MzUmhjblE9IyNjM1JoY25RQ==", network.fetchCommand());

    std::cout << "TEST 4: uploadCommand()" << std::endl;
    testFalse(network.uploadCommand("mockedResponse"));
}

void TEST_Crypto() {

    for (const std::string &plaintext : strings) {
        for (const std::string &key : strings) {
            std::string res = RC4EncryptDecrypt(plaintext, key);
            std::string dec = RC4EncryptDecrypt(res, key);
            //assert(plaintext == dec);
            test(plaintext, dec);
            //std::cout << plaintext << " " << dec << std::endl;

            res = Crypto::Encrypt(plaintext, key);
            dec = Crypto::Decrypt(res, key);
            //assert(plaintext == dec);
            test(plaintext, dec);
            //std::cout << plaintext << " " << dec << std::endl;

            res = Base64_encode((const unsigned char *) plaintext.c_str(), plaintext.length());
            dec = Base64_decode(res);
            assert(plaintext == dec);
        }
    }
}

void TEST_Network() {
    Richkware richkware(appName, defaultEncryptionKey, serverAddress, port, associatedUser);

    richkware.network.server.Start(serverPort, true);

    //while (true) {
    for (int i = 0; i < 2; i++) {
        if (!richkware.network.UploadInfoToRMS()) {
            throw "Network, UploadInfoToRMS";
        }
        // upload information on RMS, every 5000 seconds
        Sleep(timeoutUploadInfo);
    }

}<commit_msg>commented test class<commit_after>//
//#include "../src/richkware.h"
//#include <assert.h>
//#include <iostream>
//
//// Global variables
//std::vector<std::string> strings = {"qwerty", "343wbt3wv3", "23v45.c-55,.v32c", "43344545tbv45v2c5223v4234", "34",
//                                    "- - ", ".-,", "&",
//                                    "123om12jo3m12oj3c123cxo1kimxo12i3c12kcm4xi1op23m4cp1m4p12i4n1p2i4xm4po12mxm4p1o2mxpm4p21om4xpm4xp14m1po2xm41po4mxp1om4p1o2xm41po4m1p4mp12m4p1m4p1mx4x1po2m4cxp1o2m4xp12om4xp121v"};
//const char *appName = "Richk";
//const char *defaultEncryptionKey = "richktest"; // pre-shared key with RMS, to enable encryption before receiving a server-side generated key
//const char *serverAddress = "127.0.0.1"; // Richkware-Manager-Server IP address
//const char *port = "8080"; // Richkware-Manager-Server TCP port
//const char *associatedUser = "richk@richk.me"; // account in RMS which is linked to
//int timeoutUploadInfo = 5000;
//const char *serverPort = "6000"; // Richkware Server port for CommandResponse protocol
//
//
//void TEST_Crypto();
//
//void TEST_ReverseCommand();
//
//void TEST_Network();
//
//void test(std::string s1, std::string s2);
//
//void test(bool b);
//
//
//int main() {
//    //ShowWindow(GetConsoleWindow(), 1);
//    std::cout << "Init test phase..." << std::endl << std::endl;
//
//    try {
//        TEST_Crypto();
//        TEST_Network();
//        TEST_ReverseCommand();
//    }
//    catch (std::string e) {
//        std::cout << "TEST Exception: " << e << std::endl;
//    }
//
//
//    std::cout << std::endl << "Tests done successfully." << std::endl;
//    system("pause");
//    return 0;
//
//}
//
//void test(std::string s1, std::string s2) {
//    if (s1 == s2) {
//        return;
//    } else {
//        throw s1 + " != " + s2;
//    }
//}
//
//void test(bool b) {
//    if (b) {
//        return;
//    } else {
//        throw "boolean false";
//    }
//}
//
//void test(int expected, int actual) {
//    if (expected == actual) {
//        return;
//    } else {
//        std::stringstream ss1;
//        std::stringstream ss2;
//        ss1 << actual;
//        std::string stringActual = ss1.str();
//        ss2 << expected;
//        std::string stringExpected = ss2.str();
//        throw "actual value different from expected: " + stringActual + " != " + stringExpected;
//    }
//}
//
//void testContains(std::string expected, std::string actual) {
//    if (actual.find(expected) != std::string::npos) {
//        return;
//    } else {
//        throw "expected string " + expected + " not found in tested string";
//    }
//}
//
//void testTrue(bool actual) {
//    if (actual) {
//        return;
//    } else {
//        throw "actual result is false";
//    }
//}
//
//void testFalse(bool actual) {
//    if (!actual) {
//        return;
//    } else {
//        throw "actual result is false";
//    }
//}
//
//void TEST_ReverseCommand() {
//    const char *appName = "Richk";
//    const char *defaultEncryptionKey = "richktest"; // pre-shared key with RMS, to enable encryption before receiving a server-side generated key
//    const char *serverAddress = "172.24.9.142"; // Richkware-Manager-Server IP address
//    const char *port = "8080"; // Richkware-Manager-Server TCP port
//    const char *associatedUser = "richk@i.it"; // account in RMS which is linked to
//
//    std::cout << "Initializing richkware..." << std::endl;
//
//    Richkware richkware(appName, defaultEncryptionKey, serverAddress, port, associatedUser);
//
//    //the agent connects to server and retrieves a 3-command-long string
//    std::cout << "TEST 1: getCommands()" << std::endl;
//    test(50, richkware.getCommands().size());
//
//    std::cout << "TEST 2: executeCommands()" << std::endl;
//    testContains("KO", richkware.executeCommand("echo OK"));
//
//    Network network(serverAddress, port, associatedUser, defaultEncryptionKey);
//
//    std::cout << "TEST 3: fetchCommands()" << std::endl;
//    test("YzNSaGNuUT0jI2MzUmhjblE9IyNjM1JoY25RQ==", network.fetchCommand());
//
//    std::cout << "TEST 4: uploadCommand()" << std::endl;
//    testFalse(network.uploadCommand("mockedResponse"));
//}
//
//void TEST_Crypto() {
//
//    for (const std::string &plaintext : strings) {
//        for (const std::string &key : strings) {
//            std::string res = RC4EncryptDecrypt(plaintext, key);
//            std::string dec = RC4EncryptDecrypt(res, key);
//            //assert(plaintext == dec);
//            test(plaintext, dec);
//            //std::cout << plaintext << " " << dec << std::endl;
//
//            res = Crypto::Encrypt(plaintext, key);
//            dec = Crypto::Decrypt(res, key);
//            //assert(plaintext == dec);
//            test(plaintext, dec);
//            //std::cout << plaintext << " " << dec << std::endl;
//
//            res = Base64_encode((const unsigned char *) plaintext.c_str(), plaintext.length());
//            dec = Base64_decode(res);
//            assert(plaintext == dec);
//        }
//    }
//}
//
//
//void TEST_Network() {
//    Richkware richkware(appName, defaultEncryptionKey, serverAddress, port, associatedUser);
//
//    richkware.network.server.Start(serverPort, true);
//
//    //while (true) {
//    for (int i = 0; i < 2; i++) {
//        if (!richkware.network.UploadInfoToRMS()) {
//            throw "Network, UploadInfoToRMS";
//        }
//        // upload information on RMS, every 5000 seconds
//        Sleep(timeoutUploadInfo);
//    }
//
//}<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TEST_HPP
#define TEST_HPP

void report_failure(char const* str, char const* file, int line);

#include <boost/config.hpp>
#include <exception>
#include <sstream>

#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
    struct BOOST_PP_CAT(type, _counter_guard) \
    { \
        ~BOOST_PP_CAT(type, _counter_guard()) \
        { \
            TEST_CHECK(counted_type<type>::count == 0); \
        } \
    } BOOST_PP_CAT(type, _guard)
#endif

#define TEST_REPORT_AUX(x, line, file) \
	report_failure(x, line, file)

#ifdef BOOST_NO_EXCEPTIONS
#define TEST_CHECK(x) \
	if (!(x)) \
		TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__);
#define TEST_EQUAL(x, y) \
	if (x != y) { \
		std::stringstream s__; \
		s__ << "TEST_EQUAL_ERROR: " << #x << ": " << x << " expected: " << y << std::endl; \
		TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
	}
#else
#define TEST_CHECK(x) \
	try \
	{ \
		if (!(x)) \
			TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#define TEST_EQUAL(x, y) \
	try { \
		if (x != y) { \
			std::stringstream s__; \
			s__ << "TEST_EQUAL_ERROR: " << #x << ": " << x << " expected: " << y << std::endl; \
			TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
		} \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}
#endif

#define TEST_ERROR(x) \
	TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)

#define TEST_NOTHROW(x) \
	try \
	{ \
		x; \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#endif // TEST_HPP

<commit_msg>test update<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TEST_HPP
#define TEST_HPP

void report_failure(char const* str, char const* file, int line);

#include <boost/config.hpp>
#include <exception>
#include <sstream>

#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
    struct BOOST_PP_CAT(type, _counter_guard) \
    { \
        ~BOOST_PP_CAT(type, _counter_guard()) \
        { \
            TEST_CHECK(counted_type<type>::count == 0); \
        } \
    } BOOST_PP_CAT(type, _guard)
#endif

#define TEST_REPORT_AUX(x, line, file) \
	report_failure(x, line, file)

#ifdef BOOST_NO_EXCEPTIONS
#define TEST_CHECK(x) \
	if (!(x)) \
		TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__);
#define TEST_EQUAL(x, y) \
	if (x != y) { \
		std::stringstream s__; \
		s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \
		TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
	}
#else
#define TEST_CHECK(x) \
	try \
	{ \
		if (!(x)) \
			TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#define TEST_EQUAL(x, y) \
	try { \
		if (x != y) { \
			std::stringstream s__; \
			s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \
			TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
		} \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}
#endif

#define TEST_ERROR(x) \
	TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)

#define TEST_NOTHROW(x) \
	try \
	{ \
		x; \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#endif // TEST_HPP

<|endoftext|>