<commit_before>// RUN: %clang_cc1 -triple %itanium_abi_triple -verify -fsyntax-only -Wsign-conversion %s

// NOTE: When a 'enumeral mismatch' warning is implemented then expect several
// of the following cases to be impacted.

// namespace for anonymous enums tests
namespace test1 {
  enum { A };
  enum { B = -1 };

  template <typename T> struct Foo {
    enum { C };
    enum { D = ~0U };
  };

  enum { E = ~0U };

  void doit_anonymous( int i ) {
    int a1 = 1 ? i : A;
    int a2 = 1 ? A : i;

    int b1 = 1 ? i : B;
    int b2 = 1 ? B : i;

    int c1 = 1 ? i : Foo<bool>::C;
    int c2 = 1 ? Foo<bool>::C : i;

    int d1a = 1 ? i : Foo<bool>::D; // expected-warning {{test1::Foo<bool>::(anonymous enum at }}
    int d1b = 1 ? i : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
    int d2a = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
    int d2b = 1 ? Foo<bool>::D : i; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
    int d3a = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
    int d3b = 1 ? B : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
    int d4a = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
    int d4b = 1 ? Foo<bool>::D : B; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}

    int e1a = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e1b = 1 ? i : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
    int e2a = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e2b = 1 ? E : i; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
    int e3a = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e3b = 1 ? E : B; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
    int e4a = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e4b = 1 ? B : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
  }
}

// namespace for named enums tests
namespace test2 {
  enum Named1 { A };
  enum Named2 { B = -1 };

  template <typename T> struct Foo {
    enum Named3 { C };
    enum Named4 { D = ~0U };
  };

  enum Named5 { E = ~0U };

  void doit_anonymous( int i ) {
    int a1 = 1 ? i : A;
    int a2 = 1 ? A : i;

    int b1 = 1 ? i : B;
    int b2 = 1 ? B : i;

    int c1 = 1 ? i : Foo<bool>::C;
    int c2 = 1 ? Foo<bool>::C : i;

    int d1 = 1 ? i : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    int d2 = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    int d3 = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    int d4 = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}

    int e1 = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    int e2 = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    int e3 = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    int e4 = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
  }
}
<commit_msg>[NFCI] Updated broken test<commit_after>// RUN: %clang_cc1 -triple %itanium_abi_triple -verify -fsyntax-only -Wsign-conversion %s

// NOTE: When a 'enumeral mismatch' warning is implemented then expect several
// of the following cases to be impacted.

// namespace for anonymous enums tests
namespace test1 {
  enum { A };
  enum { B = -1 };

  template <typename T> struct Foo {
    enum { C };
    enum { D = ~0U };
  };

  enum { E = ~0U };

  void doit_anonymous( int i ) {
    int a1 = 1 ? i : A;
    int a2 = 1 ? A : i;

    int b1 = 1 ? i : B;
    int b2 = 1 ? B : i;

    int c1 = 1 ? i : Foo<bool>::C;
    int c2 = 1 ? Foo<bool>::C : i;

    int d1a = 1 ? i : Foo<bool>::D; // expected-warning {{test1::Foo<bool>::(anonymous enum at }}
    int d1b = 1 ? i : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
    int d2a = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
    int d2b = 1 ? Foo<bool>::D : i; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
    int d3a = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
    int d3b = 1 ? B : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
    int d4a = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
    int d4b = 1 ? Foo<bool>::D : B; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}

    int e1a = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e1b = 1 ? i : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
    int e2a = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e2b = 1 ? E : i; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
    int e3a = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e3b = 1 ? E : B; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
    int e4a = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
    int e4b = 1 ? B : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
  }
}

// namespace for named enums tests
namespace test2 {
  enum Named1 { A };
  enum Named2 { B = -1 };

  template <typename T> struct Foo {
    enum Named3 { C };
    enum Named4 { D = ~0U };
  };

  enum Named5 { E = ~0U };

  void doit_anonymous( int i ) {
    int a1 = 1 ? i : A;
    int a2 = 1 ? A : i;

    int b1 = 1 ? i : B;
    int b2 = 1 ? B : i;

    int c1 = 1 ? i : Foo<bool>::C;
    int c2 = 1 ? Foo<bool>::C : i;

    int d1 = 1 ? i : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    int d2 = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    int d3 = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    // expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named2' and 'test2::Foo<bool>::Named4')}}
    int d4 = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
    // expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Foo<bool>::Named4' and 'test2::Named2')}}

    int e1 = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    int e2 = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    int e3 = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    // expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named5' and 'test2::Named2')}}
    int e4 = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
    // expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named2' and 'test2::Named5')}}
  }
}
<|endoftext|>


<commit_before>#include <utility>
#include <type_traits>

#if __cpp_deduction_guides
#else
#error "Class Template Argument Deduction is not supported by the compiler"
#endif

template<typename A, typename B>
struct MyPair
{
    MyPair(const A &, const B &)
    {
    }
};

template<int Size>
struct StaticString
{
    StaticString(const char (&str)[Size]): c_str(str)
    {
    }

    const char *c_str;
};

template<typename T>
struct Container
{
    struct Iterator
    {
        using value_type = T;
    };

    template<typename It>
    Container( It begin, It end )
    {

    }
};

// Class Template Argument Deduction guide (must be outside the class, in the same namespace).
template<typename It>
Container(It begin, It end) ->Container<typename It::value_type>;

template<typename A, typename B>
struct MyPerfectPair
{
    // perfect forwarding like
    template<typename U, typename V>
    MyPerfectPair(U &&, V &&)
    {
    }
};

/**
 * // CTAD guide, signature does not need to match.
 *
 * Use "decay by value" trick.
 *
 * Takes by value to partially simulate decay. See https://youtu.be/-H-ut6j1BYU?list=PLHTh1InhhwT6V9RVdFRoCG_Pm5udDxG1c&t=1987
 *
 * CTAD signature does not impact with ctor parameter overload resolution. It will be done as usual, but in the context of type MyPerfectPair<A,B>.
 */
template<typename A, typename B>
MyPerfectPair(A, B) -> MyPerfectPair<A, B>;

void typeTracer(int x)
{
}

int main()
{
    // CTAG automatically deduce template argument type based on constructor parameters
    MyPair p1{ 1729, 3.14 };
    StaticString s1{ "hello" };
//    typeTracer(s1);
    static_assert( std::is_same_v<decltype(s1), StaticString<6>> );

    Container<int>::Iterator it;
    Container cont{ it, it };  // using CTAD deduction guide

    int i1 = 12;
    double d2 = 3.4;
    MyPerfectPair p2{ std::move(i1), std::move(d2) };
    static_assert(std::is_same_v<decltype(p2), MyPerfectPair<int, double>>);

    return 0;
}<commit_msg>More CTAD example.<commit_after>#include <utility>
#include <type_traits>

#if __cpp_deduction_guides
#else
#error "Class Template Argument Deduction is not supported by the compiler"
#endif

template<typename A, typename B>
struct MyPair
{
    MyPair(const A &, const B &)
    {
    }
};

template<int Size>
struct StaticString
{
    StaticString(const char (&str)[Size]): c_str(str)
    {
    }

    const char *c_str;
};

template<typename T>
struct Container
{
    struct Iterator
    {
        using value_type = T;
    };

    template<typename It>
    Container( It begin, It end )
    {

    }
};

// Class Template Argument Deduction guide (must be outside the class, in the same namespace).
template<typename It>
Container(It begin, It end) ->Container<typename It::value_type>;

template<typename A, typename B>
struct MyPerfectPair
{
    // perfect forwarding like
    template<typename U, typename V>
    MyPerfectPair(U &&, V &&)
    {
    }
};

/**
 * // CTAD guide, signature does not need to match.
 *
 * Use "decay by value" trick.
 *
 * Takes by value to partially simulate decay. See https://youtu.be/-H-ut6j1BYU?list=PLHTh1InhhwT6V9RVdFRoCG_Pm5udDxG1c&t=1987
 *
 * CTAD signature does not impact with ctor parameter overload resolution. It will be done as usual, but in the context of type MyPerfectPair<A,B>.
 */
template<typename A, typename B>
MyPerfectPair(A, B) -> MyPerfectPair<A, B>;

void typeTracer(int x)
{
}

int main()
{
    // CTAG automatically deduce template argument type based on constructor parameters
    MyPair p1{ 1729, 3.14 };
    StaticString s1{ "hello" };
//    typeTracer(s1);
    static_assert( std::is_same_v<decltype(s1), StaticString<6>> );

    MyPair p1b{ 1729, "hello" };
    static_assert(std::is_same_v<decltype(p1b), MyPair<int, char[6]>>);// watch out, not const char

    Container<int>::Iterator it;
    Container cont{ it, it };  // using CTAD deduction guide

    int i1 = 12;
    double d2 = 3.4;
    MyPerfectPair p2{ std::move(i1), std::move(d2) };
    static_assert(std::is_same_v<decltype(p2), MyPerfectPair<int, double>>);

    return 0;
}<|endoftext|>


