<commit_before>#ifndef __ARRAYS_HPP__
#define __ARRAYS_HPP__

#include <string>
#include <type_traits>
#include "../static-strings/static-strings.hpp"

#ifdef __CYGWIN__
#include <sstream>
namespace std {
	inline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }
}
#endif

namespace {
namespace __typedecl {

struct split_string {
	std::string begin;
	std::string end;
	explicit operator std::string() const {
		return begin + end;
	}
};

inline split_string operator+(const std::string& s, const split_string& ss) {
	return { s + ss.begin, ss.end };
}

inline split_string operator+(const split_string& ss, const std::string& s) {
	return { ss.begin, ss.end + s };
}

using empty_ss = static_string::static_string<char>;
using space_ss = static_string::static_string<char, ' '>;

template <typename B, typename E>
struct sss {
	using begin = B;
	using end = E;
	inline static std::string string() {
		return begin::string() + end::string();
	}
};

using empty_sss = sss<empty_ss, empty_ss>;

template <typename, typename>
struct sssconcat_impl;

template <char... chars, typename SSS>
struct sssconcat_impl<static_string::static_string<char, chars...>, SSS> {
	using _begin = static_string::concat<
	                   static_string::static_string<char, chars...>,
	                   typename SSS::begin
	               >;
	using type = sss<_begin, typename SSS::end>;
};

template <typename T1, typename T2>
using sssconcat = typename sssconcat_impl<T1, T2>::type;

template <typename T>
struct impl;

template <typename T>
struct is_basic_type {
	// SFINAE!
	template <typename I>
	static constexpr bool test(typename I::template ssstring_with_cv_qual<empty_ss, empty_sss> *) {
		return true;
	}

	template <typename I>
	static constexpr bool test(...) {
		return false;
	}

	enum { value = test<impl<T>>(nullptr) };
};

template <typename T, typename SuffixSSS, typename CVQualSS, bool = is_basic_type<T>::value>
struct prefix_cv_qual_if_basictype;

template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, true> {
	using ssstring = typename impl<T>::template ssstring_with_cv_qual<CVQualSS, SuffixSSS>;
};

template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, false> {
	using ssstring = typename impl<T>::template ssstring<sssconcat<CVQualSS, SuffixSSS>>;
};

template <typename T>
struct _prefix_cv_qual_if_basictype {
	/*
	 * == SFINAE ==
	 * If impl<T> has a static member function named "value_with_cv_qual", then
	 * the forward() overload below is defined, and the call for forward() will
	 * prefer this overload over the other one that has varargs ("...").
	 * If impl<T> does not have such member, then the varargs overload is the
	 * only option.
	 */
	template <typename I>
	inline static split_string forward(const std::string& cv_qual, const split_string& suffix, decltype(I::value_with_cv_qual)*) {
		return I::value_with_cv_qual(cv_qual, suffix);
	}

	template <typename I>
	inline static split_string forward(const std::string& cv_qual, const split_string& suffix, ...) {
		return I::value(cv_qual + suffix);
	}

	inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
		return forward<impl<T>>(cv_qual, suffix, nullptr);
	}
};

template <typename T>
struct has_ssstring {
	template <typename TT>
	constexpr static bool test(typename TT::template ssstring<>*) { return true; }

	template <typename TT>
	constexpr static bool test(...) { return false; }

	enum { value = test<impl<T>>(nullptr) };
};

template <typename T, bool = has_ssstring<T>::value>
struct const_impl;

template <typename T>
struct const_impl<T, true> {
	using _token_ss = static_string::static_string<char, 'c','o','n','s','t'>;

	template <typename SuffixSSS = empty_sss>
	using ssstring = typename prefix_cv_qual_if_basictype<T, SuffixSSS, _token_ss>::ssstring;
};

template <typename T>
struct const_impl<T, false> {};

template <typename T>
struct impl<const T> : const_impl<T> {
	inline static split_string value(const split_string& suffix = {}) {
		return _prefix_cv_qual_if_basictype<T>::value("const", suffix);
	}
};

template <typename T, bool = has_ssstring<T>::value>
struct volatile_impl;

template <typename T>
struct volatile_impl<T, true> {
	using _token_ss = static_string::static_string<char, 'v','o','l','a','t','i','l','e'>;

	template <typename SuffixSSS = empty_sss>
	using ssstring = typename prefix_cv_qual_if_basictype<T, SuffixSSS, _token_ss>::ssstring;
};

template <typename T>
struct volatile_impl<T, false> {};

template <typename T>
struct impl<volatile T> : volatile_impl<T> {
	inline static split_string value(const split_string& suffix = {}) {
		return _prefix_cv_qual_if_basictype<T>::value("volatile", suffix);
	}
};

// Required to disambiguate between <const T> and <volatile T>
template <typename T>
struct impl<const volatile T> {
	inline static split_string value(const split_string& suffix = {}) {
		return _prefix_cv_qual_if_basictype<T>::value("const volatile", suffix);
	}
};

template <typename T>
struct is_array_or_function : std::integral_constant<
	bool,
	std::is_array<T>::value || std::is_function<T>::value
> {};

template <typename T, bool = is_array_or_function<T>::value>
struct parenthesize_if_array_or_function;

template <typename T>
struct parenthesize_if_array_or_function<T, false> {
	inline static split_string value(const split_string& arg) {
		return impl<T>::value(arg);
	}
};

template <typename T>
struct parenthesize_if_array_or_function<T, true> {
	inline static split_string value(const split_string& arg) {
		return impl<T>::value("(" + arg + ")");
	}
};

template <typename T>
struct impl<T*> {
	inline static split_string value(const split_string& suffix = {}) {
		return parenthesize_if_array_or_function<T>::value("*" + suffix);
	}
};

template <typename T>
struct impl<T&> {
	inline static split_string value(const split_string& suffix = {}) {
		return parenthesize_if_array_or_function<T>::value("&" + suffix);
	}
};

template <typename T>
struct impl<T&&> {
	inline static split_string value(const split_string& suffix = {}) {
		return parenthesize_if_array_or_function<T>::value("&&" + suffix);
	}
};

template <typename T>
struct array_impl {
	inline static split_string value(const split_string& prefix = {}) {
		return impl<T>::value(prefix + "[]");
	}
};

template <typename T>
struct impl<T[]> : array_impl<T> {};

// Required to disambiguate between <const T> and <T[]>
template <typename T>
struct impl<const T[]> : array_impl<const T> {};

// Required to disambiguate between <volatile T> and <T[]>
template <typename T>
struct impl<volatile T[]> : array_impl<volatile T> {};

// Required to disambiguate between <const T>, <volatile T>, <const volatile T>,  <T[]>, <const T[]> and <volatile T[]>
template <typename T>
struct impl<const volatile T[]> : array_impl<const volatile T> {};

template <typename T, size_t N>
struct sized_array_impl {
	inline static split_string value(const split_string& prefix = {}) {
		return impl<T>::value(prefix + ("[" + std::to_string(N) + "]"));
	}
};

template <typename T, size_t N>
struct impl<T[N]> : sized_array_impl<T, N> {};

// Required to disambiguate between <const T> and <T[N]>
template <typename T, size_t N>
struct impl<const T[N]> : sized_array_impl<const T, N> {};

// Required to disambiguate between <volatile T> and <T[N]>
template <typename T, size_t N>
struct impl<volatile T[N]> : sized_array_impl<volatile T, N> {};

// Required to disambiguate between <const T>, <volatile T>, <const volatile T>,  <T[N]>, <const T[N]> and <volatile T[N]>
template <typename T, size_t N>
struct impl<const volatile T[N]> : sized_array_impl<const volatile T, N> {};

template <typename... T>
struct type_list_impl;

template <>
struct type_list_impl<> {
	inline static std::string value() {
		return "";
	}
};

struct varargs;

template <>
struct type_list_impl<varargs> {
	inline static std::string value() {
		return "...";
	}
};

template <typename T>
struct type_list_impl<T> {
	inline static std::string value() {
		return static_cast<std::string>(impl<T>::value());
	}
};

template <typename T1, typename T2, typename... U>
struct type_list_impl<T1, T2, U...> {
	inline static std::string value() {
		return type_list_impl<T1>::value() + ", " + type_list_impl<T2, U...>::value();
	}
};

template <bool RIsPtrOrRef, typename R, typename... A>
struct function_impl;

template <typename R, typename... A>
struct function_impl<false, R, A...> {
	inline static split_string value(const split_string& infix = {}) {
		return static_cast<std::string>(impl<R>::value()) + infix + "(" + type_list_impl<A...>::value() + ")";
	}
};

template <typename R, typename... A>
struct function_impl<true, R, A...> {
	inline static split_string value(const split_string& prefix = {}) {
		return impl<R>::value(prefix + "(" + type_list_impl<A...>::value() + ")");
	}
};

template <typename T>
struct is_pointer_or_reference : std::integral_constant<
	bool,
	std::is_pointer<T>::value || std::is_reference<T>::value
> {};

template <typename R, typename... A>
struct function_args_impl : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, A...> {};

template <typename R, typename... A>
struct impl<R(A...)>      : function_args_impl<R, A...> {};

template <typename R, typename... A>
struct impl<R(A..., ...)> : function_args_impl<R, A..., varargs> {};

template <typename T>
struct str_provider;

template <typename T, bool = has_ssstring<T>::value>
struct impl_proxy;

template <typename T>
struct impl_proxy<T, true> {
	inline static std::string value(const std::string& arg = "") {
		using i_sss = typename impl<T>::template ssstring<>;
		return i_sss::begin::string() + arg + i_sss::end::string();
	}
};

template <typename T>
struct impl_proxy<T, false> {
	inline static std::string value(const std::string& arg = "") {
		split_string ss = impl<T>::value();
		return ss.begin + arg + ss.end;
	}
};

} /* namespace __typedecl */
} /* unnamed namespace */

