text:
namespace net {

// static
bool DataURL::Parse(const GURL& url, std::string* mime_type,
                    std::string* charset, std::string* data) {
  DCHECK(mime_type->empty());
  DCHECK(charset->empty());
  std::string::const_iterator begin = url.spec().begin();
  std::string::const_iterator end = url.spec().end();

  std::string::const_iterator after_colon = std::find(begin, end, ':');
  if (after_colon == end)
    return false;
  ++after_colon;

  std::string::const_iterator comma = std::find(after_colon, end, ',');
  if (comma == end)
    return false;

  std::vector<std::string> meta_data;
  std::string unparsed_meta_data(after_colon, comma);
  base::SplitString(unparsed_meta_data, ';', &meta_data);

  std::vector<std::string>::iterator iter = meta_data.begin();
  if (iter != meta_data.end()) {
    mime_type->swap(*iter);
    base::StringToLowerASCII(mime_type);
    ++iter;
  }

  static const char kBase64Tag[] = "base64";
  static const char kCharsetTag[] = "charset=";
  const size_t kCharsetTagLength = arraysize(kCharsetTag) - 1;

  bool base64_encoded = false;
  for (; iter != meta_data.end(); ++iter) {
    if (!base64_encoded && *iter == kBase64Tag) {
      base64_encoded = true;
    } else if (charset->empty() &&
               iter->compare(0, kCharsetTagLength, kCharsetTag) == 0) {
      charset->assign(iter->substr(kCharsetTagLength));
    }
  }

  if (mime_type->empty()) {
    // fallback to defaults if nothing specified in the URL:
    mime_type->assign("text/plain");
  } else if (!ParseMimeTypeWithoutParameter(*mime_type, NULL, NULL)) {
    return false;
  }
  if (charset->empty())
    charset->assign("US-ASCII");

  // The caller may not be interested in receiving the data.
  if (!data)
    return true;

  // Preserve spaces if dealing with text or xml input, same as mozilla:
  //   https://bugzilla.mozilla.org/show_bug.cgi?id=138052
  // but strip them otherwise:
  //   https://bugzilla.mozilla.org/show_bug.cgi?id=37200
  // (Spaces in a data URL should be escaped, which is handled below, so any
  // spaces now are wrong. People expect to be able to enter them in the URL
  // bar for text, and it can't hurt, so we allow it.)
  std::string temp_data = std::string(comma + 1, end);

  // For base64, we may have url-escaped whitespace which is not part
  // of the data, and should be stripped. Otherwise, the escaped whitespace
  // could be part of the payload, so don't strip it.
  if (base64_encoded) {
    temp_data = UnescapeURLComponent(temp_data,
        UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS |
        UnescapeRule::CONTROL_CHARS);
  }

  // Strip whitespace.
  if (base64_encoded || !(mime_type->compare(0, 5, "text/") == 0 ||
                          mime_type->find("xml") != std::string::npos)) {
    temp_data.erase(std::remove_if(temp_data.begin(), temp_data.end(),
                                   IsAsciiWhitespace<wchar_t>),
                    temp_data.end());
  }

  if (!base64_encoded) {
    temp_data = UnescapeURLComponent(temp_data,
        UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS |
        UnescapeRule::CONTROL_CHARS);
  }

  if (base64_encoded) {
    size_t length = temp_data.length();
    size_t padding_needed = 4 - (length % 4);
    // If the input wasn't padded, then we pad it as necessary until we have a
    // length that is a multiple of 4 as required by our decoder. We don't
    // correct if the input was incorrectly padded. If |padding_needed| == 3,
    // then the input isn't well formed and decoding will fail with or without
    // padding.
    if ((padding_needed == 1 || padding_needed == 2) &&
        temp_data[length - 1] != '=') {
      temp_data.resize(length + padding_needed, '=');
    }
    return base::Base64Decode(temp_data, data);
  }

  temp_data.swap(*data);
  return true;
}

}  // namespace net


text:
DD_DETAIL_BEGIN_
struct ReferenceManagerBase_ {
	protected:
	DD_ALIAS(ThisType, ReferenceManagerBase_);

	private:
	friend ThisType& get_instance<ThisType>() DD_NOEXCEPT;

	protected:
#	if __cplusplus >= 201103L
	constexpr ReferenceManagerBase_() = default;
#	else
	ReferenceManagerBase_() throw() {
	}
#	endif

	protected:
	DD_DELETE_COPY_CONSTRUCTOR(ReferenceManagerBase_)

	protected:
	DD_DELETE_MOVE_CONSTRUCTOR(ReferenceManagerBase_)

	protected:
#	if __cplusplus >= 201103L
	virtual ~ReferenceManagerBase_() = default;
#	else
	virtual ~ReferenceManagerBase_() {
	}
#	endif

	public:
	static ThisType* get_nil_reference_manager_() DD_NOEXCEPT {
		return ::DD::address_of(get_instance<ThisType>());
	}

	public:
	virtual GlobalPointerType get_global_pointer_() const DD_NOEXCEPT {
		return GlobalPointerType();
	}

	public:
	GlobalConstPointerType get_global_const_pointer_() const DD_NOEXCEPT {
		return get_global_pointer_();
	}

	public:
	virtual LengthType get_strong_reference_count_() const DD_NOEXCEPT {
		return LengthType();
	}

	public:
	virtual LengthType get_weak_reference_count_() const DD_NOEXCEPT {
		return LengthType();
	}

	public:
	virtual ProcessType strongly_referred_() DD_NOEXCEPT {
	}

	public:
	virtual ProcessType weakly_referred_() DD_NOEXCEPT {
	}

	public:
	virtual ProcessType strongly_released_() DD_NOEXCEPT {
	}

	public:
	virtual ProcessType weakly_released_() DD_NOEXCEPT {
	}

	protected:
	DD_DELETE_ALL_ASSIGNMENTS(ReferenceManagerBase_)

};

template <typename ValueT_, typename DeleterT_, typename ThisDeleterT_>
struct ReferenceManager_ :
	protected Agent<DeleterT_>,
	protected Agent<ThisDeleterT_>,
	ReferenceManagerBase_,
	protected ReferenceCounter
{
	private:
	DD_ALIAS(DestroyAgent, Agent<DeleterT_>);
	DD_ALIAS(DestroyThisAgent, Agent<ThisDeleterT_>);
	DD_ALIAS(SuperType, ReferenceManagerBase_);
	DD_ALIAS(CounterType, ReferenceCounter);
	DD_ALIAS(ThisType, ReferenceManager_<ValueT_ DD_COMMA DeleterT_ DD_COMMA ThisDeleterT_>);
	DD_VALUE_TYPE_NESTED(ValueT_)
	DD_ALIAS(DeleterType, DeleterT_);
	DD_ALIAS(ThisDeleterType, ThisDeleterT_);

	private:
	PointerType m_pointer_;

	private:
	DD_DELETE_ALL_CONSTRUCTORS(ReferenceManager_)

	public:
	ReferenceManager_(DeleterType const& deleter_, ThisDeleterType const& this_deleter_, PointerType pointer_) DD_NOEXCEPT_IF(
		noexcept(DestroyAgent(deleter_)) && noexcept(DestroyThisAgent(this_deleter_))
	) : DestroyAgent(deleter_), DestroyThisAgent(this_deleter_), m_pointer_(pointer_) {
	}

	public:
#	if __cplusplus >= 201103L
	~ReferenceManager_() override = default;
#	else
	~ReferenceManager_() throw() {
	}
#	endif

	private:
	PointerType get_pointer_() const DD_NOEXCEPT {
		return m_pointer_;
	}

	public:
	GlobalPointerType get_global_pointer_() const DD_NOEXCEPT DD_OVERRIDE {
		return get_pointer_();
	}

	public:
	LengthType get_strong_reference_count_() const DD_NOEXCEPT DD_OVERRIDE {
		return get_strong_reference_count();
	}

	public:
	LengthType get_weak_reference_count_() const DD_NOEXCEPT DD_OVERRIDE {
		return get_weak_reference_count();
	}

	public:
	ProcessType strongly_referred_() DD_NOEXCEPT DD_OVERRIDE {
		strongly_referred();
	}

	public:
	ProcessType weakly_referred_() DD_NOEXCEPT DD_OVERRIDE {
		weakly_referred();
	}

	public:
	ProcessType strongly_released_() DD_NOEXCEPT DD_OVERRIDE {
		strongly_released();
		if (is_expired()) {
			destroy_target_();
			if (has_weak_reference()) {
				m_pointer_ = PointerType();
			} else {
				destroy_this_();
			}
		}
	}

	public:
	ProcessType weakly_released_() DD_NOEXCEPT DD_OVERRIDE {
		if (is_expired() && is_unique_weak_reference()) {
			destroy_this_();
		} else {
			weakly_released();
		}
	}

	private:
	ProcessType destroy_target_() const DD_NOEXCEPT {
		::DD::destroy(get_pointer_(), DestroyAgent::get_instance());
	}

	private:
	ProcessType destroy_this_() DD_NOEXCEPT {
		::DD::destroy(this, DestroyThisAgent::get_instance());
	}

	private:
	DD_DELETE_ALL_ASSIGNMENTS(ReferenceManager_)

};

#	if __cplusplus >= 201103L
template <typename ValueT_, typename DeleterT_>
struct AggregateReferenceManager_ : protected Agent<DeleterT_>, ReferenceManagerBase_, protected ReferenceCounter {
	private:
	using DestroyAgent = Agent<DeleterT_>;
	using SuperType = ReferenceManagerBase_;
	using CounterType = ReferenceCounter;
	using ThisType = AggregateReferenceManager_<ValueT_, DeleterT_>;
	DD_VALUE_TYPE_NESTED(ValueT_)
	using DeleterType = DeleterT_;

	private:
	SingleStorage<ValueType> mutable m_storage_;

	private:
	DD_DELETE_ALL_CONSTRUCTORS(AggregateReferenceManager_)

	public:
	template <typename... ArgumentsT__>
	AggregateReferenceManager_(DeleterType const& deleter_, ArgumentsT__&&... arguments___) noexcept(
		noexcept(DestroyAgent(deleter_)) && noexcept(m_storage_.construct(::DD::forward<ArgumentsT__>(arguments___)...))
	) : DestroyAgent(deleter_) {
		m_storage_.construct(::DD::forward<ArgumentsT__>(arguments___)...);
	}

	public:
	~AggregateReferenceManager_() override = default;

	private:
	PointerType get_pointer_() const noexcept {
		return has_strong_reference() ? m_storage_.get_pointer() : PointerType();
	}

	public:
	GlobalPointerType get_global_pointer_() const noexcept override {
		return get_pointer_();
	}

	public:
	LengthType get_strong_reference_count_() const noexcept override {
		return get_strong_reference_count();
	}

	public:
	LengthType get_weak_reference_count_() const noexcept override {
		return get_weak_reference_count();
	}

	public:
	ProcessType strongly_referred_() noexcept override {
		strongly_referred();
	}

	public:
	ProcessType weakly_referred_() noexcept override {
		weakly_referred();
	}

	public:
	ProcessType strongly_released_() noexcept override {
		strongly_released();
		if (is_expired()) {
			destruct_target_();
			if (!has_weak_reference()) {
				destroy_this_();
			}
		}
	}

	public:
	ProcessType weakly_released_() noexcept override {
		if (is_expired() && is_unique_weak_reference()) {
			destroy_this_();
		} else {
			weakly_released();
		}
	}

	private:
	ProcessType destruct_target_() const noexcept {
		m_storage_.destruct();
	}

	private:
	ProcessType destroy_this_() noexcept {
		::DD::destroy(this, DestroyAgent::get_instance());
	}

	private:
	DD_DELETE_ALL_ASSIGNMENTS(AggregateReferenceManager_)

};