<commit_before>#pragma once

#include <cfloat>
#include <cstdint>

#include <string>

#include "gmock/gmock.h"
#include "quantities/quantities.hpp"

namespace principia {
namespace testing_utilities {

template<typename T>
class VanishesBeforeMatcher;

// The matchers below are useful when a computation gives a result whose
// expected value is zero.  Because of cancellations it is unlikely that the
// computed value is exactly zero.  The matchers take a reference value, which
// represents the order of magnitude of the intermediate results that triggered
// the cancellation, and a tolerance expressed as a number of ulps in the
// error.  More precisely the matcher checks that the |reference| is equal to
// to |actual + reference| to within the specified number of ulps.

// The 2-argument version of |VanishesBefore()| should always be preferred as it
// guarantees that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
    T const& reference,
    std::int64_t const max_ulps);

// The 3-argument version of |VanishesBefore()| is exclusively for use when a
// given assertion may have different errors, e.g., because it's in a loop.  It
// doesn't guarantee that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
    T const& reference,
    std::int64_t const min_ulps,
    std::int64_t const max_ulps);

template<typename T>
class VanishesBeforeMatcher{
 public:
  explicit VanishesBeforeMatcher(T const& reference,
                                 std::int64_t const min_ulps,
                                 std::int64_t const max_ulps);
  ~VanishesBeforeMatcher() = default;

  template<typename Dimensions>
  bool MatchAndExplain(quantities::Quantity<Dimensions> const& actual,
                       testing::MatchResultListener* listener) const;
  bool MatchAndExplain(double const actual,
                       testing::MatchResultListener* listener) const;

  void DescribeTo(std::ostream* out) const;
  void DescribeNegationTo(std::ostream* out) const;

 private:
  T const reference_;
  std::int64_t const min_ulps_;
  std::int64_t const max_ulps_;
};

}  // namespace testing_utilities
}  // namespace principia

#include "testing_utilities/vanishes_before_body.hpp"
<commit_msg>Un p'tit blanc sec.<commit_after>#pragma once

#include <cfloat>
#include <cstdint>

#include <string>

#include "gmock/gmock.h"
#include "quantities/quantities.hpp"

namespace principia {
namespace testing_utilities {

template<typename T>
class VanishesBeforeMatcher;

// The matchers below are useful when a computation gives a result whose
// expected value is zero.  Because of cancellations it is unlikely that the
// computed value is exactly zero.  The matchers take a reference value, which
// represents the order of magnitude of the intermediate results that triggered
// the cancellation, and a tolerance expressed as a number of ulps in the
// error.  More precisely the matcher checks that the |reference| is equal to
// to |actual + reference| to within the specified number of ulps.

// The 2-argument version of |VanishesBefore()| should always be preferred as it
// guarantees that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
    T const& reference,
    std::int64_t const max_ulps);

// The 3-argument version of |VanishesBefore()| is exclusively for use when a
// given assertion may have different errors, e.g., because it's in a loop.  It
// doesn't guarantee that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
    T const& reference,
    std::int64_t const min_ulps,
    std::int64_t const max_ulps);

template<typename T>
class VanishesBeforeMatcher {
 public:
  explicit VanishesBeforeMatcher(T const& reference,
                                 std::int64_t const min_ulps,
                                 std::int64_t const max_ulps);
  ~VanishesBeforeMatcher() = default;

  template<typename Dimensions>
  bool MatchAndExplain(quantities::Quantity<Dimensions> const& actual,
                       testing::MatchResultListener* listener) const;
  bool MatchAndExplain(double const actual,
                       testing::MatchResultListener* listener) const;

  void DescribeTo(std::ostream* out) const;
  void DescribeNegationTo(std::ostream* out) const;

 private:
  T const reference_;
  std::int64_t const min_ulps_;
  std::int64_t const max_ulps_;
};

}  // namespace testing_utilities
}  // namespace principia

#include "testing_utilities/vanishes_before_body.hpp"
<|endoftext|>


<commit_before>#include "../../src/common/problem_definition.h"
#include "../test_utilities.h"

void setup_parameters (dealii::ParameterHandler &prm)
{
  // set entry values for those without default input
  prm.set ("reflective boundary names", "xmin");
  prm.set ("x, y, z max values of boundary locations", "1.0, 2.0");
  prm.set ("number of cells for x, y, z directions", "1, 3");
}

void find_errors (dealii::ParameterHandler &prm)
{
  // dealii::ExcInternalError() is used to indicate expected
  // condition is not satisfied.
  AssertThrow (prm.get_integer("problem dimension")==2,
               dealii::ExcInternalError());
  AssertThrow (prm.get("transport model")=="none", dealii::ExcInternalError());
  AssertThrow (prm.get("HO linear solver name")=="cg",
               dealii::ExcInternalError());
  AssertThrow (prm.get("HO preconditioner name")=="amg",
               dealii::ExcInternalError());
  AssertThrow (prm.get_double("HO ssor factor")==1.0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("NDA linear solver name")=="none",
               dealii::ExcInternalError());
  AssertThrow (prm.get("NDA preconditioner name")=="none",
               dealii::ExcInternalError());
  AssertThrow (prm.get_double("NDA ssor factor")==1.0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("angular quadrature name")=="none",
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("angular quadrature order")==4,
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("number of groups")==1,
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("thermal group boundary")==0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("spatial discretization")=="cfem",
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("do eigenvalue calculations")==false,
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("do NDA")==false, dealii::ExcInternalError());
  AssertThrow (prm.get_bool("have reflective BC")==false,
               dealii::ExcInternalError());
  AssertThrow (prm.get("reflective boundary names")=="xmin",
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("finite element polynomial degree")==1,
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("uniform refinements")==0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("x, y, z max values of boundary locations")=="1.0, 2.0",
               dealii::ExcInternalError());
  AssertThrow (prm.get("number of cells for x, y, z directions")=="1, 3",
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("number of materials")==1,
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("do print angular quadrature info")==true,
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("is mesh generated by deal.II")==true,
               dealii::ExcInternalError());
  AssertThrow (prm.get("output file name base")=="solu",
               dealii::ExcInternalError());
  AssertThrow (prm.get("mesh file name")=="mesh.msh",
               dealii::ExcInternalError());
}

void test (dealii::ParameterHandler &prm)
{
  // purpose of this test is to see whether parameters
  // are parsed correctly
  ProblemDefinition::declare_parameters (prm);
  setup_parameters (prm);
  find_errors (prm);
  dealii::deallog << "OK" << std::endl;
}

int main ()
{
  dealii::ParameterHandler prm;

  testing::init_log ();

  test (prm);
  return 0;
}
<commit_msg>Modified ProblemDefinition test w/ GGL style #61<commit_after>#include "../../src/common/problem_definition.h"
#include "../test_utilities.h"

void SetupParameters (dealii::ParameterHandler &prm)
{
  // set entry values for those without default input
  prm.set ("reflective boundary names", "xmin");
  prm.set ("x, y, z max values of boundary locations", "1.0, 2.0");
  prm.set ("number of cells for x, y, z directions", "1, 3");
}

void FindErrors (dealii::ParameterHandler &prm)
{
  // dealii::ExcInternalError() is used to indicate expected
  // condition is not satisfied.
  AssertThrow (prm.get_integer("problem dimension")==2,
               dealii::ExcInternalError());
  AssertThrow (prm.get("transport model")=="none", dealii::ExcInternalError());
  AssertThrow (prm.get("HO linear solver name")=="cg",
               dealii::ExcInternalError());
  AssertThrow (prm.get("HO preconditioner name")=="amg",
               dealii::ExcInternalError());
  AssertThrow (prm.get_double("HO ssor factor")==1.0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("NDA linear solver name")=="none",
               dealii::ExcInternalError());
  AssertThrow (prm.get("NDA preconditioner name")=="none",
               dealii::ExcInternalError());
  AssertThrow (prm.get_double("NDA ssor factor")==1.0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("angular quadrature name")=="none",
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("angular quadrature order")==4,
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("number of groups")==1,
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("thermal group boundary")==0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("spatial discretization")=="cfem",
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("do eigenvalue calculations")==false,
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("do NDA")==false, dealii::ExcInternalError());
  AssertThrow (prm.get_bool("have reflective BC")==false,
               dealii::ExcInternalError());
  AssertThrow (prm.get("reflective boundary names")=="xmin",
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("finite element polynomial degree")==1,
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("uniform refinements")==0,
               dealii::ExcInternalError());
  AssertThrow (prm.get("x, y, z max values of boundary locations")=="1.0, 2.0",
               dealii::ExcInternalError());
  AssertThrow (prm.get("number of cells for x, y, z directions")=="1, 3",
               dealii::ExcInternalError());
  AssertThrow (prm.get_integer("number of materials")==1,
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("do print angular quadrature info")==true,
               dealii::ExcInternalError());
  AssertThrow (prm.get_bool("is mesh generated by deal.II")==true,
               dealii::ExcInternalError());
  AssertThrow (prm.get("output file name base")=="solu",
               dealii::ExcInternalError());
  AssertThrow (prm.get("mesh file name")=="mesh.msh",
               dealii::ExcInternalError());
}