template <typename T>
inline std::string typedecl() {
	return __typedecl::impl_proxy<T>::value();
}

template <typename T>
inline std::string namedecl(const std::string& name) {
	return __typedecl::impl_proxy<T>::value(' ' + name);
}

#define DEFINE_TYPEDECL(T) \
	namespace { \
	namespace __typedecl { \
	template <> \
	struct str_provider<T> { \
		static constexpr const char* str() { return #T; } \
	}; \
	template <> \
	struct impl<T> { \
		using _token_ss = static_string::from_provider<str_provider<T>>; \
		template <typename SuffixSSS = empty_sss> using ssstring = sssconcat<_token_ss, SuffixSSS>; \
		template <typename CVQualSS, typename SuffixSSS> \
		using ssstring_with_cv_qual = sssconcat< \
		                                  static_string::concat<CVQualSS, space_ss, _token_ss>, \
		                                  SuffixSSS \
		                              >; \
		inline static split_string value(const split_string& suffix = {}) { \
			return #T + suffix; \
		} \
		inline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \
			return (cv_qual + " " #T) + suffix; \
		} \
	}; \
	} /* namespace __typedecl */ \
	} /* unnamed namespace */

DEFINE_TYPEDECL(void);
DEFINE_TYPEDECL(char);
DEFINE_TYPEDECL(int);

#endif
<commit_msg>typedecl: Refactor common implementation of impl<const T> and impl<volatile T><commit_after>#ifndef __ARRAYS_HPP__
#define __ARRAYS_HPP__

#include <string>
#include <type_traits>
#include "../static-strings/static-strings.hpp"

#ifdef __CYGWIN__
#include <sstream>
namespace std {
	inline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }
}
#endif

namespace {
namespace __typedecl {

struct split_string {
	std::string begin;
	std::string end;
	explicit operator std::string() const {
		return begin + end;
	}
};

inline split_string operator+(const std::string& s, const split_string& ss) {
	return { s + ss.begin, ss.end };
}

inline split_string operator+(const split_string& ss, const std::string& s) {
	return { ss.begin, ss.end + s };
}

using empty_ss = static_string::static_string<char>;
using space_ss = static_string::static_string<char, ' '>;

template <typename B, typename E>
struct sss {
	using begin = B;
	using end = E;
	inline static std::string string() {
		return begin::string() + end::string();
	}
};

using empty_sss = sss<empty_ss, empty_ss>;

template <typename, typename>
struct sssconcat_impl;

template <char... chars, typename SSS>
struct sssconcat_impl<static_string::static_string<char, chars...>, SSS> {
	using _begin = static_string::concat<
	                   static_string::static_string<char, chars...>,
	                   typename SSS::begin
	               >;
	using type = sss<_begin, typename SSS::end>;
};

template <typename T1, typename T2>
using sssconcat = typename sssconcat_impl<T1, T2>::type;

template <typename T>
struct impl;

template <typename T>
struct is_basic_type {
	// SFINAE!
	template <typename I>
	static constexpr bool test(typename I::template ssstring_with_cv_qual<empty_ss, empty_sss> *) {
		return true;
	}

	template <typename I>
	static constexpr bool test(...) {
		return false;
	}

	enum { value = test<impl<T>>(nullptr) };
};

template <typename T, typename SuffixSSS, typename CVQualSS, bool = is_basic_type<T>::value>
struct prefix_cv_qual_if_basictype;

template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, true> {
	using ssstring = typename impl<T>::template ssstring_with_cv_qual<CVQualSS, SuffixSSS>;
};

template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, false> {
	using ssstring = typename impl<T>::template ssstring<sssconcat<CVQualSS, SuffixSSS>>;
};

template <typename T>
struct _prefix_cv_qual_if_basictype {
	/*
	 * == SFINAE ==
	 * If impl<T> has a static member function named "value_with_cv_qual", then
	 * the forward() overload below is defined, and the call for forward() will
	 * prefer this overload over the other one that has varargs ("...").
	 * If impl<T> does not have such member, then the varargs overload is the
	 * only option.
	 */
	template <typename I>
	inline static split_string forward(const std::string& cv_qual, const split_string& suffix, decltype(I::value_with_cv_qual)*) {
		return I::value_with_cv_qual(cv_qual, suffix);
	}

	template <typename I>
	inline static split_string forward(const std::string& cv_qual, const split_string& suffix, ...) {
		return I::value(cv_qual + suffix);
	}

	inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
		return forward<impl<T>>(cv_qual, suffix, nullptr);
	}
};

template <typename T>
struct has_ssstring {
	// SFINAE!
	template <typename TT>
	constexpr static bool test(typename TT::template ssstring<>*) { return true; }

	template <typename TT>
	constexpr static bool test(...) { return false; }

	enum { value = test<impl<T>>(nullptr) };
};

template <typename T, typename CVQualSS, bool = has_ssstring<T>::value>
struct cvqualified_impl;

template <typename T, typename CVQualSS>
struct cvqualified_impl<T, CVQualSS, true> {
	template <typename SuffixSSS = empty_sss>
	using ssstring = typename prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS>::ssstring;
};

template <typename T, typename CVQualSS>
struct cvqualified_impl<T, CVQualSS, false> {};

template <typename T>
struct impl<const T> : cvqualified_impl<T, static_string::static_string<char, 'c','o','n','s','t'>> {
	inline static split_string value(const split_string& suffix = {}) {
		return _prefix_cv_qual_if_basictype<T>::value("const", suffix);
	}
};

template <typename T>
struct impl<volatile T> : cvqualified_impl<T, static_string::static_string<char, 'v','o','l','a','t','i','l','e'>> {
	inline static split_string value(const split_string& suffix = {}) {
		return _prefix_cv_qual_if_basictype<T>::value("volatile", suffix);
	}
};

// Required to disambiguate between <const T> and <volatile T>
template <typename T>
struct impl<const volatile T> {
	inline static split_string value(const split_string& suffix = {}) {
		return _prefix_cv_qual_if_basictype<T>::value("const volatile", suffix);
	}
};

template <typename T>
struct is_array_or_function : std::integral_constant<
	bool,
	std::is_array<T>::value || std::is_function<T>::value
> {};

template <typename T, bool = is_array_or_function<T>::value>
struct parenthesize_if_array_or_function;

template <typename T>
struct parenthesize_if_array_or_function<T, false> {
	inline static split_string value(const split_string& arg) {
		return impl<T>::value(arg);
	}
};

template <typename T>
struct parenthesize_if_array_or_function<T, true> {
	inline static split_string value(const split_string& arg) {
		return impl<T>::value("(" + arg + ")");
	}
};

template <typename T>
struct impl<T*> {
	inline static split_string value(const split_string& suffix = {}) {
		return parenthesize_if_array_or_function<T>::value("*" + suffix);
	}
};

template <typename T>
struct impl<T&> {
	inline static split_string value(const split_string& suffix = {}) {
		return parenthesize_if_array_or_function<T>::value("&" + suffix);
	}
};

template <typename T>
struct impl<T&&> {
	inline static split_string value(const split_string& suffix = {}) {
		return parenthesize_if_array_or_function<T>::value("&&" + suffix);
	}
};

template <typename T>
struct array_impl {
	inline static split_string value(const split_string& prefix = {}) {
		return impl<T>::value(prefix + "[]");
	}
};

template <typename T>
struct impl<T[]> : array_impl<T> {};

// Required to disambiguate between <const T> and <T[]>
template <typename T>
struct impl<const T[]> : array_impl<const T> {};

// Required to disambiguate between <volatile T> and <T[]>
template <typename T>
struct impl<volatile T[]> : array_impl<volatile T> {};

// Required to disambiguate between <const T>, <volatile T>, <const volatile T>,  <T[]>, <const T[]> and <volatile T[]>
template <typename T>
struct impl<const volatile T[]> : array_impl<const volatile T> {};

template <typename T, size_t N>
struct sized_array_impl {
	inline static split_string value(const split_string& prefix = {}) {
		return impl<T>::value(prefix + ("[" + std::to_string(N) + "]"));
	}
};

template <typename T, size_t N>
struct impl<T[N]> : sized_array_impl<T, N> {};

// Required to disambiguate between <const T> and <T[N]>
template <typename T, size_t N>
struct impl<const T[N]> : sized_array_impl<const T, N> {};

// Required to disambiguate between <volatile T> and <T[N]>
template <typename T, size_t N>
struct impl<volatile T[N]> : sized_array_impl<volatile T, N> {};

// Required to disambiguate between <const T>, <volatile T>, <const volatile T>,  <T[N]>, <const T[N]> and <volatile T[N]>
template <typename T, size_t N>
struct impl<const volatile T[N]> : sized_array_impl<const volatile T, N> {};

template <typename... T>
struct type_list_impl;

template <>
struct type_list_impl<> {
	inline static std::string value() {
		return "";
	}
};

struct varargs;

template <>
struct type_list_impl<varargs> {
	inline static std::string value() {
		return "...";
	}
};

template <typename T>
struct type_list_impl<T> {
	inline static std::string value() {
		return static_cast<std::string>(impl<T>::value());
	}
};

template <typename T1, typename T2, typename... U>
struct type_list_impl<T1, T2, U...> {
	inline static std::string value() {
		return type_list_impl<T1>::value() + ", " + type_list_impl<T2, U...>::value();
	}
};

template <bool RIsPtrOrRef, typename R, typename... A>
struct function_impl;

template <typename R, typename... A>
struct function_impl<false, R, A...> {
	inline static split_string value(const split_string& infix = {}) {
		return static_cast<std::string>(impl<R>::value()) + infix + "(" + type_list_impl<A...>::value() + ")";
	}
};

template <typename R, typename... A>
struct function_impl<true, R, A...> {
	inline static split_string value(const split_string& prefix = {}) {
		return impl<R>::value(prefix + "(" + type_list_impl<A...>::value() + ")");
	}
};

template <typename T>
struct is_pointer_or_reference : std::integral_constant<
	bool,
	std::is_pointer<T>::value || std::is_reference<T>::value
> {};

template <typename R, typename... A>
struct function_args_impl : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, A...> {};

template <typename R, typename... A>
struct impl<R(A...)>      : function_args_impl<R, A...> {};

template <typename R, typename... A>
struct impl<R(A..., ...)> : function_args_impl<R, A..., varargs> {};

template <typename T>
struct str_provider;

template <typename T, bool = has_ssstring<T>::value>
struct impl_proxy;

template <typename T>
struct impl_proxy<T, true> {
	inline static std::string value(const std::string& arg = "") {
		using i_sss = typename impl<T>::template ssstring<>;
		return i_sss::begin::string() + arg + i_sss::end::string();
	}
};

template <typename T>
struct impl_proxy<T, false> {
	inline static std::string value(const std::string& arg = "") {
		split_string ss = impl<T>::value();
		return ss.begin + arg + ss.end;
	}
};

} /* namespace __typedecl */
} /* unnamed namespace */