#	endif
template <typename ValueT_>
struct StrongPointer;

template <typename ValueT_>
struct WeakPointer;

template <typename ValueT_>
struct StronglyReferable;

#	if __cplusplus >= 201103L
template <typename ValueT_>
inline ProcessType try_set_manager_for_strongly_referable_(
	ReferenceManagerBase_* manager_pointer_,
	StronglyReferable<ValueT_>* pointer_
) noexcept;

#	endif
template <typename ValueT_>
struct StronglyReferable {
	protected:
	DD_ALIAS(ThisType, StronglyReferable<ValueT_>);
	DD_VALUE_TYPE_NESTED(ValueT_);

	protected:
	DD_ALIAS(StrongPointerType, StrongPointer<ValueType>);
	DD_ALIAS(ConstStrongPointerType, StrongPointer<ValueConstType>);
	DD_ALIAS(WeakPointerType, WeakPointer<ValueType>);
	DD_ALIAS(ConstWeakPointerType, WeakPointer<ValueConstType>);

	private:
	DD_SPECIFIC_TYPE_NESTED(Manager, ReferenceManagerBase_);

	private:
	friend StrongPointer<void>;
#	if __cplusplus >= 201103L
	template <typename ValueT__>
	friend inline ProcessType try_set_manager_for_strongly_referable_(
		ReferenceManagerBase_* manager_pointer_,
		StronglyReferable<ValueT__>* pointer_
	) noexcept;
#	endif

	private:
	WeakPointerType m_weak_pointer_;

	protected:
	StronglyReferable() DD_NOEXCEPT;

	protected:
	StronglyReferable(ThisType const& origin_) DD_NOEXCEPT;

#	if __cplusplus >= 201103L
	protected:
	StronglyReferable(ThisType&& origin_) noexcept;

#	endif

	protected:
	StrongPointerType get_strong_pointer() DD_NOEXCEPT;

	protected:
	ConstStrongPointerType get_strong_pointer() const DD_NOEXCEPT;

	protected:
	WeakPointerType get_weak_pointer() DD_NOEXCEPT;

	protected:
	ConstWeakPointerType get_weak_pointer() const DD_NOEXCEPT;

	private:
	ProcessType set_manager_(ManagerPointerType manager_pointer_) DD_NOEXCEPT;

	protected:
	ThisType& operator =(ThisType const& origin_) DD_NOEXCEPT {
	}

#	if __cplusplus >= 201103L
	protected:
	ThisType& operator =(ThisType&& origin_) noexcept {
	}

#	endif

};

template <>
#	if __cplusplus >= 201103L
struct StrongPointer<void> : Comparable<StrongPointer<void>> {
#	else
struct StrongPointer<void> : Comparable<StrongPointer<void> > {
#	endif
	public:
	DD_ALIAS(ThisType, StrongPointer<void>);
	DD_VALUE_TYPE_NESTED(void)

	public:
	DD_ALIAS(ConstStrongType, StrongPointer<ValueConstType>);
	DD_ALIAS(WeakType, WeakPointer<ValueType>);
	DD_ALIAS(ConstWeakType, WeakPointer<ValueConstType>);

	protected:
	DD_SPECIFIC_TYPE_NESTED(Manager, ReferenceManagerBase_);

	public:
	friend ConstStrongType;
	friend WeakType;
	friend ConstWeakType;

	private:
	ManagerPointerType m_manager_pointer_ DD_IN_CLASS_INITIALIZE(get_nil_reference_manager_());

	public:
#	if __cplusplus >= 201103L
	StrongPointer() = default;
#	else
	StrongPointer() throw() : m_manager_pointer_(get_nil_reference_manager_()) {
	}
#	endif

	public:
	StrongPointer(ThisType const& origin_) DD_NOEXCEPT : m_manager_pointer_(origin_.get_manager_pointer_()) {
		get_manager_pointer_()->strongly_referred_();
	}

	public:
	StrongPointer(ThisType&& origin_) DD_NOEXCEPT : m_manager_pointer_(origin_.get_manager_pointer_()) {
		origin_.m_manager_pointer_ = get_nil_reference_manager_();
	}

	public:
	template <typename ValueT__>
	StrongPointer(ValueT__* pointer_) : m_manager_pointer_(
		create_manager_((DDCPP_DEFAULT_REFERENCE_MANAGER_ALLOCATOR), universal_deleter, pointer_, pointer_)
	) {
		get_manager_pointer_()->strongly_referred_();
	}

	protected:
	StrongPointer(ManagerPointerType manager_pointer_) DD_NOEXCEPT : m_manager_pointer_(manager_pointer_) {
		get_manager_pointer_()->strongly_referred_();
	}

#	if __cplusplus >= 201103L
	protected:
	StrongPointer(UnguardedTag tag_, ManagerPointerType manager_pointer_) DD_NOEXCEPT : m_manager_pointer_(manager_pointer_) {
	}

#	endif

	public:
	~StrongPointer() DD_NOEXCEPT {
		destruct_();
	}

	private:
	static ManagerPointerType get_nil_reference_manager_() DD_NOEXCEPT {
		return ManagerType::get_nil_reference_manager_();
	}

	protected:
	ManagerPointerType get_manager_pointer_() const DD_NOEXCEPT {
		return m_manager_pointer_;
	}

	public:
	PointerType get_global_pointer() const DD_NOEXCEPT {
		return get_manager_pointer_()->get_global_pointer_();
	}

	public:
	LengthType get_strong_reference_count() const DD_NOEXCEPT {
		return get_manager_pointer_()->get_strong_reference_count_();
	}

	public:
	LengthType get_weak_reference_count() const DD_NOEXCEPT {
		return get_manager_pointer_()->get_weak_reference_count_();
	}

	public:
	ValidityType is_valid() const DD_NOEXCEPT {
		return get_manager_pointer_() != get_nil_reference_manager_();
	}

	public:
	ValidityType is_unique() const DD_NOEXCEPT {
		return get_strong_reference_count() == LengthType(1);
	}

	public:
	ValidityType equal(ThisType const& other_) const DD_NOEXCEPT {
		return get_manager_pointer_() == other_.get_manager_pointer_();
	}

	public:
	ValidityType less(ThisType const& other_) const DD_NOEXCEPT {
		return get_manager_pointer_() < other_.get_manager_pointer_();
	}

	public:
	ProcessType swap(ThisType& other_) DD_NOEXCEPT {
		::DD::swap(m_manager_pointer_, other_.m_manager_pointer_);
	}

	public:
	ProcessType reset() DD_NOEXCEPT {
		ThisType temp_;
		swap(temp_);
	}

	public:
	ProcessType reset(ThisType const& origin_) DD_NOEXCEPT {
		ThisType temp_(origin_);
		swap(temp_);
	}

#	if __cplusplus >= 201103L
	public:
	ProcessType reset(ThisType&& origin_) noexcept {
		swap(origin_);
	}

#	endif

	private:
	template <typename AllocatorT__, typename DeleterT__, typename ValueT__>
	static ManagerPointerType create_manager_(
		AllocatorT__ allocator___,
		DeleterT__ const& deleter___,
		ValueT__* pointer_,
		StronglyReferable<ValueT__>* strongly_referable_target_
	) {
		ManagerPointerType result_ = create_manager_(allocator___, deleter___, pointer_);
		strongly_referable_target_->set_manager_(result_);
		return result_;
	}

	private:
	template <typename AllocatorT__, typename DeleterT__, typename ValueT__>
	static ManagerPointerType create_manager_(
		AllocatorT__ allocator___,
		DeleterT__ const& deleter___,
		ValueT__* pointer_,
		void const volatile* workaround_
	) {
		if (pointer_) {
			ReferenceManager_<
				ValueT__, DeleterT__, Deleter<AllocatorT__>
			>* result_ = static_cast<ReferenceManager_<
				ValueT__, DeleterT__, Deleter<AllocatorT__>
			>*>(allocator___.AllocatorT__::Basic::allocate(sizeof(*result_)));
			try {
#	if __cplusplus >= 201103L
				::DD::construct(result_, deleter___, Deleter<AllocatorT__>(allocator___), pointer_);
#	else
				new (result_) ReferenceManager_<
					ValueT__, UniversalDeleter, Deleter<AllocatorT__>
				>(deleter___, Deleter<AllocatorT__>(allocator___), pointer_);
#	endif
			} catch (...) {
				allocator___.AllocatorT__::Basic::deallocate(result_, sizeof(*result_));
				throw;
			}
			return result_;
		}
		return get_nil_reference_manager_();
	}

	private:
	ProcessType destruct_() DD_NOEXCEPT {
		get_manager_pointer_()->strongly_released_();
	}

	public:
	ThisType& operator =(ThisType const& origin_) DD_NOEXCEPT {
		reset(origin_);
		return *this;
	}

#	if __cplusplus >= 201103L
	public:
	ThisType& operator =(ThisType&& origin_) noexcept {
		reset(::DD::move(origin_));
		return *this;
	}

#	endif

#	if __cplusplus >= 201103L
	public:
	explicit operator ValidityType() const DD_NOEXCEPT {
		return is_valid();
	}

#	endif
};

#	if __cplusplus >= 201103L
template <typename ValueT_, typename... ArgumentsT_>
inline StrongPointer<ValueT_> make_strong(ArgumentsT_&&... arguments__);

#	endif
template <typename ValueT_>
#	if __cplusplus >= 201103L
struct StrongPointer : Comparable<StrongPointer<ValueT_>>, StrongPointer<void> {
#	else
struct StrongPointer : Comparable<StrongPointer<ValueT_> >, StrongPointer<void> {
#	endif
	public:
	DD_ALIAS(SuperType, StrongPointer<void>);
	DD_ALIAS(ThisType, StrongPointer<ValueT_>);
	DD_VALUE_TYPE_NESTED(ValueT_);

	public:
	DD_ALIAS(ConstStrongType, StrongPointer<ValueConstType>);
	DD_ALIAS(WeakType, WeakPointer<ValueType>);
	DD_ALIAS(ConstWeakType, WeakPointer<ValueConstType>);

	private:
	DD_SPECIFIC_TYPE_NESTED(Manager, ReferenceManagerBase_);

	public:
	friend WeakType;
	friend StrongPointer<DD_MODIFY_TRAIT(RemoveConst, ValueType)>;
#	if __cplusplus >= 201103L
	template <typename ValueT__, typename... ArgumentsT__>
	friend inline StrongPointer<ValueT__> make_strong(ArgumentsT__&&... arguments__);
#	endif

#	if __cplusplus >= 201103L
	public:
	StrongPointer() = default;

	public:
	StrongPointer(ThisType const& origin_) = default;

	public:
	StrongPointer(ThisType&& origin_) = default;
#	else
	public:
	StrongPointer() throw() : SuperType(get_nil_reference_manager_()) {
	}
#	endif

	public:
	StrongPointer(PointerType pointer_) : SuperType(pointer_) {
	}

	private:
	StrongPointer(ManagerPointerType manager_pointer_) : SuperType(manager_pointer_) {
	}

#	if __cplusplus >= 201103L
	private:
	StrongPointer(UnguardedTag tag_, ManagerPointerType manager_pointer_) : SuperType(tag_, manager_pointer_) {
	}

#	endif

#	if __cplusplus >= 201103L
	public:
	~StrongPointer() = default;

#	endif
	public:
	PointerType get_pointer() const DD_NOEXCEPT {
		return static_cast<PointerType>(get_global_pointer());
	}

	public:
	ValidityType equal(ThisType const& other_) const DD_NOEXCEPT {
		return SuperType::equal(other_);
	}

	public:
	ValidityType less(ThisType const& other_) const DD_NOEXCEPT {
		return SuperType::less(other_);
	}