void Test (dealii::ParameterHandler &prm)
{
  // purpose of this test is to see whether parameters
  // are parsed correctly
  ProblemDefinition::DeclareParameters (prm);
  SetupParameters (prm);
  FindErrors (prm);
  dealii::deallog << "OK" << std::endl;
}

int main ()
{
  dealii::ParameterHandler prm;

  testing::init_log ();

  Test (prm);
  return 0;
}
<|endoftext|>


<commit_before>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "task.h"

#include <libkcal/todo.h>
#include <kdebug.h>

using namespace Kolab;

KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
  Task task( tz );
  task.load( xml );
  KCal::Todo* todo = new KCal::Todo();
  task.saveTo( todo );
  return todo;
}

QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
  Task task( tz, todo );
  return task.saveXML();
}

Task::Task( const QString& tz, KCal::Todo* task )
  : Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),
    mStatus( KCal::Incidence::StatusNone ),
    mHasDueDate( false ), mHasCompletedDate( false )
{
  if ( task )
    setFields( task );
}

Task::~Task()
{
}

void Task::setPriority( int priority )
{
  mPriority = priority;
}

int Task::priority() const
{
  return mPriority;
}

void Task::setPercentCompleted( int percent )
{
  mPercentCompleted = percent;
}

int Task::percentCompleted() const
{
  return mPercentCompleted;
}

void Task::setStatus( KCal::Incidence::Status status )
{
  mStatus = status;
}

KCal::Incidence::Status Task::status() const
{
  return mStatus;
}

void Task::setParent( const QString& parentUid )
{
  mParent = parentUid;
}

QString Task::parent() const
{
  return mParent;
}

void Task::setDueDate( const QDateTime& date )
{
  mDueDate = date;
  mHasDueDate = true;
}

QDateTime Task::dueDate() const
{
  return mDueDate;
}

bool Task::hasDueDate() const
{
  return mHasDueDate;
}

void Task::setCompletedDate( const QDateTime& date )
{
  mCompletedDate = date;
  mHasCompletedDate = true;
}

QDateTime Task::completedDate() const
{
  return mCompletedDate;
}

bool Task::hasCompletedDate() const
{
  return mHasCompletedDate;
}

bool Task::loadAttribute( QDomElement& element )
{
  QString tagName = element.tagName();

  if ( tagName == "priority" ) {
    bool ok;
    int priority = element.text().toInt( &ok );
    if ( !ok || priority < 0 || priority > 5 )
      priority = 3;
    setPriority( priority );
  } else if ( tagName == "completed" ) {
    bool ok;
    int percent = element.text().toInt( &ok );
    if ( !ok || percent < 0 || percent > 100 )
      percent = 0;
    setPercentCompleted( percent );
  } else if ( tagName == "status" ) {
    if ( element.text() == "in-progress" )
      setStatus( KCal::Incidence::StatusInProcess );
    else if ( element.text() == "completed" )
      setStatus( KCal::Incidence::StatusCompleted );
    else if ( element.text() == "waiting-on-someone-else" )
      setStatus( KCal::Incidence::StatusNeedsAction );
    else if ( element.text() == "deferred" )
      // Guessing a status here
      setStatus( KCal::Incidence::StatusCanceled );
    else
      // Default
      setStatus( KCal::Incidence::StatusNone );
  } else if ( tagName == "due-date" )
    setDueDate( stringToDateTime( element.text() ) );
  else if ( tagName == "parent" )
    setParent( element.text() );
  else if ( tagName == "x-completed-date" )
    setCompletedDate( stringToDateTime( element.text() ) );
  else
    return Incidence::loadAttribute( element );

  // We handled this
  return true;
}

bool Task::saveAttributes( QDomElement& element ) const
{
  // Save the base class elements
  Incidence::saveAttributes( element );

  writeString( element, "priority", QString::number( priority() ) );
  writeString( element, "completed", QString::number( percentCompleted() ) );

  switch( status() ) {
  case KCal::Incidence::StatusInProcess:
    writeString( element, "status", "in-progress" );
    break;
  case KCal::Incidence::StatusCompleted:
    writeString( element, "status", "completed" );
    break;
  case KCal::Incidence::StatusNeedsAction:
    writeString( element, "status", "waiting-on-someone-else" );
    break;
  case KCal::Incidence::StatusCanceled:
    writeString( element, "status", "deferred" );
    break;
  case KCal::Incidence::StatusNone:
    writeString( element, "status", "not-started" );
    break;
  case KCal::Incidence::StatusTentative:
  case KCal::Incidence::StatusConfirmed:
  case KCal::Incidence::StatusDraft:
  case KCal::Incidence::StatusFinal:
  case KCal::Incidence::StatusX:
    // All of these are saved as StatusNone.
    writeString( element, "status", "not-started" );
    break;
  }

  if ( hasDueDate() )
    writeString( element, "due-date", dateTimeToString( dueDate() ) );

  if ( !parent().isNull() )
    writeString( element, "parent", parent() );

  if ( hasCompletedDate() )
    writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );

  return true;
}

bool Task::loadXML( const QDomDocument& document )
{
  QDomElement top = document.documentElement();

  if ( top.tagName() != "task" ) {
    qWarning( "XML error: Top tag was %s instead of the expected task",
              top.tagName().ascii() );
    return false;
  }

  for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    if ( n.isComment() )
      continue;
    if ( n.isElement() ) {
      QDomElement e = n.toElement();
      if ( !loadAttribute( e ) )
        // TODO: Unhandled tag - save for later storage
        kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
    } else
      kdDebug() << "Node is not a comment or an element???" << endl;
  }

  return true;
}

QString Task::saveXML() const
{
  QDomDocument document = domTree();
  QDomElement element = document.createElement( "task" );
  element.setAttribute( "version", "1.0" );
  saveAttributes( element );
  document.appendChild( element );
  return document.toString();
}

void Task::setFields( const KCal::Todo* task )
{
  Incidence::setFields( task );

  setPriority( task->priority() );
  setPercentCompleted( task->percentComplete() );
  setStatus( task->status() );
  if ( task->hasDueDate() )
    setDueDate( localToUTC( task->dtDue() ) );
  else
    mHasDueDate = false;
  setParent( QString::null );

  if ( task->hasCompletedDate() )
    setCompletedDate( localToUTC( task->completed() ) );
  else
    mHasCompletedDate = false;
}

void Task::saveTo( KCal::Todo* task )
{
  Incidence::saveTo( task );

  task->setPriority( priority() );
  task->setPercentComplete( percentCompleted() );
  task->setStatus( status() );
  task->setHasDueDate( hasDueDate() );
  if ( hasDueDate() )
    task->setDtDue( utcToLocal( dueDate() ) );

  if ( parent() != QString::null )
    task->setRelatedToUid( parent() );

  if ( hasCompletedDate() )
    task->setCompleted( utcToLocal( mCompletedDate ) );
}
<commit_msg>Save the parent of todos if they have one.<commit_after>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "task.h"

#include <libkcal/todo.h>
#include <kdebug.h>

using namespace Kolab;

KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
  Task task( tz );
  task.load( xml );
  KCal::Todo* todo = new KCal::Todo();
  task.saveTo( todo );
  return todo;
}

QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
  Task task( tz, todo );
  return task.saveXML();
}

Task::Task( const QString& tz, KCal::Todo* task )
  : Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),
    mStatus( KCal::Incidence::StatusNone ),
    mHasDueDate( false ), mHasCompletedDate( false )
{
  if ( task )
    setFields( task );
}

Task::~Task()
{
}

void Task::setPriority( int priority )
{
  mPriority = priority;
}

int Task::priority() const
{
  return mPriority;
}

void Task::setPercentCompleted( int percent )
{
  mPercentCompleted = percent;
}

int Task::percentCompleted() const
{
  return mPercentCompleted;
}

void Task::setStatus( KCal::Incidence::Status status )
{
  mStatus = status;
}

KCal::Incidence::Status Task::status() const
{
  return mStatus;
}

void Task::setParent( const QString& parentUid )
{
  mParent = parentUid;
}

QString Task::parent() const
{
  return mParent;
}

void Task::setDueDate( const QDateTime& date )
{
  mDueDate = date;
  mHasDueDate = true;
}

QDateTime Task::dueDate() const
{
  return mDueDate;
}

bool Task::hasDueDate() const
{
  return mHasDueDate;
}

void Task::setCompletedDate( const QDateTime& date )
{
  mCompletedDate = date;
  mHasCompletedDate = true;
}

QDateTime Task::completedDate() const
{
  return mCompletedDate;
}