template <typename T>
inline std::string typedecl() {
	return __typedecl::impl_proxy<T>::value();
}

template <typename T>
inline std::string namedecl(const std::string& name) {
	return __typedecl::impl_proxy<T>::value(' ' + name);
}

#define DEFINE_TYPEDECL(T) \
	namespace { \
	namespace __typedecl { \
	template <> \
	struct str_provider<T> { \
		static constexpr const char* str() { return #T; } \
	}; \
	template <> \
	struct impl<T> { \
		using _token_ss = static_string::from_provider<str_provider<T>>; \
		template <typename SuffixSSS = empty_sss> using ssstring = sssconcat<_token_ss, SuffixSSS>; \
		template <typename CVQualSS, typename SuffixSSS> \
		using ssstring_with_cv_qual = sssconcat< \
		                                  static_string::concat<CVQualSS, space_ss, _token_ss>, \
		                                  SuffixSSS \
		                              >; \
		inline static split_string value(const split_string& suffix = {}) { \
			return #T + suffix; \
		} \
		inline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \
			return (cv_qual + " " #T) + suffix; \
		} \
	}; \
	} /* namespace __typedecl */ \
	} /* unnamed namespace */

DEFINE_TYPEDECL(void);
DEFINE_TYPEDECL(char);
DEFINE_TYPEDECL(int);

#endif
<|endoftext|>


<commit_before>#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <string>

#include "caffe/caffe.hpp"
#include "caffe_mobile.hpp"

#define  LOG_TAG    "MiRA-CNN"
#define  LOGV(...)  __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG, __VA_ARGS__)
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG, __VA_ARGS__)
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG, __VA_ARGS__)
#define  LOGW(...)  __android_log_print(ANDROID_LOG_WARN,LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, __VA_ARGS__)

#ifdef __cplusplus
extern "C" {
#endif

caffe::CaffeMobile *caffe_mobile;

int getTimeSec();

void JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_CaffeMobile_enableLog(JNIEnv* env, jobject thiz, jboolean enabled)
{
    caffe::LogMessage::Enable(enabled != JNI_FALSE);
}

jint JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_CaffeMobile_loadModel(JNIEnv* env, jobject thiz, jstring modelPath, jstring weightsPath)
{
    const char *model_path = env->GetStringUTFChars(modelPath, 0);
    const char *weights_path = env->GetStringUTFChars(weightsPath, 0);
    caffe_mobile = new caffe::CaffeMobile(string(model_path), string(weights_path));
    env->ReleaseStringUTFChars(modelPath, model_path);
    env->ReleaseStringUTFChars(weightsPath, weights_path);
    return 0;
}

jint JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_CaffeMobile_predictImage(JNIEnv* env, jobject thiz, jstring imgPath)
{
    const char *img_path = env->GetStringUTFChars(imgPath, 0);
    caffe::vector<int> top_k = caffe_mobile->predict_top_k(string(img_path), 3);
    LOGD("top-1 result: %d", top_k[0]);

    env->ReleaseStringUTFChars(imgPath, img_path);

    return top_k[0];
}

int getTimeSec() {
    struct timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    return (int) now.tv_sec;
}
/*
JavaVM *g_jvm = NULL;
jobject g_obj = NULL;

void JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_MainActivity_MainActivity_setJNIEnv(JNIEnv* env, jobject obj)
{
    env->GetJavaVM(&g_jvm);
    g_obj = env->NewGlobalRef(obj);
}
*/
jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
    JNIEnv* env = NULL;
    jint result = -1;

    if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
        LOGE("GetEnv failed!");
        return result;
    }

    return JNI_VERSION_1_6;
}

int main(int argc, char const *argv[])
{
    string usage("usage: main <model> <weights> <img>");
    if (argc < 4) {
        std::cerr << usage << std::endl;
        return 1;
    }

    caffe::LogMessage::Enable(true); // enable logging
    caffe_mobile = new caffe::CaffeMobile(string(argv[1]), string(argv[2]));
    caffe::vector<int> top_3 = caffe_mobile->predict_top_k(string(argv[3]));
    for (auto k : top_3) {
        std::cout << k << std::endl;
    }
    return 0;
}

#ifdef __cplusplus
}
#endif
<commit_msg>redirect stderr to android log in a naive way<commit_after>#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <string>

#include "caffe/caffe.hpp"
#include "caffe_mobile.hpp"

#define  LOG_TAG    "MiRA-CNN"
#define  LOGV(...)  __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG, __VA_ARGS__)
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG, __VA_ARGS__)
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG, __VA_ARGS__)
#define  LOGW(...)  __android_log_print(ANDROID_LOG_WARN,LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, __VA_ARGS__)

#ifdef __cplusplus
extern "C" {
#endif

caffe::CaffeMobile *caffe_mobile;

int getTimeSec();

static int pfd[2];
static pthread_t thr;
static const char *tag = "myapp";

static void *thread_func(void*) {
    ssize_t rdsz;
    char buf[1024];
    while ((rdsz = read(pfd[0], buf, sizeof(buf) - 1)) > 0) {
        buf[rdsz] = 0;  // add null-terminator
        __android_log_write(ANDROID_LOG_DEBUG, tag, buf);
    }
    return 0;
}

static int start_logger() {
    /* make stdout line-buffered and stderr unbuffered */
    // setvbuf(stdout, 0, _IOLBF, 0);
    setvbuf(stderr, 0, _IONBF, 0);

    /* create the pipe and redirect stdout and stderr */
    pipe(pfd);
    // dup2(pfd[1], 1);
    dup2(pfd[1], 2);

    /* spawn the logging thread */
    if(pthread_create(&thr, 0, thread_func, 0) == -1)
        return -1;
    pthread_detach(thr);
    return 0;
}

void JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_CaffeMobile_enableLog(JNIEnv* env, jobject thiz, jboolean enabled)
{
    start_logger();
    caffe::LogMessage::Enable(enabled != JNI_FALSE);
}

jint JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_CaffeMobile_loadModel(JNIEnv* env, jobject thiz, jstring modelPath, jstring weightsPath)
{
    const char *model_path = env->GetStringUTFChars(modelPath, 0);
    const char *weights_path = env->GetStringUTFChars(weightsPath, 0);
    caffe_mobile = new caffe::CaffeMobile(string(model_path), string(weights_path));
    env->ReleaseStringUTFChars(modelPath, model_path);
    env->ReleaseStringUTFChars(weightsPath, weights_path);
    return 0;
}

jint JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_CaffeMobile_predictImage(JNIEnv* env, jobject thiz, jstring imgPath)
{
    const char *img_path = env->GetStringUTFChars(imgPath, 0);
    caffe::vector<int> top_k = caffe_mobile->predict_top_k(string(img_path), 3);
    LOGD("top-1 result: %d", top_k[0]);

    env->ReleaseStringUTFChars(imgPath, img_path);

    return top_k[0];
}

int getTimeSec() {
    struct timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    return (int) now.tv_sec;
}
/*
JavaVM *g_jvm = NULL;
jobject g_obj = NULL;

void JNIEXPORT JNICALL
Java_com_sh1r0_caffe_1android_1demo_MainActivity_MainActivity_setJNIEnv(JNIEnv* env, jobject obj)
{
    env->GetJavaVM(&g_jvm);
    g_obj = env->NewGlobalRef(obj);
}
*/
jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
    JNIEnv* env = NULL;
    jint result = -1;

    if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
        LOGE("GetEnv failed!");
        return result;
    }

    return JNI_VERSION_1_6;
}

int main(int argc, char const *argv[])
{
    string usage("usage: main <model> <weights> <img>");
    if (argc < 4) {
        std::cerr << usage << std::endl;
        return 1;
    }

    caffe::LogMessage::Enable(true); // enable logging
    caffe_mobile = new caffe::CaffeMobile(string(argv[1]), string(argv[2]));
    caffe::vector<int> top_3 = caffe_mobile->predict_top_k(string(argv[3]));
    for (auto k : top_3) {
        std::cout << k << std::endl;
    }
    return 0;
}