	public:
	ConstStrongType get_const_strong_pointer() const DD_CALLABLE_WITH_LVALUE_ONLY DD_NOEXCEPT {
		return ConstStrongType(get_manager_pointer_());
	}

#	if __cplusplus >= 201103L
	public:
	ConstStrongType get_const_strong_pointer() const DD_CALLABLE_WITH_RVALUE_ONLY DD_NOEXCEPT {
		ManagerPointerType manager_pointer_ = get_manager_pointer_();
		m_manager_pointer_ = get_nil_reference_manager_();
		return ConstStrongType(unguarded_tag, manager_pointer_);
	}

#	endif

	public:
	ProcessType swap(ThisType& other_) DD_NOEXCEPT {
		SuperType::swap(other_);
	}

	public:
	ProcessType reset() DD_NOEXCEPT {
		ThisType temp_();
		swap(temp_);
	}

#	if __cplusplus >= 201103L
	public:
	ProcessType reset(ThisType&& origin_) noexcept {
		swap(origin_);
	}

	public:
	template <typename ObjectT_>
	ProcessType reset(ObjectT_&& object__) noexcept(noexcept(ThisType(::DD::forward<ObjectT_>(object__)))) {
		ThisType temp_(::DD::forward<ObjectT_>(object__));
		swap(temp_);
	}
#	else
	public:
	template <typename ObjectT_>
	ProcessType reset(ObjectT_ const& object__) {
		ThisType temp_(object__);
		swap(temp_);
	}
#	endif

#	if __cplusplus >= 201103L
	public:
	ThisType& operator =(ThisType const& origin_) = default;

	public:
	ThisType& operator =(ThisType&& origin_) = default;

	public:
	template <typename ObjectT__>
	ThisType& operator =(ObjectT__&& object___) noexcept(
		noexcept(::DD::fabricate<ThisType>().reset(::DD::forward<ObjectT__>(object___)))
	) {
		reset(::DD::forward<ObjectT__>(object___));
		return *this;
	}
#	else
	public:
	template <typename ObjectT__>
	ThisType& operator =(ObjectT__ const& object___) {
		reset(object___);
		return *this;
	}
#	endif

	public:
	ReferenceType operator *() const DD_NOEXCEPT {
		return *get_pointer();
	}

	public:
	PointerType operator ->() const DD_NOEXCEPT {
		return get_pointer();
	}

};

#	if __cplusplus >= 201103L
template <typename ValueT_>
inline ProcessType try_set_manager_for_strongly_referable_(
	ReferenceManagerBase_* manager_pointer_,
	StronglyReferable<ValueT_>* pointer_
) noexcept {
	pointer_->set_manager_(manager_pointer_);
}

inline ProcessType try_set_manager_for_strongly_referable_(
	ReferenceManagerBase_* manager_pointer_,
	void const volatile* workaround_
) noexcept {
}

template <typename ValueT_, typename AllocatorT_, typename... ArgumentsT_>
inline AggregateReferenceManager_<ValueT_, Deleter<AllocatorT_>>* create_aggregate_reference_manager_(
	AllocatorT_ allocator__, ArgumentsT_&&... arguments__
) {
	AggregateReferenceManager_<
		ValueT_, Deleter<AllocatorT_>
	>* result_ = static_cast<AggregateReferenceManager_<
		ValueT_, Deleter<AllocatorT_>
	>*>(allocator__.AllocatorT_::Basic::allocate(sizeof(*result_)));
	try {
		::DD::construct(result_, Deleter<AllocatorT_>(allocator__), ::DD::forward<ArgumentsT_>(arguments__)...);
	} catch (...) {
		allocator__.AllocatorT_::Basic::deallocate(result_, sizeof(*result_));
		throw;
	}
	try_set_manager_for_strongly_referable_(result_, static_cast<ValueT_*>(result_->get_global_pointer_()));
	return result_;
}

template <typename ValueT_, typename... ArgumentsT_>
inline StrongPointer<ValueT_> make_strong(ArgumentsT_&&... arguments__) {
	return StrongPointer<ValueT_>(create_aggregate_reference_manager_<ValueT_>(
		(DDCPP_DEFAULT_REFERENCE_MANAGER_ALLOCATOR), ::DD::forward<ArgumentsT_>(arguments__)...
	));
}
#	else
template <typename ValueT_>
inline StrongPointer<ValueT_> make_strong() {
	return StrongPointer<ValueT_>(new ValueT_());
}

template <typename ValueT_, typename ArgumentT_>
inline StrongPointer<ValueT_> make_strong(ArgumentT_ const& argument__) {
	return StrongPointer<ValueT_>(new ValueT_(argument__));
}
#	endif

template <typename ValueT_>
inline ValidityType operator ==(
	StrongPointer<ValueT_> const& strong_pointer_1_, StrongPointer<ValueT_> const& strong_pointer_2_
) DD_NOEXCEPT {
	return strong_pointer_1_.equal(strong_pointer_2_);
}

template <typename ValueT_>
inline ValidityType operator <(
	StrongPointer<ValueT_> const& strong_pointer_1_, StrongPointer<ValueT_> const& strong_pointer_2_
) DD_NOEXCEPT {
	return strong_pointer_1_.less(strong_pointer_2_);
}

DD_DETAIL_END_

DD_BEGIN_
using detail_::StrongPointer;
using detail_::make_strong;

DD_END_

#endif

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
import six

from django.core.urlresolvers import reverse
from django.views.generic import DetailView, TemplateView
from django.utils.translation import gettext_lazy as _
from django.utils.encoding import force_text
from django.template.defaultfilters import escape

from celery import app, states

celery_app = app.app_or_default()

from django.contrib.contenttypes.models import ContentType

from ..models import WooeyJob, WooeyFile, Favorite
from .. import settings as wooey_settings
from ..backend.utils import valid_user, get_file_previews
from ..django_compat import JsonResponse
from django.db.models import Q
from django.views.generic import ListView

SPANBASE = " "
MAXIMUM_JOBS_NAVBAR = 10
STATE_MAPPER = {
    #  Default Primary Success Info Warning Danger
    WooeyJob.COMPLETED: SPANBASE.format(_('Success'), 'success glyphicon-ok'),
    WooeyJob.RUNNING: SPANBASE.format(_('Executing'), 'success glyphicon-refresh spinning'),
    states.PENDING: SPANBASE.format(_('Queued'), 'glyphicon-time'),
    states.REVOKED: SPANBASE.format(_('Halted'), 'danger glyphicon-stop'),
    states.FAILURE: SPANBASE.format(_('Failure'), 'danger glyphicon-exclamation-sign'),
    WooeyJob.SUBMITTED: SPANBASE.format(_('Waiting'), 'glyphicon-hourglass'),
}

def generate_job_list(job_query):

    if job_query is None:
        return []

    jobs = []

    for job in job_query:
        jobs.append({
            'id': job.pk,
            'name': escape(job.job_name),
            'description': escape(six.u('Script: {}\n{}').format(job.script.script_name, job.job_description)),
            'url': reverse('wooey:celery_results', kwargs={'job_id': job.pk}),
            'submitted': job.created_date.strftime('%b %d %Y, %H:%M:%S'),
            'status': STATE_MAPPER.get(job.status, job.status),
        })
    return jobs

def get_global_queue(request):
    jobs = WooeyJob.objects.filter( Q(status=WooeyJob.RUNNING) | Q(status=WooeyJob.SUBMITTED) )
    return jobs.order_by('-created_date')

def global_queue_json(request):
    jobs = get_global_queue(request)
    return JsonResponse(generate_job_list(jobs), safe=False)

def get_user_queue(request):
    user = request.user
    jobs = WooeyJob.objects.filter(Q(user=None) | Q(user=user) if request.user.is_authenticated() else Q(user=None))
    jobs = jobs.exclude(Q(status=WooeyJob.DELETED) | Q(status=WooeyJob.COMPLETED))
    return jobs.order_by('-created_date')

def user_queue_json(request):
    jobs = get_user_queue(request)
    return JsonResponse(generate_job_list(jobs), safe=False)

def get_user_results(request):
    user = request.user
    jobs = WooeyJob.objects.filter(Q(status=WooeyJob.COMPLETED) & ( Q(user=None) | Q(user=user) if request.user.is_authenticated() else Q(user=None)) )
    jobs = jobs.exclude(status=WooeyJob.DELETED)
    return jobs.order_by('-created_date')

def user_results_json(request):
    jobs = get_user_results(request)
    return JsonResponse(generate_job_list(jobs), safe=False)

def all_queues_json(request):

    global_queue = get_global_queue(request)
    user_queue = get_user_queue(request)
    user_results = get_user_results(request)

    return JsonResponse({
        'totals':{
            'global': global_queue.count(),
            'user': user_queue.count(),
            'results': user_results.count(),
        },
        'items':{
            'global': generate_job_list(global_queue[:MAXIMUM_JOBS_NAVBAR]),
            'user': generate_job_list(user_queue[:MAXIMUM_JOBS_NAVBAR]),
            'results': generate_job_list(user_results[:MAXIMUM_JOBS_NAVBAR]),
        },
    }, safe=False)

def celery_task_command(request):

    command = request.POST.get('celery-command')
    job_id = request.POST.get('job-id')
    job = WooeyJob.objects.get(pk=job_id)
    response = {'valid': False,}
    valid = valid_user(job.script, request.user)
    if valid.get('valid') is True:
        user = request.user if request.user.is_authenticated() else None
        if user == job.user or job.user == None:
            if command == 'resubmit':
                new_job = job.submit_to_celery(resubmit=True, user=request.user)
                response.update({'valid': True, 'extra': {'job_url': reverse('wooey:celery_results', kwargs={'job_id': new_job.pk})}})
            elif command == 'rerun':
                job.submit_to_celery(user=request.user, rerun=True)
                response.update({'valid': True, 'redirect': reverse('wooey:celery_results', kwargs={'job_id': job_id})})
            elif command == 'clone':
                response.update({'valid': True, 'redirect': reverse('wooey:wooey_script_clone', kwargs={'slug': job.script.slug, 'job_id': job_id})})
            elif command == 'delete':
                job.status = WooeyJob.DELETED
                job.save()
                response.update({'valid': True, 'redirect': reverse('wooey:wooey_home')})
            elif command == 'stop':
                celery_app.control.revoke(job.celery_id, signal='SIGKILL', terminate=True)
                job.status = states.REVOKED
                job.save()
                response.update({'valid': True, 'redirect': reverse('wooey:celery_results', kwargs={'job_id': job_id})})
            else:
                response.update({'errors': {'__all__': [force_text(_("Unknown Command"))]}})
    else:
        response.update({'errors': {'__all__': [force_text(valid.get('error'))]}})
    return JsonResponse(response)

class JobBase(DetailView):

    model = WooeyJob

    def get_object(self):
        # FIXME: Update urls to use PK
        self.kwargs['pk'] = self.kwargs.get('job_id')
        return super(JobBase, self).get_object()

    def get_context_data(self, **kwargs):
        ctx = super(JobBase, self).get_context_data(**kwargs)
        wooey_job = ctx['wooeyjob']

        user = self.request.user
        user = None if not user.is_authenticated() and wooey_settings.WOOEY_ALLOW_ANONYMOUS else user
        job_user = wooey_job.user
        if job_user == None or job_user == user or (user != None and user.is_superuser):
            out_files = get_file_previews(wooey_job)
            all = out_files.pop('all', [])
            archives = out_files.pop('archives', [])

            # Get the favorite (scrapbook) status for each file
            ctype = ContentType.objects.get_for_model(WooeyFile)
            favorite_file_ids = Favorite.objects.filter(content_type=ctype, object_id__in=[f['id'] for f in all],
                                                        user=user).values_list('object_id', flat=True)

            ctx['job_info'] = {
                    'all_files': all,
                    'archives': archives,
                    'file_groups': out_files,
                    'status': wooey_job.status,
                    'last_modified': wooey_job.modified_date,
                    'job': wooey_job,

                }

