text:
namespace sol {
	namespace stack {
		template <typename T>
		struct pusher<detail::as_value_tag<T>> {
			template <typename F, typename... Args>
			static int push_fx(lua_State* L, F&& f, Args&&... args) {
				// Basically, we store all user-data like this:
				// If it's a movable/copyable value (no std::ref(x)), then we store the pointer to the new
				// data in the first sizeof(T*) bytes, and then however many bytes it takes to
				// do the actual object. Things that are std::ref or plain T* are stored as
				// just the sizeof(T*), and nothing else.
				T** pointerpointer = static_cast<T**>(lua_newuserdata(L, sizeof(T*) + sizeof(T)));
				T*& referencereference = *pointerpointer;
				T* allocationtarget = reinterpret_cast<T*>(pointerpointer + 1);
				referencereference = allocationtarget;
				std::allocator<T> alloc{};
				alloc.construct(allocationtarget, std::forward<Args>(args)...);
				f();
				return 1;
			}

			template <typename K, typename... Args>
			static int push_keyed(lua_State* L, K&& k, Args&&... args) {
				return push_fx(L, [&L, &k]() {
					luaL_newmetatable(L, &k[0]);
					lua_setmetatable(L, -2);
				}, std::forward<Args>(args)...);
			}

			template <typename... Args>
			static int push(lua_State* L, Args&&... args) {
				return push_keyed(L, usertype_traits<T>::metatable(), std::forward<Args>(args)...);
			}
		};

		template <typename T>
		struct pusher<detail::as_pointer_tag<T>> {
			template <typename F>
			static int push_fx(lua_State* L, F&& f, T* obj) {
				if (obj == nullptr)
					return stack::push(L, nil);
				T** pref = static_cast<T**>(lua_newuserdata(L, sizeof(T*)));
				*pref = obj;
				f();
				return 1;
			}

			template <typename K>
			static int push_keyed(lua_State* L, K&& k, T* obj) {
				return push_fx(L, [&L, &k]() {
					luaL_newmetatable(L, &k[0]);
					lua_setmetatable(L, -2);
				}, obj);
			}

			static int push(lua_State* L, T* obj) {
				return push_keyed(L, usertype_traits<meta::unqualified_t<T>*>::metatable(), obj);
			}
		};

		template <>
		struct pusher<detail::as_reference_tag> {
			template <typename T>
			static int push(lua_State* L, T&& obj) {
				return stack::push(L, detail::ptr(obj));
			}
		};

		template<typename T, typename>
		struct pusher {
			template <typename... Args>
			static int push(lua_State* L, Args&&... args) {
				return pusher<detail::as_value_tag<T>>{}.push(L, std::forward<Args>(args)...);
			}
		};

		template<typename T>
		struct pusher<T*, meta::disable_if_t<meta::all<meta::has_begin_end<meta::unqualified_t<T>>, meta::neg<meta::any<std::is_base_of<reference, meta::unqualified_t<T>>, std::is_base_of<stack_reference, meta::unqualified_t<T>>>>>::value>> {
			template <typename... Args>
			static int push(lua_State* L, Args&&... args) {
				return pusher<detail::as_pointer_tag<T>>{}.push(L, std::forward<Args>(args)...);
			}
		};

		template<typename T>
		struct pusher<T, std::enable_if_t<is_unique_usertype<T>::value>> {
			typedef typename unique_usertype_traits<T>::type P;
			typedef typename unique_usertype_traits<T>::actual_type Real;

			template <typename Arg, meta::enable<std::is_base_of<Real, meta::unqualified_t<Arg>>> = meta::enabler>
			static int push(lua_State* L, Arg&& arg) {
				if (unique_usertype_traits<T>::is_null(arg))
					return stack::push(L, nil);
				return push_deep(L, std::forward<Arg>(arg));
			}

			template <typename Arg0, typename Arg1, typename... Args>
			static int push(lua_State* L, Arg0&& arg0, Arg0&& arg1, Args&&... args) {
				return push_deep(L, std::forward<Arg0>(arg0), std::forward<Arg1>(arg1), std::forward<Args>(args)...);
			}

			template <typename... Args>
			static int push_deep(lua_State* L, Args&&... args) {
				P** pref = static_cast<P**>(lua_newuserdata(L, sizeof(P*) + sizeof(detail::special_destruct_func) + sizeof(Real)));
				detail::special_destruct_func* fx = static_cast<detail::special_destruct_func*>(static_cast<void*>(pref + 1));
				Real* mem = static_cast<Real*>(static_cast<void*>(fx + 1));
				*fx = detail::special_destruct<P, Real>;
				detail::default_construct::construct(mem, std::forward<Args>(args)...);
				*pref = unique_usertype_traits<T>::get(*mem);
				if (luaL_newmetatable(L, &usertype_traits<detail::unique_usertype<P>>::metatable()[0]) == 1) {
					set_field(L, "__gc", detail::unique_destruct<P>);
				}
				lua_setmetatable(L, -2);
				return 1;
			}
		};

		template<typename T>
		struct pusher<std::reference_wrapper<T>> {
			static int push(lua_State* L, const std::reference_wrapper<T>& t) {
				return stack::push(L, std::addressof(detail::deref(t.get())));
			}
		};

		template<typename T>
		struct pusher<T, std::enable_if_t<std::is_floating_point<T>::value>> {
			static int push(lua_State* L, const T& value) {
				lua_pushnumber(L, value);
				return 1;
			}
		};

		template<typename T>
		struct pusher<T, std::enable_if_t<meta::all<std::is_integral<T>, std::is_signed<T>>::value>> {
			static int push(lua_State* L, const T& value) {
				lua_pushinteger(L, static_cast<lua_Integer>(value));
				return 1;
			}
		};

		template<typename T>
		struct pusher<T, std::enable_if_t<std::is_enum<T>::value>> {
			static int push(lua_State* L, const T& value) {
				if (std::is_same<char, T>::value) {
					return stack::push(L, static_cast<int>(value));
				}
				return stack::push(L, static_cast<std::underlying_type_t<T>>(value));
			}
		};

		template<typename T>
		struct pusher<T, std::enable_if_t<meta::all<std::is_integral<T>, std::is_unsigned<T>>::value>> {
			static int push(lua_State* L, const T& value) {
				lua_pushinteger(L, static_cast<lua_Integer>(value));
				return 1;
			}
		};

		template<typename T>
		struct pusher<as_table_t<T>, std::enable_if_t<!meta::has_key_value_pair<meta::unqualified_t<std::remove_pointer_t<T>>>::value>> {
			static int push(lua_State* L, const as_table_t<T>& tablecont) {
				auto& cont = detail::deref(detail::unwrap(tablecont.source));
				lua_createtable(L, static_cast<int>(cont.size()), 0);
				int tableindex = lua_gettop(L);
				std::size_t index = 1;
				for (const auto& i : cont) {
#if SOL_LUA_VERSION >= 503
					int p = stack::push(L, i);
					for (int pi = 0; pi < p; ++pi) {
						lua_seti(L, tableindex, static_cast<lua_Integer>(index++));
					}
#else
					lua_pushinteger(L, static_cast<lua_Integer>(index));
					int p = stack::push(L, i);
					if (p == 1) {
						++index;
						lua_settable(L, tableindex);
					}
					else {
						int firstindex = tableindex + 1 + 1;
						for (int pi = 0; pi < p; ++pi) {
							stack::push(L, index);
							lua_pushvalue(L, firstindex);
							lua_settable(L, tableindex);
							++index;
							++firstindex;
						}
						lua_pop(L, 1 + p);
					}
#endif
				}
				// TODO: figure out a better way to do this...?
				//set_field(L, -1, cont.size());
				return 1;
			}
		};

		template<typename T>
		struct pusher<as_table_t<T>, std::enable_if_t<meta::has_key_value_pair<meta::unqualified_t<std::remove_pointer_t<T>>>::value>> {
			static int push(lua_State* L, const as_table_t<T>& tablecont) {
				auto& cont = detail::deref(detail::unwrap(tablecont.source));
				lua_createtable(L, static_cast<int>(cont.size()), 0);
				int tableindex = lua_gettop(L);
				for (const auto& pair : cont) {
					set_field(L, pair.first, pair.second, tableindex);
				}
				return 1;
			}
		};

		template<typename T>
		struct pusher<T, std::enable_if_t<std::is_base_of<reference, T>::value || std::is_base_of<stack_reference, T>::value>> {
			static int push(lua_State*, const T& ref) {
				return ref.push();
			}

			static int push(lua_State*, T&& ref) {
				return ref.push();
			}
		};

		template<>
		struct pusher<bool> {
			static int push(lua_State* L, bool b) {
				lua_pushboolean(L, b);
				return 1;
			}
		};

		template<>
		struct pusher<nil_t> {
			static int push(lua_State* L, nil_t) {
				lua_pushnil(L);
				return 1;
			}
		};

		template<>
		struct pusher<metatable_key_t> {
			static int push(lua_State* L, metatable_key_t) {
				lua_pushlstring(L, "__mt", 4);
				return 1;
			}
		};

		template<>
		struct pusher<std::remove_pointer_t<lua_CFunction>> {
			static int push(lua_State* L, lua_CFunction func, int n = 0) {
				lua_pushcclosure(L, func, n);
				return 1;
			}
		};

		template<>
		struct pusher<lua_CFunction> {
			static int push(lua_State* L, lua_CFunction func, int n = 0) {
				lua_pushcclosure(L, func, n);
				return 1;
			}
		};

		template<>
		struct pusher<c_closure> {
			static int push(lua_State* L, c_closure cc) {
				lua_pushcclosure(L, cc.c_function, cc.upvalues);
				return 1;
			}
		};

		template<typename Arg, typename... Args>
		struct pusher<closure<Arg, Args...>> {
			template <std::size_t... I, typename T>
			static int push(std::index_sequence<I...>, lua_State* L, T&& c) {
				int pushcount = multi_push(L, detail::forward_get<I>(c.upvalues)...);
				return stack::push(L, c_closure(c.c_function, pushcount));
			}

			template <typename T>
			static int push(lua_State* L, T&& c) {
				return push(std::make_index_sequence<1 + sizeof...(Args)>(), L, std::forward<T>(c));
			}
		};

		template<>
		struct pusher<void*> {
			static int push(lua_State* L, void* userdata) {
				lua_pushlightuserdata(L, userdata);
				return 1;
			}
		};

		template<>
		struct pusher<lightuserdata_value> {
			static int push(lua_State* L, lightuserdata_value userdata) {
				lua_pushlightuserdata(L, userdata);
				return 1;
			}
		};

		template<typename T>
		struct pusher<light<T>> {
			static int push(lua_State* L, light<T> l) {
				lua_pushlightuserdata(L, static_cast<void*>(l.value));
				return 1;
			}
		};

		template<typename T>
		struct pusher<user<T>> {
			template <bool with_meta = true, typename Key, typename... Args>
			static int push_with(lua_State* L, Key&& name, Args&&... args) {
				// A dumb pusher
				void* rawdata = lua_newuserdata(L, sizeof(T));
				T* data = static_cast<T*>(rawdata);
				std::allocator<T> alloc;
				alloc.construct(data, std::forward<Args>(args)...);
				if (with_meta) {
					lua_CFunction cdel = detail::user_alloc_destroy<T>;
					// Make sure we have a plain GC set for this data
					if (luaL_newmetatable(L, name) != 0) {
						lua_pushlightuserdata(L, rawdata);
						lua_pushcclosure(L, cdel, 1);
						lua_setfield(L, -2, "__gc");
					}
					lua_setmetatable(L, -2);
				}
				return 1;
			}

			template <typename Arg, typename... Args, meta::disable<meta::any_same<meta::unqualified_t<Arg>, no_metatable_t, metatable_key_t>> = meta::enabler>
			static int push(lua_State* L, Arg&& arg, Args&&... args) {
				const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable()[0];
				return push_with(L, name, std::forward<Arg>(arg), std::forward<Args>(args)...);
			}

			template <typename... Args>
			static int push(lua_State* L, no_metatable_t, Args&&... args) {
				const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable()[0];
				return push_with<false>(L, name, std::forward<Args>(args)...);
			}