#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before>#include <complex>
#include <vector>
#include <fstream>
// boost/geometry/algorithms/detail/overlay/handle_colocations.hpp:198:10:
// error: no member named 'cout' in namespace 'std'
#include <iostream>

#include "base/base.h"
#include "boost/rational.hpp"
#include <boost/geometry.hpp>
#include <boost/geometry/algorithms/area.hpp>
#include <boost/geometry/algorithms/sym_difference.hpp>
// #include <boost/geometry/algorithms/equals.hpp>
// #include <boost/geometry/algorithms/is_empty.hpp>
#include <boost/geometry/algorithms/union.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/multiprecision/gmp.hpp>
#include "polygon.h"
#include "problem.h"
#include "solution.h"

DEFINE_string(problem, "", "input problem file");
DEFINE_string(solution, "", "input solution file");
DEFINE_bool(show_figure, false, "show rich output");

namespace bg = boost::geometry;

using gPoint = bg::model::d2::point_xy<Q>;
using ccwRing = bg::model::ring<gPoint, false, false>;
using ccwPolygon = bg::model::polygon<gPoint, false, false>;
using ccwMultiPolygon = bg::model::multi_polygon<ccwPolygon>;
using namespace std;

namespace boost {
// For bg::convert across coordinate systems from gPoint to RealPoint
template <>
double numeric_cast<double>(const Q& x) {
  return x.convert_to<double>();
}
}

gPoint rotCCW(const gPoint& p) { return gPoint(-p.y(), p.x()); }

Q cross(const gPoint& lhs, const gPoint& rhs) {
  return lhs.x() * rhs.y() - lhs.y() * rhs.x();
}

// namespace boost {
// namespace multiprecision {
// // False sqrt for bg::equals
// // boost/geometry/algorithms/detail/equals/collect_vectors.hpp:138:48
// // that uses sqrt to compare vector directions with unit vectors.
// Q sqrt(const Q& q) {
//   long double x = sqrtl(q.convert_to<long double>());
//   long double i;
//   long double f = modfl(x, &i);
//   if (f == 0) return Q((long long)i);
//   int exp;
//   x = frexpl(x, &exp);
//   const int kBias = 20;
//   x = ldexpl(x, exp + 20);
//   return Q((long long)roundl(x), 1ll << kBias);
// }
// }
// }

template <typename T>
void normalize_pair(std::pair<T, T>* p) {
  if (p->second < p->first) std::swap(p->first, p->second);
}

int main(int argc, char** argv) {
  ParseCommandLineFlags(&argc, &argv);

  VLOG(2) << "Loading file " << FLAGS_problem;
  Problem problem;
  std::ifstream problem_ifs(FLAGS_problem);
  CHECK(ReadProblem(problem_ifs, &problem)) << "Failed to load file "
                                            << FLAGS_problem;
  VLOG(2) << "Loading file " << FLAGS_solution;
  Solution solution;
  std::ifstream solution_ifs(FLAGS_solution);
  CHECK(ReadSolution(solution_ifs, &solution)) << "Failed to load file "
                                               << FLAGS_solution;
  VLOG(2) << "Files loaded";

  // edge (normalized pair of vertex ids) to facet ids
  map<pair<int, int>, set<int>> edge_to_facet;
  for (int i = 0; i < solution.facets.size(); ++i) {
    for (int j = 0; j < solution.facets[i].size() - 1; ++j) {
      pair<int, int> edge(solution.facets[i][j], solution.facets[i][j + 1]);
      normalize_pair(&edge);
      edge_to_facet[edge].insert(i);
    }
  }
  for (const auto& it : edge_to_facet) {
    const auto& edge = it.first;
    const auto& adj_facets = it.second;
    if (adj_facets.size() > 2) {
      LOG(FATAL) << "Edge[" << edge.first << "," << edge.second
                 << "] is shared by more than 2 facets ("
                 << strings::JoinInts(adj_facets, ",") << ")";
    }
  }

  // Verify src facets congruence vs dst
  vector<ccwRing> dst_rings;
  for (int facet_id = 0; facet_id < solution.facets.size(); ++facet_id) {
    const auto& facet = solution.facets[facet_id];
    LOG_IF(FATAL, facet.size() < 3) << "Facet[" << facet_id << "]("
                                    << strings::JoinInts(facet, " ")
                                    << ") has less than 3 vertices";
    ccwRing src_ring, dst_ring;
    for (const auto& i : facet) {
      bg::append(src_ring,
                 gPoint(solution.src_verts[i].x, solution.src_verts[i].y));
      bg::append(dst_ring,
                 gPoint(solution.dst_verts[i].x, solution.dst_verts[i].y));
    }
    bool mirror;
    bool error = false;
    for (int i = 1; i < src_ring.size() - 1; ++i) {
      gPoint s1 = src_ring[i];
      gPoint s2 = src_ring[i + 1];
      bg::subtract_point(s1, src_ring[0]);
      bg::subtract_point(s2, src_ring[0]);
      Q gs1 = bg::dot_product(s1, s2);
      Q gs2 = bg::dot_product(rotCCW(s1), s2);
      gPoint d1 = dst_ring[i];
      gPoint d2 = dst_ring[i + 1];
      bg::subtract_point(d1, dst_ring[0]);
      bg::subtract_point(d2, dst_ring[0]);
      Q gd1 = bg::dot_product(d1, d2);
      Q gd2 = bg::dot_product(rotCCW(d1), d2);
      // find if flipped or not with the first angle
      if (i == 1) mirror = gs2.sign() != gd2.sign();
      bool congruent = gs1 == gd1 && gs2 == (mirror ? -gd2 : gd2);
      LOG_IF(FATAL, !congruent)
          << "Facet[" << facet_id << "](" << strings::JoinInts(facet, " ")
          << ") is not congruent between source and destination: "
          << bg::wkt(src_ring) << " vs " << bg::wkt(dst_ring);
    }

    bg::correct(dst_ring);
    dst_rings.push_back(std::move(dst_ring));
  }

  // Verify dst facets shape problem silhouette
  ccwMultiPolygon dst_mpoly;
  for (const auto& ring : dst_rings) {
    ccwMultiPolygon tmp;
    bg::union_(dst_mpoly, ring, tmp);
    dst_mpoly.swap(tmp);
  }
  ccwPolygon silhouette;
  for (const auto& poly : problem.polygons) {
    ccwRing ring;
    for (const auto& v : poly) {
      bg::append(ring, gPoint(v.x, v.y));
    }
    ccwMultiPolygon out;
    if (bg::area(ring) > 0) {
      bg::union_(silhouette, ring, out);
    } else {
      bg::correct(ring);
      bg::difference(silhouette, ring, out);
    }
    if (out.size() == 0) {
      LOG(ERROR) << "Found holes before positive silhouette.";
    } else {
      LOG_IF(ERROR, out.size() > 1)
          << "Problem silhouette has disjoint polygons: " << bg::wkt(out);
      silhouette = out[0];
    }
  }
  LOG_IF(ERROR, !bg::is_valid(silhouette)) << "Problem silhouette is invalid."
                                           << bg::wkt(silhouette);
  auto silhouette_area = bg::area(silhouette);
  LOG_IF(ERROR, silhouette_area < 0 || 1 < silhouette_area)
      << "Silhouette doesn't have area between [0,1]: " << silhouette_area;
  ccwMultiPolygon diff;
  bg::sym_difference(silhouette, dst_mpoly, diff);
  if (!bg::area(diff).is_zero()) {
    LOG(WARNING) << "Destionation silhouette doesn't match.";
    ccwMultiPolygon diff1, diff2;
    bg::difference(silhouette, dst_mpoly, diff1);
    bg::difference(dst_mpoly, silhouette, diff2);
    if (FLAGS_show_figure) {
      using RealPoint = bg::model::d2::point_xy<double>;
      bg::model::multi_polygon<bg::model::polygon<RealPoint, false, false>>
          real_diff1, real_diff2;
      bg::convert(diff1, real_diff1);
      bg::convert(diff2, real_diff2);
      bg::model::box<RealPoint> rect = {{0, 0}, {1, 1}};
      bg::svg_mapper<RealPoint> mapper(
          std::cout, 1000, 1000,
          R"(width="400px" height="400px" viewBox="0 0 1000 1000")");
      mapper.add(rect);
      mapper.add(real_diff1);
      mapper.add(real_diff2);
      mapper.map(rect, "fill:none;stroke:blue;stroke-width:5");
      mapper.map(real_diff1, "fill:turquoise");
      mapper.map(real_diff2, "fill:tomato");
    }
    LOG(WARNING) << "Diff1: " << bg::wkt(diff1);
    LOG(WARNING) << "Diff2: " << bg::wkt(diff2);
  }

  // TODO: Calculate score?

  LOG(INFO) << "Validated";

  return 0;
}
<commit_msg>render intersection of silhouette differences<commit_after>#include <complex>
#include <vector>
#include <fstream>
// boost/geometry/algorithms/detail/overlay/handle_colocations.hpp:198:10:
// error: no member named 'cout' in namespace 'std'
#include <iostream>

#include "base/base.h"
#include "boost/rational.hpp"
#include <boost/geometry.hpp>
#include <boost/geometry/algorithms/area.hpp>
#include <boost/geometry/algorithms/sym_difference.hpp>
// #include <boost/geometry/algorithms/equals.hpp>
// #include <boost/geometry/algorithms/is_empty.hpp>
#include <boost/geometry/algorithms/union.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/multiprecision/gmp.hpp>
#include "polygon.h"
#include "problem.h"
#include "solution.h"