            ctx['favorite_file_ids'] = favorite_file_ids

        else:
            ctx['job_error'] = _('You are not authenticated to view this job.')
        return ctx

class JobView(JobBase):
    template_name = 'wooey/jobs/job_view.html'

class JobJSON(JobBase):

    def render_to_response(self, context, *args, **kwargs):
        return JsonResponse(context)

class JobListBase(ListView):
    template_name = 'wooey/jobs/job_list.html'

    def get_context_data(self, **kwargs):
        ctx = super(JobListBase, self).get_context_data(**kwargs)
        if 'title' not in ctx:
            ctx['title'] = self.title
        return ctx

class GlobalQueueView(JobListBase):
    title = "Global Queue"

    def get_queryset(self, *args, **kwargs):
        return get_global_queue(self.request)

class UserQueueView(JobListBase):
    title = "My Queue"

    def get_queryset(self, *args, **kwargs):
        return get_user_queue(self.request)

class UserResultsView(JobListBase):

    def get_context_data(self, **kwargs):
        if self.request.user and self.request.user.is_authenticated():
            kwargs['title'] = "My Results"
        else:
            kwargs['title'] = "Public Results"

        return super(UserResultsView, self).get_context_data(**kwargs)

    def get_queryset(self, *args, **kwargs):
        return get_user_results(self.request)


text:
import gimpbbio.gpio as gpio
import gimpbbio.devices as devices
import time
import random
import threading
from seven_segment import display_digit

sequence = []
input_enabled = False
next_expected_color = 0
game_over = threading.Event()

def setup_led(pin):
	pin.open_for_output()
	pin.set_low()
	return pin

def setup_switch(pin):
	pin.open_for_input(pull = gpio.PULL_UP, active_state = gpio.ACTIVE_LOW)
	switch = devices.Switch(pin)
	switch.watch(on_press, on_release)
	return switch

class Color:
	def __init__(self, led, switch):
		self.led = led
		self.switch = switch

		led.color = self
		switch.color = self

def play_beginning_of_game():
	for x in range(20):
		for color in colors:
			color.led.set_high()
			time.sleep(.05)
			color.led.set_low()
	time.sleep(2)

def play_end_of_game():
	for x in range(50):
		for color in colors:
			color.led.set_high()
		time.sleep(.04)
		for color in colors:
			color.led.set_low()
		time.sleep(.04)

def play_sequence():
	for color in sequence:
		color.led.set_high()
		time.sleep(.65)
		color.led.set_low()
		time.sleep(.5)

def setup_game():
	global next_expected_color
	global input_enabled
	global sequence

	input_enabled = False
	next_expected_color = 0
	sequence = [random.choice(colors)]
	display_digit(0)

def on_press(switch):
	global input_enabled

	if input_enabled:
		switch.color.led.set_high()

		if switch.color != sequence[next_expected_color]:
			game_over.set()

def on_release(switch):
	global next_expected_color
	global input_enabled

	if input_enabled:
		switch.color.led.set_low()

		next_expected_color += 1

		if next_expected_color == len(sequence):
			input_enabled = False
			if len(sequence) <= 9:
				display_digit(len(sequence))
			time.sleep(1)
			sequence.append(random.choice(colors))
			play_sequence()
			next_expected_color = 0
			input_enabled = True

red_led = setup_led(gpio.pins.p9_12)
green_led = setup_led(gpio.pins.p9_14)
yellow_led = setup_led(gpio.pins.p9_16)
blue_led = setup_led(gpio.pins.p9_18)

red_switch = setup_switch(gpio.pins.p9_11)
green_switch = setup_switch(gpio.pins.p9_13)
yellow_switch = setup_switch(gpio.pins.p9_15)
blue_switch = setup_switch(gpio.pins.p9_17)

red = Color(red_led, red_switch)
green = Color(green_led, green_switch)
yellow = Color(yellow_led, yellow_switch)
blue = Color(blue_led, blue_switch)

colors = [red, green, yellow, blue]

while True:
	setup_game()
	play_beginning_of_game()
	input_enabled = False
	play_sequence()
	input_enabled = True

	game_over.wait()

	input_enabled = False
	play_end_of_game()
	game_over.clear()
	time.sleep(2)


text:
package fr.dgrandemange.txnmgrworkflow.service.support;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import fr.dgrandemange.txnmgrworkflow.helper.GraphHelper;
import fr.dgrandemange.txnmgrworkflow.model.DetailedNodeNatureEnum;
import fr.dgrandemange.txnmgrworkflow.model.Node;
import fr.dgrandemange.txnmgrworkflow.model.NodeNatureEnum;
import fr.dgrandemange.txnmgrworkflow.model.ParticipantInfo;
import fr.dgrandemange.txnmgrworkflow.model.Transition;
import fr.dgrandemange.txnmgrworkflow.service.IDOTLabelFactory;

/**
 * Implementation using Velocity engine along pre-defined templates to generate
 * HTML tooltips
 *
 * @author dgrandemange
 *
 */
public class TooltipFactoryVelocityImpl implements IDOTLabelFactory {

	private VelocityEngine ve;

	private Template nodeTooltipTemplate;

	private Template edgeTooltipTemplate;

	protected void init() {
		if (null == ve) {
			VelocityEngine ve = new VelocityEngine();
			ve.setProperty("resource.loader", "class");
			ve.setProperty("class.resource.loader.class",
					"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			nodeTooltipTemplate = ve
					.getTemplate("/fr/dgrandemange/txnmgrworkflow/service/support/template/node_tooltip.vm");
			edgeTooltipTemplate = ve
					.getTemplate("/fr/dgrandemange/txnmgrworkflow/service/support/template/edge_tooltip.vm");
		}
	}

	/* (non-Javadoc)
	 * @see fr.dgrandemange.txnmgrworkflow.service.IDOTLabelFactory#create(fr.dgrandemange.txnmgrworkflow.model.Node)
	 */
	public String create(Node node) {
		init();

		VelocityContext context = new VelocityContext();

		ParticipantInfo pInfo = node.getParticipant();

		putHtmlEncodedValInVelocityContext(context, "nodeTooltipInfo1",
				GraphHelper.getLabelFromNodeData(node));

		if (NodeNatureEnum.INITIAL.equals(node.getNodeNature())) {
			putHtmlEncodedValInVelocityContext(context, "nodeTooltipInfo1",
					"Initial state");
		} else if (NodeNatureEnum.FINAL.equals(node.getNodeNature())) {
			putHtmlEncodedValInVelocityContext(context, "nodeTooltipInfo1",
					"Final state");
		} else if (GraphHelper.isGroup(pInfo)
				&& (!(GraphHelper.isDynaGroup(pInfo)))) {
			putHtmlEncodedValInVelocityContext(context, "nodeTooltipInfo2",
					GraphHelper.getGroupName(pInfo));

			if (GraphHelper.isUndefined(pInfo)) {
				putHtmlEncodedValInVelocityContext(context, "nodeNature",
						DetailedNodeNatureEnum.undefGroupNature.name());
			} else {
				if (GraphHelper.isSubFlow(pInfo)) {
					putHtmlEncodedValInVelocityContext(context, "nodeNature",
							DetailedNodeNatureEnum.subflowNature.name());
					context.put("nodeTooltipInfo3", "(subflow)");
				} else {
					putHtmlEncodedValInVelocityContext(context, "nodeNature",
							DetailedNodeNatureEnum.groupNature.name());
					context.put("nodeTooltipInfo3",
							GraphHelper.getClassName(pInfo));
				}
			}
		} else {
			context.put("nodeTooltipInfo2", null);

			if (GraphHelper.isUndefined(pInfo)) {
				putHtmlEncodedValInVelocityContext(context, "nodeNature",
						DetailedNodeNatureEnum.undefParticipantNature.name());
			} else {
				putHtmlEncodedValInVelocityContext(context, "nodeNature",
						DetailedNodeNatureEnum.participantNature.name());
				context.put("nodeTooltipInfo3", GraphHelper.getClassName(pInfo));
			}
		}

		if (null != pInfo) {
			putHtmlEncodedValInVelocityContext(context, "guaranteedAttributes",
					pInfo.getGuaranteedCtxAttributes());
			putHtmlEncodedValInVelocityContext(context,
					"nonGuaranteedAttributes", pInfo.getOptionalCtxAttributes());
		} else {
			context.put("guaranteedAttributes", null);
			context.put("nonGuaranteedAttributes", null);
		}

		return doMerge(context, nodeTooltipTemplate);
	}

	/* (non-Javadoc)
	 * @see fr.dgrandemange.txnmgrworkflow.service.IDOTLabelFactory#create(fr.dgrandemange.txnmgrworkflow.model.Transition)
	 */
	public String create(Transition t) {
		init();

		VelocityContext context = new VelocityContext();

		context.put("sourceIsSubflow", false);
		ParticipantInfo pInfo = t.getSource().getParticipant();
		if (null != pInfo) {
			context.put("sourceIsSubflow", GraphHelper.isSubFlow(pInfo));
		}

		putHtmlEncodedValInVelocityContext(context, "guaranteedAttributes",
				t.getGuaranteedCtxAttributes());
		putHtmlEncodedValInVelocityContext(context, "nonGuaranteedAttributes",
				t.getOptionalCtxAttributes());

		String transitionName = t.getName();
		if (!("".equals(transitionName))) {
			putHtmlEncodedValInVelocityContext(context, "transitionName",
					transitionName);
		} else {
			context.put("transitionName", null);
		}

		String transitionDesc = t.getDesc();
		if ((null != transitionDesc) && (transitionDesc.trim().length() > 0)) {
			putHtmlEncodedValInVelocityContext(context, "transitionDesc",
					transitionDesc);
		} else {
			context.put("transitionDesc", null);
		}

		putHtmlEncodedValInVelocityContext(context, "attributesAdded",
				t.getAttributesAdded());

		return doMerge(context, edgeTooltipTemplate);
	}

	protected String doMerge(VelocityContext context, Template template) {
		StringWriter sw = new StringWriter();
		template.merge(context, sw);
		return String.format("<\n%s\n>", sw.toString());
	}

	protected void putHtmlEncodedValInVelocityContext(VelocityContext context,
			String key, String val) {
		String escaped = StringEscapeUtils.escapeHtml(val);
		context.put(key, escaped);
	}

	protected void putHtmlEncodedValInVelocityContext(VelocityContext context,
			String key, List<String> strList) {
		if ((strList == null) || (0 == strList.size())) {
			context.put(key, strList);
		} else {
			List<String> encodedList = new ArrayList<String>();
			for (String str : strList) {
				String escaped = StringEscapeUtils.escapeHtml(str);
				encodedList.add(escaped);
			}
			context.put(key, encodedList);
		}
	}

}


text:
require 'spec_helper'

RSpec.describe 'RSpec removes monkey patches' do
  let(:rewriter_name) { 'rspec/remove_monkey_patches' }

  context 'unit test' do
    let(:fake_file_path) { 'spec/models/post_spec.rb' }
    let(:test_content) { <<~EOS }
      describe Post do
        describe '.active' do
        end
      end
    EOS

    let(:test_rewritten_content) { <<~EOS }
      RSpec.describe Post do
        describe '.active' do
        end
      end
    EOS

    include_examples 'convertable'
  end

  context 'unit test with RSpec' do
    let(:fake_file_path) { 'spec/models/comment_spec.rb' }
    let(:test_content) { <<~EOS }
      RSpec.describe Comment do
        describe '.active' do
        end
      end
    EOS

    let(:test_rewritten_content) { <<~EOS }
      RSpec.describe Comment do
        describe '.active' do
        end
      end
    EOS

    include_examples 'convertable'
  end