			template <typename Key, typename... Args>
			static int push(lua_State* L, metatable_key_t, Key&& key, Args&&... args) {
				const auto name = &key[0];
				return push_with<true>(L, name, std::forward<Args>(args)...);
			}

			static int push(lua_State* L, const user<T>& u) {
				const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable()[0];
				return push_with(L, name, u.value);
			}

			static int push(lua_State* L, user<T>&& u) {
				const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable()[0];
				return push_with(L, name, std::move(u.value));
			}

			static int push(lua_State* L, no_metatable_t, const user<T>& u) {
				const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable()[0];
				return push_with<false>(L, name, u.value);
			}

			static int push(lua_State* L, no_metatable_t, user<T>&& u) {
				const auto name = &usertype_traits<meta::unqualified_t<T>>::user_gc_metatable()[0];
				return push_with<false>(L, name, std::move(u.value));
			}
		};

		template<>
		struct pusher<userdata_value> {
			static int push(lua_State* L, userdata_value data) {
				void** ud = static_cast<void**>(lua_newuserdata(L, sizeof(void*)));
				*ud = data.value;
				return 1;
			}
		};

		template<>
		struct pusher<const char*> {
			static int push_sized(lua_State* L, const char* str, std::size_t len) {
				lua_pushlstring(L, str, len);
				return 1;
			}

			static int push(lua_State* L, const char* str) {
				return push_sized(L, str, std::char_traits<char>::length(str));
			}

			static int push(lua_State* L, const char* strb, const char* stre) {
				return push_sized(L, strb, stre - strb);
			}

			static int push(lua_State* L, const char* str, std::size_t len) {
				return push_sized(L, str, len);
			}
		};

		template<size_t N>
		struct pusher<char[N]> {
			static int push(lua_State* L, const char(&str)[N]) {
				lua_pushlstring(L, str, N - 1);
				return 1;
			}

			static int push(lua_State* L, const char(&str)[N], std::size_t sz) {
				lua_pushlstring(L, str, sz);
				return 1;
			}
		};

		template <>
		struct pusher<char> {
			static int push(lua_State* L, char c) {
				const char str[2] = { c, '\0' };
				return stack::push(L, str, 1);
			}
		};

		template<>
		struct pusher<std::string> {
			static int push(lua_State* L, const std::string& str) {
				lua_pushlstring(L, str.c_str(), str.size());
				return 1;
			}

			static int push(lua_State* L, const std::string& str, std::size_t sz) {
				lua_pushlstring(L, str.c_str(), sz);
				return 1;
			}
		};

		template<>
		struct pusher<meta_function> {
			static int push(lua_State* L, meta_function m) {
				const std::string& str = name_of(m);
				lua_pushlstring(L, str.c_str(), str.size());
				return 1;
			}
		};

#ifdef SOL_CODECVT_SUPPORT
		template<>
		struct pusher<const wchar_t*> {
			static int push(lua_State* L, const wchar_t* wstr) {
				return push(L, wstr, std::char_traits<wchar_t>::length(wstr));
			}

			static int push(lua_State* L, const wchar_t* wstr, std::size_t sz) {
				return push(L, wstr, wstr + sz);
			}

			static int push(lua_State* L, const wchar_t* strb, const wchar_t* stre) {
				if (sizeof(wchar_t) == 2) {
					std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;
					std::string u8str = convert.to_bytes(strb, stre);
					return stack::push(L, u8str);
				}
				std::wstring_convert<std::codecvt_utf8<wchar_t>> convert;
				std::string u8str = convert.to_bytes(strb, stre);
				return stack::push(L, u8str);
			}
		};

		template<>
		struct pusher<const char16_t*> {
			static int push(lua_State* L, const char16_t* u16str) {
				return push(L, u16str, std::char_traits<char16_t>::length(u16str));
			}

			static int push(lua_State* L, const char16_t* u16str, std::size_t sz) {
				return push(L, u16str, u16str + sz);
			}

			static int push(lua_State* L, const char16_t* strb, const char16_t* stre) {
#ifdef _MSC_VER
				std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> convert;
				std::string u8str = convert.to_bytes(reinterpret_cast<const int16_t*>(strb), reinterpret_cast<const int16_t*>(stre));
#else
				std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
				std::string u8str = convert.to_bytes(strb, stre);
#endif // VC++ is a shit
				return stack::push(L, u8str);
			}
		};

		template<>
		struct pusher<const char32_t*> {
			static int push(lua_State* L, const char32_t* u32str) {
				return push(L, u32str, u32str + std::char_traits<char32_t>::length(u32str));
			}

			static int push(lua_State* L, const char32_t* u32str, std::size_t sz) {
				return push(L, u32str, u32str + sz);
			}

			static int push(lua_State* L, const char32_t* strb, const char32_t* stre) {
#ifdef _MSC_VER
				std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> convert;
				std::string u8str = convert.to_bytes(reinterpret_cast<const int32_t*>(strb), reinterpret_cast<const int32_t*>(stre));
#else
				std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
				std::string u8str = convert.to_bytes(strb, stre);
#endif // VC++ is a shit
				return stack::push(L, u8str);
			}
		};

		template<size_t N>
		struct pusher<wchar_t[N]> {
			static int push(lua_State* L, const wchar_t(&str)[N]) {
				return push(L, str, N - 1);
			}

			static int push(lua_State* L, const wchar_t(&str)[N], std::size_t sz) {
				return stack::push<const wchar_t*>(L, str, str + sz);
			}
		};

		template<size_t N>
		struct pusher<char16_t[N]> {
			static int push(lua_State* L, const char16_t(&str)[N]) {
				return push(L, str, N - 1);
			}

			static int push(lua_State* L, const char16_t(&str)[N], std::size_t sz) {
				return stack::push<const char16_t*>(L, str, str + sz);
			}
		};

		template<size_t N>
		struct pusher<char32_t[N]> {
			static int push(lua_State* L, const char32_t(&str)[N]) {
				return push(L, str, N - 1);
			}

			static int push(lua_State* L, const char32_t(&str)[N], std::size_t sz) {
				return stack::push<const char32_t*>(L, str, str + sz);
			}
		};

		template <>
		struct pusher<wchar_t> {
			static int push(lua_State* L, wchar_t c) {
				const wchar_t str[2] = { c, '\0' };
				return stack::push(L, str, 1);
			}
		};

		template <>
		struct pusher<char16_t> {
			static int push(lua_State* L, char16_t c) {
				const char16_t str[2] = { c, '\0' };
				return stack::push(L, str, 1);
			}
		};

		template <>
		struct pusher<char32_t> {
			static int push(lua_State* L, char32_t c) {
				const char32_t str[2] = { c, '\0' };
				return stack::push(L, str, 1);
			}
		};

		template<>
		struct pusher<std::wstring> {
			static int push(lua_State* L, const std::wstring& wstr) {
				return push(L, wstr.data(), wstr.size());
			}

			static int push(lua_State* L, const std::wstring& wstr, std::size_t sz) {
				return stack::push(L, wstr.data(), wstr.data() + sz);
			}
		};

		template<>
		struct pusher<std::u16string> {
			static int push(lua_State* L, const std::u16string& u16str) {
				return push(L, u16str, u16str.size());
			}

			static int push(lua_State* L, const std::u16string& u16str, std::size_t sz) {
				return stack::push(L, u16str.data(), u16str.data() + sz);
			}
		};

		template<>
		struct pusher<std::u32string> {
			static int push(lua_State* L, const std::u32string& u32str) {
				return push(L, u32str, u32str.size());
			}

			static int push(lua_State* L, const std::u32string& u32str, std::size_t sz) {
				return stack::push(L, u32str.data(), u32str.data() + sz);
			}
		};
#endif // codecvt Header Support

		template<typename... Args>
		struct pusher<std::tuple<Args...>> {
			template <std::size_t... I, typename T>
			static int push(std::index_sequence<I...>, lua_State* L, T&& t) {
				int pushcount = 0;
				(void)detail::swallow{ 0, (pushcount += stack::push(L,
					  detail::forward_get<I>(t)
				), 0)... };
				return pushcount;
			}

			template <typename T>
			static int push(lua_State* L, T&& t) {
				return push(std::index_sequence_for<Args...>(), L, std::forward<T>(t));
			}
		};

		template<typename A, typename B>
		struct pusher<std::pair<A, B>> {
			template <typename T>
			static int push(lua_State* L, T&& t) {
				int pushcount = stack::push(L, detail::forward_get<0>(t));
				pushcount += stack::push(L, detail::forward_get<1>(t));
				return pushcount;
			}
		};

		template<typename O>
		struct pusher<optional<O>> {
			template <typename T>
			static int push(lua_State* L, T&& t) {
				if (t == nullopt) {
					return stack::push(L, nullopt);
				}
				return stack::push(L, t.value());
			}
		};

		template<>
		struct pusher<nullopt_t> {
			static int push(lua_State* L, nullopt_t) {
				return stack::push(L, nil);
			}
		};

		template<>
		struct pusher<std::nullptr_t> {
			static int push(lua_State* L, std::nullptr_t) {
				return stack::push(L, nil);
			}
		};

		template<>
		struct pusher<this_state> {
			static int push(lua_State*, const this_state&) {
				return 0;
			}
		};
	} // stack
} // sol

#endif // SOL_STACK_PUSH_HPP


text:
.example {
  position: relative;
  padding: 10px;
  border: 1px solid #e4eaec;
}
.example .scrollable-horizontal .scrollable-content {
  width: 1400px;
}

redpajama_set_name: RedPajamaGithub


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#222222"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    tools:context="com.example.matmap.record_managers.RenameRecord">

    <EditText
        android:id="@+id/renameRecordTextField"
        android:layout_width="fill_parent"
        android:gravity="center"
        android:text=""
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginTop="20dp"
        android:textSize="50px"
        android:layout_height="70dp"
        android:textColor="#FFFFFF"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"/>

    <Button
        android:id="@+id/renameRecordButton"
        android:layout_width="fill_parent"
        android:layout_height="70dp"
        android:text="Save changes"
        android:layout_below="@id/renameRecordTextField"
        android:onClick="renameRecord"
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:layout_centerHorizontal="true"
        android:padding="10dp"/>

</RelativeLayout>


text:
The affected site should be secured utilising the latest and most
secure encryption protocols. These include SSL version 3.0 and TLS
version 1.2. While TLS 1.2 is the latest and the most preferred
protocol, not all browsers will support this encryption method.
Therefore, the more common SSL is included. Older protocols such as
SSL version 2, and weak ciphers (< 128 bit) should also be disabled.


text:
package com.wookler.server.river;

/**
 * Error type escalated by the Processors. If the processor is marked as ignore
 * getError (default) these errors will just be logged. Else the processor chain
 * will be terminated. But subscribers will continue with the subsequent
 * iterations.
 *
 * @author geiyer
 */
@SuppressWarnings("serial")
public class NonFatalProcessorException extends Exception {
    private static final String _PREFIX_ = "Non Fatal Processor Exception : ";

    /**
     * Instantiates a new non fatal processor exception with exception message
     *
     * @param mesg
     *            the exception mesg
     */
    public NonFatalProcessorException(String mesg) {
        super(_PREFIX_ + mesg);
    }

    /**
     * Instantiates a new non fatal processor exception with exception message
     * and exception cause
     *
     * @param mesg
     *            the exception mesg
     * @param inner
     *            the exception cause
     */
    public NonFatalProcessorException(String mesg, Throwable inner) {
        super(_PREFIX_ + mesg, inner);
    }
}


text:
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from baseline.tensorflow_serving.apis import classification_pb2 as tensorflow__serving_dot_apis_dot_classification__pb2
from baseline.tensorflow_serving.apis import get_model_metadata_pb2 as tensorflow__serving_dot_apis_dot_get__model__metadata__pb2
from baseline.tensorflow_serving.apis import inference_pb2 as tensorflow__serving_dot_apis_dot_inference__pb2
from baseline.tensorflow_serving.apis import predict_pb2 as tensorflow__serving_dot_apis_dot_predict__pb2
from baseline.tensorflow_serving.apis import regression_pb2 as tensorflow__serving_dot_apis_dot_regression__pb2