DEFINE_string(problem, "", "input problem file");
DEFINE_string(solution, "", "input solution file");
DEFINE_bool(show_figure, false, "show rich output");

namespace bg = boost::geometry;

using gPoint = bg::model::d2::point_xy<Q>;
using ccwRing = bg::model::ring<gPoint, false, false>;
using ccwPolygon = bg::model::polygon<gPoint, false, false>;
using ccwMultiPolygon = bg::model::multi_polygon<ccwPolygon>;
using namespace std;

namespace boost {
// For bg::convert across coordinate systems from gPoint to RealPoint
template <>
double numeric_cast<double>(const Q& x) {
  return x.convert_to<double>();
}
}

gPoint rotCCW(const gPoint& p) { return gPoint(-p.y(), p.x()); }

Q cross(const gPoint& lhs, const gPoint& rhs) {
  return lhs.x() * rhs.y() - lhs.y() * rhs.x();
}

// namespace boost {
// namespace multiprecision {
// // False sqrt for bg::equals
// // boost/geometry/algorithms/detail/equals/collect_vectors.hpp:138:48
// // that uses sqrt to compare vector directions with unit vectors.
// Q sqrt(const Q& q) {
//   long double x = sqrtl(q.convert_to<long double>());
//   long double i;
//   long double f = modfl(x, &i);
//   if (f == 0) return Q((long long)i);
//   int exp;
//   x = frexpl(x, &exp);
//   const int kBias = 20;
//   x = ldexpl(x, exp + 20);
//   return Q((long long)roundl(x), 1ll << kBias);
// }
// }
// }

template <typename T>
void normalize_pair(std::pair<T, T>* p) {
  if (p->second < p->first) std::swap(p->first, p->second);
}

int main(int argc, char** argv) {
  ParseCommandLineFlags(&argc, &argv);

  VLOG(2) << "Loading file " << FLAGS_problem;
  Problem problem;
  std::ifstream problem_ifs(FLAGS_problem);
  CHECK(ReadProblem(problem_ifs, &problem)) << "Failed to load file "
                                            << FLAGS_problem;
  VLOG(2) << "Loading file " << FLAGS_solution;
  Solution solution;
  std::ifstream solution_ifs(FLAGS_solution);
  CHECK(ReadSolution(solution_ifs, &solution)) << "Failed to load file "
                                               << FLAGS_solution;
  VLOG(2) << "Files loaded";

  // edge (normalized pair of vertex ids) to facet ids
  map<pair<int, int>, set<int>> edge_to_facet;
  for (int i = 0; i < solution.facets.size(); ++i) {
    for (int j = 0; j < solution.facets[i].size() - 1; ++j) {
      pair<int, int> edge(solution.facets[i][j], solution.facets[i][j + 1]);
      normalize_pair(&edge);
      edge_to_facet[edge].insert(i);
    }
  }
  for (const auto& it : edge_to_facet) {
    const auto& edge = it.first;
    const auto& adj_facets = it.second;
    if (adj_facets.size() > 2) {
      LOG(FATAL) << "Edge[" << edge.first << "," << edge.second
                 << "] is shared by more than 2 facets ("
                 << strings::JoinInts(adj_facets, ",") << ")";
    }
  }

  // Verify src facets congruence vs dst
  vector<ccwRing> dst_rings;
  for (int facet_id = 0; facet_id < solution.facets.size(); ++facet_id) {
    const auto& facet = solution.facets[facet_id];
    LOG_IF(FATAL, facet.size() < 3) << "Facet[" << facet_id << "]("
                                    << strings::JoinInts(facet, " ")
                                    << ") has less than 3 vertices";
    ccwRing src_ring, dst_ring;
    for (const auto& i : facet) {
      bg::append(src_ring,
                 gPoint(solution.src_verts[i].x, solution.src_verts[i].y));
      bg::append(dst_ring,
                 gPoint(solution.dst_verts[i].x, solution.dst_verts[i].y));
    }
    bool mirror;
    bool error = false;
    for (int i = 1; i < src_ring.size() - 1; ++i) {
      gPoint s1 = src_ring[i];
      gPoint s2 = src_ring[i + 1];
      bg::subtract_point(s1, src_ring[0]);
      bg::subtract_point(s2, src_ring[0]);
      Q gs1 = bg::dot_product(s1, s2);
      Q gs2 = bg::dot_product(rotCCW(s1), s2);
      gPoint d1 = dst_ring[i];
      gPoint d2 = dst_ring[i + 1];
      bg::subtract_point(d1, dst_ring[0]);
      bg::subtract_point(d2, dst_ring[0]);
      Q gd1 = bg::dot_product(d1, d2);
      Q gd2 = bg::dot_product(rotCCW(d1), d2);
      // find if flipped or not with the first angle
      if (i == 1) mirror = gs2.sign() != gd2.sign();
      bool congruent = gs1 == gd1 && gs2 == (mirror ? -gd2 : gd2);
      LOG_IF(FATAL, !congruent)
          << "Facet[" << facet_id << "](" << strings::JoinInts(facet, " ")
          << ") is not congruent between source and destination: "
          << bg::wkt(src_ring) << " vs " << bg::wkt(dst_ring);
    }

    bg::correct(dst_ring);
    dst_rings.push_back(std::move(dst_ring));
  }

  // Verify dst facets shape problem silhouette
  ccwMultiPolygon dst_mpoly;
  for (const auto& ring : dst_rings) {
    ccwMultiPolygon tmp;
    bg::union_(dst_mpoly, ring, tmp);
    dst_mpoly.swap(tmp);
  }
  ccwPolygon silhouette;
  for (const auto& poly : problem.polygons) {
    ccwRing ring;
    for (const auto& v : poly) {
      bg::append(ring, gPoint(v.x, v.y));
    }
    ccwMultiPolygon out;
    if (bg::area(ring) > 0) {
      bg::union_(silhouette, ring, out);
    } else {
      bg::correct(ring);
      bg::difference(silhouette, ring, out);
    }
    if (out.size() == 0) {
      LOG(ERROR) << "Found holes before positive silhouette.";
    } else {
      LOG_IF(ERROR, out.size() > 1)
          << "Problem silhouette has disjoint polygons: " << bg::wkt(out);
      silhouette = out[0];
    }
  }
  LOG_IF(ERROR, !bg::is_valid(silhouette)) << "Problem silhouette is invalid."
                                           << bg::wkt(silhouette);
  auto silhouette_area = bg::area(silhouette);
  LOG_IF(ERROR, silhouette_area < 0 || 1 < silhouette_area)
      << "Silhouette doesn't have area between [0,1]: " << silhouette_area;
  ccwMultiPolygon diff;
  bg::sym_difference(silhouette, dst_mpoly, diff);
  if (!bg::area(diff).is_zero()) {
    LOG(WARNING) << "Destionation silhouette doesn't match.";
    ccwMultiPolygon diff1, diff2, inters;
    bg::difference(silhouette, dst_mpoly, diff1);
    bg::difference(dst_mpoly, silhouette, diff2);
    bg::intersection(silhouette, dst_mpoly, inters);
    if (FLAGS_show_figure) {
      using RealPoint = bg::model::d2::point_xy<double>;
      bg::model::multi_polygon<bg::model::polygon<RealPoint, false, false>>
          real_diff1, real_diff2, real_inters;
      bg::convert(diff1, real_diff1);
      bg::convert(diff2, real_diff2);
      bg::convert(inters, real_inters);
      bg::model::box<RealPoint> rect = {{0, 0}, {1, 1}};
      bg::svg_mapper<RealPoint> mapper(
          std::cout, 1000, 1000,
          R"(width="400px" height="400px" viewBox="0 0 1000 1000")");
      mapper.add(rect);
      mapper.add(real_inters);
      mapper.add(real_diff1);
      mapper.add(real_diff2);
      mapper.map(rect, "fill:none;stroke:blue;stroke-width:5");
      mapper.map(real_inters, "fill:none;stroke:yellowgreen;stroke-width:2");
      mapper.map(real_diff1, "fill:turquoise");
      mapper.map(real_diff2, "fill:tomato");
    }
    LOG(WARNING) << "Diff1: " << bg::wkt(diff1);
    LOG(WARNING) << "Diff2: " << bg::wkt(diff2);
  }

  // TODO: Calculate score?

  LOG(INFO) << "Validated";

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>made ComponentJSONLoader work with arrays<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OResultSetMetaData.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:35:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ODBC_ORESULTSETMETADATA_HXX_
#include "odbc/OResultSetMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "odbc/OTools.hxx"
#endif

using namespace connectivity::odbc;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;

// -------------------------------------------------------------------------
OResultSetMetaData::~OResultSetMetaData()
{
}
// -------------------------------------------------------------------------
::rtl::OUString OResultSetMetaData::getCharColAttrib(sal_Int32 _column,sal_Int32 ident) throw(SQLException, RuntimeException)
{
    sal_Int32 column = _column;
    if(_column <(sal_Int32) m_vMapping.size()) // use mapping
        column = m_vMapping[_column];

    SQLSMALLINT BUFFER_LEN = 128;
    char *pName = new char[BUFFER_LEN+1];
    SQLSMALLINT nRealLen=0;
    SQLRETURN nRet = N3SQLColAttribute(m_aStatementHandle,
                                    (SQLUSMALLINT)column,
                                    (SQLUSMALLINT)ident,
                                    (SQLPOINTER)pName,
                                    BUFFER_LEN,
                                    &nRealLen,
                                    NULL
                                    );
    ::rtl::OUString sValue;
    if ( nRet == SQL_SUCCESS )
        sValue = ::rtl::OUString(pName,nRealLen,m_pConnection->getTextEncoding());
    delete [] pName;
    OTools::ThrowException(m_pConnection,nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this);
    if(nRealLen > BUFFER_LEN)
    {
        pName = new char[nRealLen+1];
        nRet = N3SQLColAttribute(m_aStatementHandle,
                                    (SQLUSMALLINT)column,
                                    (SQLUSMALLINT)ident,
                                    (SQLPOINTER)pName,
                                    nRealLen,
                                    &nRealLen,
                                    NULL
                                    );
        if ( nRet == SQL_SUCCESS )
            sValue = ::rtl::OUString(pName,nRealLen,m_pConnection->getTextEncoding());
        delete [] pName;
        OTools::ThrowException(m_pConnection,nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this);
    }

    return  sValue;
}
// -------------------------------------------------------------------------
sal_Int32 OResultSetMetaData::getNumColAttrib(sal_Int32 _column,sal_Int32 ident) throw(SQLException, RuntimeException)
{
    sal_Int32 column = _column;
    if(_column < (sal_Int32)m_vMapping.size()) // use mapping
        column = m_vMapping[_column];

    sal_Int32 nValue=0;
    sal_Int16 nLen = sizeof(nValue);
    OTools::ThrowException(m_pConnection,N3SQLColAttribute(m_aStatementHandle,
                                         (SQLUSMALLINT)column,
                                         (SQLUSMALLINT)ident,
                                         NULL,
                                         0,
                                         NULL,
                                         &nValue),m_aStatementHandle,SQL_HANDLE_STMT,*this);
    return nValue;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_DISPLAY_SIZE);
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nType = 0;
    if(!m_bUseODBC2Types)
    {
        try
        {
            nType = getNumColAttrib(column,SQL_DESC_CONCISE_TYPE);
            if(nType == SQL_UNKNOWN_TYPE)
                nType = getNumColAttrib(column, SQL_DESC_TYPE);
            nType = OTools::MapOdbcType2Jdbc(nType);
        }
        catch(SQLException& ) // in this case we have an odbc 2.0 driver
        {
            m_bUseODBC2Types = sal_True;
            nType = OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_CONCISE_TYPE ));
        }
    }
    else
        nType = OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_CONCISE_TYPE ));

    return nType;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount(  ) throw(SQLException, RuntimeException)
{
    if(m_nColCount != -1)
        return m_nColCount;
    sal_Int16 nNumResultCols=0;
    OTools::ThrowException(m_pConnection,N3SQLNumResultCols(m_aStatementHandle,&nNumResultCols),m_aStatementHandle,SQL_HANDLE_STMT,*this);
    return m_nColCount = nNumResultCols;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_CASE_SENSITIVE) == SQL_TRUE;
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_SCHEMA_NAME);
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_TABLE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_CATALOG_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_TYPE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_LABEL);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_FIXED_PREC_SCALE) == SQL_TRUE;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_AUTO_UNIQUE_VALUE) == SQL_TRUE;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UNSIGNED) == SQL_FALSE;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nType = 0;
    try
    {
        nType = getNumColAttrib(column,SQL_DESC_PRECISION);
    }
    catch(const SQLException& ) // in this case we have an odbc 2.0 driver
    {
        m_bUseODBC2Types = sal_True;
        nType = getNumColAttrib(column,SQL_COLUMN_PRECISION );
    }
    return nType;
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    sal_Int32 nType = 0;
    try
    {
        nType = getNumColAttrib(column,SQL_DESC_SCALE);
    }
    catch(const SQLException& ) // in this case we have an odbc 2.0 driver
    {
        m_bUseODBC2Types = sal_True;
        nType = getNumColAttrib(column,SQL_COLUMN_SCALE );
    }
    return nType;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_NULLABLE);
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_SEARCHABLE) != SQL_PRED_NONE;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_READONLY;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
}
// -------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS warnings01 (1.17.30); FILE MERGED 2005/11/16 12:59:21 fs 1.17.30.2: #i57457# warning free code 2005/11/07 14:44:03 fs 1.17.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OResultSetMetaData.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:56:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ODBC_ORESULTSETMETADATA_HXX_
#include "odbc/OResultSetMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "odbc/OTools.hxx"
#endif