  context 'support' do
    let(:fake_file_path) { 'spec/support/post.rb' }
    let(:test_content) { <<~EOS }
      shared_examples 'shared examples' do
      end
    EOS

    let(:test_rewritten_content) { <<~EOS }
      RSpec.shared_examples 'shared examples' do
      end
    EOS

    include_examples 'convertable'
  end

  context 'spec_helper' do
    let(:fake_file_path) { 'spec/spec_helper.rb' }
    let(:test_content) { <<~EOS }
      RSpec.configure do |config|
      end
    EOS

    let(:test_rewritten_content) { <<~EOS }
      RSpec.configure do |config|
        config.expose_dsl_globally = false
      end
    EOS

    include_examples 'convertable'
  end
end


text:
package hudson.util;

/**
 * Indicates that JNA is already loaded in another class loader.
 *
 * @author Kohsuke Kawaguchi
 */
public class JNADoublyLoaded extends HudsonFailedToLoad {

    public JNADoublyLoaded(Throwable exception) {
        super(exception);
    }
}


text:
import authentication from './authentication';

export default {
  authentication
};


text: SELECT fts3_tokenizer_internal_test()


text:
package easymvp;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by megrez on 2017/3/12.
 */
public class RxPresenter<V> extends AbstractPresenter<V> {
    private CompositeDisposable subscriptions = new CompositeDisposable();

    @Override
    public void onDestroyed() {
        super.onDestroyed();
        subscriptions.dispose();
    }

    public void addSubscription(Disposable subscription) {
        subscriptions.add(subscription);
    }

    public void removeSubscription(Disposable subscription) {
        subscriptions.remove(subscription);
    }
}


text:
"""
URLConf for Django user registration and authentication.

If the default behavior of the registration views is acceptable to
you, simply use a line like this in your root URLConf to set up the
default URLs for registration::

    (r'^accounts/', include('registration.urls')),

This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.

But if you'd like to customize the behavior (e.g., by passing extra
arguments to the various views) or split up the URLs, feel free to set
up your own URL patterns for these views instead. If you do, it's a
good idea to use the names ``registration_activate``,
``registration_complete`` and ``registration_register`` for the
various steps of the user-signup process.

"""

import functools

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.auth import views as auth_views

from registration.views import activate
from registration.views import register

from registration.forms import RegistrationFormUniqueEmailWithCaptcha

# register2 is register with the form_class given
register2 = functools.partial(register,
              form_class = RegistrationFormUniqueEmailWithCaptcha)

urlpatterns = patterns('',
                       # Activation keys get matched by \w+ instead of the more specific
                       # [a-fA-F0-9]{40} because a bad activation key should still get to the view;
                       # that way it can return a sensible "invalid key" message instead of a
                       # confusing 404.
                       url(r'^activate/(?P<activation_key>\w+)/$',
                           activate,
                           name='registration_activate'),
                       url(r'^login/$',
                           auth_views.login,
                           {'template_name': 'registration/login.html'},
                           name='auth_login'),
                       url(r'^logout/$',
                           auth_views.logout,
                           name='auth_logout'),
                       url(r'^password/change/$',
                           auth_views.password_change,
                           name='auth_password_change'),
                       url(r'^password/change/done/$',
                           auth_views.password_change_done,
                           name='auth_password_change_done'),
                       url(r'^password/reset/$',
                           auth_views.password_reset,
                           name='auth_password_reset'),
                       url(r'^password/reset/confirm/(?P<uidb36>.+)/(?P<token>.+)/$',
                           auth_views.password_reset_confirm,
                           name='auth_password_reset_confirm'),
                       url(r'^password/reset/complete/$',
                           auth_views.password_reset_complete,
                           name='auth_password_reset_complete'),
                       url(r'^password/reset/done/$',
                           auth_views.password_reset_done,
                           name='auth_password_reset_done'),
                       url(r'^register/$',
                           register2,
                           name='registration_register'),
                       url(r'^register/complete/$',
                           direct_to_template,
                           {'template': 'registration/registration_complete.html'},
                           name='registration_complete'),
                       )


text:
package com.cloud.agent.resource.kvm.wrapper;

import com.cloud.agent.resource.kvm.LibvirtComputingResource;
import com.cloud.common.request.ResourceWrapper;
import com.cloud.legacymodel.communication.answer.Answer;
import com.cloud.legacymodel.communication.command.PingTestCommand;
import com.cloud.utils.script.Script;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ResourceWrapper(handles = PingTestCommand.class)
public final class LibvirtPingTestCommandWrapper
        extends LibvirtCommandWrapper<PingTestCommand, Answer, LibvirtComputingResource> {

    private static final Logger s_logger = LoggerFactory.getLogger(LibvirtPingTestCommandWrapper.class);

    @Override
    public Answer execute(final PingTestCommand command, final LibvirtComputingResource libvirtComputingResource) {
        String result = null;
        final String computingHostIp = command.getComputingHostIp(); // TODO, split the command into 2 types

        if (computingHostIp != null) {
            result = doPingTest(libvirtComputingResource, computingHostIp);
        } else if (command.getRouterIp() != null && command.getPrivateIp() != null) {
            result = doPingTest(libvirtComputingResource, command.getRouterIp(), command.getPrivateIp());
        } else {
            return new Answer(command, false, "routerip and private ip is null");
        }

        if (result != null) {
            return new Answer(command, false, result);
        }
        return new Answer(command);
    }

    protected String doPingTest(final LibvirtComputingResource libvirtComputingResource, final String computingHostIp) {
        final Script command = new Script(libvirtComputingResource.getPingTestPath(), 10000, s_logger);
        command.add("-h", computingHostIp);
        return command.execute();
    }

    protected String doPingTest(final LibvirtComputingResource libvirtComputingResource, final String domRIp,
                                final String vmIp) {
        final Script command = new Script(libvirtComputingResource.getPingTestPath(), 10000, s_logger);
        command.add("-i", domRIp);
        command.add("-p", vmIp);
        return command.execute();
    }
}


text:
require 'money'
require 'date'
require 'yajl'

require "#{__dir__}/../../open_exchange_rates_fetcher"

class Money
  module Bank
    class InvalidCache < StandardError; end

    class HistoricalBank < Base
      attr_reader :rates

      # Available formats for importing/exporting rates.
      RATE_FORMATS = %i[json ruby yaml].freeze

      def setup
        @rates = {}
        @mutex = Mutex.new
        self
      end

      # Set the rate for the given currency pair at a given date.
      # Uses +Mutex+ to synchronize data access.
      #
      # @param [Date] date Date for which the rate is valid.
      # @param [Currency, String, Symbol] from Currency to exchange from.
      # @param [Currency, String, Symbol] to Currency to exchange to.
      # @param [Numeric] rate Rate to use when exchanging currencies.
      #
      # @return [Numeric]
      # @example
      #   bank = Money::Bank::HistoricalBank.new
      #   bank.set_rate(Date.new(2001, 1, 1), "USD", "CAD", 1.24514)
      def set_rate(date, from, to, rate)
        @mutex.synchronize do
          internal_set_rate(date, from, to, rate)
        end
      end

      # Retrieve the rate for the given currencies. Uses +Mutex+ to synchronize
      # data access. If no rates have been set for +date+, will try to load them
      # using #load_data.
      #
      # @param [Date] date Date to retrieve the exchange rate at.
      # @param [Currency, String, Symbol] from Currency to exchange from.
      # @param [Currency, String, Symbol] to Currency to exchange to.
      #
      # @return [Numeric]
      #
      # @example
      #   bank = Money::Bank::HistoricalBank.new
      #   d1 = Date.new(2001, 1, 1)
      #   d2 = Date.new(2002, 1, 1)
      #   bank.set_rate(d1, "USD", "CAD", 1.24515)
      #   bank.set_rate(d2, "CAD", "USD", 0.803115)
      #
      #   bank.get_rate(d1, "USD", "CAD") #=> 1.24515
      #   bank.get_rate(d2, "CAD", "USD") #=> 0.803115
      def get_rate(date, from, to)
        @mutex.synchronize do
          unless existing_rates = @rates[date.to_s]
            load_data(date)
            existing_rates = @rates[date.to_s]
          end
          rate = nil
          if existing_rates
            rate = existing_rates[rate_key_for(from, to)]
            unless rate
              # Tries to calculate an inverse rate
              inverse_rate = existing_rates[rate_key_for(to, from)]
              rate = 1.0 / inverse_rate if inverse_rate
            end
            unless rate
              # Tries to calculate a pair rate using USD rate
              unless from_base_rate = existing_rates[rate_key_for('USD', from)]
                from_inverse_rate = existing_rates[rate_key_for(from, 'USD')]
                from_base_rate = 1.0 / from_inverse_rate if from_inverse_rate
              end
              unless to_base_rate = existing_rates[rate_key_for('USD', to)]
                to_inverse_rate = existing_rates[rate_key_for(to, 'USD')]
                to_base_rate = 1.0 / to_inverse_rate if to_inverse_rate
              end
              rate = to_base_rate / from_base_rate if to_base_rate && from_base_rate
            end
          end
          rate
        end
      end

      # Tries to load data from OpenExchangeRates for the given rate.
      # Won't do anything if there's no data available for that date
      # in OpenExchangeRates (short) history.
      def load_data(date)
        data = OpenExchangeRatesFetcher.fetch_data(date)
        doc = Yajl::Parser.parse(data)

        base_currency = doc['base'] || 'USD'

        doc['rates'].each do |currency, rate|
          # Don't use set_rate here, since this method can only be called from
          # get_rate, which already aquired a mutex.
          internal_set_rate(date, base_currency, currency, rate)
        end
      end

      #
      # @overload exchange_with(from, to_currency)
      #   Exchanges the given +Money+ object to a new +Money+ object in
      #   +to_currency+. The exchange rate used will be for Date.today.
      #   If no rates are here for Date.today, it will try to load them.
      #   @param  [Money] from
      #           The +Money+ object to exchange.
      #   @param  [Currency, String, Symbol] to_currency
      #           The currency to exchange to.
      #
      # @overload exchange_with(date, from, to_currency)
      #   Exchanges the +Money+ object +from+ to a new +Money+ object in +to_currency+, using
      #   the exchange rate available on +date+.
      #   @param  [Date] date The +Date+ at which you want to calculate the rate.
      #   @param  [Money] from
      #           The +Money+ object to exchange.
      #   @param  [Currency, String, Symbol] to_currency
      #           The currency to exchange to.
      #
      # @yield [n] Optional block to use when rounding after exchanging one
      #  currency for another.
      # @yieldparam [Float] n The resulting float after exchanging one currency
      #  for another.
      # @yieldreturn [Integer]
      #
      # @return [Money]
      #
      # @raise +Money::Bank::UnknownRate+ if the conversion rate is unknown.
      #
      # @example
      #   bank = Money::Bank::VariableExchange.new
      #   bank.add_rate(Date.today, "USD", "CAD", 1.24515)
      #   bank.add_rate(Date.new(2011,1,1), "CAD", "USD", 0.803115)
      #
      #   c1 = 100_00.to_money("USD")
      #   c2 = 100_00.to_money("CAD")
      #
      #   # Exchange 100 USD to CAD:
      #   bank.exchange_with(c1, "CAD") #=> #<Money @cents=1245150>
      #
      #   # Exchange 100 CAD to USD:
      #   bank.exchange_with(Date.new(2011,1,1), c2, "USD") #=> #<Money @cents=803115>
      def exchange_with(*args)
        date, from, to_currency = args.length == 2 ? [Date.today] + args : args

        return from if same_currency?(from.currency, to_currency)

        rate = get_rate(date, from.currency, to_currency)
        raise UnknownRate, "No conversion rate available for #{date} '#{from.currency.iso_code}' -> '#{to_currency}'" unless rate