DESCRIPTOR = _descriptor.FileDescriptor(
  name='tensorflow_serving/apis/prediction_service.proto',
  package='tensorflow.serving',
  syntax='proto3',
  serialized_pb=_b('\n0tensorflow_serving/apis/prediction_service.proto\x12\x12tensorflow.serving\x1a,tensorflow_serving/apis/classification.proto\x1a\x30tensorflow_serving/apis/get_model_metadata.proto\x1a\'tensorflow_serving/apis/inference.proto\x1a%tensorflow_serving/apis/predict.proto\x1a(tensorflow_serving/apis/regression.proto2\xfc\x03\n\x11PredictionService\x12\x61\n\x08\x43lassify\x12).tensorflow.serving.ClassificationRequest\x1a*.tensorflow.serving.ClassificationResponse\x12X\n\x07Regress\x12%.tensorflow.serving.RegressionRequest\x1a&.tensorflow.serving.RegressionResponse\x12R\n\x07Predict\x12\".tensorflow.serving.PredictRequest\x1a#.tensorflow.serving.PredictResponse\x12g\n\x0eMultiInference\x12).tensorflow.serving.MultiInferenceRequest\x1a*.tensorflow.serving.MultiInferenceResponse\x12m\n\x10GetModelMetadata\x12+.tensorflow.serving.GetModelMetadataRequest\x1a,.tensorflow.serving.GetModelMetadataResponseB\x03\xf8\x01\x01\x62\x06proto3')
  ,
  dependencies=[tensorflow__serving_dot_apis_dot_classification__pb2.DESCRIPTOR,tensorflow__serving_dot_apis_dot_get__model__metadata__pb2.DESCRIPTOR,tensorflow__serving_dot_apis_dot_inference__pb2.DESCRIPTOR,tensorflow__serving_dot_apis_dot_predict__pb2.DESCRIPTOR,tensorflow__serving_dot_apis_dot_regression__pb2.DESCRIPTOR,])

_sym_db.RegisterFileDescriptor(DESCRIPTOR)

DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\370\001\001'))

_PREDICTIONSERVICE = _descriptor.ServiceDescriptor(
  name='PredictionService',
  full_name='tensorflow.serving.PredictionService',
  file=DESCRIPTOR,
  index=0,
  options=None,
  serialized_start=291,
  serialized_end=799,
  methods=[
  _descriptor.MethodDescriptor(
    name='Classify',
    full_name='tensorflow.serving.PredictionService.Classify',
    index=0,
    containing_service=None,
    input_type=tensorflow__serving_dot_apis_dot_classification__pb2._CLASSIFICATIONREQUEST,
    output_type=tensorflow__serving_dot_apis_dot_classification__pb2._CLASSIFICATIONRESPONSE,
    options=None,
  ),
  _descriptor.MethodDescriptor(
    name='Regress',
    full_name='tensorflow.serving.PredictionService.Regress',
    index=1,
    containing_service=None,
    input_type=tensorflow__serving_dot_apis_dot_regression__pb2._REGRESSIONREQUEST,
    output_type=tensorflow__serving_dot_apis_dot_regression__pb2._REGRESSIONRESPONSE,
    options=None,
  ),
  _descriptor.MethodDescriptor(
    name='Predict',
    full_name='tensorflow.serving.PredictionService.Predict',
    index=2,
    containing_service=None,
    input_type=tensorflow__serving_dot_apis_dot_predict__pb2._PREDICTREQUEST,
    output_type=tensorflow__serving_dot_apis_dot_predict__pb2._PREDICTRESPONSE,
    options=None,
  ),
  _descriptor.MethodDescriptor(
    name='MultiInference',
    full_name='tensorflow.serving.PredictionService.MultiInference',
    index=3,
    containing_service=None,
    input_type=tensorflow__serving_dot_apis_dot_inference__pb2._MULTIINFERENCEREQUEST,
    output_type=tensorflow__serving_dot_apis_dot_inference__pb2._MULTIINFERENCERESPONSE,
    options=None,
  ),
  _descriptor.MethodDescriptor(
    name='GetModelMetadata',
    full_name='tensorflow.serving.PredictionService.GetModelMetadata',
    index=4,
    containing_service=None,
    input_type=tensorflow__serving_dot_apis_dot_get__model__metadata__pb2._GETMODELMETADATAREQUEST,
    output_type=tensorflow__serving_dot_apis_dot_get__model__metadata__pb2._GETMODELMETADATARESPONSE,
    options=None,
  ),
])
_sym_db.RegisterServiceDescriptor(_PREDICTIONSERVICE)

DESCRIPTOR.services_by_name['PredictionService'] = _PREDICTIONSERVICE

# @@protoc_insertion_point(module_scope)


text:
#include <PiPei.h>

//
// The protocols, PPI and GUID defintions for this module
//
#include <Ppi/MasterBootMode.h>
#include <Ppi/BootInRecoveryMode.h>
#include <Ppi/GuidedSectionExtraction.h>
//
// The Library classes this module consumes
//
#include <Library/ArmPlatformLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/HobLib.h>
#include <Library/PeimEntryPoint.h>
#include <Library/PeiServicesLib.h>
#include <Library/PcdLib.h>

EFI_STATUS
EFIAPI
InitializePlatformPeim (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  );

EFI_STATUS
EFIAPI
PlatformPeim (
  VOID
  );