bool Task::hasCompletedDate() const
{
  return mHasCompletedDate;
}

bool Task::loadAttribute( QDomElement& element )
{
  QString tagName = element.tagName();

  if ( tagName == "priority" ) {
    bool ok;
    int priority = element.text().toInt( &ok );
    if ( !ok || priority < 0 || priority > 5 )
      priority = 3;
    setPriority( priority );
  } else if ( tagName == "completed" ) {
    bool ok;
    int percent = element.text().toInt( &ok );
    if ( !ok || percent < 0 || percent > 100 )
      percent = 0;
    setPercentCompleted( percent );
  } else if ( tagName == "status" ) {
    if ( element.text() == "in-progress" )
      setStatus( KCal::Incidence::StatusInProcess );
    else if ( element.text() == "completed" )
      setStatus( KCal::Incidence::StatusCompleted );
    else if ( element.text() == "waiting-on-someone-else" )
      setStatus( KCal::Incidence::StatusNeedsAction );
    else if ( element.text() == "deferred" )
      // Guessing a status here
      setStatus( KCal::Incidence::StatusCanceled );
    else
      // Default
      setStatus( KCal::Incidence::StatusNone );
  } else if ( tagName == "due-date" )
    setDueDate( stringToDateTime( element.text() ) );
  else if ( tagName == "parent" )
    setParent( element.text() );
  else if ( tagName == "x-completed-date" )
    setCompletedDate( stringToDateTime( element.text() ) );
  else
    return Incidence::loadAttribute( element );

  // We handled this
  return true;
}

bool Task::saveAttributes( QDomElement& element ) const
{
  // Save the base class elements
  Incidence::saveAttributes( element );

  writeString( element, "priority", QString::number( priority() ) );
  writeString( element, "completed", QString::number( percentCompleted() ) );

  switch( status() ) {
  case KCal::Incidence::StatusInProcess:
    writeString( element, "status", "in-progress" );
    break;
  case KCal::Incidence::StatusCompleted:
    writeString( element, "status", "completed" );
    break;
  case KCal::Incidence::StatusNeedsAction:
    writeString( element, "status", "waiting-on-someone-else" );
    break;
  case KCal::Incidence::StatusCanceled:
    writeString( element, "status", "deferred" );
    break;
  case KCal::Incidence::StatusNone:
    writeString( element, "status", "not-started" );
    break;
  case KCal::Incidence::StatusTentative:
  case KCal::Incidence::StatusConfirmed:
  case KCal::Incidence::StatusDraft:
  case KCal::Incidence::StatusFinal:
  case KCal::Incidence::StatusX:
    // All of these are saved as StatusNone.
    writeString( element, "status", "not-started" );
    break;
  }

  if ( hasDueDate() )
    writeString( element, "due-date", dateTimeToString( dueDate() ) );

  if ( !parent().isNull() )
    writeString( element, "parent", parent() );

  if ( hasCompletedDate() )
    writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );

  return true;
}

bool Task::loadXML( const QDomDocument& document )
{
  QDomElement top = document.documentElement();

  if ( top.tagName() != "task" ) {
    qWarning( "XML error: Top tag was %s instead of the expected task",
              top.tagName().ascii() );
    return false;
  }

  for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    if ( n.isComment() )
      continue;
    if ( n.isElement() ) {
      QDomElement e = n.toElement();
      if ( !loadAttribute( e ) )
        // TODO: Unhandled tag - save for later storage
        kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
    } else
      kdDebug() << "Node is not a comment or an element???" << endl;
  }

  return true;
}

QString Task::saveXML() const
{
  QDomDocument document = domTree();
  QDomElement element = document.createElement( "task" );
  element.setAttribute( "version", "1.0" );
  saveAttributes( element );
  document.appendChild( element );
  return document.toString();
}

void Task::setFields( const KCal::Todo* task )
{
  Incidence::setFields( task );

  setPriority( task->priority() );
  setPercentCompleted( task->percentComplete() );
  setStatus( task->status() );
  if ( task->hasDueDate() )
    setDueDate( localToUTC( task->dtDue() ) );
  else
    mHasDueDate = false;
  if ( task->relatedTo() )
    setParent( task->relatedTo()->uid() );
  else
    setParent( QString::null );

  if ( task->hasCompletedDate() )
    setCompletedDate( localToUTC( task->completed() ) );
  else
    mHasCompletedDate = false;
}

void Task::saveTo( KCal::Todo* task )
{
  Incidence::saveTo( task );

  task->setPriority( priority() );
  task->setPercentComplete( percentCompleted() );
  task->setStatus( status() );
  task->setHasDueDate( hasDueDate() );
  if ( hasDueDate() )
    task->setDtDue( utcToLocal( dueDate() ) );

  if ( parent() != QString::null )
    task->setRelatedToUid( parent() );

  if ( hasCompletedDate() )
    task->setCompleted( utcToLocal( mCompletedDate ) );
}
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#include "mfem.hpp"
#include "catch.hpp"

#include <iostream>
#include <cmath>

using namespace mfem;

/**
 * Utility function to generate IntegerationPoints, based on param ip
 * that are outside the unit interval.  Results are placed in output
 * parameter arr.
 *
 * Note: this is defined in test_calcshape.cpp
 */
void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,
                                 Array<IntegrationPoint>& arr);

/**
 * Utility function to setup IsoparametricTransformations for reference
 * elements of various types.
 *
 * Note: this is defined in test_calcvshape.cpp
 */
void GetReferenceTransformation(const Element::Type ElemType,
                                IsoparametricTransformation & T);

/**
 * Linear test function whose curl is equal to 1 in 2D and (1,1,1) in 3D.
*/
void test_curl_func(const Vector &x, Vector &v)
{
   int dim = x.Size();
   v.SetSize(dim);
   v[0] = 4.0 * x[1];
   v[1] = 5.0 * x[0];
   if (dim == 3)
   {
      v[0] += 3.0 * x[2];
      v[1] += x[2];
      v[2] = 2.0 * (x[0] + x[1]);
   }
}

/**
 * Tests fe->CalcCurlShape() over a grid of IntegrationPoints
 * of resolution res. Also tests at integration points
 * that are outside the element.
 */
void TestCalcCurlShape(FiniteElement* fe, ElementTransformation * T, int res)
{
   int  dof = fe->GetDof();
   int  dim = fe->GetDim();
   int cdim = 2 * dim - 3;

   Vector dofs(dof);
   Vector v(cdim);
   DenseMatrix weights( dof, cdim );

   VectorFunctionCoefficient vCoef(dim, test_curl_func);

   fe->Project(vCoef, *T, dofs);

   // Get a uniform grid or integration points
   RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);
   const IntegrationRule& intRule = ref->RefPts;

   int npoints = intRule.GetNPoints();
   for (int i=0; i < npoints; ++i)
   {
      // Get the current integration point from intRule
      IntegrationPoint pt = intRule.IntPoint(i);

      // Get several variants of this integration point
      // some of which are inside the element and some are outside
      Array<IntegrationPoint> ipArr;
      GetRelatedIntegrationPoints( pt, dim, ipArr );

      // For each such integration point check that the weights
      // from CalcCurlShape() sum to one
      for (int j=0; j < ipArr.Size(); ++j)
      {
         IntegrationPoint& ip = ipArr[j];
         fe->CalcCurlShape(ip, weights);

         weights.MultTranspose(dofs, v);
         REQUIRE( v[0] == Approx(1.) );
         if (dim == 3)
         {
            REQUIRE( v[1] == Approx(1.) );
            REQUIRE( v[2] == Approx(1.) );
         }
      }
   }
}

TEST_CASE("CalcCurlShape for several ND FiniteElement instances",
          "[ND_TriangleElement]"
          "[ND_QuadrilateralElement]"
          "[ND_TetrahedronElement]"
          "[ND_WedgeElement]"
          "[ND_HexahedronElement]")
{
   int maxOrder = 5;
   int resolution = 10;

   SECTION("ND_TriangleElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::TRIANGLE, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_TriangleElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_TriangleElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_QuadrilateralElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::QUADRILATERAL, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_QuadrilateralElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_QuadrilateralElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_TetrahedronElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::TETRAHEDRON, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_TetrahedronElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_TetrahedronElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_WedgeElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::WEDGE, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_WedgeElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_WedgeElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_HexahedronElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::HEXAHEDRON, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_HexahedronElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_HexahedronElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }
}
<commit_msg>Partial copyright statement fix for testing<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#include "mfem.hpp"
#include "catch.hpp"

#include <iostream>
#include <cmath>

using namespace mfem;

/**
 * Utility function to generate IntegerationPoints, based on param ip
 * that are outside the unit interval.  Results are placed in output
 * parameter arr.
 *
 * Note: this is defined in test_calcshape.cpp
 */
void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,
                                 Array<IntegrationPoint>& arr);