using namespace connectivity::odbc;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;

// -------------------------------------------------------------------------
OResultSetMetaData::~OResultSetMetaData()
{
}
// -------------------------------------------------------------------------
::rtl::OUString OResultSetMetaData::getCharColAttrib(sal_Int32 _column,sal_Int32 ident) throw(SQLException, RuntimeException)
{
    sal_Int32 column = _column;
    if(_column <(sal_Int32) m_vMapping.size()) // use mapping
        column = m_vMapping[_column];

    SQLSMALLINT BUFFER_LEN = 128;
    char *pName = new char[BUFFER_LEN+1];
    SQLSMALLINT nRealLen=0;
    SQLRETURN nRet = N3SQLColAttribute(m_aStatementHandle,
                                    (SQLUSMALLINT)column,
                                    (SQLUSMALLINT)ident,
                                    (SQLPOINTER)pName,
                                    BUFFER_LEN,
                                    &nRealLen,
                                    NULL
                                    );
    ::rtl::OUString sValue;
    if ( nRet == SQL_SUCCESS )
        sValue = ::rtl::OUString(pName,nRealLen,m_pConnection->getTextEncoding());
    delete [] pName;
    OTools::ThrowException(m_pConnection,nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this);
    if(nRealLen > BUFFER_LEN)
    {
        pName = new char[nRealLen+1];
        nRet = N3SQLColAttribute(m_aStatementHandle,
                                    (SQLUSMALLINT)column,
                                    (SQLUSMALLINT)ident,
                                    (SQLPOINTER)pName,
                                    nRealLen,
                                    &nRealLen,
                                    NULL
                                    );
        if ( nRet == SQL_SUCCESS )
            sValue = ::rtl::OUString(pName,nRealLen,m_pConnection->getTextEncoding());
        delete [] pName;
        OTools::ThrowException(m_pConnection,nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this);
    }

    return  sValue;
}
// -------------------------------------------------------------------------
sal_Int32 OResultSetMetaData::getNumColAttrib(sal_Int32 _column,sal_Int32 ident) throw(SQLException, RuntimeException)
{
    sal_Int32 column = _column;
    if(_column < (sal_Int32)m_vMapping.size()) // use mapping
        column = m_vMapping[_column];

    sal_Int32 nValue=0;
    OTools::ThrowException(m_pConnection,N3SQLColAttribute(m_aStatementHandle,
                                         (SQLUSMALLINT)column,
                                         (SQLUSMALLINT)ident,
                                         NULL,
                                         0,
                                         NULL,
                                         &nValue),m_aStatementHandle,SQL_HANDLE_STMT,*this);
    return nValue;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_DISPLAY_SIZE);
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nType = 0;
    if(!m_bUseODBC2Types)
    {
        try
        {
            nType = getNumColAttrib(column,SQL_DESC_CONCISE_TYPE);
            if(nType == SQL_UNKNOWN_TYPE)
                nType = getNumColAttrib(column, SQL_DESC_TYPE);
            nType = OTools::MapOdbcType2Jdbc(nType);
        }
        catch(SQLException& ) // in this case we have an odbc 2.0 driver
        {
            m_bUseODBC2Types = sal_True;
            nType = OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_CONCISE_TYPE ));
        }
    }
    else
        nType = OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_CONCISE_TYPE ));

    return nType;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount(  ) throw(SQLException, RuntimeException)
{
    if(m_nColCount != -1)
        return m_nColCount;
    sal_Int16 nNumResultCols=0;
    OTools::ThrowException(m_pConnection,N3SQLNumResultCols(m_aStatementHandle,&nNumResultCols),m_aStatementHandle,SQL_HANDLE_STMT,*this);
    return m_nColCount = nNumResultCols;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_CASE_SENSITIVE) == SQL_TRUE;
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_SCHEMA_NAME);
}
// -------------------------------------------------------------------------

::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_TABLE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_CATALOG_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_TYPE_NAME);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getCharColAttrib(column,SQL_DESC_LABEL);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException)
{
    return ::rtl::OUString();
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_FIXED_PREC_SCALE) == SQL_TRUE;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_AUTO_UNIQUE_VALUE) == SQL_TRUE;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UNSIGNED) == SQL_FALSE;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nType = 0;
    try
    {
        nType = getNumColAttrib(column,SQL_DESC_PRECISION);
    }
    catch(const SQLException& ) // in this case we have an odbc 2.0 driver
    {
        m_bUseODBC2Types = sal_True;
        nType = getNumColAttrib(column,SQL_COLUMN_PRECISION );
    }
    return nType;
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    sal_Int32 nType = 0;
    try
    {
        nType = getNumColAttrib(column,SQL_DESC_SCALE);
    }
    catch(const SQLException& ) // in this case we have an odbc 2.0 driver
    {
        m_bUseODBC2Types = sal_True;
        nType = getNumColAttrib(column,SQL_COLUMN_SCALE );
    }
    return nType;
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_NULLABLE);
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_SEARCHABLE) != SQL_PRED_NONE;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_READONLY;
}
// -------------------------------------------------------------------------

sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE;
}
// -------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*
*** ALEX ***
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#define NOMINMAX
#include <algorithm>

#include "bt2DShape.h"

#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
#include "LinearMath/btQuaternion.h"

bt2DarcShape::bt2DarcShape(btScalar mx, btScalar my, btScalar mradius, btScalar mangle1, btScalar mangle2)
{
	x = mx;
	y = my;
	radius = mradius;
	angle1 = mangle1;
	angle2 = mangle2;
	m_shapeType = ARC_SHAPE_PROXYTYPE;
}