//
// Module globals
//
CONST EFI_PEI_PPI_DESCRIPTOR  mPpiListBootMode = {
  (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
  &gEfiPeiMasterBootModePpiGuid,
  NULL
};

CONST EFI_PEI_PPI_DESCRIPTOR  mPpiListRecoveryBootMode = {
  (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
  &gEfiPeiBootInRecoveryModePpiGuid,
  NULL
};

/*++

Routine Description:

Arguments:

  FileHandle  - Handle of the file being invoked.
  PeiServices - Describes the list of possible PEI Services.

Returns:

  Status -  EFI_SUCCESS if the boot mode could be set

--*/
EFI_STATUS
EFIAPI
InitializePlatformPeim (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )
{
  EFI_STATUS                    Status;
  EFI_BOOT_MODE                 BootMode;

  DEBUG ((EFI_D_LOAD | EFI_D_INFO, "Platform PEIM Loaded\n"));

  Status = PeiServicesSetBootMode (ArmPlatformGetBootMode ());
  ASSERT_EFI_ERROR (Status);

  PlatformPeim ();

  Status = PeiServicesGetBootMode (&BootMode);
  ASSERT_EFI_ERROR (Status);

  Status = PeiServicesInstallPpi (&mPpiListBootMode);
  ASSERT_EFI_ERROR (Status);

  if (BootMode == BOOT_IN_RECOVERY_MODE) {
    Status = PeiServicesInstallPpi (&mPpiListRecoveryBootMode);
    ASSERT_EFI_ERROR (Status);
  }

  return Status;
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Zeitung (Berlin) 7:870. 1849 Dec

#### Original name
null

### Remarks
null


text:
namespace CoinNews.Northwind {

    @Serenity.Decorators.registerClass()
    export class TerritoryDialog extends Serenity.EntityDialog<TerritoryRow, any> {
        protected getFormKey() { return TerritoryForm.formKey; }
        protected getIdProperty() { return TerritoryRow.idProperty; }
        protected getLocalTextPrefix() { return TerritoryRow.localTextPrefix; }
        protected getNameProperty() { return TerritoryRow.nameProperty; }
        protected getService() { return TerritoryService.baseUrl; }

        protected form = new TerritoryForm(this.idPrefix);

        protected getLanguages() {
            return LanguageList.getValue();
        }
    }
}


text:
<org.kie.server.api.model.definition.ProcessDefinitionList>
  <processes>
    <org.kie.server.api.model.definition.ProcessDefinition>
      <id>1</id>
      <name>Evaluation updated</name>
      <version>3</version>
      <packageName>org.jbpm</packageName>
      <containerId>evaluation_3.4</containerId>
    </org.kie.server.api.model.definition.ProcessDefinition>
    <org.kie.server.api.model.definition.ProcessDefinition>
      <id>2</id>
      <name>rewards-multi-approval</name>
      <version>2.0</version>
      <packageName>com.redhat.jboss.hr.rewards</packageName>
      <containerId>evaluation_3.4</containerId>
    </org.kie.server.api.model.definition.ProcessDefinition>
  </processes>
</org.kie.server.api.model.definition.ProcessDefinitionList>


text:
<?php
require_once realpath(__DIR__ . '/../..') . '/vendor/autoload.php';
require_once realpath(__DIR__ . '/../..') . '/Utils.php';

use Aspose\Barcode\BarcodeApi;
use Aspose\Barcode\AsposeApp;

class RecognizeBarcode {

	public $barcodeApi;

	public function __construct() {
		AsposeApp::$appSID = Utils::appSID;
		AsposeApp::$apiKey = Utils::apiKey;
		$this->barcodeApi = new BarcodeApi();
	}

	public function readBarcodeFromSpecificRegionOfImage() {

		// Set input file name
		$name = "sample-barcode.jpeg";

		// The barcode type.
		// If this parameter is empty, autodetection of all supported types is used.
		$type = "";

		// Set mode for checksum validation during recognition
		$checksumValidation = "";

		// Set if FNC symbol stripping should be performed.
		$stripFnc = "";

		// Set recognition of rotated barcode
		$rotationAngle = "";

		// Set exact number of barcodes to recognize
		$barcodesCount = "";

		// Set recognition of barcode inside specified Rectangle region
		$rectX = 10;
		$rectY = 10;
		$rectWidth = 200;
		$rectHeight = 200;

		// Set 3rd party cloud storage server (if any)
		$storage = "";

		// Set folder location at cloud storage
		$folder = "";

		// Set local file (if any)
		$file = null;

		// upload file to aspose cloud storage
		Utils::uploadFile($name);

		// invoke Aspose.BarCode Cloud SDK API to read barcode with specific region of image
		$response = $this->barcodeApi->GetBarcodeRecognize ( $name, $type, $checksumValidation, $stripFnc, $rotationAngle, $barcodesCount, $rectX, $rectY, $rectWidth, $rectHeight, $storage, $folder );
		print_r ( $response );
	}
}

$recognizeBarcode = new RecognizeBarcode();
$recognizeBarcode->readBarcodeFromSpecificRegionOfImage();

?>
//ExEnd:


text:
package org.kurento.modulecreator.codegen.function;

import java.util.List;

import org.kurento.modulecreator.definition.Return;
import org.kurento.modulecreator.definition.Type;
import org.kurento.modulecreator.definition.TypeRef;

import freemarker.ext.beans.StringModel;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

public class JavaObjectType implements TemplateMethodModelEx {

  @Override
  public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {

    Object type = arguments.get(0);

    if (type instanceof StringModel) {
      type = ((StringModel) type).getWrappedObject();
      if (type instanceof Return) {
        type = ((Return) type).getType();
      }
    }

    boolean asObject = true;
    if (arguments.size() > 1) {
      asObject = ((TemplateBooleanModel) arguments.get(1)).getAsBoolean();
    }

    if (type == null) {
      if (asObject) {
        return "Void";
      } else {
        return "void";
      }
    }

    if (type instanceof TypeRef) {
      TypeRef typeRef = (TypeRef) type;
      if (typeRef.isList()) {
        return "java.util.List<" + getTypeAsString(typeRef.getType(), true) + ">";
      } else if (typeRef.isMap()) {
        return "java.util.Map<String," + getTypeAsString(typeRef.getType(), true) + ">";
      } else {
        return getTypeAsString(typeRef.getType(), asObject);
      }
    }

    if (type instanceof Type) {
      return getTypeAsString((Type) type, asObject);
    }

    if (type instanceof String) {
      return getTypeAsString((String) type, asObject);
    }

    return type;
  }

  private String getTypeAsString(Type type, boolean asObject) {

    String typeName = type.getName();

    String typeAsString = getTypeAsString(typeName, asObject);

    if (typeAsString != null) {
      return typeAsString;
    }

    return type.getModule().getCode().getApi().get("java").get("packageName") + "." + typeName;
  }

  private String getTypeAsString(String typeName, boolean asObject) {

    if (asObject) {
      if (typeName.equals("int")) {
        return "Integer";
      } else if (typeName.equals("float")) {
        return "Float";
      } else if (typeName.equals("boolean")) {
        return "Boolean";
      } else if (typeName.equals("double")) {
        return "Double";
      } else if (typeName.equals("int64")) {
        return "Long";
      }

    } else {
      if (typeName.equals("int") || typeName.equals("float") || typeName.equals("boolean")
          || typeName.equals("double")) {
        return typeName;
      }

      if (typeName.equals("int64")) {
        return "long";
      }
    }

    if (typeName.equals("String")) {
      return typeName;
    }

    return null;
  }
}


text:
/**
 * @Title: PrruService.java
 * @Package com.sva.service
 * @Description: Prru服务类
 * @author labelCS
 * @date 2016年9月27日 上午11:29:33
 * @version V1.0
 */
package com.sva.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.sva.common.ConvertUtil;
import com.sva.common.conf.GlobalConf;
import com.sva.dao.PrruSignalDao;
import com.sva.model.LocationModel;
import com.sva.model.PrruFeatureDetailModel;
import com.sva.model.PrruFeatureModel;
import com.sva.model.PrruSignalModel;
import com.sva.web.models.PrruFeatureApiModel;

/**
 * @ClassName: PrruService
 * @Description: Prru服务类
 * @author labelCS
 * @date 2016年9月27日 上午11:29:33
 *
 */
@Service("prruService")
public class PrruService {
    /**
     * @Fields log 输出日志
     */
    private static final Logger LOG = Logger.getLogger(PrruService.class);

    /**
     * @Fields DEFAULT_VALUE : 计算特征值时的默认值
     */
    private static final BigDecimal DEFAULT_VALUE = new BigDecimal(-1400);

    /**
     * @Fields THRESHOLD : 特征值的阈值
     */
    private static final BigDecimal THRESHOLD = new BigDecimal(-1300);

    /**
     * @Fields MULTIPLE10 : 倍数10
     */
    private static final BigDecimal MULTIPLE10 = new BigDecimal(10);

    /**
     * @Fields prruSignalDao : prruSignal数据库操作DAO
     */
    @Autowired
    private PrruSignalDao prruSignalDao;

    @Value("${sva.prruRatio}")
    private String ratio;

    @Value("${sva.correction}")
    private String correction;

    @Value("${sva.prruDistance}")
    private String prruDistance;

    @Value("${prru.disArray}")
    private String disArrayStr;

    @Value("${prru.ratioArray}")
    private String ratioArrayStr;

    @Value("${prru.gppCount}")
    private String gppCount;

    /**
     * @Title: collectFeatureValue
     * @Description: 采集特征库
     * @param model
     * @return
     */
    public Map<String, Object> collectFeatureValue(PrruFeatureApiModel model){
        // 返回值
        Map<String, Object> result = new HashMap<String, Object>();
        // 检查该点是否已采集过有效的特征库
        PrruFeatureModel feature =
                prruSignalDao.getFeatureByPosition(model.getX(), model.getY(), model.getFloorNo());
        //BigDecimal radius = feature.getFeatureRadius();
        if(feature != null && feature.getFeatureRadius() != null){
            // 采集完成,且结果有效,禁止重复采集
            result.put("error", "该位置已有特征库,请勿重复采集!");
        }else{
            CollectThread thread = new CollectThread(model, prruSignalDao);
            thread.start();
            result.put("data", "采集进行中,请稍后");
        }
        return result;
    }

    /**
     * @Title: getLocationPrru
     * @Description: 根据用户id,匹配特征库,获取定位信息
     * @param userId:用户id
     * @param x 上一次定位点x坐标
     * @param y 上一次定位点y坐标
     * @return
     */
    public Map<String, Object> getLocationPrru(String userId, String x, String y, String x1, String y1, String floorNo){
        LOG.debug("用户id:"+userId);
        // 结果
        Map<String, Object> result = new HashMap<String,Object>();
        if (StringUtils.isEmpty(userId))
        {
            LOG.error("用户id为空!");
            result.put("error", "用户id为空!");
            return result;
        }
        // 取出当前用户的prru信号信息 TODO:新定位算法的场合要用另一个dao方法
        //List<PrruSignalModel> signals = prruSignalDao.getCurrentSignalByUserId(ConvertUtil.convertMacOrIp(userId));
        List<PrruSignalModel> signals = prruSignalDao.getTwoSignalByUserId(ConvertUtil.convertMacOrIp(userId));
        // 修改gpp的值,添加enbId
        editGpp(signals);
        // 取出信号信息中的柜框槽号,并拼接成字符串
        List<String> gpps = new ArrayList<String>();
        for(PrruSignalModel item : signals){
            gpps.add(item.getGpp());
            LOG.debug("用户["+userId+"]的信号信息:"+item.toString());
        }
        LOG.debug("用户柜框槽号信息:"+gpps.toString());

        // 如果未找到信号数据,返回错误信息
        if(signals.isEmpty()){
            LOG.error("用户信号数据为空");
            result.put("error", "用户信号数据为空");
            return result;
        }

        // TODO 新定位算法的场合,去重
        getAvgPrruSignals(signals, gpps);
        LOG.debug("去重后的柜框槽号信息:"+gpps.toString());
        // 获取楼层号
        if(floorNo == null || "null".equals(floorNo)){
            try{
                floorNo = prruSignalDao.queryFloorNoByUseId(ConvertUtil.convertMacOrIp(userId));
            }catch(Exception e){
                LOG.error("获取楼层号失败:" + e.getMessage());
                result.put("error", "获取楼层号失败!");
                return result;
            }
        }
        LOG.debug("用户所在楼层:"+floorNo);
        // 取出与用户信号prru有交集的特征库
        List<PrruFeatureModel> prruFeatures = prruSignalDao.getRelativeFeature(gpps,floorNo);
        // 如果没有匹配的特征库,返回错误信息
        if(prruFeatures.isEmpty()){
            LOG.error("用户信号没有匹配的特征库");
            result.put("error", "用户信号没有匹配的特征库");
            return result;
        }

        // 格式转换
        Map<Integer,PrruFeatureModel> formated = formatFeature(prruFeatures);
        // 计算最接近点
        PrruFeatureModel closest = calcClosestPoint(signals,formated,x,y,x1,y1,floorNo);
        //数据格式转换
        LocationModel data = new LocationModel();
        data.setX(new BigDecimal(closest.getX()).multiply(MULTIPLE10));
        data.setY(new BigDecimal(closest.getY()).multiply(MULTIPLE10));
        data.setZ(new BigDecimal(closest.getFloorNo()));
        data.setUserID(closest.getUserId());
        data.setTimestamp(new BigDecimal(System.currentTimeMillis()));
        data.setTimestampPrru(new BigDecimal(closest.getTimestamp()));
        // 返回
        result.put("data", data);
        return result;
    }

    /**
     * @Title: getLocationPrru
     * @Description: 根据用户id,匹配特征库,获取定位信息
     * @param userId:用户id
     * @param x 上一次定位点x坐标
     * @param y 上一次定位点y坐标
     * @return
     */
    public Map<String, Object> getLocationPrruBak(String userId, String x, String y, String floorNo){
        LOG.debug("用户id:"+userId);
        // 结果
        Map<String, Object> result = new HashMap<String,Object>();
        if (StringUtils.isEmpty(userId))
        {
            LOG.error("用户id为空!");
            result.put("error", "用户id为空!");
            return result;
        }
        // 取出当前用户的prru信号信息 TODO:新定位算法的场合要用另一个dao方法
        //List<PrruSignalModel> signals = prruSignalDao.getCurrentSignalByUserId(ConvertUtil.convertMacOrIp(userId));
        List<PrruSignalModel> signals = prruSignalDao.getTwoSignalByUserId(ConvertUtil.convertMacOrIp(userId));
        // 取出信号信息中的柜框槽号,并拼接成字符串
        List<PrruSignalModel> validSignals = new ArrayList<PrruSignalModel>();
        List<String> validGpp = new ArrayList<String>();
        for(PrruSignalModel item : signals){
            if(item.getRsrp().compareTo(DEFAULT_VALUE) > 0){
                validSignals.add(item);
                validGpp.add(item.getGpp());
            }
        }
        LOG.debug("用户柜框槽号信息:"+validGpp.toString());

        // 如果未找到信号数据,返回错误信息
        if(validSignals.isEmpty()){
            LOG.error("用户信号数据为空");
            result.put("error", "用户信号数据为空");
            return result;
        }

        // TODO 新定位算法的场合,去重
        getAvgPrruSignals(validSignals, validGpp);
        LOG.debug("去重后的柜框槽号信息:"+validGpp.toString());
        // 获取楼层号
        if(floorNo == null || "null".equals(floorNo)){
            try{
                floorNo = prruSignalDao.queryFloorNoByUseId(ConvertUtil.convertMacOrIp(userId));
            }catch(Exception e){
                LOG.error("获取楼层号失败:" + e.getMessage());
                result.put("error", "获取楼层号失败!");
                return result;
            }
        }
        LOG.debug("用户所在楼层:"+floorNo);
        // 取出与用户信号prru有交集的特征库
        List<PrruFeatureModel> prruFeatures = prruSignalDao.getRelativeFeature(validGpp,floorNo);
        // 如果没有匹配的特征库,返回错误信息
        if(prruFeatures.isEmpty()){
            LOG.error("用户信号没有匹配的特征库");
            result.put("error", "用户信号没有匹配的特征库");
            return result;
        }

        // 格式转换
        Map<Integer,PrruFeatureModel> formated = formatFeature(prruFeatures);
        // 计算最接近点
        PrruFeatureModel closest = calcClosestPoint(validSignals,formated,x,y,"","",floorNo);
        //数据格式转换
        LocationModel data = new LocationModel();
        data.setX(new BigDecimal(closest.getX()).multiply(MULTIPLE10));
        data.setY(new BigDecimal(closest.getY()).multiply(MULTIPLE10));
        data.setZ(new BigDecimal(closest.getFloorNo()));
        data.setUserID(closest.getUserId());
        data.setTimestamp(new BigDecimal(System.currentTimeMillis()));
        data.setTimestampPrru(new BigDecimal(closest.getTimestamp()));
        // 返回
        result.put("data", data);
        return result;
    }

    /**
     * @Title: checkIsFinished
     * @Description: 检查采集是否成功
     * @param model
     * @return
     */
    public Map<String,Object> checkIsFinished(PrruFeatureApiModel model){
        // 返回值
        Map<String, Object> result = new HashMap<String,Object>();
        //查看该线程是否存在
        Thread  t = GlobalConf.getPrruThread(model.getUserId());
        if (t!=null) {
            result.put("data", "waiting");
        }else
        {
            // 查询生成的特征半径
            PrruFeatureModel feature =
                    prruSignalDao.getFeatureByPosition(model.getX(), model.getY(), model.getFloorNo());
            BigDecimal radius = null;
            if(feature!=null)
            {
                radius = feature.getFeatureRadius();
            }
            // radius为null说明异常中断,否则采集完成
            if (radius==null) {
                result.put("data", "server error");
            }else
            {
                // 无效的 需要删除,否则采集数据有效
                if (radius.compareTo(model.getRadius())>0) {
                    prruSignalDao.deletFeatureById(feature.getId());
                    prruSignalDao.deleteFeatureDetailByFeatureId(feature.getId());
                    result.put("data", "failed");
                }else
                {
                    result.put("data", "success");
                }
            }
        }

        return result;
    }

    /**
     * @Title: getAllFeaturePosition
     * @Description: 获取指定楼层所有的特征点
     * @param floorNo
     * @return
     */
    public Map<String,Object> getAllFeaturePosition(String floorNo){
        // 返回值
        Map<String,Object> result = new HashMap<String,Object>();
        List<PrruFeatureModel> data = prruSignalDao.getAllFeaturePostion(floorNo);
        result.put("data", data);
        return result;
    }

    /**
     * @Title: deleteFeatureById
     * @Description: 删除指定id的特征库信息
     * @param id
     * @return
     */
    public Map<String,Object> deleteFeatureById(int id){
     // 返回值
        Map<String,Object> result = new HashMap<String,Object>();
        int res1 = prruSignalDao.deletFeatureById(id);
        int res2 = prruSignalDao.deleteFeatureDetailByFeatureId(id);
        if(res1==1 && res2==1){
            result.put("data", "success");
        }else{
            result.put("error", true);
        }
        return result;
    }

    /**
     * @Title: getCurrentPrruWithRsrp
     * @Description: 取出用户id对应的prru信息
     * @param userId
     * @return
     */
    public Map<String,Object> getCurrentPrruWithRsrp(String userId){
        // 返回值
        Map<String,Object> result = new HashMap<String,Object>();
        // 取出用户id对应的prru信息
        List<PrruSignalModel> res1 = prruSignalDao.getCurrentSignalByUserId(ConvertUtil.convertMacOrIp(userId));
        result.put("data", res1);
        return result;
       }

    /**
     * @Title: formatFeature
     * @Description: 将特征库数据转换格式,便于接下来计算
     * @param datas:源数据
     * @return
     */
    private Map<Integer,PrruFeatureModel> formatFeature(List<PrruFeatureModel> datas){
        // 转换中间格式
        Map<Integer,PrruFeatureModel> result = new HashMap<Integer,PrruFeatureModel>();
        // 遍历list,格式化
        for(PrruFeatureModel item:datas){
            // 需要整合的特征值
            PrruFeatureDetailModel detail = new PrruFeatureDetailModel();
            detail.setGpp(item.getGpp());
            detail.setFeatureValue(item.getFeatureValue());
            // 如果结构里已存在该定位点的特征信息,则将特征值加入
            if(result.get(item.getId())!=null){
                result.get(item.getId()).getFeatureValues().add(detail);
            }
            // 否则,初始化该定位点的特征信息
            else{
                List<PrruFeatureDetailModel> features = new ArrayList<PrruFeatureDetailModel>();
                features.add(detail);
                item.setFeatureValues(features);
                result.put(item.getId(), item);
            }
        }
        return result;
    }

    /**
     * @Title: calcClosestPoint
     * @Description: 计算信号对应的特征库里最接近的点
     * @param signals:信号数据
     * @param datas:特征库数据
     * @return
     */
    private PrruFeatureModel calcClosestPoint(
            List<PrruSignalModel> signals,
            Map<Integer,PrruFeatureModel> datas,
            String x,
            String y,
            String x1,
            String y1,
            String floorNo){
        // 距离阈值数组
        String[] disArray = disArrayStr.split(",");
        // 系数数组
        String[] ratioArray = ratioArrayStr.split(",");
        // 特征半径集合
        Map<Integer, BigDecimal> distance = new HashMap<Integer, BigDecimal>();

        // 遍历map,计算各个特征半径
        Iterator<Entry<Integer, PrruFeatureModel>> it = datas.entrySet().iterator();
        while(it.hasNext())
        {
            Entry<Integer, PrruFeatureModel> entity = it.next();
            int id = entity.getKey();
            PrruFeatureModel featureModel = entity.getValue();
            // 计算该点特征值得最小值
            BigDecimal minusFeature = calcMinus(featureModel);
            // 特征半径
            BigDecimal dis = new BigDecimal(0);

            for(PrruSignalModel p:signals){
                String gpp = p.getGpp();
                BigDecimal rsrp = p.getRsrp();
                BigDecimal featureValue = getFeatureValue(gpp,featureModel,minusFeature);

                dis = dis.add(rsrp.subtract(featureValue).pow(2));
            }
            LOG.debug("半径:"+dis);
            LOG.debug(featureModel.getX());
            LOG.debug(x);
            LOG.debug(featureModel.getY());
            LOG.debug(y);
            LOG.debug(featureModel.getFloorNo());
            LOG.debug(floorNo);
            LOG.debug("特征库ID:"+featureModel.getId());
            if(new BigDecimal(x).compareTo(new BigDecimal(0)) != 0 && new BigDecimal(y).compareTo(new BigDecimal(0)) != 0){
                // 如果特征点是上一个定位点,特征半径要乘以小于1的系数ratio
                if(new BigDecimal(featureModel.getX()).compareTo(new BigDecimal(x)) == 0
                        && new BigDecimal(featureModel.getY()).compareTo(new BigDecimal(y)) == 0
                        && new BigDecimal(featureModel.getFloorNo()).compareTo(new BigDecimal(floorNo)) == 0){
                    LOG.debug("找到上一个定位点:x-"+x+",y-"+y+",z-"+floorNo+"。原半径:"+dis);
                    dis = dis.multiply(new BigDecimal(ratio)).divide(new BigDecimal(100));
                    LOG.debug("乘系数后半径:"+dis);
                }
                // 如果特征点是上上一个定位点,特征半径要乘以大于1的系数correction
                else if(new BigDecimal(featureModel.getX()).compareTo(new BigDecimal(x1)) == 0
                        && new BigDecimal(featureModel.getY()).compareTo(new BigDecimal(y1)) == 0
                        && new BigDecimal(featureModel.getFloorNo()).compareTo(new BigDecimal(floorNo)) == 0){
                    LOG.debug("找到上上一个定位点:x1-"+x1+",y1-"+y1+",z-"+floorNo+"。原半径:"+dis);
                    dis = dis.multiply(new BigDecimal(correction));
                    LOG.debug("乘系数后半径:"+dis);
                }
                // 否则,特征半径要乘以对应的系数
                else if(new BigDecimal(featureModel.getFloorNo()).compareTo(new BigDecimal(floorNo)) == 0){
                    double disReal = Math.sqrt(Math.pow(Double.parseDouble(featureModel.getX()) - Double.parseDouble(x),2D)
                            + Math.pow(Double.parseDouble(featureModel.getY()) - Double.parseDouble(y),2D));
                    LOG.debug("距离:"+disReal);
                    dis = dis.multiply(findRatio(disArray, ratioArray, new BigDecimal(disReal)));
                    LOG.debug("乘系数后距离:"+dis);
                }
            }
            // 将特征半径放入集合
            distance.put(id, dis);
        }

        // 获取半径最小的key
        int minId = getKeyOfMinValue(distance);

        // 判断新定位点与上次定位点之间的距离是否超过阈值
        PrruFeatureModel currentPoint = datas.get(minId);
//        LOG.debug("本次计算的定位坐标:x-"+currentPoint.getX()+",y-"+currentPoint.getY());
//        double disReal = Math.pow(Double.parseDouble(currentPoint.getX()) - Double.parseDouble(x),2D)
//                + Math.pow(Double.parseDouble(currentPoint.getY()) - Double.parseDouble(y),2D);
//        LOG.debug("两次定位之间的距离:"+disReal);
//        // 如果超过阈值,返回上次的定位点信息
//        try{
//            if(disReal > Math.pow(Double.parseDouble(prruDistance),2D)){
//                LOG.debug("距离超过:"+Math.pow(Double.parseDouble(prruDistance),2D));
//                currentPoint = prruSignalDao.getFeatureByPositionTemp(new BigDecimal(x), new BigDecimal(y));
//                LOG.debug("数据库返回:x-"+currentPoint.getX()+",y-"+currentPoint.getY());
//            }
//        }catch(Exception e){
//            LOG.error(e);
//        }
//        if(currentPoint.getX() == null){
//            currentPoint = datas.get(minId);
//        }
        LOG.debug("返回的点:x-"+currentPoint.getX()+",y-"+currentPoint.getY()+",z-"+currentPoint.getFloorNo());
        return currentPoint;
    }

    /**
     * @Title: calcDataCheckValue
     * @Description: 计算单条信号数据的dataCheckValue
     * @param datas:信号数据
     * @return
     */
    private BigDecimal calcDataCheckValue(List<PrruSignalModel> datas){
        // 结果
        BigDecimal result = new BigDecimal(0);
        // 计数器
        int counter = 0;
        // 遍历,符合条件的求和
        for(PrruSignalModel item:datas){
            BigDecimal temp = item.getRsrp();
            if(temp.compareTo(THRESHOLD)>0){
                result = result.add(temp);
                counter++;
            }
        }
        // 返回平均值
        if(counter > 0){
            result = result.divide(new BigDecimal(counter),2);
        }
        return result;
    }

    /**
     * @Title: getFeatureValue
     * @Description: 从特征库里找出指定prru对应的特征值,没有的话使用默认值
     * @param gpp:柜框槽号
     * @param model:特征库
     * @return
     */
    private BigDecimal getFeatureValue(String gpp, PrruFeatureModel model, BigDecimal defaultVal){
        // 结果
        BigDecimal result = defaultVal;
        // 特征值list
        List<PrruFeatureDetailModel> list = model.getFeatureValues();
        // 遍历list,取出对应gpp的特征值
        for(PrruFeatureDetailModel item:list){
            if(item.getGpp().equals(gpp)){
                result = item.getFeatureValue();
                break;
            }
        }
        return result;
    }

    /**
     * @Title: getKeyOfMinValue
     * @Description: 取指定类型的map里,value最小的对应的key
     * @param data:源map
     * @return
     */
    private int getKeyOfMinValue(Map<Integer, BigDecimal> data){
        // 排序
        List<Map.Entry<Integer, BigDecimal>> entryList = new ArrayList<Map.Entry<Integer, BigDecimal>>(data.entrySet());
        Collections.sort(entryList, new Comparator<Map.Entry<Integer, BigDecimal>>() {
            public int compare(Entry<Integer, BigDecimal> entry1,
                    Entry<Integer, BigDecimal> entry2) {
                int value1 = entry1.getValue().intValue();
                int value2 = entry2.getValue().intValue();

                return value1 - value2;
            }
        });

        // 返回最小值
        return entryList.get(0).getKey();
    }

    /**
     * @Title: findRatio
     * @Description: 找到距离对应的系数
     * @param disArray
     * @param ratioArray
     * @param distance
     * @return
     */
    private BigDecimal findRatio(String[] disArray, String[] ratioArray, BigDecimal distance){
        BigDecimal result = new BigDecimal(0);
        for(int i = 0; i<disArray.length; i++){
            BigDecimal disTemp = new BigDecimal(disArray[i]);
            if(distance.compareTo(disTemp)> 0){
                result = new BigDecimal(ratioArray[i]);
            }
        }
        return result;
    }

    /**
     * @Title: getAvgPrruSignals
     * @Description: 按gpp去重
     * @param validSignals
     * @param validGpp
     */
    private void getAvgPrruSignals(List<PrruSignalModel> signals, List<String> gpps){
        Map<Long, BigDecimal> rsrpAvg = new HashMap<Long, BigDecimal>();
        Map<Long, BigDecimal> rsrpCount = new HashMap<Long, BigDecimal>();
        // 遍历
        for(int i = 0;i<signals.size();i++){
            // 时间戳
            long timestamp = signals.get(i).getTimestamp();
            // 不存在就创建
            if(rsrpAvg.get(timestamp) == null){
                rsrpAvg.put(timestamp, signals.get(i).getRsrp());
                rsrpCount.put(timestamp, new BigDecimal(1));
            }else{
                // 存在,则相加
                BigDecimal rsrpTemp = signals.get(i).getRsrp().add(rsrpAvg.get(timestamp));
                rsrpAvg.put(timestamp, rsrpTemp);
                rsrpCount.put(timestamp, rsrpCount.get(timestamp).add(new BigDecimal(1)));
            }
        }
        // 取平均值,计算checkValue
        Iterator<Entry<Long, BigDecimal>> it = rsrpAvg.entrySet().iterator();
        while(it.hasNext())
        {
            Map.Entry<Long, BigDecimal> entity = (Entry<Long, BigDecimal>) it.next();
            Long key = entity.getKey();
            BigDecimal value = entity.getValue();
            entity.setValue(value.divide(rsrpCount.get(key),2));
        }
        // 修正rsrp,得到data值
        for(PrruSignalModel p:signals){
            long timestamp = p.getTimestamp();
            p.setRsrp(p.getRsrp().subtract(rsrpAvg.get(timestamp)));
        }

        Map<String, PrruSignalModel> temp = new HashMap<String, PrruSignalModel>();
        // 遍历
        for(int i = 0;i<gpps.size();i++){
            String s = gpps.get(i);
            // gpp在map中不存在,则加入
            if(temp.get(s) == null){
                temp.put(s, signals.get(i));
                // 否则,将2个rsrp值求和取平均
            }else{
                BigDecimal secondRsrp = signals.get(i).getRsrp();
                BigDecimal firstRsrp = temp.get(s).getRsrp();
                temp.get(s).setRsrp(firstRsrp.add(secondRsrp).divide(new BigDecimal(2)));
            }
        }

        // 对入参重新赋值
        signals.clear();
        gpps.clear();
        //List<PrruSignalModel> tempList = new ArrayList<PrruSignalModel>();
        Iterator<Entry<String, PrruSignalModel>> itModel = temp.entrySet().iterator();
        while(itModel.hasNext()){
            Entry<String,PrruSignalModel> entity = itModel.next();
            //tempList.add(entity.getValue());
            gpps.add(entity.getKey());
            signals.add(entity.getValue());
        }
        /* 测试算法
        // 按gpp从高到低排序
        Collections.sort(tempList, new Comparator<PrruSignalModel>() {
            public int compare(PrruSignalModel d1,
                    PrruSignalModel d2) {
                BigDecimal value1 = d1.getRsrp();
                BigDecimal value2 = d2.getRsrp();

                return value2.compareTo(value1);
            }
        });

        // 取排序后的前gppCount个
        for(int i = 0; i < Integer.parseInt(gppCount); i++){
            // 如果tempList的个数不够,则提前结束循环
            if(i == tempList.size()){
                break;
            }

            signals.add(tempList.get(i));
            gpps.add(tempList.get(i).getGpp());
        }
        */
        LOG.debug("final rsrp:"+signals.toString());
    }

    /**
     * @Title: getAvgPrruSignals
     * @Description: 按gpp去重
     * @param validSignals
     * @param validGpp
     */
    private void getAvgPrruSignalsBak(List<PrruSignalModel> validSignals, List<String> validGpp){
        Map<String, PrruSignalModel> temp = new HashMap<String, PrruSignalModel>();
        // 遍历
        for(int i = 0;i<validGpp.size();i++){
            String s = validGpp.get(i);
            // gpp在map中不存在,则加入
            if(temp.get(s) == null){
                temp.put(s, validSignals.get(i));
                // 否则,将2个rsrp值求和取平均
            }else{
                BigDecimal secondRsrp = validSignals.get(i).getRsrp();
                BigDecimal firstRsrp = temp.get(s).getRsrp();
                temp.get(s).setRsrp(firstRsrp.add(secondRsrp).divide(new BigDecimal(2)));
            }
        }

        // 对入参重新赋值
        validSignals.clear();
        validGpp.clear();
        Iterator<Entry<String, PrruSignalModel>> it = temp.entrySet().iterator();
        while(it.hasNext()){
            Entry<String,PrruSignalModel> entity = it.next();
            validGpp.add(entity.getKey());
            validSignals.add(entity.getValue());
        }
    }

    /**
     * @Title: calcMinus
     * @Description: 计算特征值的最小值
     * @param feature
     * @return:BigDecimal
     * @throws
     */
    private BigDecimal calcMinus(PrruFeatureModel feature){
        // 特征值列表
        List<PrruFeatureDetailModel> featureValues = feature.getFeatureValues();
        // 排序
        Collections.sort(featureValues, new Comparator<PrruFeatureDetailModel>() {
            public int compare(PrruFeatureDetailModel d1,
                    PrruFeatureDetailModel d2) {
                BigDecimal value1 = d1.getFeatureValue();
                BigDecimal value2 = d2.getFeatureValue();

                return value1.compareTo(value2);
            }
        });

        // 返回最小值
        return featureValues.get(0).getFeatureValue();
    }

    /**
     * @Title: editGpp
     * @Description: gpp添加enbId标识
     * @param data
     */
    private void editGpp(List<PrruSignalModel> data){
        for(PrruSignalModel p:data){
            p.setGpp(p.getEnbid() + "__" + p.getGpp());
        }
    }
}


text:
package mdb

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/mabetle/mcore/mmodel"
)

// Xorm extends xorm.Engine and mdb.Sql.
// so we can provide more functions.
type Xorm struct {
	*xorm.Engine
}

func NewXorm(e *xorm.Engine) *Xorm {
	//logger.Trace("Create new mdb.Xorm")
	return &Xorm{Engine: e}
}

// Overide Engine.Insert
func (s Xorm) Insert(model interface{}) (int64, error) {
	return s.UuidSave(model)
}

// equal to Insert.
func (s Xorm) Save(model interface{}) (int64, error) {
	return s.Insert(model)
}

// SaveOrUpdate
func (s Xorm) SaveOrUpdate(model interface{}) (int64, error) {
	// id == ""; insert with new uuid.
	id := mmodel.GetModelId(model)
	if id == "" {
		logger.Trace("uuid save")
		return s.UuidSave(model)
	}

	// id!=null && id in db, update
	tableName := mmodel.GetModelTableName(model)
	q := fmt.Sprintf("select Id from %s where Id = ? ", tableName)
	row, _ := s.Engine.Query(q, id)
	if len(row) > 0 {
		logger.Trace("update")
		n, err := s.Engine.Id(id).Update(model)
		logger.CheckError(err)
		return n, err
	}

	// id != null && id not in db, insert with provide id
	logger.Trace("normal insert.")
	n, err := s.Engine.Insert(model)
	logger.CheckError(err)
	return n, err
}

// model must have field Id and Id not null.
func (s Xorm) Update(model interface{}) (int64, error) {
	id := mmodel.GetModelId(model)
	if id == "" {
		err := fmt.Errorf("Cannot update model without Id")
		return 0, err
	}
	n, err := s.Engine.Id(id).Update(model)
	logger.CheckError(err)
	return n, err
}

// Id is uuid value.
// model is a pointer.
func (s Xorm) UuidSave(model interface{}) (int64, error) {
	logger.Trace("UuidSave modell")
	if mmodel.GetModelId(model) == "" {
		mmodel.AddModelUuid(model)
	}
	n, err := s.Engine.Insert(model)
	logger.CheckError(err)
	return n, err
}

// GetById
func (s Xorm) GetById(model interface{}, id interface{}) (bool, error) {
	b, err := s.Engine.Id(id).Get(model)
	logger.CheckError(err)
	return b, err
}

// Migrate models
func (s Xorm) Migrate(models ...interface{}) error {
	err := s.Engine.Sync(models...)
	logger.CheckError(err)
	return err
}

// Drop
func (s Xorm) DropTables(models ...interface{}) error {
	var err error
	for _, model := range models {
		q := fmt.Sprintf("drop %s", GetTableName(model))
		_, e := s.Engine.Exec(q)
		if logger.CheckError(e) {
			err = e
		}
	}
	return err
}

func (s Xorm) DropMigrate(models ...interface{}) error {
	var err error
	e := s.DropTables(models...)
	if logger.CheckError(e) {
		err = e
	}
	e2 := s.Migrate(models...)
	if logger.CheckError(e2) {
		err = e2
	}
	return err
}

// Find wraps xorm Find.
func (s Xorm) Find(beans interface{}, condiBeans ...interface{}) error {
	err := s.Engine.Find(beans, condiBeans...)
	logger.CheckError(err)
	return err
}


text:
package com.cowthan.algrithm.java3d;

import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.ColorCube;
import javax.media.j3d.*;
import javax.vecmath.*;
import java.awt.GraphicsConfiguration;

/**
 * Simple Java 3D example program to display a spinning cube.
 */
public class HelloUniverse extends javax.swing.JFrame {

    private SimpleUniverse univ = null;
    private BranchGroup scene = null;

    public BranchGroup createSceneGraph() {
 // Create the root of the branch graph
 BranchGroup objRoot = new BranchGroup();

 // Create the TransformGroup node and initialize it to the
 // identity. Enable the TRANSFORM_WRITE capability so that
 // our behavior code can modify it at run time. Add it to
 // the root of the subgraph.
 TransformGroup objTrans = new TransformGroup();
 objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
 objRoot.addChild(objTrans);

 // Create a simple Shape3D node; add it to the scene graph.
 objTrans.addChild(new ColorCube(0.4));

 // Create a new Behavior object that will perform the
 // desired operation on the specified transform and add
 // it into the scene graph.
 Transform3D yAxis = new Transform3D();
 Alpha rotationAlpha = new Alpha(-1, 4000);

 RotationInterpolator rotator =
     new RotationInterpolator(rotationAlpha, objTrans, yAxis,
         0.0f, (float) Math.PI*2.0f);
 BoundingSphere bounds =
     new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
 rotator.setSchedulingBounds(bounds);
 objRoot.addChild(rotator);

        // Have Java 3D perform optimizations on this scene graph.
        objRoot.compile();

 return objRoot;
    }

    private Canvas3D createUniverse() {
 // Get the preferred graphics configuration for the default screen
 GraphicsConfiguration config =
     SimpleUniverse.getPreferredConfiguration();

 // Create a Canvas3D using the preferred configuration
 Canvas3D c = new Canvas3D(config);

 // Create simple universe with view branch
 univ = new SimpleUniverse(c);

 // This will move the ViewPlatform back a bit so the
 // objects in the scene can be viewed.
 univ.getViewingPlatform().setNominalViewingTransform();

 // Ensure at least 5 msec per frame (i.e., < 200Hz)
 univ.getViewer().getView().setMinimumFrameCycleTime(5);

 return c;
    }

    /**
     * Creates new form HelloUniverse
     */
    public HelloUniverse() {
 // Initialize the GUI components
 initComponents();

 // Create Canvas3D and SimpleUniverse; add canvas to drawing panel
 Canvas3D c = createUniverse();
 drawingPanel.add(c, java.awt.BorderLayout.CENTER);

 // Create the content branch and add it to the universe
 scene = createSceneGraph();
 univ.addBranchGraph(scene);
    }

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

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        drawingPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("HelloUniverse");
        drawingPanel.setLayout(new java.awt.BorderLayout());

        drawingPanel.setPreferredSize(new java.awt.Dimension(250, 250));
        getContentPane().add(drawingPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new HelloUniverse().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel drawingPanel;
    // End of variables declaration//GEN-END:variables

}


text:
date: 2016-12-15T00:00:00
draft: false
title: "Privacy Concerns"
type: "post"
---

## [Our Privacy Mission](/privacy)

There's been chatter about Snoonet, or myself Shane "rdv" Allen individually as Snoonet's owner that we log all traffic on Snoonet, which is incorrect. I'll clarify in a short, simple post.

These accusations are false, the logs are fabricated, and targeted to hinder Snoonet's vision. Snoonet does not log messages on its network, or have any ability to spy on its users. [The staff](/staff) all work together to keep each other accountable for their actions. I would be no exception, even as Snoonet's owner.

However the users on Snoonet do keep private logs of the channels they are in, which can not be avoided on any platform.

I personally was doxxed, harassed, threatened, and belittled. However, I'll take one for the team.

I made a post clarifying the situation [here on reddit](https://www.reddit.com/r/Drama/comments/5igq1w/snoonet_owner_bans_techsupport_over_a_minor/)

## SSL
If you feel your messages are being spied on by your internet service provider, the government, or even on Snoonet's end, please connect to irc.snoonet.org on port 6697.
We have a signed certificate for secure authentication.
If you need help setting up your IRC client, please ask in #help

## Extra security online
Snoonet will be working directly with [Private Internet Access](https://www.privateinternetaccess.com/) to provide users with home VPNs for their home devices. This will help increase anonymity if users such are looking for extra security online.
The details have not yet been worked out on its partnership, however we look to have the ability to offer free, or reduced payment to users on Snoonet.

## [If you would like to apply/be in the queue for a Private Internet Access VPN, make a post with this form](https://docs.google.com/forms/d/1Ot_vyJ5ak77X_qSCsQupPmUpcNe9x3hpGd7aXAGiSUA/viewform?ts=5852bf5a&edit_requested=true)

## [Snoonet's Mission Statement](/mission-statement)
This is a reminder of what Snoonet is about. Trolls will not sway this vision.


text:
#pragma once

#include <hikyuu/utilities/IniParser.h>
#include "../common/log.h"
#include "db.h"

namespace hku {

std::unique_ptr<ConnectPool<SQLiteConnect>> DB::ms_sqlite_pool;
std::unique_ptr<ConnectPool<MySQLConnect>> DB::ms_mysql_pool;

DB::snowflake_t DB::ms_userid_generator;
DB::snowflake_t DB::ms_td_id_generator;
DB::snowflake_t DB::ms_sta_id_generator;

void DB::init(const std::string& config_file) {
    if (ms_sqlite_pool || ms_mysql_pool) {
        return;
    }

    ms_userid_generator.init(1, 1);
    ms_td_id_generator.init(1, 1);
    ms_sta_id_generator.init(1, 1);

    IniParser ini;
    ini.read(config_file);

    Parameter param;
    auto options = ini.getOptionList("database");
    for (auto& option : *options) {
        param.set<string>(option, ini.get("database", option));
    }

    initDB(param);
}

void DB::initSqlite(const Parameter& param) {
    Parameter sqlite_param;
    sqlite_param.set<string>("db", param.get<string>("db"));
    sqlite_param.set<int>("flags",
                          SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX);
    ms_sqlite_pool = std::make_unique<ConnectPool<SQLiteConnect>>(sqlite_param);
}

void DB::initMysql(const Parameter& param) {
    Parameter mysql_param;
    mysql_param.set<string>("host", param.get<string>("host"));
    mysql_param.set<string>("usr", param.get<string>("usr"));
    mysql_param.set<string>("pwd", param.get<string>("pwd"));
    mysql_param.set<string>("db", param.get<string>("db"));
    mysql_param.set<int>("port", std::stoi(param.get<string>("port")));
    ms_mysql_pool = std::make_unique<ConnectPool<MySQLConnect>>(mysql_param);
}

void DB::initDB(const Parameter& params) {
    string type = params.get<string>("type");
    if (type == "sqlite3") {
        APP_TRACE("use sqlite3 database");
        initSqlite(params);
    } else if (type == "mysql") {
        APP_TRACE("use mysql database");
        initMysql(params);
    } else {
        throw std::invalid_argument(fmt::format("Invalid database type: {}", type));
    }
}

DBConnectPtr DB::getConnect() {
    return ms_sqlite_pool  ? ms_sqlite_pool->getAndWait()
           : ms_mysql_pool ? ms_mysql_pool->getAndWait()
                           : DBConnectPtr();
}

bool DB::isValidEumValue(const std::string& table, const std::string& field,
                         const std::string& val) {
    int count = getConnect()->queryInt(fmt::format(
      R"(select count(1) from td_enum where table_name="{}" and field_name="{}" and value="{}")",
      table, field, val));
    return count > 0;
}

}  // namespace hku


text:
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi.Enums
{
	 /// <summary>
	 /// SupportByVersion Excel 14, 15, 16
	 /// </summary>
	 ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.XlSpanishModes"/> </remarks>
	[SupportByVersion("Excel", 14,15,16)]
	[EntityType(EntityType.IsEnum)]
	public enum XlSpanishModes
	{
		 /// <summary>
		 /// SupportByVersion Excel 14, 15, 16
		 /// </summary>
		 /// <remarks>0</remarks>
		 [SupportByVersion("Excel", 14,15,16)]
		 xlSpanishTuteoOnly = 0,

		 /// <summary>
		 /// SupportByVersion Excel 14, 15, 16
		 /// </summary>
		 /// <remarks>1</remarks>
		 [SupportByVersion("Excel", 14,15,16)]
		 xlSpanishTuteoAndVoseo = 1,

		 /// <summary>
		 /// SupportByVersion Excel 14, 15, 16
		 /// </summary>
		 /// <remarks>2</remarks>
		 [SupportByVersion("Excel", 14,15,16)]
		 xlSpanishVoseoOnly = 2
	}
}


text:
using System.Text;

namespace System
{
    public static class StringExtensions
    {
        /// <summary>
        /// Converts a hexadecimal string into a byte array. If the string is not formed in a
        /// hexadecimal format then there will be a <see cref="FormatException"/> thrown.
        /// </summary>
        public static byte[] ToHexBytes(this string @this)
        {
            if (string.IsNullOrWhiteSpace(@this))
                return null;

            var rootHexString = @this.Replace("-", "");

            var numberOfChars = rootHexString.Length;
            if (numberOfChars % 2 != 0 || numberOfChars < 1)
            {
                return null;
            }
            var byteCount = numberOfChars / 2;
            var bytes = new byte[byteCount];
            for (var i = 0; i < byteCount; i++)
            {
                bytes[i] = Convert.ToByte(rootHexString.Substring(i * 2, 2), 16);
            }
            return bytes;
        }

        /// <summary>
        /// Converts the string into a UTF8 Byte Array
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static byte[] ToUtf8Bytes(this string @this)
        {
            if (string.IsNullOrWhiteSpace(@this))
            {
                return null;
            }
            var enc = new UTF8Encoding(false).GetBytes(@this);
            return enc;
        }
    }
}


text:
Travelling Salesman Problem

## task

- [Travelling Salesman Problem](https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm)
- [Branch and bound](https://en.wikipedia.org/wiki/Branch_and_bound) method
- [Little's Algorithm](http://dspace.mit.edu/bitstream/handle/1721.1/46828/algorithmfortrav00litt.pdf)

## dependencies

- [python](https://www.python.org/) ~ `v2.7.10`
- [graphviz](https://github.com/xflr6/graphviz) ~ `v0.6`
- [numpy](http://www.numpy.org/) ~ `v1.11.2`
- [calculator](http://habr.x1site.ru/) - for `Branch and bound` tree generation

## result

- [`report.md`](https://github.com/Drapegnik/bsu/tree/master/decision-science/lab5/report.md) -
  lab outputs


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE toc PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 2.0//EN" "http://java.sun.com/products/javahelp/toc_2_0.dtd">
<toc version="2.0">
	<tocitem text="ZAP User Guide" tocid="toplevelitem">
		<tocitem text="Add Ons" tocid="addons">
			<tocitem text="SOAP Support" image="soap-icon" target="soap">
				<tocitem text="Automation" image="soap-icon" target="soap.automation"/>
			</tocitem>
		</tocitem>
	</tocitem>
</toc>


text:
<?php

// No direct access
defined('_JEXEC') or die;

/**
 * Joomla User plugin
 *
 * @package		Joomla.Plugin
 * @subpackage	User.joomla
 * @since		1.5
 */
class plgUserJoomla extends JPlugin
{
	/**
	 * Remove all sessions for the user name
	 *
	 * Method is called after user data is deleted from the database
	 *
	 * @param	array		$user	Holds the user data
	 * @param	boolean		$succes	True if user was succesfully stored in the database
	 * @param	string		$msg	Message
	 *
	 * @return	boolean
	 * @since	1.6
	 */
	public function onUserAfterDelete($user, $succes, $msg)
	{
		if (!$succes) {
			return false;
		}

		$db = JFactory::getDbo();
		$db->setQuery(
			'DELETE FROM '.$db->quoteName('#__session') .
			' WHERE '.$db->quoteName('userid').' = '.(int) $user['id']
		);
		$db->Query();

		return true;
	}

	/**
	 * Utility method to act on a user after it has been saved.
	 *
	 * This method sends a registration email to new users created in the backend.
	 *
	 * @param	array		$user		Holds the new user data.
	 * @param	boolean		$isnew		True if a new user is stored.
	 * @param	boolean		$success	True if user was succesfully stored in the database.
	 * @param	string		$msg		Message.
	 *
	 * @return	void
	 * @since	1.6
	 */
	public function onUserAfterSave($user, $isnew, $success, $msg)
	{
		// Initialise variables.
		$app	= JFactory::getApplication();
		$config	= JFactory::getConfig();
		$mail_to_user = $this->params->get('mail_to_user', 1);

		if ($isnew) {
			// TODO: Suck in the frontend registration emails here as well. Job for a rainy day.

			if ($app->isAdmin()) {
				if ($mail_to_user) {

					// Load user_joomla plugin language (not done automatically).
					$lang = JFactory::getLanguage();
					$lang->load('plg_user_joomla', JPATH_ADMINISTRATOR);

					// Compute the mail subject.
					$emailSubject = JText::sprintf(
						'PLG_USER_JOOMLA_NEW_USER_EMAIL_SUBJECT',
						$user['name'],
						$config->get('sitename')
					);

					// Compute the mail body.
					$emailBody = JText::sprintf(
						'PLG_USER_JOOMLA_NEW_USER_EMAIL_BODY',
						$user['name'],
						$config->get('sitename'),
						JUri::root(),
						$user['username'],
						$user['password_clear']
					);

					// Assemble the email data...the sexy way!
					$mail = JFactory::getMailer()
						->setSender(
							array(
								$config->get('mailfrom'),
								$config->get('fromname')
							)
						)
						->addRecipient($user['email'])
						->setSubject($emailSubject)
						->setBody($emailBody);

					if (!$mail->Send()) {
						// TODO: Probably should raise a plugin error but this event is not error checked.
						JError::raiseWarning(500, JText::_('ERROR_SENDING_EMAIL'));
					}
				}
			}
		}
		else {
			// Existing user - nothing to do...yet.
		}
	}

	/**
	 * This method should handle any login logic and report back to the subject
	 *
	 * @param	array	$user		Holds the user data
	 * @param	array	$options	Array holding options (remember, autoregister, group)
	 *
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	public function onUserLogin($user, $options = array())
	{
		$instance = $this->_getUser($user, $options);

		// If _getUser returned an error, then pass it back.
		if ($instance instanceof Exception) {
			return false;
		}

		// If the user is blocked, redirect with an error
		if ($instance->get('block') == 1) {
			JError::raiseWarning('SOME_ERROR_CODE', JText::_('JERROR_NOLOGIN_BLOCKED'));
			return false;
		}

		// Authorise the user based on the group information
		if (!isset($options['group'])) {
			$options['group'] = 'USERS';
		}

		// Chek the user can login.
		$result	= $instance->authorise($options['action']);
		if (!$result) {

			JError::raiseWarning(401, JText::_('JERROR_LOGIN_DENIED'));
			return false;
		}

		// Mark the user as logged in
		$instance->set('guest', 0);

		// Register the needed session variables
		$session = JFactory::getSession();
		$session->set('user', $instance);

		$db = JFactory::getDBO();

		// Check to see the the session already exists.
		$app = JFactory::getApplication();
		$app->checkSession();

		// Update the user related fields for the Joomla sessions table.
		$db->setQuery(
			'UPDATE '.$db->quoteName('#__session') .
			' SET '.$db->quoteName('guest').' = '.$db->quote($instance->get('guest')).',' .
			'	'.$db->quoteName('username').' = '.$db->quote($instance->get('username')).',' .
			'	'.$db->quoteName('userid').' = '.(int) $instance->get('id') .
			' WHERE '.$db->quoteName('session_id').' = '.$db->quote($session->getId())
		);
		$db->query();

		// Hit the user last visit field
		$instance->setLastVisit();

		return true;
	}

	/**
	 * This method should handle any logout logic and report back to the subject
	 *
	 * @param	array	$user		Holds the user data.
	 * @param	array	$options	Array holding options (client, ...).
	 *
	 * @return	object	True on success
	 * @since	1.5
	 */
	public function onUserLogout($user, $options = array())
	{
		$my 		= JFactory::getUser();
		$session 	= JFactory::getSession();
		$app 		= JFactory::getApplication();

		// Make sure we're a valid user first
		if ($user['id'] == 0 && !$my->get('tmp_user')) {
			return true;
		}

		// Check to see if we're deleting the current session
		if ($my->get('id') == $user['id'] && $options['clientid'] == $app->getClientId()) {
			// Hit the user last visit field
			$my->setLastVisit();

			// Destroy the php session for this user
			$session->destroy();
		}

		// Force logout all users with that userid
		$db = JFactory::getDBO();
		$db->setQuery(
			'DELETE FROM '.$db->quoteName('#__session') .
			' WHERE '.$db->quoteName('userid').' = '.(int) $user['id'] .
			' AND '.$db->quoteName('client_id').' = '.(int) $options['clientid']
		);
		$db->query();

		return true;
	}

	/**
	 * This method will return a user object
	 *
	 * If options['autoregister'] is true, if the user doesn't exist yet he will be created
	 *
	 * @param	array	$user		Holds the user data.
	 * @param	array	$options	Array holding options (remember, autoregister, group).
	 *
	 * @return	object	A JUser object
	 * @since	1.5
	 */
	protected function _getUser($user, $options = array())
	{
		$instance = JUser::getInstance();
		if ($id = intval(JUserHelper::getUserId($user['username'])))  {
			$instance->load($id);
			return $instance;
		}

		//TODO : move this out of the plugin
		jimport('joomla.application.component.helper');
		$config	= JComponentHelper::getParams('com_users');
		// Default to Registered.
		$defaultUserGroup = $config->get('new_usertype', 2);

		$acl = JFactory::getACL();

		$instance->set('id'			, 0);
		$instance->set('name'			, $user['fullname']);
		$instance->set('username'		, $user['username']);
		$instance->set('password_clear'	, $user['password_clear']);
		$instance->set('email'			, $user['email']);	// Result should contain an email (check)
		$instance->set('usertype'		, 'deprecated');
		$instance->set('groups'		, array($defaultUserGroup));

		//If autoregister is set let's register the user
		$autoregister = isset($options['autoregister']) ? $options['autoregister'] :  $this->params->get('autoregister', 1);

		if ($autoregister) {
			if (!$instance->save()) {
				return JError::raiseWarning('SOME_ERROR_CODE', $instance->getError());
			}
		}
		else {
			// No existing user and autoregister off, this is a temporary user.
			$instance->set('tmp_user', true);
		}

		return $instance;
	}
}


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */
package org.modeshape.sequencer.ddl;

import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.modeshape.sequencer.ddl.StandardDdlLexicon.TYPE_ALTER_TABLE_STATEMENT;
import static org.modeshape.sequencer.ddl.StandardDdlLexicon.TYPE_CREATE_SCHEMA_STATEMENT;
import static org.modeshape.sequencer.ddl.StandardDdlLexicon.TYPE_DROP_SCHEMA_STATEMENT;
import static org.modeshape.sequencer.ddl.StandardDdlLexicon.TYPE_PROBLEM;
import static org.modeshape.sequencer.ddl.StandardDdlLexicon.TYPE_UNKNOWN_STATEMENT;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.modeshape.common.text.ParsingException;
import org.modeshape.sequencer.ddl.DdlParsers.ParsingResult;
import org.modeshape.sequencer.ddl.dialect.derby.DerbyDdlParser;
import org.modeshape.sequencer.ddl.dialect.oracle.OracleDdlParser;
import org.modeshape.sequencer.ddl.dialect.postgres.PostgresDdlParser;
import org.modeshape.sequencer.ddl.node.AstNode;
import org.modeshape.sequencer.ddl.node.AstNodeFactory;

/**
 *
 */
public class DdlParsersTest extends DdlParserTestHelper {
    private DdlParsers parsers;
    public static final String DDL_TEST_FILE_PATH = "ddl/";

    @Before
    public void beforeEach() {
        parsers = new DdlParsers();
    }

    @Test
    public void shouldParseUntypedDdlFileWithTypeInFilename() {
        printTest("shouldParseUntypedDdlFileWithTypeInFilename()");
        String content = "-- SAMPLE DDL FILE\n"
                         + "CREATE TABLE myTableName (PART_COLOR VARCHAR(255) NOT NULL, PART_ID INTEGER DEFAULT (100))\n"
                         + "DROP TABLE list_customers CASCADE";

        rootNode = parsers.parse(content, "someSQL92.ddl");

        assertEquals("SQL92", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));
    }

    @Test
    public void shouldParseTypedDdlFileWith() {
        printTest("shouldParseTypedDdlFileWith()");
        String content = "-- SAMPLE SQL92 DDL FILE\n"
                         + "CREATE TABLE myTableName (PART_COLOR VARCHAR(255) NOT NULL, PART_ID INTEGER DEFAULT (100))\n"
                         + "DROP TABLE list_customers CASCADE";

        rootNode = parsers.parse(content, null);

        assertEquals("SQL92", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));
    }

    @Test
    public void shouldParseUntypedDdlFile() {
        printTest("shouldParseUntypedDdlFile()");
        String content = "\n" + "-- SAMPLE DDL FILE\n"
                         + "CREATE TABLE myTableName (PART_COLOR VARCHAR(255) NOT NULL, PART_ID INTEGER DEFAULT (100))\n"
                         + "DROP TABLE list_customers CASCADE";

        rootNode = parsers.parse(content, null);

        assertEquals("SQL92", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));
    }

    @Test
    public void shouldParseUntypedDerbyFile() {
        printTest("shouldParseUntypedDerbyFile()");
        String content = getFileContent(DDL_TEST_FILE_PATH + "dialect/derby/derby_test_statements.ddl");

        rootNode = parsers.parse(content, null);

        assertEquals("DERBY", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));
    }

    @Test
    public void shouldParseTypedDerbyFile() {
        printTest("shouldParseTypedDerbyFile()");
        String content = getFileContent(DDL_TEST_FILE_PATH + "dialect/derby/derby_test_statements_typed.ddl");

        rootNode = parsers.parse(content, null);

        assertEquals("DERBY", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));
    }

    @Test
    public void shouldParseUntypedOracleFile() {
        printTest("shouldParseUntypedOracleFile()");
        String content = getFileContent(DDL_TEST_FILE_PATH + "dialect/oracle/oracle_test_statements_3.ddl");

        rootNode = parsers.parse(content, null);

        assertEquals("ORACLE", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));
    }

    @Test
    public void shouldParseUntypedPostgresFile() {
        printTest("shouldParseUntypedPostgresFile()");
        String content = getFileContent(DDL_TEST_FILE_PATH + "dialect/postgres/postgres_test_statements_1.ddl");

        rootNode = parsers.parse(content, null);

        assertThat("POSTGRES", is((String)rootNode.getProperty(StandardDdlLexicon.PARSER_ID)));
    }

    @Test
    public void shouldParseUnterminatedOracleFile() {
        printTest("shouldParseUnterminatedOracleFile()");
        String content = getFileContent(DDL_TEST_FILE_PATH + "GFM_Physical.ddl");

        rootNode = parsers.parse(content, null);
        assertEquals("ORACLE", rootNode.getProperty(StandardDdlLexicon.PARSER_ID));

        // printNodeChildren(rootNode);
        setPrintToConsole(true);

        final AstNodeFactory nodeFactory = new AstNodeFactory();
        List<AstNode> problems = nodeFactory.getChildrenForType(rootNode, TYPE_PROBLEM);
        for (AstNode problem : problems) {
            printTest(problem.toString());
        }

        assertThat(rootNode.getChildCount(), is(123));

        List<AstNode> schemaNodes = nodeFactory.getChildrenForType(rootNode, TYPE_CREATE_SCHEMA_STATEMENT);
        assertThat(schemaNodes.size(), is(1));
        assertThat(schemaNodes.get(0).getChildCount(), is(53));
        assertThat(schemaNodes.get(0).getName(), is("GLOBALFORCEMGMT"));
        List<AstNode> alterNodes = nodeFactory.getChildrenForType(rootNode, TYPE_ALTER_TABLE_STATEMENT);
        assertThat(alterNodes.size(), is(120));
        List<AstNode> dropSchemaNodes = nodeFactory.getChildrenForType(rootNode, TYPE_DROP_SCHEMA_STATEMENT);
        assertThat(dropSchemaNodes.size(), is(1));
        List<AstNode> unknownNodes = nodeFactory.getChildrenForType(rootNode, TYPE_UNKNOWN_STATEMENT);
        assertThat(unknownNodes.size(), is(1));
    }

    @Test( expected = ParsingException.class )
    public void shouldErrorWhenInvalidParserId() {
        final String content = getFileContent(DDL_TEST_FILE_PATH + "dialect/derby/derby_test_statements.ddl");
        this.parsers.parseUsing(content, "BOGUS");
    }

    @Test
    public void shouldParseHugeOracleFile() {
        printTest("shouldParseHugeOracleFile()");

        final String content = getFileContent(DDL_TEST_FILE_PATH + "dialect/oracle/huge.ddl");
        this.rootNode = this.parsers.parse(content, null);

        assertThat("ORACLE", is((String)this.rootNode.getProperty(StandardDdlLexicon.PARSER_ID)));
    }

    @Test
    public void shouldReturnBuiltInParsers() {
        printTest("shouldReturnBuiltInParsers()");

        assertThat(this.parsers.getParsers(),
                   hasItems(DdlParsers.BUILTIN_PARSERS.toArray(new DdlParser[DdlParsers.BUILTIN_PARSERS.size()])));
    }

    @Test
    public void shouldReturnParsersConstructedWith() {
        printTest("shouldReturnParsersConstructedWith()");

        final List<DdlParser> myParsers = new ArrayList<DdlParser>();
        myParsers.add(new DerbyDdlParser());

        final DdlParsers ddlParsers = new DdlParsers(myParsers);
        assertThat(ddlParsers.getParsers(), hasItems(myParsers.toArray(new DdlParser[myParsers.size()])));
    }

    @Test
    public void shouldReturnResultsInOrder() {
        printTest("shouldReturnResultsInOrder()");

        { // oracle
            final String ddl = getFileContent(DDL_TEST_FILE_PATH + "dialect/oracle/oracle_test_statements_3.ddl");
            final List<ParsingResult> results = this.parsers.parseUsingAll(ddl);

            assertThat(results.size(), is(DdlParsers.BUILTIN_PARSERS.size()));
            assertThat(results.get(0).getParserId(), is(OracleDdlParser.ID)); // first element should be Oracle result
        }

        { // derby
            final String ddl = getFileContent(DDL_TEST_FILE_PATH + "dialect/derby/derby_test_statements.ddl");
            final List<ParsingResult> results = this.parsers.parseUsingAll(ddl);

            assertThat(results.size(), is(DdlParsers.BUILTIN_PARSERS.size()));
            assertThat(results.get(0).getParserId(), is(DerbyDdlParser.ID)); // first element should be Teiid result
        }
    }

    @Test
    public void shouldReturnCorrectNumberOfResults() {
        printTest("shouldReturnCorrectNumberOfResults()");

        final List<DdlParser> myParsers = new ArrayList<DdlParser>(2);
        myParsers.add(new PostgresDdlParser());
        myParsers.add(new OracleDdlParser());
        final DdlParsers ddlParsers = new DdlParsers(myParsers);

        final String ddl = getFileContent(DDL_TEST_FILE_PATH + "dialect/oracle/oracle_test_statements_3.ddl");
        final List<ParsingResult> results = ddlParsers.parseUsing(ddl,
                                                                  myParsers.get(0).getId(),
                                                                  myParsers.get(1).getId(),
                                                                  (String[])null);
        assertThat(results.size(), is(myParsers.size()));
    }

    @Test( expected = ParsingException.class )
    public void shouldNotAllowInvalidParserId() {
        printTest("shouldNotAllowInvalidParserId()");

        final String ddl = getFileContent(DDL_TEST_FILE_PATH + "dialect/oracle/oracle_test_statements_3.ddl");
        this.parsers.parseUsing(ddl, this.parsers.getParsers().iterator().next().getId(), "bogusId", (String[])null);
    }

}


text:
/*global module */
// Karma configuration
// Generated on Tue Jan 19 2016 21:47:15 GMT+0530 (IST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'build/assets/js/foundation.js',
      'build/assets/js/templates.js',
      'build/assets/js/routes.js',
      // 'build/assets/js/FUSION_CONFIG.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'build/assets/js/app.js',
      'node_modules/ng-describe/dist/ng-describe.js',
      'tests/test_config.js',
      'tests/**/*Test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  });
};