/**
 * Utility function to setup IsoparametricTransformations for reference
 * elements of various types.
 *
 * Note: this is defined in test_calcvshape.cpp
 */
void GetReferenceTransformation(const Element::Type ElemType,
                                IsoparametricTransformation & T);

/**
 * Linear test function whose curl is equal to 1 in 2D and (1,1,1) in 3D.
*/
void test_curl_func(const Vector &x, Vector &v)
{
   int dim = x.Size();
   v.SetSize(dim);
   v[0] = 4.0 * x[1];
   v[1] = 5.0 * x[0];
   if (dim == 3)
   {
      v[0] += 3.0 * x[2];
      v[1] += x[2];
      v[2] = 2.0 * (x[0] + x[1]);
   }
}

/**
 * Tests fe->CalcCurlShape() over a grid of IntegrationPoints
 * of resolution res. Also tests at integration points
 * that are outside the element.
 */
void TestCalcCurlShape(FiniteElement* fe, ElementTransformation * T, int res)
{
   int  dof = fe->GetDof();
   int  dim = fe->GetDim();
   int cdim = 2 * dim - 3;

   Vector dofs(dof);
   Vector v(cdim);
   DenseMatrix weights( dof, cdim );

   VectorFunctionCoefficient vCoef(dim, test_curl_func);

   fe->Project(vCoef, *T, dofs);

   // Get a uniform grid or integration points
   RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);
   const IntegrationRule& intRule = ref->RefPts;

   int npoints = intRule.GetNPoints();
   for (int i=0; i < npoints; ++i)
   {
      // Get the current integration point from intRule
      IntegrationPoint pt = intRule.IntPoint(i);

      // Get several variants of this integration point
      // some of which are inside the element and some are outside
      Array<IntegrationPoint> ipArr;
      GetRelatedIntegrationPoints( pt, dim, ipArr );

      // For each such integration point check that the weights
      // from CalcCurlShape() sum to one
      for (int j=0; j < ipArr.Size(); ++j)
      {
         IntegrationPoint& ip = ipArr[j];
         fe->CalcCurlShape(ip, weights);

         weights.MultTranspose(dofs, v);
         REQUIRE( v[0] == Approx(1.) );
         if (dim == 3)
         {
            REQUIRE( v[1] == Approx(1.) );
            REQUIRE( v[2] == Approx(1.) );
         }
      }
   }
}

TEST_CASE("CalcCurlShape for several ND FiniteElement instances",
          "[ND_TriangleElement]"
          "[ND_QuadrilateralElement]"
          "[ND_TetrahedronElement]"
          "[ND_WedgeElement]"
          "[ND_HexahedronElement]")
{
   int maxOrder = 5;
   int resolution = 10;

   SECTION("ND_TriangleElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::TRIANGLE, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_TriangleElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_TriangleElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_QuadrilateralElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::QUADRILATERAL, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_QuadrilateralElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_QuadrilateralElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_TetrahedronElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::TETRAHEDRON, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_TetrahedronElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_TetrahedronElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_WedgeElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::WEDGE, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_WedgeElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_WedgeElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }

   SECTION("ND_HexahedronElement")
   {
      IsoparametricTransformation T;
      GetReferenceTransformation(Element::HEXAHEDRON, T);

      for (int order =1; order <= maxOrder; ++order)
      {
         std::cout << "Testing ND_HexahedronElement::CalcCurlShape() "
                   << "for order " << order << std::endl;
         ND_HexahedronElement fe(order);
         TestCalcCurlShape(&fe, &T, resolution);
      }
   }
}
<|endoftext|>


<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Tasogare Frontier support plugin
  *
  * ----
  *
  * Plugin entry point.
  */

#include <thcrap.h>
#include "thcrap_tasofro.h"
#include "th135.h"

tasofro_game_t game_id;

// Translate strings to IDs.
static tasofro_game_t game_id_from_string(const char *game)
{
	if (game == NULL) {
		return TH_NONE;
	}
	else if (!strcmp(game, "megamari")) {
		return TH_MEGAMARI;
	}
	else if (!strcmp(game, "nsml")) {
		return TH_NSML;
	}
	else if (!strcmp(game, "th105")) {
		return TH105;
	}
	else if (!strcmp(game, "th123")) {
		return TH123;
	}
	else if (!strcmp(game, "th135")) {
		return TH135;
	}
	else if (!strcmp(game, "th145")) {
		return TH145;
	}
	else if (!strcmp(game, "th155")) {
		return TH155;
	}
	return TH_FUTURE;
}

int __stdcall thcrap_plugin_init()
{
	int base_tasofro_removed = stack_remove_if_unneeded("base_tasofro");
	if (base_tasofro_removed == 1) {
		return 1;
	}

	const char *game = json_object_get_string(runconfig_get(), "game");
	game_id = game_id_from_string(game);

	if(base_tasofro_removed == -1) {
		if(game_id == TH145) {
			log_mboxf(NULL, MB_OK | MB_ICONINFORMATION,
				"Support for TH14.5 has been moved out of the sandbox.\n"
				"\n"
				"Please reconfigure your patch stack; otherwise, you might "
				"encounter errors or missing functionality after further "
				"updates.\n"
			);
		} else {
			return 1;
		}
	}

	if (game_id >= TH135) {
		return th135_init();
	}
	else {
		return nsml_init();
	}

	return 0;
}
<commit_msg>thcrap_tasofro: Add the Steam AppID for th155. [V]<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Tasogare Frontier support plugin
  *
  * ----
  *
  * Plugin entry point.
  */

#include <thcrap.h>
#include "thcrap_tasofro.h"
#include "th135.h"

tasofro_game_t game_id;

// Translate strings to IDs.
static tasofro_game_t game_id_from_string(const char *game)
{
	if (game == NULL) {
		return TH_NONE;
	}
	else if (!strcmp(game, "megamari")) {
		return TH_MEGAMARI;
	}
	else if (!strcmp(game, "nsml")) {
		return TH_NSML;
	}
	else if (!strcmp(game, "th105")) {
		return TH105;
	}
	else if (!strcmp(game, "th123")) {
		return TH123;
	}
	else if (!strcmp(game, "th135")) {
		return TH135;
	}
	else if (!strcmp(game, "th145")) {
		return TH145;
	}
	else if (!strcmp(game, "th155")) {
		return TH155;
	}
	return TH_FUTURE;
}

extern "C" __declspec(dllexport) const char* steam_appid(void)
{
	switch(game_id) {
	case TH155:
		return "716710";
	default: // -Wswitch...
		return nullptr;
	}
}

int __stdcall thcrap_plugin_init()
{
	int base_tasofro_removed = stack_remove_if_unneeded("base_tasofro");
	if (base_tasofro_removed == 1) {
		return 1;
	}

	const char *game = json_object_get_string(runconfig_get(), "game");
	game_id = game_id_from_string(game);

	if(base_tasofro_removed == -1) {
		if(game_id == TH145) {
			log_mboxf(NULL, MB_OK | MB_ICONINFORMATION,
				"Support for TH14.5 has been moved out of the sandbox.\n"
				"\n"
				"Please reconfigure your patch stack; otherwise, you might "
				"encounter errors or missing functionality after further "
				"updates.\n"
			);
		} else {
			return 1;
		}
	}

	if (game_id >= TH135) {
		return th135_init();
	}
	else {
		return nsml_init();
	}

	return 0;
}
<|endoftext|>


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

#include <thrift/lib/cpp/util/PausableTimer.h>

#include <stdint.h>
#include <sys/time.h>

namespace apache { namespace thrift { namespace util {

PausableTimer::PausableTimer(int timeLimit) {
  isTimeLimitFinite_ = timeLimit > 0;
  timeLimit_.tv_sec = static_cast<int>(timeLimit / 1000);
  timeLimit_.tv_usec = static_cast<int>((timeLimit % 1000) * 1000);
  reset();
}

void PausableTimer::reset() {
  if (isTimeLimitFinite_) {
    totalTimed_ = (struct timeval){ 0 };
    lastRunningTime_ = (struct timeval){ 0 };
    paused_ = true;
  }
}

void PausableTimer::start() {
  if (isTimeLimitFinite_) {
    if (paused_) {
      gettimeofday(&startTime_, nullptr);
      paused_ = false;
    }
  }
}

void PausableTimer::stop() {
  if (isTimeLimitFinite_) {
    if (!paused_) {
      struct timeval end;
      gettimeofday(&end, nullptr);
      timersub(&end, &startTime_, &lastRunningTime_);
      timeradd(&lastRunningTime_, &totalTimed_, &totalTimed_);
      paused_ = true;
    }
  }
}

bool PausableTimer::hasExceededTimeLimit() {
  if (isTimeLimitFinite_) {
    return timercmp(&totalTimed_, &timeLimit_, >);
  }

  return false;
}

bool PausableTimer::didLastRunningTimeExceedLimit(
  uint64_t limit_in_microseconds)
{
  if (limit_in_microseconds == 0) {
    return false;
  }

  return
    1000 * 1000 * lastRunningTime_.tv_sec +
    (uint64_t) lastRunningTime_.tv_usec >
    limit_in_microseconds;
}

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

#include <thrift/lib/cpp/util/PausableTimer.h>

#include <stdint.h>
#include <sys/time.h>

namespace apache { namespace thrift { namespace util {

PausableTimer::PausableTimer(int timeLimit) {
  isTimeLimitFinite_ = timeLimit > 0;
  timeLimit_.tv_sec = static_cast<int>(timeLimit / 1000);
  timeLimit_.tv_usec = static_cast<int>((timeLimit % 1000) * 1000);
  reset();
}

void PausableTimer::reset() {
  if (isTimeLimitFinite_) {
    totalTimed_ = timeval{ 0 };
    lastRunningTime_ = timeval{ 0 };
    paused_ = true;
  }
}

void PausableTimer::start() {
  if (isTimeLimitFinite_) {
    if (paused_) {
      gettimeofday(&startTime_, nullptr);
      paused_ = false;
    }
  }
}

void PausableTimer::stop() {
  if (isTimeLimitFinite_) {
    if (!paused_) {
      struct timeval end;
      gettimeofday(&end, nullptr);
      timersub(&end, &startTime_, &lastRunningTime_);
      timeradd(&lastRunningTime_, &totalTimed_, &totalTimed_);
      paused_ = true;
    }
  }
}

bool PausableTimer::hasExceededTimeLimit() {
  if (isTimeLimitFinite_) {
    return timercmp(&totalTimed_, &timeLimit_, >);
  }

  return false;
}

bool PausableTimer::didLastRunningTimeExceedLimit(
  uint64_t limit_in_microseconds)
{
  if (limit_in_microseconds == 0) {
    return false;
  }

  return
    1000 * 1000 * lastRunningTime_.tv_sec +
    (uint64_t) lastRunningTime_.tv_usec >
    limit_in_microseconds;
}

}}}
<|endoftext|>


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

#include "generatorBase/semanticTree/switchNode.h"

#include <qrutils/stringUtils.h>

using namespace generatorBase::semantics;
using namespace qReal;

SwitchNode::SwitchNode(const Id &idBinded, QObject *parent)
	: NonZoneNode(idBinded, parent)
	, mDefaultBranch(nullptr)
	, mBranchesMerged(false)
	, mGenerateIfs(false)
{
}

void SwitchNode::addBranch(const QString &value, SemanticNode * const node)
{
	ZoneNode * const zone = new ZoneNode(this);
	zone->setParentNode(this);
	bind(value, zone);
	if (node) {
		zone->appendChild(node);
	}
}

void SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node)
{
	Q_ASSERT(node);
	bind(value, node->parentZone());
}

bool SwitchNode::branchesMerged() const
{
	return mBranchesMerged;
}

void SwitchNode::setBranchesMergedFlag()
{
	mBranchesMerged = true;
}

void SwitchNode::setGenerateIfs()
{
	mGenerateIfs = true;
}

QString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const
{
	QString result;
	bool isHead = true;
	for (ZoneNode * const zone : mBranches.values().toSet()) {
		if (zone == mDefaultBranch) {
			// Branches merged with default on the diagram will be merged with it in code too
			continue;
		}

		result += generatePart(customizer, indent, indentString, zone, isHead
				? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())
				: customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));

		isHead = false;
	}

	if (result.isEmpty()) {
		// Then all branches lead to one block, we may ignore switch construction.
		return mDefaultBranch->toString(customizer, indent, indentString);
	}

	result += generatePart(customizer, indent, indentString, mDefaultBranch
			, customizer.factory()->switchDefaultGenerator(mId, customizer, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));

	return result;
}

void SwitchNode::bind(const QString &value, ZoneNode *zone)
{
	if (value.isEmpty()) {
		mDefaultBranch = zone;
	} else {
		mBranches[value] = zone;
	}
}

QString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer
		, int indent
		, const QString &indentString
		, ZoneNode * const zone
		, generatorBase::simple::AbstractSimpleGenerator *generator) const
{
	return utils::StringUtils::addIndent(generator->generate()
			.replace("@@BODY@@", zone->toString(customizer, indent + 1, indentString)), indent, indentString);
}