#include <stdio.h>
 btVector3	bt2DarcShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
	btVector3 supVec(0,0,0);

    btVector3 O1(x,y,0);

    btVector3 D( supVec-O1 );
    D.normalize();

    supVec = D * radius;

	return supVec;
}

 void	bt2DarcShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
	printf("NOT SUPPORTED!! \n");
}

void	bt2DarcShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
	//***TO DO***
	//as an approximation, take the inertia of the box that bounds the barrell

	btTransform ident;
	ident.setIdentity();

	btVector3 halfExtents;

	halfExtents.setValue((radius),
						 (radius),
						 (radius));

	btScalar margin = CONVEX_DISTANCE_MARGIN;

	btScalar lx=btScalar(2.)*(halfExtents[0]+margin);
	btScalar ly=btScalar(2.)*(halfExtents[1]+margin);
	btScalar lz=btScalar(2.)*(halfExtents[2]+margin);
	const btScalar x2 = lx*lx;
	const btScalar y2 = ly*ly;
	const btScalar z2 = lz*lz;
	const btScalar scaledmass = mass * btScalar(.08333333);

	inertia[0] = scaledmass * (y2+z2);
	inertia[1] = scaledmass * (x2+z2);
	inertia[2] = scaledmass * (x2+y2);
}

void bt2DarcShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
	btVector3 halfExtents;
	halfExtents.setValue((radius),
						 (radius),
						 (radius));

	btMatrix3x3 abs_b = t.getBasis().absolute();
	btVector3 center = t.getOrigin();
	btVector3 extent = btVector3(abs_b[0].dot(halfExtents),
		   abs_b[1].dot(halfExtents),
		  abs_b[2].dot(halfExtents));
	extent += btVector3(getMargin(),getMargin(),getMargin());

	aabbMin = center - extent;
	aabbMax = center + extent;

}

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

bt2DsegmentShape::bt2DsegmentShape(btVector3 mP1, btVector3 mP2)
{
	P1 = mP1;
	P2 = mP2;
	m_shapeType = SEGMENT_SHAPE_PROXYTYPE;
}

#include <stdio.h>
 btVector3	bt2DsegmentShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
	btVector3 supVec(0,0,0);

    btScalar L1 = (vec0-P1).length();
    btScalar L2 = (vec0-P2).length();

    if(L1<L2)
        return P1;

    return P2;
}

 void	bt2DsegmentShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
	printf("NOT SUPPORTED!! \n");
}

void	bt2DsegmentShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
	//***TO DO***
	//as an approximation, take the inertia of the box that bounds the barrell

	btTransform ident;
	ident.setIdentity();

    double hlen = 0.5*(P2-P1).length();

	btVector3 halfExtents;

	halfExtents.setValue((hlen),
						 (hlen),
						 (hlen));

	btScalar margin = CONVEX_DISTANCE_MARGIN;

	btScalar lx=btScalar(2.)*(halfExtents[0]+margin);
	btScalar ly=btScalar(2.)*(halfExtents[1]+margin);
	btScalar lz=btScalar(2.)*(halfExtents[2]+margin);
	const btScalar x2 = lx*lx;
	const btScalar y2 = ly*ly;
	const btScalar z2 = lz*lz;
	const btScalar scaledmass = mass * btScalar(.08333333);

	inertia[0] = scaledmass * (y2+z2);
	inertia[1] = scaledmass * (x2+z2);
	inertia[2] = scaledmass * (x2+y2);
}

void bt2DsegmentShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
    btVector3 mvmin (std::min(P1.x(),P2.x()), std::min(P1.y(),P2.y()), std::min(P1.z(),P2.z()));
    btVector3 mvmax (std::max(P1.x(),P2.x()), std::max(P1.y(),P2.y()), std::max(P1.z(),P2.z()));

	btMatrix3x3 abs_b = t.getBasis().absolute();
	btVector3 center = t.getOrigin();
	btVector3 vminabs = btVector3(   abs_b[0].dot(mvmin),
		                             abs_b[1].dot(mvmin),
		                             abs_b[2].dot(mvmin));
	vminabs -= btVector3(getMargin(),getMargin(),getMargin());
    btVector3 vmaxabs = btVector3(   abs_b[0].dot(mvmax),
		                             abs_b[1].dot(mvmax),
		                             abs_b[2].dot(mvmax));
	vmaxabs += btVector3(getMargin(),getMargin(),getMargin());

	aabbMin = center+vminabs;
	aabbMax = center+vmaxabs;

}