        _to_currency_ = Currency.wrap(to_currency)

        cents = BigDecimal(from.cents.to_s) / (BigDecimal(from.currency.subunit_to_unit.to_s) / BigDecimal(_to_currency_.subunit_to_unit.to_s))

        ex = cents * BigDecimal(rate.to_s)
        ex = ex.to_f
        ex = if block_given?
               yield ex
             elsif @rounding_method
               @rounding_method.call(ex)
             else
               ex.to_s.to_i
             end
        Money.new(ex, _to_currency_)
      end

      # Return the known rates as a string in the format specified. If +file+
      # is given will also write the string out to the file specified.
      # Available formats are +:json+, +:ruby+ and +:yaml+.
      #
      # @param [Symbol] format Request format for the resulting string.
      # @param [String] file Optional file location to write the rates to.
      #
      # @return [String]
      #
      # @raise +Money::Bank::UnknownRateFormat+ if format is unknown.
      #
      # @example
      #   bank = Money::Bank::VariableExchange.new
      #   bank.set_rate("USD", "CAD", 1.24515)
      #   bank.set_rate("CAD", "USD", 0.803115)
      #
      #   s = bank.export_rates(:json)
      #   s #=> "{\"USD_TO_CAD\":1.24515,\"CAD_TO_USD\":0.803115}"
      def export_rates(format, file = nil)
        raise Money::Bank::UnknownRateFormat unless
          RATE_FORMATS.include? format

        s = ''
        @mutex.synchronize do
          s = case format
              when :json
                JSON.dump(@rates)
              when :ruby
                Marshal.dump(@rates)
              when :yaml
                YAML.dump(@rates)
              end

          File.open(file, 'w').write(s) unless file.nil?
        end
        s
      end

      # Loads rates provided in +s+ given the specified format. Available
      # formats are +:json+, +:ruby+ and +:yaml+.
      #
      # @param [Symbol] format The format of +s+.
      # @param [String] s The rates string.
      #
      # @return [self]
      #
      # @raise +Money::Bank::UnknownRateFormat+ if format is unknown.
      #
      # @example
      #   s = "{\"USD_TO_CAD\":1.24515,\"CAD_TO_USD\":0.803115}"
      #   bank = Money::Bank::VariableExchange.new
      #   bank.import_rates(:json, s)
      #
      #   bank.get_rate("USD", "CAD") #=> 1.24515
      #   bank.get_rate("CAD", "USD") #=> 0.803115
      def import_rates(format, s)
        raise Money::Bank::UnknownRateFormat unless
          RATE_FORMATS.include? format

        @mutex.synchronize do
          @rates = case format
                   when :json
                     JSON.load(s)
                   when :ruby
                     Marshal.load(s)
                   when :yaml
                     YAML.safe_load(s)
                   end
        end
        self
      end

      private

      # Return the rate hashkey for the given currencies.
      #
      # @param [Currency, String, Symbol] from The currency to exchange from.
      # @param [Currency, String, Symbol] to The currency to exchange to.
      #
      # @return [String]
      #
      # @example
      #   rate_key_for("USD", "CAD") #=> "USD_TO_CAD"
      def rate_key_for(from, to)
        "#{Currency.wrap(from).iso_code}_TO_#{Currency.wrap(to).iso_code}".upcase
      end