QLinkedList<SemanticNode *> SwitchNode::children() const
{
	QLinkedList<SemanticNode *> result;
	for (ZoneNode * const zone : mBranches.values().toSet()) {
		result << zone;
	}

	if (mDefaultBranch) {
		result << mDefaultBranch;
	}

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

#include "generatorBase/semanticTree/switchNode.h"

#include <qrutils/stringUtils.h>

using namespace generatorBase::semantics;
using namespace qReal;

SwitchNode::SwitchNode(const Id &idBinded, QObject *parent)
	: NonZoneNode(idBinded, parent)
	, mDefaultBranch(nullptr)
	, mBranchesMerged(false)
	, mGenerateIfs(false)
{
}

void SwitchNode::addBranch(const QString &value, SemanticNode * const node)
{
	ZoneNode * const zone = new ZoneNode(this);
	zone->setParentNode(this);
	bind(value, zone);
	if (node) {
		zone->appendChild(node);
	}
}

void SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node)
{
	Q_ASSERT(node);
	bind(value, node->parentZone());
}

bool SwitchNode::branchesMerged() const
{
	return mBranchesMerged;
}

void SwitchNode::setBranchesMergedFlag()
{
	mBranchesMerged = true;
}

void SwitchNode::setGenerateIfs()
{
	mGenerateIfs = true;
}

QString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const
{
	QString result;
	bool isHead = true;
	for (ZoneNode * const zone : mBranches.values().toSet()) {
		if (zone == mDefaultBranch) {
			// Branches merged with default on the diagram will be merged with it in code too
			continue;
		}

		result += generatePart(customizer, indent, indentString, zone, isHead
				? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone)
						, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())
				: customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone)
						, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));

		isHead = false;
	}

	if (result.isEmpty()) {
		// Then all branches lead to one block, we may ignore switch construction.
		return mDefaultBranch->toString(customizer, indent, indentString);
	}

	result += generatePart(customizer, indent, indentString, mDefaultBranch
			, customizer.factory()->switchDefaultGenerator(mId, customizer
			, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));

	return result;
}

void SwitchNode::bind(const QString &value, ZoneNode *zone)
{
	if (value.isEmpty()) {
		mDefaultBranch = zone;
	} else {
		mBranches[value] = zone;
	}
}

QString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer
		, int indent
		, const QString &indentString
		, ZoneNode * const zone
		, generatorBase::simple::AbstractSimpleGenerator *generator) const
{
	return utils::StringUtils::addIndent(generator->generate()
			.replace("@@BODY@@", zone->toString(customizer, indent + 1, indentString)), indent, indentString);
}

QLinkedList<SemanticNode *> SwitchNode::children() const
{
	QLinkedList<SemanticNode *> result;
	for (ZoneNode * const zone : mBranches.values().toSet()) {
		result << zone;
	}

	if (mDefaultBranch) {
		result << mDefaultBranch;
	}

	return result;
}
<|endoftext|>


<commit_before>// @(#)root/tmva $Id$
// Author: Simon Pfreundschuh