<commit_msg>Avoid warnings<commit_after>/*
*** ALEX ***
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

//#define NOMINMAX
#include <algorithm>

#include "bt2DShape.h"

#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
#include "LinearMath/btQuaternion.h"

bt2DarcShape::bt2DarcShape(btScalar mx, btScalar my, btScalar mradius, btScalar mangle1, btScalar mangle2)
{
	x = mx;
	y = my;
	radius = mradius;
	angle1 = mangle1;
	angle2 = mangle2;
	m_shapeType = ARC_SHAPE_PROXYTYPE;
}

#include <stdio.h>
 btVector3	bt2DarcShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
	btVector3 supVec(0,0,0);

    btVector3 O1(x,y,0);

    btVector3 D( supVec-O1 );
    D.normalize();

    supVec = D * radius;

	return supVec;
}

 void	bt2DarcShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
	printf("NOT SUPPORTED!! \n");
}

void	bt2DarcShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
	//***TO DO***
	//as an approximation, take the inertia of the box that bounds the barrell

	btTransform ident;
	ident.setIdentity();

	btVector3 halfExtents;

	halfExtents.setValue((radius),
						 (radius),
						 (radius));

	btScalar margin = CONVEX_DISTANCE_MARGIN;

	btScalar lx=btScalar(2.)*(halfExtents[0]+margin);
	btScalar ly=btScalar(2.)*(halfExtents[1]+margin);
	btScalar lz=btScalar(2.)*(halfExtents[2]+margin);
	const btScalar x2 = lx*lx;
	const btScalar y2 = ly*ly;
	const btScalar z2 = lz*lz;
	const btScalar scaledmass = mass * btScalar(.08333333);

	inertia[0] = scaledmass * (y2+z2);
	inertia[1] = scaledmass * (x2+z2);
	inertia[2] = scaledmass * (x2+y2);
}

void bt2DarcShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
	btVector3 halfExtents;
	halfExtents.setValue((radius),
						 (radius),
						 (radius));

	btMatrix3x3 abs_b = t.getBasis().absolute();
	btVector3 center = t.getOrigin();
	btVector3 extent = btVector3(abs_b[0].dot(halfExtents),
		   abs_b[1].dot(halfExtents),
		  abs_b[2].dot(halfExtents));
	extent += btVector3(getMargin(),getMargin(),getMargin());

	aabbMin = center - extent;
	aabbMax = center + extent;

}

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

bt2DsegmentShape::bt2DsegmentShape(btVector3 mP1, btVector3 mP2)
{
	P1 = mP1;
	P2 = mP2;
	m_shapeType = SEGMENT_SHAPE_PROXYTYPE;
}

#include <stdio.h>
 btVector3	bt2DsegmentShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
	btVector3 supVec(0,0,0);

    btScalar L1 = (vec0-P1).length();
    btScalar L2 = (vec0-P2).length();

    if(L1<L2)
        return P1;

    return P2;
}

 void	bt2DsegmentShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
	printf("NOT SUPPORTED!! \n");
}

void	bt2DsegmentShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
	//***TO DO***
	//as an approximation, take the inertia of the box that bounds the barrell

	btTransform ident;
	ident.setIdentity();

    double hlen = 0.5*(P2-P1).length();

	btVector3 halfExtents;

	halfExtents.setValue((btScalar)(hlen),
						 (btScalar)(hlen),
						 (btScalar)(hlen));

	btScalar margin = CONVEX_DISTANCE_MARGIN;

	btScalar lx=btScalar(2.)*(halfExtents[0]+margin);
	btScalar ly=btScalar(2.)*(halfExtents[1]+margin);
	btScalar lz=btScalar(2.)*(halfExtents[2]+margin);
	const btScalar x2 = lx*lx;
	const btScalar y2 = ly*ly;
	const btScalar z2 = lz*lz;
	const btScalar scaledmass = mass * btScalar(.08333333);

	inertia[0] = scaledmass * (y2+z2);
	inertia[1] = scaledmass * (x2+z2);
	inertia[2] = scaledmass * (x2+y2);
}

void bt2DsegmentShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
    btVector3 mvmin (std::min(P1.x(),P2.x()), std::min(P1.y(),P2.y()), std::min(P1.z(),P2.z()));
    btVector3 mvmax (std::max(P1.x(),P2.x()), std::max(P1.y(),P2.y()), std::max(P1.z(),P2.z()));

	btMatrix3x3 abs_b = t.getBasis().absolute();
	btVector3 center = t.getOrigin();
	btVector3 vminabs = btVector3(   abs_b[0].dot(mvmin),
		                             abs_b[1].dot(mvmin),
		                             abs_b[2].dot(mvmin));
	vminabs -= btVector3(getMargin(),getMargin(),getMargin());
    btVector3 vmaxabs = btVector3(   abs_b[0].dot(mvmax),
		                             abs_b[1].dot(mvmax),
		                             abs_b[2].dot(mvmax));
	vmaxabs += btVector3(getMargin(),getMargin(),getMargin());

	aabbMin = center+vminabs;
	aabbMax = center+vmaxabs;

}

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"

static const char* kRootFiles[] = {
  "clear.html",
//  "complex-keys.html",  // Output too big for a cookie.  crbug.com/33472
//  "complex-values.html",  // crbug.com/33472
  "quota.html",
  "remove-item.html",
  "window-attributes-exist.html",
  NULL
};

static const char* kEventsFiles[] = {
//  "basic-body-attribute.html",  // crbug.com/33472
//  "basic.html",  // crbug.com/33472
//  "basic-setattribute.html",  // crbug.com/33472
  "case-sensitive.html",
  "documentURI.html",
  NULL
};

static const char* kStorageFiles[] = {
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  "index-get-and-set.html",
  "simple-usage.html",
  "string-conversion.html",
//  "window-open.html", // TODO(jorlow): Fix
  NULL
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().
                  AppendASCII("storage").AppendASCII("domstorage")) {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    UILayoutTest::SetUp();
  }

  // We require fast/js/resources for most of the DOM Storage layout tests.
  // Add those to the list to be copied.
  void AddJSTestResources() {
    // Add other paths our tests require.
    FilePath js_dir = FilePath().
                      AppendASCII("fast").AppendASCII("js");
    AddResourceForLayoutTest(js_dir, FilePath().AppendASCII("resources"));
  }

  // This is somewhat of a hack because we're running a real browser that
  // actually persists the LocalStorage state vs. DRT and TestShell which don't.
  // The correct fix is to fix the LayoutTests, but similar patches have been
  // rejected in the past.
  void ClearDOMStorage() {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    const FilePath dir(FILE_PATH_LITERAL("layout_tests"));
    const FilePath file(FILE_PATH_LITERAL("clear_dom_storage.html"));
    GURL url = ui_test_utils::GetTestUrl(dir, file);
    ASSERT_TRUE(tab->SetCookie(url, ""));
    ASSERT_TRUE(tab->NavigateToURL(url));

    WaitUntilCookieNonEmpty(tab.get(), url, "cleared",
                            TestTimeouts::action_max_timeout_ms());
  }

  // Runs each test in an array of strings until it hits a NULL.
  void RunTests(const char** files) {
    while (*files) {
      ClearDOMStorage();
      RunLayoutTest(*files, kNoHttpPort);
      ++files;
    }
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, RootLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath(), kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("script-tests"));
  RunTests(kRootFiles);
}

TEST_F(DOMStorageTest, EventLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("events"),
                          kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events").
                                      AppendASCII("resources"));
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events").
                                      AppendASCII("script-tests"));
  RunTests(kEventsFiles);
}

TEST_F(DOMStorageTest, LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage").
                                      AppendASCII("resources"));
  RunTests(kStorageFiles);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage").
                                      AppendASCII("resources"));
  RunTests(kStorageFiles);
}

class DomStorageEmptyDatabaseTest : public UITest {
 protected:
  FilePath StorageDir() const {
    FilePath storage_dir = user_data_dir();
    storage_dir = storage_dir.AppendASCII("Default");
    storage_dir = storage_dir.AppendASCII("Local Storage");
    return storage_dir;
  }

  bool StorageDirIsEmpty() const {
    FilePath storage_dir = StorageDir();
    if (!file_util::DirectoryExists(storage_dir))
      return true;
    return file_util::IsDirectoryEmpty(storage_dir);
  }

  GURL TestUrl() const {
    FilePath test_dir = test_data_directory_;
    FilePath test_file = test_dir.AppendASCII("dom_storage_empty_db.html");
    return net::FilePathToFileURL(test_file);
  }
};

// Fails, see http://crbug.com/76008
TEST_F(DomStorageEmptyDatabaseTest, FAILS_EmptyDirAfterClear) {
  NavigateToURL(TestUrl());
  ASSERT_TRUE(StorageDirIsEmpty());

  NavigateToURL(GURL("javascript:set()"));
  NavigateToURL(GURL("javascript:clear()"));
  QuitBrowser();
  EXPECT_TRUE(StorageDirIsEmpty());
}

TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterGet) {
  NavigateToURL(TestUrl());
  ASSERT_TRUE(StorageDirIsEmpty());

  NavigateToURL(GURL("javascript:get()"));
  QuitBrowser();
  EXPECT_TRUE(StorageDirIsEmpty());
}

// Flaky, see http://crbug.com/73776
TEST_F(DomStorageEmptyDatabaseTest, FLAKY_NonEmptyDirAfterSet) {
  NavigateToURL(TestUrl());
  ASSERT_TRUE(StorageDirIsEmpty());

  NavigateToURL(GURL("javascript:set()"));
  QuitBrowser();
  EXPECT_FALSE(StorageDirIsEmpty());

  LaunchBrowserAndServer();
  NavigateToURL(TestUrl());
  NavigateToURL(GURL("javascript:clear()"));
  QuitBrowser();
  EXPECT_TRUE(StorageDirIsEmpty());
}
<commit_msg>Remove "FAILS" from DomStorageEmptyDatabaseTest.EmptyDirAfterClear.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"

static const char* kRootFiles[] = {
  "clear.html",
//  "complex-keys.html",  // Output too big for a cookie.  crbug.com/33472
//  "complex-values.html",  // crbug.com/33472
  "quota.html",
  "remove-item.html",
  "window-attributes-exist.html",
  NULL
};

static const char* kEventsFiles[] = {
//  "basic-body-attribute.html",  // crbug.com/33472
//  "basic.html",  // crbug.com/33472
//  "basic-setattribute.html",  // crbug.com/33472
  "case-sensitive.html",
  "documentURI.html",
  NULL
};

static const char* kStorageFiles[] = {
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  "index-get-and-set.html",
  "simple-usage.html",
  "string-conversion.html",
//  "window-open.html", // TODO(jorlow): Fix
  NULL
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().
                  AppendASCII("storage").AppendASCII("domstorage")) {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    UILayoutTest::SetUp();
  }

  // We require fast/js/resources for most of the DOM Storage layout tests.
  // Add those to the list to be copied.
  void AddJSTestResources() {
    // Add other paths our tests require.
    FilePath js_dir = FilePath().
                      AppendASCII("fast").AppendASCII("js");
    AddResourceForLayoutTest(js_dir, FilePath().AppendASCII("resources"));
  }

  // This is somewhat of a hack because we're running a real browser that
  // actually persists the LocalStorage state vs. DRT and TestShell which don't.
  // The correct fix is to fix the LayoutTests, but similar patches have been
  // rejected in the past.
  void ClearDOMStorage() {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    const FilePath dir(FILE_PATH_LITERAL("layout_tests"));
    const FilePath file(FILE_PATH_LITERAL("clear_dom_storage.html"));
    GURL url = ui_test_utils::GetTestUrl(dir, file);
    ASSERT_TRUE(tab->SetCookie(url, ""));
    ASSERT_TRUE(tab->NavigateToURL(url));

    WaitUntilCookieNonEmpty(tab.get(), url, "cleared",
                            TestTimeouts::action_max_timeout_ms());
  }

  // Runs each test in an array of strings until it hits a NULL.
  void RunTests(const char** files) {
    while (*files) {
      ClearDOMStorage();
      RunLayoutTest(*files, kNoHttpPort);
      ++files;
    }
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, RootLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath(), kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("script-tests"));
  RunTests(kRootFiles);
}

TEST_F(DOMStorageTest, EventLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("events"),
                          kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events").
                                      AppendASCII("resources"));
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events").
                                      AppendASCII("script-tests"));
  RunTests(kEventsFiles);
}

TEST_F(DOMStorageTest, LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage").
                                      AppendASCII("resources"));
  RunTests(kStorageFiles);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          kNoHttpPort);
  AddJSTestResources();
  AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage").
                                      AppendASCII("resources"));
  RunTests(kStorageFiles);
}

class DomStorageEmptyDatabaseTest : public UITest {
 protected:
  FilePath StorageDir() const {
    FilePath storage_dir = user_data_dir();
    storage_dir = storage_dir.AppendASCII("Default");
    storage_dir = storage_dir.AppendASCII("Local Storage");
    return storage_dir;
  }

  bool StorageDirIsEmpty() const {
    FilePath storage_dir = StorageDir();
    if (!file_util::DirectoryExists(storage_dir))
      return true;
    return file_util::IsDirectoryEmpty(storage_dir);
  }

  GURL TestUrl() const {
    FilePath test_dir = test_data_directory_;
    FilePath test_file = test_dir.AppendASCII("dom_storage_empty_db.html");
    return net::FilePathToFileURL(test_file);
  }
};

TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterClear) {
  NavigateToURL(TestUrl());
  ASSERT_TRUE(StorageDirIsEmpty());

  NavigateToURL(GURL("javascript:set()"));
  NavigateToURL(GURL("javascript:clear()"));
  QuitBrowser();
  EXPECT_TRUE(StorageDirIsEmpty());
}

TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterGet) {
  NavigateToURL(TestUrl());
  ASSERT_TRUE(StorageDirIsEmpty());

  NavigateToURL(GURL("javascript:get()"));
  QuitBrowser();
  EXPECT_TRUE(StorageDirIsEmpty());
}

// Flaky, see http://crbug.com/73776
TEST_F(DomStorageEmptyDatabaseTest, FLAKY_NonEmptyDirAfterSet) {
  NavigateToURL(TestUrl());
  ASSERT_TRUE(StorageDirIsEmpty());

  NavigateToURL(GURL("javascript:set()"));
  QuitBrowser();
  EXPECT_FALSE(StorageDirIsEmpty());

  LaunchBrowserAndServer();
  NavigateToURL(TestUrl());
  NavigateToURL(GURL("javascript:clear()"));
  QuitBrowser();
  EXPECT_TRUE(StorageDirIsEmpty());
}
<|endoftext|>