      # Set the rate for the given currency pair at a given date.
      # Doesn't use any mutex.
      #
      # @param [Date] date Date for which the rate is valid.
      # @param [Currency, String, Symbol] from Currency to exchange from.
      # @param [Currency, String, Symbol] to Currency to exchange to.
      # @param [Numeric] rate Rate to use when exchanging currencies.
      #
      # @return [Numeric]
      def internal_set_rate(date, from, to, rate)
        if Money::Currency.find(from) && Money::Currency.find(to)
          date_rates = @rates[date.to_s] ||= {}
          date_rates[rate_key_for(from, to)] = rate
        end
      end
    end
  end
end


text:
Chartbuilder / Gneisschart
==========================

Chartbuilder / Gneisschart is a D3.js based front-end charting application that facilitates easy creation of simple beautiful charts.

Chartbuilder is the user and export interface. Gneisschart is the charting framework.

What Chartbuilder is not
-------------------------
+ A replacement for Excel
+ A replacement for Google Spreadsheet
+ A data analysis tool
+ A data transformation tool

What Chartbuilder is
--------------------
Chartbuilder is the final step in charting. Paste data into it and export an svg or png chart in a style that has been predefined.

Who is using Chartbuilder
--------------------
Other than Quartz, customized Chartbuilder created charts have been seen in many publications:
+ [NPR](http://www.npr.org/blogs/parallels/2013/10/24/240493422/in-most-every-european-country-bikes-are-outselling-cars)
+ [The Wall Street Journal](http://blogs.wsj.com/korearealtime/2014/03/07/for-korean-kids-mobile-chat-rules/)
+ [CNBC](http://www.cnbc.com/id/101009116)
+ [The New Yorker](http://www.newyorker.com/online/blogs/currency/2013/12/2013-the-year-in-charts.html)
+ [The Press-Enterprise](http://blog.pe.com/political-empire/2013/07/31/ppic-poll-global-warming-a-concern-for-inland-voters/)
+ [New Hampshire Public Radio](http://nhpr.org/post/water-cleanup-commences-beede-story-shows-superfund-laws-flaws)
+ [CFO Magazine](http://ww2.cfo.com/the-economy/2013/11/retail-sales-growth-stalls/)
+ [Australian Broadcasting Corporation](http://www.abc.net.au/news/2013-10-11/nobel-prize3a-why-2001-was-the-best-year-to-win/5016010)

How to use Chartbuilder
------------------------
###Getting started
If you are not interested in customizing the styles of your charts use the hosted version: http://quartz.github.io/Chartbuilder/

Alternatively:

1. [Download source](https://github.com/Quartz/Chartbuilder/archive/master.zip) (and unzip)
3. from the terminal navigate to the source folder (on a Mac: `cd ~/Downloads/Chartbuilder-master/`)
4. run `python -m SimpleHTTPServer`
5. Open Google Chrome, Apple Safari, or Opera and navigate to [http://localhost:8000/](http://localhost:8000/)

####Charting time Series Data
1. Find some time series data (may I suggest [this](https://docs.google.com/a/qz.com/spreadsheet/ccc?key=0AtrPfe-ScVhJdGg0a2hKZU1JaWZ4ZGMxY3NKbWozYUE#gid=0))
2. Make sure the first column is your dates, and the heading on the first column is "date"
3. Copy and paste into chart builder

####Charting ordinal series data
1. Find some ordinal series data (may I suggest [this](https://docs.google.com/a/qz.com/spreadsheet/ccc?key=0AtrPfe-ScVhJdDZrODFnM3Q1TTlfSHA2Z3lrSjJrUmc#gid=0))
2. Make sure the first column are your categories, and the heading on the first column _isn't_ "date"
3. Copy and paste into chartbuilder

####Finishing up
_steps 2-4 are optional_

1. Pick your series types
2. Set a title
3. Set your units using the axis prefix and suffix field
4. Adjust your max and min (if you so choose)
4. Add a credit line and/or a source line
6. Click create chart
7. Select to download an svg or png

###Examples of charts made with Chartbuilder
####Line charts

####Column charts

####Bar grids

####Mixed

Deploying Chartbuilder
------------------------
ChartBuilder is meant to be deployed by an organization and then customized for the design consistency of that organization so that the reporters or other people in that organization can make charts.

###Deploying
ChartBuild is an HTML/CSS/JS application.  You can easy copy, fork, and install the files wherever.  It can be easily put up on Github Pages.

###Configuration
Once you deploy it, configuring is either through CSS overrides, custom HTML, or Javascript configuration.

####Chart configuration
Chart configuration is handled by passing a configuration object through to `ChartBuilder.start()`.

    ChartBuilder.start({
      colors: ["#ff4cf4","#ffb3ff","#e69ce6","#cc87cc","#b373b3","#995f99"],
      creditline: 'NewsPost Inc.'
    });

You can see all the configuration options in the [Gneisschart.js library](https://github.com/Quartz/Chartbuilder/blob/master/js/gneisschart.js).

###Getting started

Why Chartbuilder / Gneisschart
-----------------
+ You're a writer, blogger, reporter who hates the way screenshotted research reports and excel charts look in your stories
+ You're a graphic designer or graphics editor spending too much time making simple charts in the same style
+ You're a developer at an organization looking to add consistency to employee generated charts

Chartbuilder was created to speed workflow in a newsroom and give reporters more responsibility over their content. It allows someone to create simple graphics quickly within a pre-specified style guide without needing specialized design software.

The output formats are can be used anywhere images and svgs are accepted. There's no need for CMS integration or complex back end systems.

There are fewer excuses to use screenshots from analyst reports or charts in Excel.

More about that here http://yanofsky.info/demos/chartbuilder/slides/

Gneisschart was created to assist in the above as well as establish the starting point for a touch focused responsive charting library.

###Styling the chart
Chart styles are contained in `css/gneisschart.css`. The color palette is defined in the configuration object


text:
<?php

namespace Catrineta\orm;

use \Catrineta\tools\StringTools;

/**
 * Description of ModelTools
 *
 * @author Luís Pinto / luis.nestesitio@gmail.com
 * Created @Sep 8, 2017
 */
class ModelTools
{
    use \Catrineta\orm\ModelCrudTools;

    /**
     *
     * @param string $table
     * @return \Catrineta\orm\Model
     */
    public static function startModel($table)
    {
        $class = self::getModelNamespace($table);
        $model = new $class();
        return $model;
    }

    /**
     * @param $name
     * @return mixed
     */
    public static function buildModelName($name)
    {
        $name = str_replace('_', ' ', $name);
        $name = ucwords($name);
        return str_replace(' ', '', $name);
    }

    /**
     * @param $table
     * @return mixed
     */
    public static function getModelQuery($table)
    {
        $class = '\\Model\\querys\\' . self::buildModelName($table) . 'Query';
        return $class::create();
    }

    /**
     * @param $table
     * @return mixed
     */
    public static function getModelForm($table)
    {
        $class = '\\Model\\forms\\' . self::buildModelName($table) . 'Form';
        return new $class();
    }

    /**
     * @param $table
     * @return \Catrineta\orm\Model
     */
    public static function getModel($table)
    {
        $class = '\\Model\\models\\' . self::buildModelName($table);
        return new $class();
    }

    /**
     * @param $table
     * @return mixed
     */
    public static function getModelNamespace($table)
    {
        return '\\Model\\models\\' . self::buildModelName($table);
    }

    /**
     *
     * @param string $table
     * @param string $field
     * @return string
     */
    public static function getFieldConstant($table, $field, $maintable = null)
    {
        $str = ($maintable == null || $table == $maintable)? $table . '_' : StringTools::getStringAfterLastChar($table, '_') . '_';
        return 'FIELD_' . strtoupper($str) . strtoupper($field);
    }

    /**
     * get the column name without table name
     * @param string $column
     * @return string
     */
    public static function getColumnName($column)
    {
        return StringTools::getStringAfterLastChar($column, '.');
    }

    public static function completeColumnName($table, $column)
    {
        return $table . '.' . self::getColumnName($column);
    }

        /**
     * Get the columns with alias from a table
     * @param string $table
     * @param boolean $id If false don't return primary keys
     * @return array
     */
    public static function getColumns($table, $id = true)
    {
        $columns = [];
        $model = self::startModel($table);
        $fields = $model->getFields();
        $pks = $model->getPrimaryKeys();
        foreach($fields as $field){
            if($id == false && in_array($field, $pks)){
                continue;
            }
            $columns[] = self::completeColumnName($table, $field);

        }
        return $columns;
    }

    /**
     *
     * @param string $table
     * @return array
     */
    public static function getPrimary($table)
    {
        $arr = [];
        $model = self::startModel($table);
        foreach($model->getPrimaryKeys() as $pk){
            $arr[] = self::completeColumnName($table, $pk);
        }

        return $arr;
    }

    public static function getReferencedConstraints($constraints, $table)
    {
        $arr = [];
        foreach($constraints as $constrain){
            if($constrain['CONSTRAINED'] == $table){
                $arr[$constrain['COLUMN_NAME']] = $constrain;
            }
        }

        return $arr;
    }

    public static function mergeName($name)
    {
        return str_replace('.', '_', $name);
    }

}


text:
namespace Steady_Image_Merger
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.label1 = new System.Windows.Forms.Label();
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.rbCrop = new System.Windows.Forms.RadioButton();
            this.rbFill = new System.Windows.Forms.RadioButton();
            this.rbOutline = new System.Windows.Forms.RadioButton();
            this.rbCenter = new System.Windows.Forms.RadioButton();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(12, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Go";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // openFileDialog1
            //
            this.openFileDialog1.FileName = "video.mp4";
            this.openFileDialog1.Filter = "All Files|*.*";
            this.openFileDialog1.Title = "Select a Video";
            //
            // progressBar1
            //
            this.progressBar1.Location = new System.Drawing.Point(93, 12);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(547, 23);
            this.progressBar1.TabIndex = 1;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(90, 38);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(37, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "Ready";
            //
            // saveFileDialog1
            //
            this.saveFileDialog1.FileName = "finished.avi";
            this.saveFileDialog1.Filter = "AVI Movies|*.avi";
            this.saveFileDialog1.Title = "Save Finished Movie As";
            //
            // rbCrop
            //
            this.rbCrop.AutoSize = true;
            this.rbCrop.Location = new System.Drawing.Point(12, 57);
            this.rbCrop.Name = "rbCrop";
            this.rbCrop.Size = new System.Drawing.Size(47, 17);
            this.rbCrop.TabIndex = 7;
            this.rbCrop.Text = "Crop";
            this.rbCrop.UseVisualStyleBackColor = true;
            //
            // rbFill
            //
            this.rbFill.AutoSize = true;
            this.rbFill.Checked = true;
            this.rbFill.Location = new System.Drawing.Point(65, 57);
            this.rbFill.Name = "rbFill";
            this.rbFill.Size = new System.Drawing.Size(37, 17);
            this.rbFill.TabIndex = 8;
            this.rbFill.TabStop = true;
            this.rbFill.Text = "Fill";
            this.rbFill.UseVisualStyleBackColor = true;
            //
            // rbOutline
            //
            this.rbOutline.AutoSize = true;
            this.rbOutline.Location = new System.Drawing.Point(108, 57);
            this.rbOutline.Name = "rbOutline";
            this.rbOutline.Size = new System.Drawing.Size(58, 17);
            this.rbOutline.TabIndex = 9;
            this.rbOutline.Text = "Outline";
            this.rbOutline.UseVisualStyleBackColor = true;
            //
            // rbCenter
            //
            this.rbCenter.AutoSize = true;
            this.rbCenter.Location = new System.Drawing.Point(172, 57);
            this.rbCenter.Name = "rbCenter";
            this.rbCenter.Size = new System.Drawing.Size(56, 17);
            this.rbCenter.TabIndex = 10;
            this.rbCenter.Text = "Center";
            this.rbCenter.UseVisualStyleBackColor = true;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(652, 86);
            this.Controls.Add(this.rbCenter);
            this.Controls.Add(this.rbOutline);
            this.Controls.Add(this.rbFill);
            this.Controls.Add(this.rbCrop);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.progressBar1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Steady Image Merger";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.ProgressBar progressBar1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        private System.Windows.Forms.RadioButton rbCrop;
        private System.Windows.Forms.RadioButton rbFill;
        private System.Windows.Forms.RadioButton rbOutline;
        private System.Windows.Forms.RadioButton rbCenter;
    }
}


text:
[![Alire](https://img.shields.io/endpoint?url=https://alire.ada.dev/badges/serverfaces.json)](https://alire.ada.dev/crates/serverfaces)
[![Alire](https://img.shields.io/endpoint?url=https://alire.ada.dev/badges/serverfaces_unit.json)](https://alire.ada.dev/crates/serverfaces_unit)
[![Build Status](https://img.shields.io/jenkins/s/http/jenkins.vacs.fr/Ada-Server-Faces.svg)](https://jenkins.vacs.fr/job/Ada-Server-Faces/)
[![Test Status](https://img.shields.io/jenkins/t/http/jenkins.vacs.fr/Ada-Server-Faces.svg)](https://jenkins.vacs.fr/job/Ada-Server-Faces/)
[![codecov](https://codecov.io/gh/stcarrez/ada-asf/branch/master/graph/badge.svg)](https://codecov.io/gh/stcarrez/ada-asf)
[![Download](https://img.shields.io/badge/download-1.5.0-brightgreen.svg)](http://download.vacs.fr/ada-asf/ada-asf-1.5.0.tar.gz)
[![License](https://img.shields.io/badge/license-APACHE2-blue.svg)](LICENSE)
[![GitLab](https://img.shields.io/badge/repo-GitLab-6C488A.svg)](https://gitlab.com/stcarrez/ada-asf)
![Commits](https://img.shields.io/github/commits-since/stcarrez/ada-asf/1.5.0.svg)

Ada Server Faces allows to create web applications using the same pattern
as the Java Server Faces (See JSR 252, JSR 314 and JSR 344).

It is part of [Ada Web Application](https://github.com/stcarrez/ada-awa/)
framework.

To build ASF, you will need:

* Ada Util     (https://github.com/stcarrez/ada-util          2.5.0)
* Ada EL       (https://github.com/stcarrez/ada-el            1.8.5)
* Ada Security (https://github.com/stcarrez/ada-security      1.4.1)
* Ada Servlet  (https://github.com/stcarrez/ada-servlet       1.6.0)
* AWS          (https://libre.adacore.com/libre/tools/aws/     2018 or 20)
* XML/Ada      (https://libre.adacore.com/libre/tools/xmlada/  4.4)

## Version 1.5.0   - Aug 2022
- New widget <w:progress> to display horizontal/vertical progress bars

[List all versions](https://github.com/stcarrez/ada-asf/blob/master/NEWS.md)

## Build

Build with the following commands:
```
   ./configure
   make
```

The samples can be built using:
```
   gnatmake -Psamples
```

The unit tests are built using:
```
   gnatmake -Ptests
```

And unit tests are executed with:
```
   bin/asf_harness
```

# Documentation

* [Ada Server Faces Programmer's Guide](https://ada-asf.readthedocs.io/en/latest/) [PDF](https://github.com/stcarrez/ada-asf/blob/master/docs/asf-book.pdf)
* [Ada Server Faces wiki (old documentation)](https://github.com/stcarrez/ada-asf/wiki)

## Tutorial

* [Ada Server Faces Application Example part 1: the presentation](http://blog.vacs.fr/index.php?post/2011/03/21/Ada-Server-Faces-Application-Example)
* [Ada Server Faces Application Example part 2: the Ada beans](http://blog.vacs.fr/index.php?post/2011/04/10/Ada-Server-Faces-Application-Example-part-2%3A-the-Ada-beans)
* [Ada Server Faces Application Example part 3: the action bean](http://blog.vacs.fr/index.php?post/2011/05/02/Ada-Server-Faces-Application-Example-part-3%3A-the-action-bean)
* [Ada Server Faces Application Example part 4: the server](http://blog.vacs.fr/index.php?post/2011/05/18/Ada-Server-Faces-Application-Example-part-3-the-server)

## Components

The following tags are supported:

| Documentation    | Namespace                                            | Tags                                                                  |
|----------|------------------------------------------------------|---------------------------------------------------------------------- |
| [JSTL]( https://demo.vacs.fr/demo/jstl/view.html) | `xmlns:c="http://java.sun.com/jstl/core"`            | <c:set>, <c:if>, <c:choose>, <c:when>, <c:otherwise> |
| [Facelets](https://demo.vacs.fr/demo/facelet/view.html) | `xmlns:ui="http://java.sun.com/jsf/facelets"`        | <ui:composition>, <ui:define>, <ui:decorate>, <ui:include>, <ui:insert>, <ui:param> |
| [JSF Core](https://demo.vacs.fr/demo/jsf/core/view.html) | `xmlns:f="http://java.sun.com/jsf/core"`             | <f:attribute>, <f:convertDateTime>, <f:converter>, <f:facet>, <f:metadata>, <f:param>, <f:selectItem>, <f:selectItems>, <f:validateLength>, <f:validateLongRange>, <f:validateRegex>, <f:validator>, <f:view>, <f:viewAction>, <f:viewParam> |
| [JSF HTML](https://demo.vacs.fr/demo/jsf/html/view.html) | `xmlns:h="http://java.sun.com/jsf/html"`             | <h:body>, <h:commandButton>, <h:form>, <h:head>, <h:inputFile>, <h:inputHidden>, <h:inputSecret>, <h:inputText>, <h:inputTextarea>, <h:list>, <h:message>, <h:messages>, <h:ouputFormat>, <h:outputLabel>, <h:outputLink>, <h:outputText>, <h:panelGroup>, <h:selectBooleanCheckbox>, <h:selectOneMenu>, <h:selectOneRadio> |
| [Widget](https://demo.vacs.fr/demo/widgets/view.html) | `xmlns:w="http://code.google.com/p/ada-asf/widget"`  | <w:accordion>, <w:autocomplete>, <w:chosen>, <w:inputDate>, <w:inputText>, <w:gravatar>, <w:like>, <w:panel>, <w:tab>, <w:tabView> |
| [Util](https://demo.vacs.fr/demo/util/view.html)     | `xmlns:util="http://code.google.com/p/ada-asf/util"` | <util:escape>, <util:file>, <util:flush>, <util:script> |

# Licenses

Ada Server Faces integrates the Javascript library jQuery licensed under
MIT or GPL (See https://jquery.org/license/).

Ada Server Faces integrates a generated version of 960 grid system
licensed under MIT or GPL (See https://960.gs/ and https://grids.heroku.com/
for the CSS generator).


text:
namespace verilog {
namespace analysis {

// VoidCastRule checks that void casts do not contain certain function/method
// calls.
class VoidCastRule : public verible::SyntaxTreeLintRule {
 public:
  using rule_type = verible::SyntaxTreeLintRule;

  static const LintRuleDescriptor& GetDescriptor();

  void HandleSymbol(const verible::Symbol& symbol,
                    const verible::SyntaxTreeContext& context) final;

  verible::LintRuleStatus Report() const final;

 private:
  // Generate diagnostic message of why lint error occurred.
  static std::string FormatReason(const verible::SyntaxTreeLeaf& leaf);

  static const std::set<std::string>& ForbiddenFunctionsSet();

  std::set<verible::LintViolation> violations_;
};

}  // namespace analysis
}  // namespace verilog

#endif  // VERIBLE_VERILOG_ANALYSIS_CHECKERS_VOID_CAST_RULE_H_


text:
<?php

namespace Magento\Sales\Controller\AbstractController;

abstract class Creditmemo extends \Magento\Sales\Controller\AbstractController\View
{
}


text:
package shapeless

import org.junit.Assert._

object testutil {
  def assertTypedEquals[A](expected: A, actual: A): Unit = assertEquals(expected, actual)

  def assertTypedSame[A <: AnyRef](expected: A, actual: A): Unit = assertSame(expected, actual)
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var TechnicianQuality;
(function (TechnicianQuality) {
    TechnicianQuality[TechnicianQuality["GREEN_HAND"] = 1.2] = "GREEN_HAND";
    TechnicianQuality[TechnicianQuality["SKILLED"] = 1.4] = "SKILLED";
})(TechnicianQuality || (TechnicianQuality = {}));
var Technician = (function () {
    function Technician(_technicianQuality, _name) {
        this.name = _name;
        this.technicianQuality = _technicianQuality;
        // this.attack = this.getAttack();
    }
    var d = __define,c=Technician,p=c.prototype;
    p.getAttack = function () {
        return Properties.getInstance().technicianProperty[TechnicianPropertyName.technician_Status].value * this.technicianQuality;
    };
    //@Cache
    p.calFightPower = function () {
        return this.getAttack() * 1.4 + Properties.getInstance().technicianProperty[TechnicianPropertyName.technician_Level].value * 2;
    };
    p.disPlayDetail = function () {
        ShowPanel.detailed.text = "";
        ShowPanel.detailed.text = "Attack: + " + this.getAttack().toString() + "\n" + "FightPower: + " + this.calFightPower().toString() + "\n";
        return PropertiesDisplayFactory.createAllDescription(Properties.getInstance().technicianProperty, ShowPanel.detailed);
    };
    __decorate([
        Cache
    ], p, "getAttack", null);
    return Technician;
}());
egret.registerClass(Technician,'Technician');
//return property.name + ": + " + property.value + "\n";
//# sourceMappingURL=Technician.js.map


text:
package com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.converters;

import com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.description.LoadBalancersDescription;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component
abstract class AbstractLoadBalancersAtomicOperationConverter
    extends AbstractCloudFoundryServerGroupAtomicOperationConverter {
  @Override
  public LoadBalancersDescription convertDescription(Map input) {
    List<String> routes = (List<String>) input.get("loadBalancerNames");
    if (routes.isEmpty()) {
      throw new IllegalArgumentException("No routes supplied.");
    }

    LoadBalancersDescription converted =
        getObjectMapper().convertValue(input, LoadBalancersDescription.class);

    converted.setClient(getClient(input));
    converted.setServerGroupId(
        getServerGroupId(
            converted.getServerGroupName(), converted.getRegion(), converted.getClient()));
    converted.setRoutes(routes);

    return findSpace(converted.getRegion(), converted.getClient())
        .map(converted::setSpace)
        .orElseThrow(() -> new IllegalArgumentException("No space supplied."));
  }
}


text:
package com.palantir.atlasdb.keyvalue.api;

import com.palantir.common.persist.Persistable;
import com.palantir.logsafe.Preconditions;
import java.io.Serializable;

public final class ColumnRangeSelections implements Serializable {
    private static final long serialVersionUID = 1L;

    private ColumnRangeSelections() {
        // Utility class
    }

    public static BatchColumnRangeSelection createPrefixRange(byte[] prefix, int batchSize) {
        byte[] startCol =
                Preconditions.checkNotNull(prefix, "prefix cannot be null").clone();
        byte[] endCol = RangeRequests.createEndNameForPrefixScan(prefix);
        return BatchColumnRangeSelection.create(startCol, endCol, batchSize);
    }

    public static BatchColumnRangeSelection createPrefixRange(Persistable persistable, int batchSize) {
        return createPrefixRange(persistable.persistToBytes(), batchSize);
    }
}


text:
using Newtonsoft.Json;

namespace PlanGrid.Api
{
    public class ShareableObject
    {
        [JsonProperty("uid")]
        public string Uid { get; set; }

        [JsonProperty("file_url")]
        public string FileUrl { get; set; }

        [JsonProperty("resource")]
        public ShareableObject Resource { get; set; }

        [JsonProperty("status")]
        public Status Status { get; set; }
    }
}


text:
Ext.define('example.controller.One', {
  extend: 'example.controller.Two',

  requires: [
    'example.view.One'
  ]
});


text:
'''
JSON related utilities.

This module provides a few things:

#. A handy function for getting an object down to something that can be
   JSON serialized.  See :func:`.to_primitive`.
#. Wrappers around :func:`.loads` and :func:`.dumps`. The :func:`.dumps`
   wrapper will automatically use :func:`.to_primitive` for you if needed.
#. This sets up ``anyjson`` to use the :func:`.loads` and :func:`.dumps`
   wrappers if ``anyjson`` is available.
'''

import codecs
import datetime
import functools
import inspect
import itertools
import sys
import uuid

is_simplejson = False
if sys.version_info < (2, 7):
    # On Python <= 2.6, json module is not C boosted, so try to use
    # simplejson module if available
    try:
        import simplejson as json
        # NOTE(mriedem): Make sure we have a new enough version of simplejson
        # to support the namedobject_as_tuple argument. This can be removed
        # in the Kilo release when python 2.6 support is dropped.
        if 'namedtuple_as_object' in inspect.getargspec(json.dumps).args:
            is_simplejson = True
        else:
            import json
    except ImportError:
        import json
else:
    import json

from oslo_utils import encodeutils
from oslo_utils import importutils
from oslo_utils import timeutils
import six
import six.moves.xmlrpc_client as xmlrpclib

netaddr = importutils.try_import("netaddr")

_nasty_type_tests = [inspect.ismodule, inspect.isclass, inspect.ismethod,
                     inspect.isfunction, inspect.isgeneratorfunction,
                     inspect.isgenerator, inspect.istraceback, inspect.isframe,
                     inspect.iscode, inspect.isbuiltin, inspect.isroutine,
                     inspect.isabstract]

_simple_types = (six.string_types + six.integer_types
                 + (type(None), bool, float))

def to_primitive(value, convert_instances=False, convert_datetime=True,
                 level=0, max_depth=3):
    """Convert a complex object into primitives.

    Handy for JSON serialization. We can optionally handle instances,
    but since this is a recursive function, we could have cyclical
    data structures.

    To handle cyclical data structures we could track the actual objects
    visited in a set, but not all objects are hashable. Instead we just
    track the depth of the object inspections and don't go too deep.

    Therefore, ``convert_instances=True`` is lossy ... be aware.
    """
    # handle obvious types first - order of basic types determined by running
    # full tests on nova project, resulting in the following counts:
    # 572754 <type 'NoneType'>
    # 460353 <type 'int'>
    # 379632 <type 'unicode'>
    # 274610 <type 'str'>
    # 199918 <type 'dict'>
    # 114200 <type 'datetime.datetime'>
    #  51817 <type 'bool'>
    #  26164 <type 'list'>
    #   6491 <type 'float'>
    #    283 <type 'tuple'>
    #     19 <type 'long'>
    if isinstance(value, _simple_types):
        return value

    # It's not clear why xmlrpclib created their own DateTime type, but
    # for our purposes, make it a datetime type which is explicitly
    # handled
    if isinstance(value, xmlrpclib.DateTime):
        value = datetime.datetime(*tuple(value.timetuple())[:6])

    if isinstance(value, datetime.datetime):
        if convert_datetime:
            return value.strftime(timeutils.PERFECT_TIME_FORMAT)
        else:
            return value

    if isinstance(value, uuid.UUID):
        return six.text_type(value)

    if netaddr and isinstance(value, netaddr.IPAddress):
        return six.text_type(value)

    # value of itertools.count doesn't get caught by nasty_type_tests
    # and results in infinite loop when list(value) is called.
    if type(value) == itertools.count:
        return six.text_type(value)

    if any(test(value) for test in _nasty_type_tests):
        return six.text_type(value)

    # FIXME(vish): Workaround for LP bug 852095. Without this workaround,
    #              tests that raise an exception in a mocked method that
    #              has a @wrap_exception with a notifier will fail. If
    #              we up the dependency to 0.5.4 (when it is released) we
    #              can remove this workaround.
    if getattr(value, '__module__', None) == 'mox':
        return 'mock'

    if level > max_depth:
        return '?'

    # The try block may not be necessary after the class check above,
    # but just in case ...
    try:
        recursive = functools.partial(to_primitive,
                                      convert_instances=convert_instances,
                                      convert_datetime=convert_datetime,
                                      level=level,
                                      max_depth=max_depth)
        if isinstance(value, dict):
            return dict((recursive(k), recursive(v))
                        for k, v in six.iteritems(value))
        elif hasattr(value, 'iteritems'):
            return recursive(dict(value.iteritems()), level=level + 1)
        # Python 3 does not have iteritems
        elif hasattr(value, 'items'):
            return recursive(dict(value.items()), level=level + 1)
        elif hasattr(value, '__iter__'):
            return list(map(recursive, value))
        elif convert_instances and hasattr(value, '__dict__'):
            # Likely an instance of something. Watch for cycles.
            # Ignore class member vars.
            return recursive(value.__dict__, level=level + 1)
    except TypeError:
        # Class objects are tricky since they may define something like
        # __iter__ defined but it isn't callable as list().
        return six.text_type(value)

    return value

JSONEncoder = json.JSONEncoder
JSONDecoder = json.JSONDecoder

def dumps(obj, default=to_primitive, **kwargs):
    """Serialize ``obj`` to a JSON formatted ``str``.

    :param obj: object to be serialized
    :param default: function that returns a serializable version of an object
    :param kwargs: extra named parameters, please see documentation \
    of `json.dumps <https://docs.python.org/2/library/json.html#basic-usage>`_
    :returns: json formatted string

    Use dump_as_bytes() to ensure that the result type is ``bytes`` on Python 2
    and Python 3.
    """
    if is_simplejson:
        kwargs['namedtuple_as_object'] = False
    return json.dumps(obj, default=default, **kwargs)

def dump_as_bytes(obj, default=to_primitive, encoding='utf-8', **kwargs):
    """Serialize ``obj`` to a JSON formatted ``bytes``.

    :param obj: object to be serialized
    :param default: function that returns a serializable version of an object
    :param encoding: encoding used to encode the serialized JSON output
    :param kwargs: extra named parameters, please see documentation \
    of `json.dumps <https://docs.python.org/2/library/json.html#basic-usage>`_
    :returns: json formatted string

    .. versionadded:: 2.0
    """
    serialized = dumps(obj, default=default, **kwargs)
    if isinstance(serialized, six.text_type):
        # On Python 3, json.dumps() returns Unicode
        serialized = serialized.encode(encoding)
    return serialized

def dump(obj, fp, *args, **kwargs):
    """Serialize ``obj`` as a JSON formatted stream to ``fp``

    :param obj: object to be serialized
    :param fp: a ``.write()``-supporting file-like object
    :param default: function that returns a serializable version of an object
    :param args: extra arguments, please see documentation \
    of `json.dump <https://docs.python.org/2/library/json.html#basic-usage>`_
    :param kwargs: extra named parameters, please see documentation \
    of `json.dump <https://docs.python.org/2/library/json.html#basic-usage>`_
    """
    default = kwargs.get('default', to_primitive)
    if is_simplejson:
        kwargs['namedtuple_as_object'] = False
    return json.dump(obj, fp, default=default, *args, **kwargs)

def loads(s, encoding='utf-8', **kwargs):
    """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON

    :param s: string to deserialize
    :param encoding: encoding used to interpret the string
    :param kwargs: extra named parameters, please see documentation \
    of `json.loads <https://docs.python.org/2/library/json.html#basic-usage>`_
    :returns: python object
    """
    return json.loads(encodeutils.safe_decode(s, encoding), **kwargs)

def load(fp, encoding='utf-8', **kwargs):
    """Deserialize ``fp`` to a Python object.

    :param fp: a ``.read()`` -supporting file-like object
    :param encoding: encoding used to interpret the string
    :param kwargs: extra named parameters, please see documentation \
    of `json.loads <https://docs.python.org/2/library/json.html#basic-usage>`_
    :returns: python object
    """
    return json.load(codecs.getreader(encoding)(fp), **kwargs)

try:
    import anyjson
except ImportError:
    pass
else:
    anyjson._modules.append((__name__, 'dumps', TypeError,
                                       'loads', ValueError, 'load'))
    anyjson.force_implementation(__name__)