/*************************************************************************
 * Copyright (C) 2016, Simon Pfreundschuh                                *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

////////////////////////////////////////////////////////////////////
// Concrete instantiation of the generic backpropagation test for //
// multi-threaded CPU architectures.                              //
////////////////////////////////////////////////////////////////////

#include "TMatrix.h"
#include "TMVA/DNN/Architectures/Cpu.h"
#include "TestBackpropagation.h"

using namespace TMVA::DNN;

int main()
{
   using Scalar_t = Double_t;
   std::cout << "Testing Backpropagation:" << std::endl;

   double error;

   error = testBackpropagationWeightsLinear<TCpu<Scalar_t>>(1.0);
   if (error > 1e-3)
       return 1;

   error = testBackpropagationL1Regularization<TCpu<Scalar_t>>(1e-2);
   if (error > 1e-3)
       return 1;

   error = testBackpropagationL2Regularization<TCpu<Scalar_t>>(1.0);
   if (error > 1e-3)
       return 1;

   error = testBackpropagationBiasesLinear<TCpu<Scalar_t>>(1.0);
   if (error > 1e-3)
       return 1;

   return 0;
}
<commit_msg>Continue testing if one test fails<commit_after>// @(#)root/tmva $Id$
// Author: Simon Pfreundschuh

/*************************************************************************
 * Copyright (C) 2016, Simon Pfreundschuh                                *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

////////////////////////////////////////////////////////////////////
// Concrete instantiation of the generic backpropagation test for //
// multi-threaded CPU architectures.                              //
////////////////////////////////////////////////////////////////////

#include "TMatrix.h"
#include "TMVA/DNN/Architectures/Cpu.h"
#include "TestBackpropagation.h"

using namespace TMVA::DNN;

int main()
{
   using Scalar_t = Double_t;
   std::cout << "Testing Backpropagation:" << std::endl;

   double error;
   int iret = 0;

   error = testBackpropagationWeightsLinear<TCpu<Scalar_t>>(1.0);
   if (error > 1e-3)
       iret++;

   error = testBackpropagationL1Regularization<TCpu<Scalar_t>>(1e-2);
   if (error > 1e-3)
       iret++;

   error = testBackpropagationL2Regularization<TCpu<Scalar_t>>(1.0);
   if (error > 1e-3)
       iret++;

   error = testBackpropagationBiasesLinear<TCpu<Scalar_t>>(1.0);
   if (error > 1e-3)
       iret++;

   return iret;
}
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "keeper.hpp"

#include <iostream>
#include <glog/logging.h>

#include "../common/membership.hpp"
#include "../common/exception.hpp"
#include "server_util.hpp"

using namespace jubatus;
using namespace jubatus::framework;

keeper::keeper(const keeper_argv& a)
  : pfi::network::mprpc::rpc_server(a.timeout),
    a_(a),
    zk_(common::create_lock_service("cached_zk", a.z, a.timeout))
    //    zk_(common::create_lock_service("zk", a.z, a.timeout))
{
  ls = zk_;
  jubatus::common::prepare_jubatus(*zk_);
  if(!register_keeper(*zk_, a_.eth, a_.port) ){
    throw JUBATUS_EXCEPTION(membership_error("can't register to zookeeper."));
  }
}

keeper::~keeper(){
}

int keeper::run()
{
  try {
    { LOG(INFO) << "running in port=" << a_.port; }
    set_exit_on_term();
    return this->serv(a_.port, a_.threadnum);
  } catch (const jubatus::exception::jubatus_exception& e) {
    std::cout << e.diagnostic_information(true) << std::endl;
    return -1;
  }
}

void keeper::get_members_(const std::string& name, std::vector<std::pair<std::string, int> >& ret){
  using namespace std;
  ret.clear();
  vector<string> list;
  string path = common::ACTOR_BASE_PATH + "/" + name + "/nodes";

  {
    pfi::concurrent::scoped_lock lk(mutex_);
    zk_->list(path, list);
  }
  vector<string>::const_iterator it;

  // FIXME:
  // do you return all server list? it can be very large
  for(it = list.begin(); it!= list.end(); ++it){
    string ip;
    int port;
    common::revert(*it, ip, port);
    ret.push_back(make_pair(ip,port));
  }
}
<commit_msg>Fix ignoring SIGPIPE deleted by 877d3a9086c0e0cc58b07afe32514a0f76fa3a80<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "keeper.hpp"

#include <iostream>
#include <glog/logging.h>

#include "../common/membership.hpp"
#include "../common/exception.hpp"
#include "server_util.hpp"

using namespace jubatus;
using namespace jubatus::framework;

keeper::keeper(const keeper_argv& a)
  : pfi::network::mprpc::rpc_server(a.timeout),
    a_(a),
    zk_(common::create_lock_service("cached_zk", a.z, a.timeout))
    //    zk_(common::create_lock_service("zk", a.z, a.timeout))
{
  ls = zk_;
  jubatus::common::prepare_jubatus(*zk_);
  if(!register_keeper(*zk_, a_.eth, a_.port) ){
    throw JUBATUS_EXCEPTION(membership_error("can't register to zookeeper."));
  }
}

keeper::~keeper(){
}

int keeper::run()
{
  try {
    { LOG(INFO) << "running in port=" << a_.port; }
    set_exit_on_term();
    ignore_sigpipe();
    return this->serv(a_.port, a_.threadnum);
  } catch (const jubatus::exception::jubatus_exception& e) {
    std::cout << e.diagnostic_information(true) << std::endl;
    return -1;
  }
}

void keeper::get_members_(const std::string& name, std::vector<std::pair<std::string, int> >& ret){
  using namespace std;
  ret.clear();
  vector<string> list;
  string path = common::ACTOR_BASE_PATH + "/" + name + "/nodes";

  {
    pfi::concurrent::scoped_lock lk(mutex_);
    zk_->list(path, list);
  }
  vector<string>::const_iterator it;

  // FIXME:
  // do you return all server list? it can be very large
  for(it = list.begin(); it!= list.end(); ++it){
    string ip;
    int port;
    common::revert(*it, ip, port);
    ret.push_back(make_pair(ip,port));
  }
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2016, Jeff Hutchinson
// 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 project 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.
//-----------------------------------------------------------------------------

#ifndef _GRAPHICS_CONTEXT_HPP_
#define _GRAPHICS_CONTEXT_HPP_

#include "graphics/renderer.hpp"

class Window;

enum ContextAPI : int {
	OpenGL,
	// WebGL,
	D3D11
};

class Context {
public:
	void init(Window *window);
	virtual void destroy() = 0;

	virtual void swapBuffers() const = 0;

	virtual Renderer* getRenderer() const = 0;

protected:
	Renderer *mRenderer;
	Window *mWindow;

	virtual void initContext() = 0;
};

class ContextFactory {
public:
	static Context* createContext(ContextAPI api);
	static void releaseContext(Context *context);

	static void setCurrentContext(Context *current);
};

extern Context *gCurrentContext;
#define RENDERER gCurrentContext->getRenderer()

#endif // _GRAPHICS_CONTEXT_HPP_<commit_msg>virtual destructor for Context<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2016, Jeff Hutchinson
// 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 project 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.
//-----------------------------------------------------------------------------

#ifndef _GRAPHICS_CONTEXT_HPP_
#define _GRAPHICS_CONTEXT_HPP_

#include "graphics/renderer.hpp"

class Window;

enum ContextAPI : int {
	OpenGL,
	// WebGL,
	D3D11
};

class Context {
public:
	virtual ~Context() {}

	void init(Window *window);
	virtual void destroy() = 0;

	virtual void swapBuffers() const = 0;

	virtual Renderer* getRenderer() const = 0;

protected:
	Renderer *mRenderer;
	Window *mWindow;

	virtual void initContext() = 0;
};

class ContextFactory {
public:
	static Context* createContext(ContextAPI api);
	static void releaseContext(Context *context);

	static void setCurrentContext(Context *current);
};

extern Context *gCurrentContext;
#define RENDERER gCurrentContext->getRenderer()

#endif // _GRAPHICS_CONTEXT_HPP_<|endoftext|>


<commit_before>#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSettings>
#include "functions.h"
#include "language-loader.h"
#include "main-screen.h"
#include "models/image.h"
#include "models/profile.h"
#include "models/qml-auth.h"
#include "models/qml-auth-setting-field.h"
#include "models/qml-image.h"
#include "models/qml-site.h"
#include "settings.h"
#include "share/share-utils.h"
#include "syntax-highlighter-helper.h"

#if defined(Q_OS_ANDROID)
	#include <QStandardPaths>
	#include <QtAndroid>
	#include "logger.h"

	bool checkPermission(const QString &perm)
	{
		auto already = QtAndroid::checkPermission(perm);
		if (already == QtAndroid::PermissionResult::Denied) {
			auto results = QtAndroid::requestPermissionsSync(QStringList() << perm);
			if (results[perm] == QtAndroid::PermissionResult::Denied) {
				return false;
			}
		}
		return true;
	}
#endif

int main(int argc, char *argv[])
{
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QGuiApplication app(argc, argv);
	app.setApplicationName("Grabber");
	app.setApplicationVersion(VERSION);
	app.setOrganizationName("Bionus");
	app.setOrganizationDomain("bionus.fr.cr");

	qmlRegisterType<ShareUtils>("Grabber", 1, 0, "ShareUtils");
	qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper");
	qRegisterMetaType<QSharedPointer<Image>>("QSharedPointer<Image>");
	qRegisterMetaType<Settings*>("Settings*");
	qRegisterMetaType<QmlImage*>("QmlImage*");
	qRegisterMetaType<QList<QmlImage*>>("QList>QmlImage*>");
	qRegisterMetaType<QmlSite*>("QmlSite*");
	qRegisterMetaType<QList<QmlSite*>>("QList<QmlSite*>");
	qRegisterMetaType<QList<QmlAuth*>>("QList<QmlAuth*>");
	qRegisterMetaType<QList<QmlAuthSettingField*>>("QList<QmlAuthSettingField*>");

	// Copy settings files to writable directory
	const QStringList toCopy { "sites/", "themes/", "webservices/" };
	for (const QString &tgt : toCopy) {
		const QString from = savePath(tgt, true, false);
		const QString to = savePath(tgt, true, true);
		if (!QDir(to).exists() && QDir(from).exists()) {
			copyRecursively(from, to);
		}
	}

	const QUrl url(QStringLiteral("qrc:/main-screen.qml"));

	QQmlApplicationEngine engine;
	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
		if (!obj && url == objUrl) {
			QCoreApplication::exit(-1);
		}
	}, Qt::QueuedConnection);

	// Define a few globals
	engine.rootContext()->setContextProperty("VERSION", QString(VERSION));
	#ifdef NIGHTLY
		engine.rootContext()->setContextProperty("NIGHTLY", true);
		engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString(NIGHTLY_COMMIT));
	#else
		engine.rootContext()->setContextProperty("NIGHTLY", false);
		engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString());
	#endif

	Profile profile(savePath());
	MainScreen mainScreen(&profile, &engine);
	engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);
	engine.rootContext()->setContextProperty("backend", &mainScreen);

	Settings settings(profile.getSettings());
	engine.rootContext()->setContextProperty("settings", &settings);

	// Load translations
	LanguageLoader languageLoader(savePath("languages/", true, false));
	languageLoader.install(qApp);
	languageLoader.setLanguage(profile.getSettings()->value("language", "English").toString());
	engine.rootContext()->setContextProperty("languageLoader", &languageLoader);
	#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
		QObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate);
	#endif

	#if defined(Q_OS_ANDROID)
		if (!checkPermission("android.permission.WRITE_EXTERNAL_STORAGE")) {
			log(QStringLiteral("Android write permission not granted"), Logger::Error);
		}

		if (settings.value("Save/path").toString().isEmpty()) {
			settings.setValue("Save/path", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first() + "/Grabber");
		}
	#endif

	engine.load(url);

	#if defined(Q_OS_ANDROID)
		QtAndroid::hideSplashScreen(250);
	#endif

	return app.exec();
}
<commit_msg>Copy words.txt file in QML version<commit_after>#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSettings>
#include "functions.h"
#include "language-loader.h"
#include "main-screen.h"
#include "models/image.h"
#include "models/profile.h"
#include "models/qml-auth.h"
#include "models/qml-auth-setting-field.h"
#include "models/qml-image.h"
#include "models/qml-site.h"
#include "settings.h"
#include "share/share-utils.h"
#include "syntax-highlighter-helper.h"

#if defined(Q_OS_ANDROID)
	#include <QStandardPaths>
	#include <QtAndroid>
	#include "logger.h"

	bool checkPermission(const QString &perm)
	{
		auto already = QtAndroid::checkPermission(perm);
		if (already == QtAndroid::PermissionResult::Denied) {
			auto results = QtAndroid::requestPermissionsSync(QStringList() << perm);
			if (results[perm] == QtAndroid::PermissionResult::Denied) {
				return false;
			}
		}
		return true;
	}
#endif

int main(int argc, char *argv[])
{
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QGuiApplication app(argc, argv);
	app.setApplicationName("Grabber");
	app.setApplicationVersion(VERSION);
	app.setOrganizationName("Bionus");
	app.setOrganizationDomain("bionus.fr.cr");

	qmlRegisterType<ShareUtils>("Grabber", 1, 0, "ShareUtils");
	qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper");
	qRegisterMetaType<QSharedPointer<Image>>("QSharedPointer<Image>");
	qRegisterMetaType<Settings*>("Settings*");
	qRegisterMetaType<QmlImage*>("QmlImage*");
	qRegisterMetaType<QList<QmlImage*>>("QList>QmlImage*>");
	qRegisterMetaType<QmlSite*>("QmlSite*");
	qRegisterMetaType<QList<QmlSite*>>("QList<QmlSite*>");
	qRegisterMetaType<QList<QmlAuth*>>("QList<QmlAuth*>");
	qRegisterMetaType<QList<QmlAuthSettingField*>>("QList<QmlAuthSettingField*>");

	// Copy settings files to writable directory
	const QStringList toCopy { "sites/", "themes/", "webservices/" };
	for (const QString &tgt : toCopy) {
		const QString from = savePath(tgt, true, false);
		const QString to = savePath(tgt, true, true);
		if (!QDir(to).exists() && QDir(from).exists()) {
			copyRecursively(from, to);
		}
	}
	const QStringList filesToCopy { "words.txt" };
	for (const QString &tgt : filesToCopy) {
		const QString from = savePath(tgt, true, false);
		const QString to = savePath(tgt, true, true);
		if (!QFile::exists(to) && QFile::exists(from)) {
			QFile::copy(from, to);
		}
	}

	const QUrl url(QStringLiteral("qrc:/main-screen.qml"));

	QQmlApplicationEngine engine;
	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
		if (!obj && url == objUrl) {
			QCoreApplication::exit(-1);
		}
	}, Qt::QueuedConnection);

	// Define a few globals
	engine.rootContext()->setContextProperty("VERSION", QString(VERSION));
	#ifdef NIGHTLY
		engine.rootContext()->setContextProperty("NIGHTLY", true);
		engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString(NIGHTLY_COMMIT));
	#else
		engine.rootContext()->setContextProperty("NIGHTLY", false);
		engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString());
	#endif

	Profile profile(savePath());
	MainScreen mainScreen(&profile, &engine);
	engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);
	engine.rootContext()->setContextProperty("backend", &mainScreen);

	Settings settings(profile.getSettings());
	engine.rootContext()->setContextProperty("settings", &settings);

	// Load translations
	LanguageLoader languageLoader(savePath("languages/", true, false));
	languageLoader.install(qApp);
	languageLoader.setLanguage(profile.getSettings()->value("language", "English").toString());
	engine.rootContext()->setContextProperty("languageLoader", &languageLoader);
	#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
		QObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate);
	#endif

	#if defined(Q_OS_ANDROID)
		if (!checkPermission("android.permission.WRITE_EXTERNAL_STORAGE")) {
			log(QStringLiteral("Android write permission not granted"), Logger::Error);
		}

		if (settings.value("Save/path").toString().isEmpty()) {
			settings.setValue("Save/path", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first() + "/Grabber");
		}
	#endif

	engine.load(url);

	#if defined(Q_OS_ANDROID)
		QtAndroid::hideSplashScreen(250);
	#endif

	return app.exec();
}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "unit_tests.hpp"

#include "test_linearform_ext.hpp"

using namespace mfem;
using namespace linearform_ext_tests;

namespace mfem
{

namespace linearform_ext_tests
{

void LinearFormExtTest::Description()
{
   mfem::out << "[LinearFormExt]"
             << " p=" << p
             << " q=" << q
             << " "<< dim << "D"
             << " "<< vdim << "-"
             << (problem%2?"Scalar":"Vector")
             << (problem>2?"Grad":"")
             //<< (gll ? "GLL" : "GL")
             << std::endl;
}

void LinearFormExtTest::Run()
{
   Description();
   AssembleBoth();
   REQUIRE((lf_full*lf_full) == MFEM_Approx(lf_legacy*lf_legacy));
}

} // namespace linearform_ext_tests

} // namespace mfem

TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]")
{
   const auto N = GENERATE(2,3,4);
   const auto dim = GENERATE(2,3);
   const auto order = GENERATE(1,2,3);
   const auto gll = GENERATE(false,true); // q=p+2, q=p+1

   SECTION("Scalar")
   {
      const auto vdim = 1;
      const auto problem = GENERATE(LinearFormExtTest::DomainLF,
                                    LinearFormExtTest::DomainLFGrad);
      LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
   }

   SECTION("Vector")
   {
      const auto vdim = GENERATE(1,2,24);
      const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF,
                                    LinearFormExtTest::VectorDomainLFGrad);
      LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
   }

} // test case

<commit_msg>Include fix<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "unit_tests.hpp"

#include "tests/unit/fem/test_linearform_ext.hpp"

using namespace mfem;
using namespace linearform_ext_tests;

namespace mfem
{

namespace linearform_ext_tests
{

void LinearFormExtTest::Description()
{
   mfem::out << "[LinearFormExt]"
             << " p=" << p
             << " q=" << q
             << " "<< dim << "D"
             << " "<< vdim << "-"
             << (problem%2?"Scalar":"Vector")
             << (problem>2?"Grad":"")
             //<< (gll ? "GLL" : "GL")
             << std::endl;
}

void LinearFormExtTest::Run()
{
   Description();
   AssembleBoth();
   REQUIRE((lf_full*lf_full) == MFEM_Approx(lf_legacy*lf_legacy));
}

} // namespace linearform_ext_tests

} // namespace mfem

TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]")
{
   const auto N = GENERATE(2,3,4);
   const auto dim = GENERATE(2,3);
   const auto order = GENERATE(1,2,3);
   const auto gll = GENERATE(false,true); // q=p+2, q=p+1

   SECTION("Scalar")
   {
      const auto vdim = 1;
      const auto problem = GENERATE(LinearFormExtTest::DomainLF,
                                    LinearFormExtTest::DomainLFGrad);
      LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
   }

   SECTION("Vector")
   {
      const auto vdim = GENERATE(1,2,24);
      const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF,
                                    LinearFormExtTest::VectorDomainLFGrad);
      LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
   }

} // test case

<|endoftext|>