text:
/* NOTE: This is an internal header file, included by other STL headers.
 *   You should not attempt to use it directly.
 */

#ifndef _STLP_INTERNAL_ALGOBASE_H
#define _STLP_INTERNAL_ALGOBASE_H

# if ! defined (_STLP_CSTDDEF)
#  include <cstddef>
# endif

#ifndef _STLP_CSTRING
# include <cstring>
#endif

#ifndef _STLP_CLIMITS
# include <climits>
#endif

# if ! defined (_STLP_CSTDLIB)
#  include <cstdlib>
# endif

# ifndef _STLP_INTERNAL_PAIR_H
#  include <stl/_pair.h>
# endif

#ifndef _STLP_INTERNAL_ITERATOR_BASE_H
# include <stl/_iterator_base.h>
#endif

_STLP_BEGIN_NAMESPACE
// swap and iter_swap
template <class _Tp>
inline void swap(_Tp& __a, _Tp& __b) {
  _Tp __tmp = __a;
  __a = __b;
  __b = __tmp;
}

template <class _ForwardIter1, class _ForwardIter2>
inline void iter_swap(_ForwardIter1 __i1, _ForwardIter2 __i2) {
  swap(*__i1, *__i2);
}

//--------------------------------------------------
// min and max

# if !defined (__BORLANDC__) || defined (_STLP_USE_OWN_NAMESPACE)
template <class _Tp>
inline const _Tp& (min)(const _Tp& __a, const _Tp& __b) { return __b < __a ? __b : __a; }
template <class _Tp>
inline const _Tp& (max)(const _Tp& __a, const _Tp& __b) {  return  __a < __b ? __b : __a; }
#endif /* __BORLANDC__ */

# if defined (__BORLANDC__) && ( __BORLANDC__ < 0x530 || defined (_STLP_USE_OWN_NAMESPACE))
inline unsigned long (min) (unsigned long __a, unsigned long __b) { return __b < __a ? __b : __a; }
inline unsigned long (max) (unsigned long __a, unsigned long __b) {  return  __a < __b ? __b : __a; }
# endif

template <class _Tp, class _Compare>
inline const _Tp& (min)(const _Tp& __a, const _Tp& __b, _Compare __comp) {
  return __comp(__b, __a) ? __b : __a;
}

template <class _Tp, class _Compare>
inline const _Tp& (max)(const _Tp& __a, const _Tp& __b, _Compare __comp) {
  return __comp(__a, __b) ? __b : __a;
}

//--------------------------------------------------
// copy

// All of these auxiliary functions serve two purposes.  (1) Replace
// calls to copy with memmove whenever possible.  (Memmove, not memcpy,
// because the input and output ranges are permitted to overlap.)
// (2) If we're using random access iterators, then write the loop as
// a for loop with an explicit count.

template <class _InputIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_InputIter __first, _InputIter __last,
                          _OutputIter __result,
                          const input_iterator_tag &, _Distance*) {
  for ( ; __first != __last; ++__result, ++__first)
    *__result = *__first;
  return __result;
}

# if defined (_STLP_NONTEMPL_BASE_MATCH_BUG)
template <class _InputIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_InputIter __first, _InputIter __last,
			  _OutputIter __result, const forward_iterator_tag &, _Distance* ) {
  for ( ; __first != __last; ++__result, ++__first)
    *__result = *__first;
  return __result;
}

template <class _InputIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_InputIter __first, _InputIter __last,
			  _OutputIter __result, const bidirectional_iterator_tag &, _Distance* __dis) {
  for ( ; __first != __last; ++__result, ++__first)
    *__result = *__first;
  return __result;
}
# endif

template <class _RandomAccessIter, class _OutputIter, class _Distance>
inline _OutputIter
__copy(_RandomAccessIter __first, _RandomAccessIter __last,
       _OutputIter __result, const random_access_iterator_tag &, _Distance*) {
  for (_Distance __n = __last - __first; __n > 0; --__n) {
    *__result = *__first;
    ++__first;
    ++__result;
  }
  return __result;
}

inline void*
__copy_trivial(const void* __first, const void* __last, void* __result) {
  return (__last == __first) ? __result :
    ((char*)memmove(__result, __first, ((const char*)__last - (const char*)__first))) +
    ((const char*)__last - (const char*)__first);
}

//--------------------------------------------------
// copy_backward auxiliary functions

template <class _BidirectionalIter1, class _BidirectionalIter2,
          class _Distance>
inline _BidirectionalIter2 __copy_backward(_BidirectionalIter1 __first,
                                           _BidirectionalIter1 __last,
                                           _BidirectionalIter2 __result,
                                           const bidirectional_iterator_tag &,
                                           _Distance*)
{
  while (__first != __last)
    *--__result = *--__last;
  return __result;
}

template <class _RandomAccessIter, class _BidirectionalIter, class _Distance>
inline _BidirectionalIter __copy_backward(_RandomAccessIter __first,
                                          _RandomAccessIter __last,
                                          _BidirectionalIter __result,
                                          const random_access_iterator_tag &,
                                          _Distance*)
{
  for (_Distance __n = __last - __first; __n > 0; --__n)
    *--__result = *--__last;
  return __result;
}

inline void*
__copy_trivial_backward(const void* __first, const void* __last, void* __result) {
  const ptrdiff_t _Num = (const char*)__last - (const char*)__first;
  return (_Num > 0) ? memmove((char*)__result - _Num, __first, _Num) : __result ;
}

template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_ptrs(_InputIter __first, _InputIter __last, _OutputIter __result, const __false_type&) {
  return __copy(__first, __last, __result,
                _STLP_ITERATOR_CATEGORY(__first, _InputIter),
                _STLP_DISTANCE_TYPE(__first, _InputIter));
}
template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_ptrs(_InputIter __first, _InputIter __last, _OutputIter __result, const __true_type&) {
// we know they all pointers, so this cast is OK
  //  return (_OutputIter)__copy_trivial(&(*__first), &(*__last), &(*__result));
  return (_OutputIter)__copy_trivial(__first, __last, __result);
}

template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_aux(_InputIter __first, _InputIter __last, _OutputIter __result, const __true_type&) {
  return __copy_ptrs(__first, __last, __result,
                     _IsOKToMemCpy(_STLP_VALUE_TYPE(__first, _InputIter),
                                   _STLP_VALUE_TYPE(__result, _OutputIter))._Ret());
}

template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_aux(_InputIter __first, _InputIter __last, _OutputIter __result, const __false_type&) {
  return __copy(__first, __last, __result,
		_STLP_ITERATOR_CATEGORY(__first, _InputIter), _STLP_DISTANCE_TYPE(__first, _InputIter));
}

template <class _InputIter, class _OutputIter>
inline _OutputIter copy(_InputIter __first, _InputIter __last, _OutputIter __result) {
  _STLP_DEBUG_CHECK(__check_range(__first, __last))
    return __copy_aux(__first, __last, __result, _BothPtrType< _InputIter, _OutputIter> :: _Ret());
}

template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_backward_ptrs(_InputIter __first, _InputIter __last, _OutputIter __result, const __false_type&) {
  return __copy_backward(__first, __last, __result, _STLP_ITERATOR_CATEGORY(__first, _InputIter), _STLP_DISTANCE_TYPE(__first, _InputIter));
}
template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_backward_ptrs(_InputIter __first, _InputIter __last, _OutputIter __result, const __true_type&) {
  return (_OutputIter)__copy_trivial_backward(__first, __last, __result);
}

template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_backward_aux(_InputIter __first, _InputIter __last, _OutputIter __result, const __false_type&) {
  return __copy_backward(__first, __last, __result, _STLP_ITERATOR_CATEGORY(__first,_InputIter), _STLP_DISTANCE_TYPE(__first, _InputIter));
}

template <class _InputIter, class _OutputIter>
inline _OutputIter __copy_backward_aux(_InputIter __first, _InputIter __last, _OutputIter __result, const __true_type&) {
  return __copy_backward_ptrs(__first, __last, __result,
                              _IsOKToMemCpy(_STLP_VALUE_TYPE(__first, _InputIter),
                                            _STLP_VALUE_TYPE(__result, _OutputIter))._Ret());
}

template <class _InputIter, class _OutputIter>
inline _OutputIter copy_backward(_InputIter __first, _InputIter __last, _OutputIter __result) {
  _STLP_DEBUG_CHECK(__check_range(__first, __last))
    return __copy_backward_aux(__first, __last, __result, _BothPtrType< _InputIter, _OutputIter> :: _Ret() );
}

#if ! defined (_STLP_CLASS_PARTIAL_SPECIALIZATION) && ! defined ( _STLP_SIMULATE_PARTIAL_SPEC_FOR_TYPE_TRAITS )
#define _STLP_DECLARE_COPY_TRIVIAL(_Tp)                                \
inline _Tp* copy(const _Tp* __first, const _Tp* __last, _Tp* __result) \
{ return (_Tp*)__copy_trivial(__first, __last, __result); } \
inline _Tp* copy_backward(const _Tp* __first, const _Tp* __last, _Tp* __result) \
{ return (_Tp*)__copy_trivial_backward(__first, __last, __result); }

_STLP_DECLARE_COPY_TRIVIAL(char)
# ifndef _STLP_NO_SIGNED_BUILTINS
_STLP_DECLARE_COPY_TRIVIAL(signed char)
# endif
_STLP_DECLARE_COPY_TRIVIAL(unsigned char)
_STLP_DECLARE_COPY_TRIVIAL(short)
_STLP_DECLARE_COPY_TRIVIAL(unsigned short)
_STLP_DECLARE_COPY_TRIVIAL(int)
_STLP_DECLARE_COPY_TRIVIAL(unsigned int)
_STLP_DECLARE_COPY_TRIVIAL(long)
_STLP_DECLARE_COPY_TRIVIAL(unsigned long)
#if !defined(_STLP_NO_WCHAR_T) && !defined (_STLP_WCHAR_T_IS_USHORT)
_STLP_DECLARE_COPY_TRIVIAL(wchar_t)
#endif
#ifdef _STLP_LONG_LONG
_STLP_DECLARE_COPY_TRIVIAL(long long)
_STLP_DECLARE_COPY_TRIVIAL(unsigned long long)
#endif
_STLP_DECLARE_COPY_TRIVIAL(float)
_STLP_DECLARE_COPY_TRIVIAL(double)
# ifndef _STLP_NO_LONG_DOUBLE
_STLP_DECLARE_COPY_TRIVIAL(long double)
# endif
#undef _STLP_DECLARE_COPY_TRIVIAL
#endif /* _STLP_CLASS_PARTIAL_SPECIALIZATION */

//--------------------------------------------------
// copy_n (not part of the C++ standard)

template <class _InputIter, class _Size, class _OutputIter>
_STLP_INLINE_LOOP
pair<_InputIter, _OutputIter> __copy_n(_InputIter __first, _Size __count,
                                       _OutputIter __result,
                                       const input_iterator_tag &) {
  for ( ; __count > 0; --__count) {
    *__result = *__first;
    ++__first;
    ++__result;
  }
  return pair<_InputIter, _OutputIter>(__first, __result);
}

template <class _RAIter, class _Size, class _OutputIter>
inline pair<_RAIter, _OutputIter>
__copy_n(_RAIter __first, _Size __count,
         _OutputIter __result,
         const random_access_iterator_tag &) {
  _RAIter __last = __first + __count;
  return pair<_RAIter, _OutputIter>(__last, copy(__first, __last, __result));
}

template <class _InputIter, class _Size, class _OutputIter>
inline pair<_InputIter, _OutputIter>
__copy_n(_InputIter __first, _Size __count, _OutputIter __result) {
  _STLP_FIX_LITERAL_BUG(__first)
  return __copy_n(__first, __count, __result, _STLP_ITERATOR_CATEGORY(__first, _InputIter));
}

template <class _InputIter, class _Size, class _OutputIter>
inline pair<_InputIter, _OutputIter>
copy_n(_InputIter __first, _Size __count, _OutputIter __result) {
  _STLP_FIX_LITERAL_BUG(__first)
  return __copy_n(__first, __count, __result, _STLP_ITERATOR_CATEGORY(__first, _InputIter));
}

//--------------------------------------------------
// fill and fill_n

template <class _ForwardIter, class _Tp>
_STLP_INLINE_LOOP
void fill(_ForwardIter __first, _ForwardIter __last, const _Tp& __val) {
  _STLP_DEBUG_CHECK(__check_range(__first, __last))
  for ( ; __first != __last; ++__first)
    *__first = __val;
}

template <class _OutputIter, class _Size, class _Tp>
_STLP_INLINE_LOOP
_OutputIter fill_n(_OutputIter __first, _Size __n, const _Tp& __val) {
  _STLP_FIX_LITERAL_BUG(__first)
  for ( ; __n > 0; --__n, ++__first)
    *__first = __val;
  return __first;
}

// Specialization: for one-byte types we can use memset.

inline void fill(unsigned char* __first, unsigned char* __last,
                 const unsigned char& __val) {
  unsigned char __tmp = __val;
  memset(__first, __tmp, __last - __first);
}
# ifndef _STLP_NO_SIGNED_BUILTINS
inline void fill(signed char* __first, signed char* __last,
                 const signed char& __val) {
  signed char __tmp = __val;
  memset(__first, __STATIC_CAST(unsigned char,__tmp), __last - __first);
}
# endif
inline void fill(char* __first, char* __last, const char& __val) {
  char __tmp = __val;
  memset(__first, __STATIC_CAST(unsigned char,__tmp), __last - __first);
}

#ifdef _STLP_FUNCTION_TMPL_PARTIAL_ORDER

template <class _Size>
inline unsigned char* fill_n(unsigned char* __first, _Size __n,
                             const unsigned char& __val) {
  fill(__first, __first + __n, __val);
  return __first + __n;
}

template <class _Size>
inline signed char* fill_n(char* __first, _Size __n,
                           const signed char& __val) {
  fill(__first, __first + __n, __val);
  return __first + __n;
}

template <class _Size>
inline char* fill_n(char* __first, _Size __n, const char& __val) {
  fill(__first, __first + __n, __val);
  return __first + __n;
}

#endif /* _STLP_FUNCTION_TMPL_PARTIAL_ORDER */

//--------------------------------------------------
// equal and mismatch

template <class _InputIter1, class _InputIter2>
_STLP_INLINE_LOOP
pair<_InputIter1, _InputIter2> mismatch(_InputIter1 __first1,
                                        _InputIter1 __last1,
                                        _InputIter2 __first2) {
  _STLP_FIX_LITERAL_BUG(__first2)
  _STLP_DEBUG_CHECK(__check_range(__first1, __last1))
  while (__first1 != __last1 && *__first1 == *__first2) {
    ++__first1;
    ++__first2;
  }
  return pair<_InputIter1, _InputIter2>(__first1, __first2);
}

template <class _InputIter1, class _InputIter2, class _BinaryPredicate>
_STLP_INLINE_LOOP
pair<_InputIter1, _InputIter2> mismatch(_InputIter1 __first1,
                                        _InputIter1 __last1,
                                        _InputIter2 __first2,
                                        _BinaryPredicate __binary_pred) {
  _STLP_FIX_LITERAL_BUG(__first2)
  _STLP_DEBUG_CHECK(__check_range(__first1, __last1))
  while (__first1 != __last1 && __binary_pred(*__first1, *__first2)) {
    ++__first1;
    ++__first2;
  }
  return pair<_InputIter1, _InputIter2>(__first1, __first2);
}

template <class _InputIter1, class _InputIter2>
_STLP_INLINE_LOOP
bool equal(_InputIter1 __first1, _InputIter1 __last1,
                  _InputIter2 __first2) {
  _STLP_FIX_LITERAL_BUG(__first1) _STLP_FIX_LITERAL_BUG(__last1)  _STLP_FIX_LITERAL_BUG(__first2)
  _STLP_DEBUG_CHECK(__check_range(__first1, __last1))
  for ( ; __first1 != __last1; ++__first1, ++__first2)
    if (!(*__first1 == *__first2))
      return false;
  return true;
}

template <class _InputIter1, class _InputIter2, class _BinaryPredicate>
_STLP_INLINE_LOOP
bool equal(_InputIter1 __first1, _InputIter1 __last1,
                  _InputIter2 __first2, _BinaryPredicate __binary_pred) {
  _STLP_FIX_LITERAL_BUG(__first2)
  _STLP_DEBUG_CHECK(__check_range(__first1, __last1))
  for ( ; __first1 != __last1; ++__first1, ++__first2)
    if (!__binary_pred(*__first1, *__first2))
      return false;
  return true;
}

//--------------------------------------------------
// lexicographical_compare and lexicographical_compare_3way.
// (the latter is not part of the C++ standard.)

template <class _InputIter1, class _InputIter2>
bool lexicographical_compare(_InputIter1 __first1, _InputIter1 __last1,
                             _InputIter2 __first2, _InputIter2 __last2);

template <class _InputIter1, class _InputIter2, class _Compare>
bool lexicographical_compare(_InputIter1 __first1, _InputIter1 __last1,
                             _InputIter2 __first2, _InputIter2 __last2,
                             _Compare __comp);

inline bool
lexicographical_compare(const unsigned char* __first1,
                        const unsigned char* __last1,
                        const unsigned char* __first2,
                        const unsigned char* __last2)
{
  const size_t __len1 = __last1 - __first1;
  const size_t __len2 = __last2 - __first2;
  _STLP_DEBUG_CHECK(__check_range(__first1, __last1))
  _STLP_DEBUG_CHECK(__check_range(__first2, __last2))

  const int __result = memcmp(__first1, __first2, (min) (__len1, __len2));
  return __result != 0 ? (__result < 0) : (__len1 < __len2);
}

# if !(CHAR_MAX == SCHAR_MAX)
inline bool lexicographical_compare(const char* __first1, const char* __last1,
                                    const char* __first2, const char* __last2)
{
  _STLP_DEBUG_CHECK(__check_range(__first1, __last1))
  _STLP_DEBUG_CHECK(__check_range(__first2, __last2))

  return lexicographical_compare((const unsigned char*) __first1,
                                 (const unsigned char*) __last1,
                                 (const unsigned char*) __first2,
                                 (const unsigned char*) __last2);
}
#endif /* CHAR_MAX == SCHAR_MAX */

template <class _InputIter1, class _InputIter2>
int __lexicographical_compare_3way(_InputIter1 __first1, _InputIter1 __last1,
                                   _InputIter2 __first2, _InputIter2 __last2);

inline int
__lexicographical_compare_3way(const unsigned char* __first1,
                               const unsigned char* __last1,
                               const unsigned char* __first2,
                               const unsigned char* __last2)
{
  const ptrdiff_t __len1 = __last1 - __first1;
  const ptrdiff_t __len2 = __last2 - __first2;
  const int __result = memcmp(__first1, __first2, (min) (__len1, __len2));
  return __result != 0 ? __result
                       : (__len1 == __len2 ? 0 : (__len1 < __len2 ? -1 : 1));
}

# if !(CHAR_MAX == SCHAR_MAX)
inline int
__lexicographical_compare_3way(const char* __first1, const char* __last1,
                               const char* __first2, const char* __last2)
{
  return __lexicographical_compare_3way((const unsigned char*) __first1,
                                        (const unsigned char*) __last1,
                                        (const unsigned char*) __first2,
                                        (const unsigned char*) __last2);
}
# endif

# ifndef _STLP_NO_EXTENSIONS

template <class _InputIter1, class _InputIter2>
int lexicographical_compare_3way(_InputIter1 __first1, _InputIter1 __last1,
                                 _InputIter2 __first2, _InputIter2 __last2);

# endif /* EXTENSIONS */

// count
template <class _InputIter, class _Tp>
_STLP_INLINE_LOOP _STLP_DIFFERENCE_TYPE(_InputIter)
count(_InputIter __first, _InputIter __last, const _Tp& __val) {
  _STLP_DEBUG_CHECK(__check_range(__first, __last))
  _STLP_DIFFERENCE_TYPE(_InputIter) __n = 0;
  for ( ; __first != __last; ++__first)
    if (*__first == __val)
      ++__n;
  return __n;
}

// find and find_if. Note find may be expressed in terms of find_if if appropriate binder was available.
template <class _InputIter, class _Tp>
_InputIter find(_InputIter __first, _InputIter __last, const _Tp& __val);
template <class _InputIter, class _Predicate>
_InputIter find_if(_InputIter __first, _InputIter __last, _Predicate __pred);

// search.
template <class _ForwardIter1, class _ForwardIter2, class _BinaryPred>
_ForwardIter1 search(_ForwardIter1 __first1, _ForwardIter1 __last1,
                     _ForwardIter2 __first2, _ForwardIter2 __last2, _BinaryPred  __predicate);

// find_first_of
template <class _InputIter, class _ForwardIter, class _BinaryPredicate>
_InputIter __find_first_of(_InputIter __first1, _InputIter __last1,
                           _ForwardIter __first2, _ForwardIter __last2,
                           _BinaryPredicate __comp);

template <class _ForwardIter1, class _ForwardIter2,
          class _BinaryPredicate>
_ForwardIter1
find_end(_ForwardIter1 __first1, _ForwardIter1 __last1,
         _ForwardIter2 __first2, _ForwardIter2 __last2,
         _BinaryPredicate __comp);

// replace
template <class _ForwardIter, class _Tp>
_STLP_INLINE_LOOP void
replace(_ForwardIter __first, _ForwardIter __last,
        const _Tp& __old_value, const _Tp& __new_value) {
  _STLP_DEBUG_CHECK(__check_range(__first, __last))
  for ( ; __first != __last; ++__first)
    if (*__first == __old_value)
      *__first = __new_value;
}

template <class _ForwardIter, class _Tp, class _Compare, class _Distance>
_ForwardIter __lower_bound(_ForwardIter __first, _ForwardIter __last,
                              const _Tp& __val, _Compare __comp, _Distance*);

_STLP_END_NAMESPACE

# if !defined (_STLP_LINK_TIME_INSTANTIATION)
#  include <stl/_algobase.c>
# endif

#endif /* _STLP_INTERNAL_ALGOBASE_H */

// Local Variables:
// mode:C++
// End:


text:
package com.github.danielwegener.logback.kafka.encoding;

import ch.qos.logback.core.Layout;

import java.nio.charset.Charset;

/**
 * @deprecated Use LayoutKafkaMessageEncoder instead!
 * @since 0.0.1
 */
@Deprecated
public class PatternLayoutKafkaMessageEncoder<E> extends LayoutKafkaMessageEncoder<E> {

    public PatternLayoutKafkaMessageEncoder() {}

    public PatternLayoutKafkaMessageEncoder(Layout<E> layout, Charset charset) {
        super(layout, charset);
    }
}

redpajama_set_name: RedPajamaGithub


text:
from django.core.checks import Error
from django.core.checks.translation import (
    check_language_settings_consistent,
    check_setting_language_code,
    check_setting_languages,
    check_setting_languages_bidi,
)
from django.test import SimpleTestCase, override_settings

class TranslationCheckTests(SimpleTestCase):
    def setUp(self):
        self.valid_tags = (
            "en",  # language
            "mas",  # language
            "sgn-ase",  # language+extlang
            "fr-CA",  # language+region
            "es-419",  # language+region
            "zh-Hans",  # language+script
            "ca-ES-valencia",  # language+region+variant
            # FIXME: The following should be invalid:
            "sr@latin",  # language+script
        )
        self.invalid_tags = (
            None,  # invalid type: None.
            123,  # invalid type: int.
            b"en",  # invalid type: bytes.
            "eü",  # non-latin characters.
            "en_US",  # locale format.
            "en--us",  # empty subtag.
            "-en",  # leading separator.
            "en-",  # trailing separator.
            "en-US.UTF-8",  # language tag w/ locale encoding.
            "en_US.UTF-8",  # locale format - language w/ region and encoding.
            "ca_ES@valencia",  # locale format - language w/ region and variant.
            # FIXME: The following should be invalid:
            # 'sr@latin',      # locale instead of language tag.
        )

    def test_valid_language_code(self):
        for tag in self.valid_tags:
            with self.subTest(tag), self.settings(LANGUAGE_CODE=tag):
                self.assertEqual(check_setting_language_code(None), [])

    def test_invalid_language_code(self):
        msg = "You have provided an invalid value for the LANGUAGE_CODE setting: %r."
        for tag in self.invalid_tags:
            with self.subTest(tag), self.settings(LANGUAGE_CODE=tag):
                self.assertEqual(
                    check_setting_language_code(None),
                    [
                        Error(msg % tag, id="translation.E001"),
                    ],
                )

    def test_valid_languages(self):
        for tag in self.valid_tags:
            with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]):
                self.assertEqual(check_setting_languages(None), [])

    def test_invalid_languages(self):
        msg = "You have provided an invalid language code in the LANGUAGES setting: %r."
        for tag in self.invalid_tags:
            with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]):
                self.assertEqual(
                    check_setting_languages(None),
                    [
                        Error(msg % tag, id="translation.E002"),
                    ],
                )

    def test_valid_languages_bidi(self):
        for tag in self.valid_tags:
            with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]):
                self.assertEqual(check_setting_languages_bidi(None), [])

    def test_invalid_languages_bidi(self):
        msg = (
            "You have provided an invalid language code in the LANGUAGES_BIDI setting: "
            "%r."
        )
        for tag in self.invalid_tags:
            with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]):
                self.assertEqual(
                    check_setting_languages_bidi(None),
                    [
                        Error(msg % tag, id="translation.E003"),
                    ],
                )

    @override_settings(USE_I18N=True, LANGUAGES=[("en", "English")])
    def test_inconsistent_language_settings(self):
        msg = (
            "You have provided a value for the LANGUAGE_CODE setting that is "
            "not in the LANGUAGES setting."
        )
        for tag in ["fr", "fr-CA", "fr-357"]:
            with self.subTest(tag), self.settings(LANGUAGE_CODE=tag):
                self.assertEqual(
                    check_language_settings_consistent(None),
                    [
                        Error(msg, id="translation.E004"),
                    ],
                )

    @override_settings(
        USE_I18N=True,
        LANGUAGES=[
            ("de", "German"),
            ("es", "Spanish"),
            ("fr", "French"),
            ("ca", "Catalan"),
        ],
    )
    def test_valid_variant_consistent_language_settings(self):
        tests = [
            # language + region.
            "fr-CA",
            "es-419",
            "de-at",
            # language + region + variant.
            "ca-ES-valencia",
        ]
        for tag in tests:
            with self.subTest(tag), self.settings(LANGUAGE_CODE=tag):
                self.assertEqual(check_language_settings_consistent(None), [])


text:
package com.android.tools.idea.sdk.remote.internal.updater;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.sdklib.SdkManager;
import com.android.tools.idea.sdk.remote.internal.*;
import com.android.tools.idea.sdk.remote.internal.sources.SdkRepoConstants;
import com.android.utils.ILogger;
import com.android.utils.IReaderLogger;
import com.android.utils.Pair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

/**
 * Performs an update using only a non-interactive console output with no GUI.
 */
public class SdkUpdaterNoWindow {

  /**
   * The {@link UpdaterData} to use.
   */
  private final UpdaterData mUpdaterData;
  /**
   * The {@link ILogger} logger to use.
   */
  private final ILogger mSdkLog;
  /**
   * The reply to any question asked by the update process. Currently this will
   * be yes/no for ability to replace modified samples or restart ADB.
   */
  private final boolean mForce;

  /**
   * Creates an UpdateNoWindow object that will update using the given SDK root
   * and outputs to the given SDK logger.
   *
   * @param osSdkRoot  The OS path of the SDK folder to update.
   * @param sdkManager An existing SDK manager to list current platforms and addons.
   * @param sdkLog     A logger object, that should ideally output to a write-only console.
   * @param force      The reply to any question asked by the update process. Currently this will
   *                   be yes/no for ability to replace modified samples or restart ADB.
   * @param useHttp    True to force using HTTP instead of HTTPS for downloads.
   * @param proxyPort  An optional HTTP/HTTPS proxy port. Can be null.
   * @param proxyHost  An optional HTTP/HTTPS proxy host. Can be null.
   */
  public SdkUpdaterNoWindow(String osSdkRoot,
                            SdkManager sdkManager,
                            ILogger sdkLog,
                            boolean force,
                            boolean useHttp,
                            String proxyHost,
                            String proxyPort) {
    mSdkLog = sdkLog;
    mForce = force;
    mUpdaterData = new UpdaterData(osSdkRoot, sdkLog);

    // Read and apply settings from settings file, so that http/https proxy is set
    // and let the command line args override them as necessary.
    SettingsController settingsController = mUpdaterData.getSettingsController();
    settingsController.loadSettings();
    settingsController.applySettings();
    setupProxy(proxyHost, proxyPort);

    // Change the in-memory settings to force the http/https mode
    settingsController.setSetting(SettingsController.KEY_FORCE_HTTP, useHttp);

    // Use a factory that only outputs to the given ILogger.
    mUpdaterData.setTaskFactory(new ConsoleTaskFactory());

    // Setup the default sources including the getenv overrides.
    mUpdaterData.setupDefaultSources();
  }

  /**
   * Performs the actual update.
   *
   * @param pkgFilter           A list of {@link SdkRepoConstants#NODES} to limit the type of packages
   *                            we can update. A null or empty list means to update everything possible.
   * @param includeAll          True to list and install all packages, including obsolete ones.
   * @param dryMode             True to check what would be updated/installed but do not actually
   *                            download or install anything.
   * @param acceptLicense       SDK licenses to automatically accept.
   * @param includeDependencies If true, also include any required dependencies
   */
  public void updateAll(ArrayList<String> pkgFilter,
                        boolean includeAll,
                        boolean dryMode,
                        String acceptLicense,
                        boolean includeDependencies) {
    mUpdaterData.updateOrInstallAll_NoGUI(pkgFilter, includeAll, dryMode, acceptLicense, includeDependencies);
  }

  // -----

  /**
   * Sets both the HTTP and HTTPS proxy system properties, overriding the ones
   * from the settings with these values if they are defined.
   */
  private void setupProxy(String proxyHost, String proxyPort) {

    // The system property constants can be found in the Java SE documentation at
    // http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
    final String JAVA_PROP_HTTP_PROXY_HOST = "http.proxyHost";      //$NON-NLS-1$
    final String JAVA_PROP_HTTP_PROXY_PORT = "http.proxyPort";      //$NON-NLS-1$
    final String JAVA_PROP_HTTPS_PROXY_HOST = "https.proxyHost";     //$NON-NLS-1$
    final String JAVA_PROP_HTTPS_PROXY_PORT = "https.proxyPort";     //$NON-NLS-1$

    Properties props = System.getProperties();

    if (proxyHost != null && proxyHost.length() > 0) {
      props.setProperty(JAVA_PROP_HTTP_PROXY_HOST, proxyHost);
      props.setProperty(JAVA_PROP_HTTPS_PROXY_HOST, proxyHost);
    }
    if (proxyPort != null && proxyPort.length() > 0) {
      props.setProperty(JAVA_PROP_HTTP_PROXY_PORT, proxyPort);
      props.setProperty(JAVA_PROP_HTTPS_PROXY_PORT, proxyPort);
    }
  }

  /**
   * A custom implementation of {@link ITaskFactory} that
   * provides {@link ConsoleTaskMonitor} objects.
   */
  private class ConsoleTaskFactory implements ITaskFactory {
    @Override
    public void start(String title, ITask task) {
      start(title, null /*parentMonitor*/, task);
    }

    @Override
    public void start(String title, ITaskMonitor parentMonitor, ITask task) {
      if (parentMonitor == null) {
        task.run(new ConsoleTaskMonitor(title, task));
      }
      else {
        // Use all the reminder of the parent monitor.
        if (parentMonitor.getProgressMax() == 0) {
          parentMonitor.setProgressMax(1);
        }

        ITaskMonitor sub = parentMonitor.createSubMonitor(parentMonitor.getProgressMax() - parentMonitor.getProgress());
        try {
          task.run(sub);
        }
        finally {
          int delta = sub.getProgressMax() - sub.getProgress();
          if (delta > 0) {
            sub.incProgress(delta);
          }
        }
      }
    }
  }

  /**
   * A custom implementation of {@link ITaskMonitor} that defers all output to the
   * super {@link SdkUpdaterNoWindow#mSdkLog}.
   */
  private class ConsoleTaskMonitor implements ITaskMonitor {

    private static final double MAX_COUNT = 10000.0;
    private double mIncCoef = 0;
    private double mValue = 0;
    private String mLastDesc = null;
    private String mLastProgressBase = null;

    /**
     * Creates a new {@link ConsoleTaskMonitor} with the given title.
     */
    public ConsoleTaskMonitor(String title, ITask task) {
      mSdkLog.info("%s:\n", title);
    }

    /**
     * Sets the description in the current task dialog.
     */
    @Override
    public void setDescription(String format, Object... args) {

      String last = mLastDesc;
      String line = String.format("  " + format, args);                       //$NON-NLS-1$

      // If the description contains a %, it generally indicates a recurring
      // progress so we want a \r at the end.
      int pos = line.indexOf('%');
      if (pos > -1) {
        String base = line.trim();
        if (mLastProgressBase != null && base.startsWith(mLastProgressBase)) {
          line = "    " + base.substring(mLastProgressBase.length());     //$NON-NLS-1$
        }
        line += '\r';
      }
      else {
        mLastProgressBase = line.trim();
        line += '\n';
      }

      // Skip line if it's the same as the last one.
      if (last != null && last.equals(line.trim())) {
        return;
      }
      mLastDesc = line.trim();

      // If the last line terminated with a \r but the new one doesn't, we need to
      // insert a \n to avoid erasing the previous line.
      if (last != null &&
          last.endsWith("\r") &&                                          //$NON-NLS-1$
          !line.endsWith("\r")) {                                         //$NON-NLS-1$
        line = '\n' + line;
      }

      mSdkLog.info("%s", line);                                             //$NON-NLS-1$
    }

    @Override
    public void log(String format, Object... args) {
      setDescription("  " + format, args);                                    //$NON-NLS-1$
    }

    @Override
    public void logError(String format, Object... args) {
      setDescription(format, args);
    }

    @Override
    public void logVerbose(String format, Object... args) {
      // The ConsoleTask does not display verbose log messages.
    }

    // --- ILogger ---

    @Override
    public void error(@Nullable Throwable t, @Nullable String errorFormat, Object... args) {
      mSdkLog.error(t, errorFormat, args);
    }

    @Override
    public void warning(@NonNull String warningFormat, Object... args) {
      mSdkLog.warning(warningFormat, args);
    }

    @Override
    public void info(@NonNull String msgFormat, Object... args) {
      mSdkLog.info(msgFormat, args);
    }

    @Override
    public void verbose(@NonNull String msgFormat, Object... args) {
      mSdkLog.verbose(msgFormat, args);
    }

    /**
     * Sets the max value of the progress bar.
     *

     * Weird things will happen if setProgressMax is called multiple times
     * *after* {@link #incProgress(int)}: we don't try to adjust it on the
     * fly.
     */
    @Override
    public void setProgressMax(int max) {
      assert max > 0;
      // Always set the dialog's progress max to 10k since it only handles
      // integers and we want to have a better inner granularity. Instead
      // we use the max to compute a coefficient for inc deltas.
      mIncCoef = max > 0 ? MAX_COUNT / max : 0;
      assert mIncCoef > 0;
    }

    @Override
    public int getProgressMax() {
      return mIncCoef > 0 ? (int)(MAX_COUNT / mIncCoef) : 0;
    }

    /**
     * Increments the current value of the progress bar.
     */
    @Override
    public void incProgress(int delta) {
      if (delta > 0 && mIncCoef > 0) {
        internalIncProgress(delta * mIncCoef);
      }
    }

    private void internalIncProgress(double realDelta) {
      mValue += realDelta;
      // max value is 10k, so 10k/100 == 100%.
      // Experimentation shows that it is not really useful to display this
      // progression since during download the description line will change.
      // mSdkLog.printf("    [%3d%%]\r", ((int)mValue) / 100);
    }

    /**
     * Returns the current value of the progress bar,
     * between 0 and up to {@link #setProgressMax(int)} - 1.
     */
    @Override
    public int getProgress() {
      assert mIncCoef > 0;
      return mIncCoef > 0 ? (int)(mValue / mIncCoef) : 0;
    }

    /**
     * Returns true if the "Cancel" button was selected.
     */
    @Override
    public boolean isCancelRequested() {
      return false;
    }

    /**
     * Display a yes/no question dialog box.
     *

     * This implementation allow this to be called from any thread, it
     * makes sure the dialog is opened synchronously in the ui thread.
     *
     * @param title   The title of the dialog box
     * @param message The error message
     * @return true if YES was clicked.
     */
    @Override
    public boolean displayPrompt(final String title, final String message) {
      // TODO Make it interactive if mForce==false
      mSdkLog.info("\n%1$s\n%2$s\n%3$s",        //$NON-NLS-1$
                   title, message, mForce ? "--force used, will reply yes\n" : "Note: you  can use --force to override to yes.\n");
      if (mForce) {
        return true;
      }

      while (true) {
        mSdkLog.info("%1$s", "[y/n] =>");     //$NON-NLS-1$
        try {
          byte[] readBuffer = new byte[2048];
          String reply = readLine(readBuffer).trim();
          mSdkLog.info("\n");               //$NON-NLS-1$
          if (reply.length() > 0 && reply.length() <= 3) {
            char c = reply.charAt(0);
            if (c == 'y' || c == 'Y') {
              return true;
            }
            else if (c == 'n' || c == 'N') {
              return false;
            }
          }
          mSdkLog.info("Unknown reply '%s'. Please use y[es]/n[o].\n");  //$NON-NLS-1$

        }
        catch (IOException e) {
          // Exception. Be conservative and say no.
          mSdkLog.info("\n");               //$NON-NLS-1$
          return false;
        }
      }
    }

    /**
     * Displays a prompt message to the user and read two values,
     * login/password.
     *

     * Asks user for login/password information.
     *

     * This method shows a question in the standard output, asking for login
     * and password.

     * Method Output:

     * Title

     * Message

     * Login: (Wait for user input)

     * Password: (Wait for user input)

     *

     *
     * @param title   The title of the iteration.
     * @param message The message to be displayed.
     * @return A {@link Pair} holding the entered login and password. The
     * first element is always the Login, and the
     * second element is always the Password. This
     * method will never return null, in case of error the pair will
     * be filled with empty strings.
     * @see ITaskMonitor#displayLoginCredentialsPrompt(String, String)
     */
    @Override
    public UserCredentials displayLoginCredentialsPrompt(String title, String message) {
      String login = "";    //$NON-NLS-1$
      String password = ""; //$NON-NLS-1$
      String workstation = ""; //$NON-NLS-1$
      String domain = ""; //$NON-NLS-1$

      mSdkLog.info("\n%1$s\n%2$s", title, message);
      byte[] readBuffer = new byte[2048];
      try {
        mSdkLog.info("\nLogin: ");
        login = readLine(readBuffer);
        mSdkLog.info("\nPassword: ");
        password = readLine(readBuffer);
        mSdkLog.info("\nIf your proxy uses NTLM authentication, provide the following information. Leave blank otherwise.");
        mSdkLog.info("\nWorkstation: ");
        workstation = readLine(readBuffer);
        mSdkLog.info("\nDomain: ");
        domain = readLine(readBuffer);

                /*
                 * TODO: Implement a way to don't echo the typed password On
                 * Java 5 there's no simple way to do this. There's just a
                 * workaround which is output backspaces on each keystroke.
                 * A good alternative is to use Java 6 java.io.Console
                 */
      }
      catch (IOException e) {
        // Reset login/pass to empty Strings.
        login = "";    //$NON-NLS-1$
        password = ""; //$NON-NLS-1$
        workstation = ""; //$NON-NLS-1$
        domain = ""; //$NON-NLS-1$
        //Just print the error to console.
        mSdkLog.info("\nError occurred during login/pass query: %s\n", e.getMessage());
      }

      return new UserCredentials(login, password, workstation, domain);
    }

    /**
     * Reads current console input in the given buffer.
     *
     * @param buffer Buffer to hold the user input. Must be larger than the largest
     *               expected input. Cannot be null.
     * @return A new string. May be empty but not null.
     * @throws IOException in case the buffer isn't long enough.
     */
    private String readLine(byte[] buffer) throws IOException {

      int count;
      if (mSdkLog instanceof IReaderLogger) {
        count = ((IReaderLogger)mSdkLog).readLine(buffer);
      }
      else {
        count = System.in.read(buffer);
      }

      // is the input longer than the buffer?
      if (count == buffer.length && buffer[count - 1] != 10) {
        throw new IOException(String.format("Input is longer than the buffer size, (%1$s) bytes", buffer.length));
      }

      // ignore end whitespace
      while (count > 0 && (buffer[count - 1] == '\r' || buffer[count - 1] == '\n')) {
        count--;
      }

      return new String(buffer, 0, count);
    }

    /**
     * Creates a sub-monitor that will use up to tickCount on the progress bar.
     * tickCount must be 1 or more.
     */
    @Override
    public ITaskMonitor createSubMonitor(int tickCount) {
      assert mIncCoef > 0;
      assert tickCount > 0;
      return new ConsoleSubTaskMonitor(this, null, mValue, tickCount * mIncCoef);
    }
  }

  private interface IConsoleSubTaskMonitor extends ITaskMonitor {
    void subIncProgress(double realDelta);
  }

  private static class ConsoleSubTaskMonitor implements IConsoleSubTaskMonitor {

    private final ConsoleTaskMonitor mRoot;
    private final IConsoleSubTaskMonitor mParent;
    private final double mStart;
    private final double mSpan;
    private double mSubValue;
    private double mSubCoef;

    /**
     * Creates a new sub task monitor which will work for the given range [start, start+span]
     * in its parent.
     *
     * @param root   The ProgressTask root
     * @param parent The immediate parent. Can be the null or another sub task monitor.
     * @param start  The start value in the root's coordinates
     * @param span   The span value in the root's coordinates
     */
    public ConsoleSubTaskMonitor(ConsoleTaskMonitor root, IConsoleSubTaskMonitor parent, double start, double span) {
      mRoot = root;
      mParent = parent;
      mStart = start;
      mSpan = span;
      mSubValue = start;
    }

    @Override
    public boolean isCancelRequested() {
      return mRoot.isCancelRequested();
    }

    @Override
    public void setDescription(String format, Object... args) {
      mRoot.setDescription(format, args);
    }

    @Override
    public void log(String format, Object... args) {
      mRoot.log(format, args);
    }

    @Override
    public void logError(String format, Object... args) {
      mRoot.logError(format, args);
    }

    @Override
    public void logVerbose(String format, Object... args) {
      mRoot.logVerbose(format, args);
    }

    @Override
    public void setProgressMax(int max) {
      assert max > 0;
      mSubCoef = max > 0 ? mSpan / max : 0;
      assert mSubCoef > 0;
    }

    @Override
    public int getProgressMax() {
      return mSubCoef > 0 ? (int)(mSpan / mSubCoef) : 0;
    }

    @Override
    public int getProgress() {
      assert mSubCoef > 0;
      return mSubCoef > 0 ? (int)((mSubValue - mStart) / mSubCoef) : 0;
    }

    @Override
    public void incProgress(int delta) {
      if (delta > 0 && mSubCoef > 0) {
        subIncProgress(delta * mSubCoef);
      }
    }

    @Override
    public void subIncProgress(double realDelta) {
      mSubValue += realDelta;
      if (mParent != null) {
        mParent.subIncProgress(realDelta);
      }
      else {
        mRoot.internalIncProgress(realDelta);
      }
    }

    @Override
    public boolean displayPrompt(String title, String message) {
      return mRoot.displayPrompt(title, message);
    }

    @Override
    public UserCredentials displayLoginCredentialsPrompt(String title, String message) {
      return mRoot.displayLoginCredentialsPrompt(title, message);
    }

    @Override
    public ITaskMonitor createSubMonitor(int tickCount) {
      assert mSubCoef > 0;
      assert tickCount > 0;
      return new ConsoleSubTaskMonitor(mRoot, this, mSubValue, tickCount * mSubCoef);
    }

    // --- ILogger ---

    @Override
    public void error(@Nullable Throwable t, @Nullable String errorFormat, Object... args) {
      mRoot.error(t, errorFormat, args);
    }

    @Override
    public void warning(@NonNull String warningFormat, Object... args) {
      mRoot.warning(warningFormat, args);
    }

    @Override
    public void info(@NonNull String msgFormat, Object... args) {
      mRoot.info(msgFormat, args);
    }

    @Override
    public void verbose(@NonNull String msgFormat, Object... args) {
      mRoot.verbose(msgFormat, args);
    }
  }
}


text:
Utilities
=========

Last Updated 2018-05-24

Subscriber Has Active Subscription Check
----------------------------------------
.. automethod:: djstripe.utils.subscriber_has_active_subscription

Supported Currency Choice Generator
-----------------------------------
.. automethod:: djstripe.utils.get_supported_currency_choices

Clear Expired Idempotency Keys
------------------------------
.. automethod:: djstripe.utils.clear_expired_idempotency_keys

Convert Stripe Timestamp to Datetime
------------------------------------
.. automethod:: djstripe.utils.convert_tstamp

Friendly Currency Amount String
-------------------------------
.. automethod:: djstripe.utils.get_friendly_currency_amount


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/item_logo_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/default_user_avatar"
    />

    <TextView
        android:id="@+id/item_title_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/item_logo_view"
        android:layout_toRightOf="@id/item_logo_view"
        android:text="微微一笑很优酷"
        android:textColor="@color/color_333333"
        android:textSize="18sp"
        android:textStyle="bold"/>

    <ImageView
        android:id="@+id/item_share_view"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/item_title_view"
        android:layout_marginRight="15dp"
        android:background="@drawable/trade_share"
    />

    <TextView
        android:id="@+id/item_info_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/item_logo_view"
        android:layout_toRightOf="@id/item_logo_view"
        android:text="@string/video"
        android:textColor="@color/result_view"
        android:textSize="16sp"
    />

    <RelativeLayout
        android:id="@+id/video_ad_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/item_logo_view"
    />

    <TextView
        android:id="@+id/item_footer_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/video_ad_layout"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:text="杨洋郑爽"聊"破次元盛,甜蜜演绎《微微一笑很优酷》优酷独家热播中"
        android:textColor="@color/color_333333"
        android:textSize="16sp"/>
</RelativeLayout>


text:
namespace {

GURL GetURLForLayoutTest(const std::string& test_name,
                         FilePath* current_working_directory,
                         bool* enable_pixel_dumping,
                         std::string* expected_pixel_hash) {
  // A test name is formated like file:///path/to/test'--pixel-test'pixelhash
  std::string path_or_url = test_name;
  std::string pixel_switch;
  std::string pixel_hash;
  std::string::size_type separator_position = path_or_url.find('\'');
  if (separator_position != std::string::npos) {
    pixel_switch = path_or_url.substr(separator_position + 1);
    path_or_url.erase(separator_position);
  }
  separator_position = pixel_switch.find('\'');
  if (separator_position != std::string::npos) {
    pixel_hash = pixel_switch.substr(separator_position + 1);
    pixel_switch.erase(separator_position);
  }
  if (enable_pixel_dumping) {
    *enable_pixel_dumping =
        (pixel_switch == "--pixel-test" || pixel_switch == "-p");
  }
  if (expected_pixel_hash)
    *expected_pixel_hash = pixel_hash;
  GURL test_url(path_or_url);
  if (!(test_url.is_valid() && test_url.has_scheme())) {
#if defined(OS_WIN)
    std::wstring wide_path_or_url =
        base::SysNativeMBToWide(path_or_url);
    test_url = net::FilePathToFileURL(FilePath(wide_path_or_url));
#else
    test_url = net::FilePathToFileURL(FilePath(path_or_url));
#endif
  }
  FilePath local_path;
  {
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    if (net::FileURLToFilePath(test_url, &local_path)) {
      // We're outside of the message loop here, and this is a test.
      file_util::SetCurrentDirectory(local_path.DirName());
    }
    if (current_working_directory)
      file_util::GetCurrentDirectory(current_working_directory);
  }
  return test_url;
}

bool GetNextTest(const CommandLine::StringVector& args,
                 size_t* position,
                 std::string* test) {
  if (*position >= args.size())
    return false;
  if (args[*position] == FILE_PATH_LITERAL("-"))
    return !!std::getline(std::cin, *test, '\n');
#if defined(OS_WIN)
  *test = WideToUTF8(args[(*position)++]);
#else
  *test = args[(*position)++];
#endif
  return true;
}

}  // namespace

// Main routine for running as the Browser process.
int ShellBrowserMain(const content::MainFunctionParams& parameters) {
  scoped_ptr<content::BrowserMainRunner> main_runner_(
      content::BrowserMainRunner::Create());

  int exit_code = main_runner_->Initialize(parameters);

  if (exit_code >= 0)
    return exit_code;

  if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kCheckLayoutTestSysDeps)) {
    return 0;
  }

  bool layout_test_mode =
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);

  if (layout_test_mode) {
    content::WebKitTestController test_controller;
    std::string test_string;
    CommandLine::StringVector args =
        CommandLine::ForCurrentProcess()->GetArgs();
    size_t command_line_position = 0;

#if defined(OS_ANDROID)
    std::cout << "#READY\n";
    std::cout.flush();
#endif

    while (GetNextTest(args, &command_line_position, &test_string)) {
      if (test_string.empty())
        continue;
      if (test_string == "QUIT")
        break;

      bool enable_pixel_dumps;
      std::string pixel_hash;
      FilePath cwd;
      GURL test_url = GetURLForLayoutTest(
          test_string, &cwd, &enable_pixel_dumps, &pixel_hash);
      if (!content::WebKitTestController::Get()->PrepareForLayoutTest(
              test_url, cwd, enable_pixel_dumps, pixel_hash)) {
        break;
      }

      main_runner_->Run();

      if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())
        break;
    }
    exit_code = 0;
  } else {
    exit_code = main_runner_->Run();
  }

  main_runner_->Shutdown();

  return exit_code;
}


text:
namespace Microsoft.Azure.Management.DataShare.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The data share error body model.
    /// </summary>
    public partial class DataShareErrorInfo
    {
        /// <summary>
        /// Initializes a new instance of the DataShareErrorInfo class.
        /// </summary>
        public DataShareErrorInfo()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the DataShareErrorInfo class.
        /// </summary>
        /// <param name="code">Code of the error</param>
        /// <param name="message">Message of the error</param>
        /// <param name="details">Nested details of the error model</param>
        /// <param name="target">Target of the error</param>
        public DataShareErrorInfo(string code, string message, IList<DataShareErrorInfo> details = default(IList<DataShareErrorInfo>), string target = default(string))
        {
            Code = code;
            Details = details;
            Message = message;
            Target = target;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets code of the error
        /// </summary>
        [JsonProperty(PropertyName = "code")]
        public string Code { get; set; }

        /// <summary>
        /// Gets or sets nested details of the error model
        /// </summary>
        [JsonProperty(PropertyName = "details")]
        public IList<DataShareErrorInfo> Details { get; set; }

        /// <summary>
        /// Gets or sets message of the error
        /// </summary>
        [JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

        /// <summary>
        /// Gets or sets target of the error
        /// </summary>
        [JsonProperty(PropertyName = "target")]
        public string Target { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Code == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Code");
            }
            if (Message == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Message");
            }
            if (Details != null)
            {
                foreach (var element in Details)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
        }
    }
}


text:
Math.js contains the following constants.

Constant        | Description | Value
--------------- | ----------- | -----
`e`, `E`        | Euler's number, the base of the natural logarithm. | 2.718281828459045
`i`             | Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part. | `sqrt(-1)`
`Infinity`      | Infinity, a number which is larger than the maximum number that can be handled by a floating point number. | `Infinity`
`LN2`           | Returns the natural logarithm of 2. | `0.6931471805599453`
`LN10`          | Returns the natural logarithm of 10. | `2.302585092994046`
`LOG2E`         | Returns the base-2 logarithm of E. | `1.4426950408889634`
`LOG10E`        | Returns the base-10 logarithm of E. | `0.4342944819032518`
`NaN`           | Not a number. | `NaN`
`null`          | Value null. | `null`
`phi`           | Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` | `1.618033988749895`
`pi`, `PI`      | The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter. | `3.141592653589793`
`SQRT1_2`       | Returns the square root of 1/2. | `0.7071067811865476`
`SQRT2`         | Returns the square root of 2. | `1.4142135623730951`
`tau`           | Tau is the ratio constant of a circle\'s circumference to radius, equal to `2 * pi`. | `6.283185307179586`
`undefined`     | An undefined value. Preferably, use `null` to indicate undefined values. | `undefined`
`version`       | Returns the version number of math.js. | For example `0.24.1`

Example usage:

```js
math.sin(math.pi / 4)          // 0.70711
math.multiply(math.i, math.i)  // -1
```


text:
@interface PBTestZeroEspressos ()

@property (nonatomic, copy) NSMutableAttributedString *lastAttributedString;

@end

@implementation PBTestZeroEspressos

- (NSMutableArray *)imageObjs {
    if (_imageObjs == nil) {
        _imageObjs = [NSMutableArray array];
    }
    return _imageObjs;
}

+ (id)testZeroEspressosWithHtmlStr:(NSString *)htmlStr {
    return [[self alloc] initWithHtmlStr:htmlStr];
}

- (id)initWithHtmlStr:(NSString *)htmlStr {
    if ([super init]) {
        // 替换为能够识别的标签
        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@""];

        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"<span" withString:@"" withString:@"strong>"];

        {
            NSMutableArray *objs = [NSMutableArray array];

            NSArray *tmpArr = [htmlStr componentsSeparatedByString:@"
"];
            for (NSString *tmpStr in tmpArr) {
                NSArray *arr = [tmpStr componentsSeparatedByString:@"
"];
                [objs addObjectsFromArray:arr];
            }
            NSLog(@"objs = %@", objs);

            NSMutableString *tmpHtmlStr = [NSMutableString string];
            for (int i = 0; i < objs.count; i++) {
                NSString *tmpStr = [NSString stringWithFormat:@"
%@
", objs[i]];
                [tmpHtmlStr appendString:tmpStr];
            }
            NSLog(@"tmpHtmlStr = %@", tmpHtmlStr);

            htmlStr = tmpHtmlStr;
        }

        TFHpple *hpple = [[TFHpple alloc]initWithHTMLData:[htmlStr dataUsingEncoding:NSUTF8StringEncoding]];
        NSArray *pEle = [hpple searchWithXPathQuery:@"//p"];

        // pEle表示所有p标签组成的数组

        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]init];

        NSMutableArray *imageArr = [NSMutableArray array];
        NSMutableArray *imageViewArr = [NSMutableArray array];

        for (TFHppleElement *hppleEle in pEle) { // 每执行一次此循环,会换一次行
            // hppleEle表示所有p标签组成的数组中的其中一个p标签

            self.lastAttributedString = attributedString.copy;

            for (int i = 0; i < hppleEle.children.count; i++) {
                TFHppleElement *ele = hppleEle.children[i];

                // 去除首尾空格和换行
                //NSString *content = [ele.content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

                if ([ele.tagName isEqualToString:@"text"]) {
                    NSMutableAttributedString *tmpStr = [[NSMutableAttributedString alloc]initWithString:[ele.content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                    [tmpStr yy_setFont:[UIFont systemFontOfSize:17] range:NSMakeRange(0, tmpStr.length)];
                    [tmpStr yy_setColor:UIColorFromRGB(0x666666) range:NSMakeRange(0, tmpStr.length)];
                    [tmpStr yy_setLineSpacing:10 range:NSMakeRange(0, tmpStr.length)];

                    [attributedString appendAttributedString:tmpStr];
                }

                if ([ele.tagName isEqualToString:@"strong"]) {
                    // strong->img
                    for (int j = 0; j < ele.children.count; j++) {
                        TFHppleElement *elee = ele.children[j];

                        if ([elee.tagName isEqualToString:@"text"]) {
                            NSMutableAttributedString *tmpStr = [[NSMutableAttributedString alloc]initWithString:[elee.content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                            [tmpStr yy_setFont:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, tmpStr.length)];
                            [tmpStr yy_setColor:[UIColor redColor] range:NSMakeRange(0, tmpStr.length)];
                            [tmpStr yy_setLineSpacing:10 range:NSMakeRange(0, tmpStr.length)];

                            [attributedString appendAttributedString:tmpStr];
                        }

                        if ([elee.tagName isEqualToString:@"img"]) {
                            CGFloat height = [elee.attributes[@"height"] floatValue];
                            CGFloat width = [elee.attributes[@"width"] floatValue];

                            CGFloat imageViewW = [UIScreen mainScreen].bounds.size.width-20;
                            CGFloat imageViewH = 0;
                            if (width != 0 && height != 0) {
                                imageViewH = (imageViewW/width) * height;
                            } else {
                                imageViewH = (0.618) * imageViewW;
                            }

                            PBContentModel *contentModel = [[PBContentModel alloc]init];
                            contentModel.isImg = YES;
                            contentModel.src = elee.attributes[@"src"];
                            contentModel.imgWidth = imageViewW;
                            contentModel.imgHeight = imageViewH;

                            [imageArr addObject:elee.attributes[@"src"]];

                            {
                                UIImageView *imageView = [[UIImageView alloc]init];
                                imageView.frame = CGRectMake(0, 0, imageViewW, imageViewH);
                                imageView.backgroundColor = [UIColor lightGrayColor];
                                [imageView sd_setImageWithURL:[NSURL URLWithString:contentModel.src]];
                                imageView.layer.cornerRadius = 10;
                                imageView.layer.masksToBounds = YES;
                                imageView.userInteractionEnabled = YES;

                                [imageViewArr addObject:imageView];

                                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
                                [imageView addGestureRecognizer:tap];
                                tap.view.tag = imageArr.count-1;

                                NSMutableAttributedString *tmpStr = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.frame.size alignToFont:[UIFont boldSystemFontOfSize:17] alignment:YYTextVerticalAlignmentCenter];
                                [tmpStr yy_setLineSpacing:10 range:tmpStr.yy_rangeOfAll];

                                [attributedString appendAttributedString:tmpStr];
                            }
                        }

                        if ([elee.tagName isEqualToString:@"a"]) {
                            NSMutableAttributedString *tmpStr = [[NSMutableAttributedString alloc]initWithString:[elee.content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                            [tmpStr yy_setFont:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, tmpStr.length)];
                            [tmpStr yy_setColor:[UIColor blueColor] range:NSMakeRange(0, tmpStr.length)];
                            [tmpStr yy_setLineSpacing:10 range:NSMakeRange(0, tmpStr.length)];

                            [attributedString appendAttributedString:tmpStr];
                        }
                    }
                }

                if ([ele.tagName isEqualToString:@"img"]) {
                    CGFloat height = [ele.attributes[@"height"] floatValue];
                    CGFloat width = [ele.attributes[@"width"] floatValue];

                    CGFloat imageViewW = [UIScreen mainScreen].bounds.size.width-20;
                    CGFloat imageViewH = 0;
                    if (width != 0 && height != 0) {
                        imageViewH = (imageViewW/width) * height;
                    } else {
                        imageViewH = (0.618) * imageViewW;
                    }

                    PBContentModel *contentModel = [[PBContentModel alloc]init];
                    contentModel.isImg = YES;
                    contentModel.src = ele.attributes[@"src"];
                    contentModel.imgWidth = imageViewW;
                    contentModel.imgHeight = imageViewH;

                    [imageArr addObject:ele.attributes[@"src"]];

                    {
                        UIImageView *imageView = [[UIImageView alloc]init];
                        imageView.frame = CGRectMake(0, 0, imageViewW, imageViewH);
                        imageView.backgroundColor = [UIColor lightGrayColor];
                        [imageView sd_setImageWithURL:[NSURL URLWithString:contentModel.src]];
                        imageView.layer.cornerRadius = 10;
                        imageView.layer.masksToBounds = YES;
                        imageView.userInteractionEnabled = YES;

                        [imageViewArr addObject:imageView];

                        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
                        [imageView addGestureRecognizer:tap];
                        tap.view.tag = imageArr.count-1;

                        NSMutableAttributedString *tmpStr = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.frame.size alignToFont:[UIFont boldSystemFontOfSize:17] alignment:YYTextVerticalAlignmentCenter];
                        [tmpStr yy_setLineSpacing:10 range:tmpStr.yy_rangeOfAll];

                        [attributedString appendAttributedString:tmpStr];
                    }
                }

                if ([ele.tagName isEqualToString:@"a"]) {
                    NSMutableAttributedString *tmpStr = [[NSMutableAttributedString alloc]initWithString:[ele.content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                    [tmpStr yy_setFont:[UIFont systemFontOfSize:17] range:NSMakeRange(0, tmpStr.length)];
                    [tmpStr yy_setColor:[UIColor blueColor] range:NSMakeRange(0, tmpStr.length)];
                    [tmpStr yy_setLineSpacing:10 range:NSMakeRange(0, tmpStr.length)];

                    [attributedString appendAttributedString:tmpStr];
                }
            }

            if (self.lastAttributedString.length != attributedString.length) {
                [attributedString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
            }
        }

        // 移除可能出现的最后一个换行
        NSString *str = [attributedString.string substringFromIndex:attributedString.length-1];
        if ([str isEqualToString:@"\n"]) {
            [attributedString deleteCharactersInRange:NSMakeRange(attributedString.length-1, 1)];
        }

        NSMutableArray *objsP = [[NSMutableArray alloc]init];

        PBContentModel *contentModel = [[PBContentModel alloc]init];
        contentModel.text = attributedString;
        contentModel.imageArr = imageArr;
        contentModel.imageViewArr = imageViewArr;

        [objsP addObject:contentModel];

        self.pEle = objsP;
    }
    return self;
}

- (void)tapClick:(UITapGestureRecognizer *)tap {
    NSDictionary *userInfo = @{@"tag":@(tap.view.tag)};
    [[NSNotificationCenter defaultCenter]postNotificationName:@"hhhh" object:nil userInfo:userInfo];
}

@end


text:
Your rentals:

{{error}}

{{succes.Succes}}

Current rental

Rented bike: {{rental.bike.brand}}

Rented {{formatStartDate(rental.rentDate)}} in {{rental.origin.name}}

 0">Users authorized to return this bike: (Besides you)

{{usr}}

                <button ng-click="authorizeUser(rental)" class="btn btn-sp-blue client">Authorize user to return this bike</button>

Past rentals

Rented bike: {{rental.bike.brand}}

Rented {{formatPastDates(rental.rentDate)}} in {{rental.origin.name}}

Returned {{formatPastDates(rental.modifiedAt)}} in {{rental.drop.name}}

<link rel="stylesheet" href="/modules/user-rental/user-rental.css">


text:
#include "GrAtlas.h"
#include "GrContext.h"
#include "GrGpu.h"
#include "GrRectanizer.h"
#include "GrPlotMgr.h"

#if 0
#define GR_PLOT_WIDTH   8
#define GR_PLOT_HEIGHT  4
#define GR_ATLAS_WIDTH  256
#define GR_ATLAS_HEIGHT 256

#define GR_ATLAS_TEXTURE_WIDTH  (GR_PLOT_WIDTH * GR_ATLAS_WIDTH)
#define GR_ATLAS_TEXTURE_HEIGHT (GR_PLOT_HEIGHT * GR_ATLAS_HEIGHT)

#else

#define GR_ATLAS_TEXTURE_WIDTH  1024
#define GR_ATLAS_TEXTURE_HEIGHT 2048

#define GR_ATLAS_WIDTH  341
#define GR_ATLAS_HEIGHT 341

#define GR_PLOT_WIDTH   (GR_ATLAS_TEXTURE_WIDTH / GR_ATLAS_WIDTH)
#define GR_PLOT_HEIGHT  (GR_ATLAS_TEXTURE_HEIGHT / GR_ATLAS_HEIGHT)

#endif

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

#define BORDER      1

#if GR_DEBUG
    static int gCounter;
#endif

// for testing
#define FONT_CACHE_STATS 0
#if FONT_CACHE_STATS
static int g_UploadCount = 0;
#endif

GrAtlas::GrAtlas(GrAtlasMgr* mgr, int plotX, int plotY, GrMaskFormat format) {
    fAtlasMgr = mgr;    // just a pointer, not an owner
    fNext = NULL;
    fUsed = false;

    fTexture = mgr->getTexture(format); // we're not an owner, just a pointer
    fPlot.set(plotX, plotY);

    fRects = GrRectanizer::Factory(GR_ATLAS_WIDTH - BORDER,
                                   GR_ATLAS_HEIGHT - BORDER);

    fMaskFormat = format;

#if GR_DEBUG
//    GrPrintf(" GrAtlas %p [%d %d] %d\n", this, plotX, plotY, gCounter);
    gCounter += 1;
#endif
}

GrAtlas::~GrAtlas() {
    fAtlasMgr->freePlot(fMaskFormat, fPlot.fX, fPlot.fY);

    delete fRects;

#if GR_DEBUG
    --gCounter;
//    GrPrintf("~GrAtlas %p [%d %d] %d\n", this, fPlot.fX, fPlot.fY, gCounter);
#endif
}

bool GrAtlas::RemoveUnusedAtlases(GrAtlasMgr* atlasMgr, GrAtlas** startAtlas) {
    // GrAtlas** is used so that a pointer to the head element can be passed in and
    // modified when the first element is deleted
    GrAtlas** atlasRef = startAtlas;
    GrAtlas* atlas = *startAtlas;
    bool removed = false;
    while (NULL != atlas) {
        if (!atlas->used()) {
            *atlasRef = atlas->fNext;
            atlasMgr->deleteAtlas(atlas);
            atlas = *atlasRef;
            removed = true;
        } else {
            atlasRef = &atlas->fNext;
            atlas = atlas->fNext;
        }
    }

    return removed;
}

static void adjustForPlot(GrIPoint16* loc, const GrIPoint16& plot) {
    loc->fX += plot.fX * GR_ATLAS_WIDTH;
    loc->fY += plot.fY * GR_ATLAS_HEIGHT;
}

static uint8_t* zerofill(uint8_t* ptr, int count) {
    while (--count >= 0) {
        *ptr++ = 0;
    }
    return ptr;
}

bool GrAtlas::addSubImage(int width, int height, const void* image,
                          GrIPoint16* loc) {
    if (!fRects->addRect(width + BORDER, height + BORDER, loc)) {
        return false;
    }

    SkAutoSMalloc<1024> storage;
    int dstW = width + 2*BORDER;
    int dstH = height + 2*BORDER;
    if (BORDER) {
        const int bpp = GrMaskFormatBytesPerPixel(fMaskFormat);
        const size_t dstRB = dstW * bpp;
        uint8_t* dst = (uint8_t*)storage.reset(dstH * dstRB);
        Gr_bzero(dst, dstRB);                // zero top row
        dst += dstRB;
        for (int y = 0; y < height; y++) {
            dst = zerofill(dst, bpp);   // zero left edge
            memcpy(dst, image, width * bpp);
            dst += width * bpp;
            dst = zerofill(dst, bpp);   // zero right edge
            image = (const void*)((const char*)image + width * bpp);
        }
        Gr_bzero(dst, dstRB);                // zero bottom row
        image = storage.get();
    }
    adjustForPlot(loc, fPlot);
    GrContext* context = fTexture->getContext();
    // We pass the flag that does not force a flush. We assume our caller is
    // smart and hasn't referenced the part of the texture we're about to update
    // since the last flush.
    context->writeTexturePixels(fTexture,
                                loc->fX, loc->fY, dstW, dstH,
                                fTexture->config(), image, 0,
                                GrContext::kDontFlush_PixelOpsFlag);

    // now tell the caller to skip the top/left BORDER
    loc->fX += BORDER;
    loc->fY += BORDER;

#if FONT_CACHE_STATS
    ++g_UploadCount;
#endif

    return true;
}

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

GrAtlasMgr::GrAtlasMgr(GrGpu* gpu) {
    fGpu = gpu;
    gpu->ref();
    Gr_bzero(fTexture, sizeof(fTexture));
    fPlotMgr = SkNEW_ARGS(GrPlotMgr, (GR_PLOT_WIDTH, GR_PLOT_HEIGHT));
}

GrAtlasMgr::~GrAtlasMgr() {
    for (size_t i = 0; i < GR_ARRAY_COUNT(fTexture); i++) {
        GrSafeUnref(fTexture[i]);
    }
    delete fPlotMgr;

    fGpu->unref();
#if FONT_CACHE_STATS
      GrPrintf("Num uploads: %d\n", g_UploadCount);
#endif
}

static GrPixelConfig maskformat2pixelconfig(GrMaskFormat format) {
    switch (format) {
        case kA8_GrMaskFormat:
            return kAlpha_8_GrPixelConfig;
        case kA565_GrMaskFormat:
            return kRGB_565_GrPixelConfig;
        case kA888_GrMaskFormat:
            return kSkia8888_GrPixelConfig;
        default:
            GrAssert(!"unknown maskformat");
    }
    return kUnknown_GrPixelConfig;
}

GrAtlas* GrAtlasMgr::addToAtlas(GrAtlas** atlas,
                                int width, int height, const void* image,
                                GrMaskFormat format,
                                GrIPoint16* loc) {
    GrAssert(NULL == *atlas || (*atlas)->getMaskFormat() == format);

    // iterate through entire atlas list, see if we can find a hole
    GrAtlas* atlasIter = *atlas;
    while (atlasIter) {
        if (atlasIter->addSubImage(width, height, image, loc)) {
            return atlasIter;
        }
        atlasIter = atlasIter->fNext;
    }

    // If the above fails, then either we have no starting atlas, or the current
    // atlas list is full. Either way we need to allocate a new atlas

    GrIPoint16 plot;
    if (!fPlotMgr->newPlot(&plot)) {
        return NULL;
    }

    GrAssert(0 == kA8_GrMaskFormat);
    GrAssert(1 == kA565_GrMaskFormat);
    if (NULL == fTexture[format]) {
        // TODO: Update this to use the cache rather than directly creating a texture.
        GrTextureDesc desc;
        desc.fFlags = kDynamicUpdate_GrTextureFlagBit;
        desc.fWidth = GR_ATLAS_TEXTURE_WIDTH;
        desc.fHeight = GR_ATLAS_TEXTURE_HEIGHT;
        desc.fConfig = maskformat2pixelconfig(format);

        fTexture[format] = fGpu->createTexture(desc, NULL, 0);
        if (NULL == fTexture[format]) {
            return NULL;
        }
    }

    GrAtlas* newAtlas = SkNEW_ARGS(GrAtlas, (this, plot.fX, plot.fY, format));
    if (!newAtlas->addSubImage(width, height, image, loc)) {
        delete newAtlas;
        return NULL;
    }

    // new atlas, put at head
    newAtlas->fNext = *atlas;
    *atlas = newAtlas;

    return newAtlas;
}

void GrAtlasMgr::freePlot(GrMaskFormat format, int x, int y) {
    GrAssert(fPlotMgr->isBusy(x, y));
    fPlotMgr->freePlot(x, y);
}


text:
package controllers

import controllers.ItemsController._
import models.{Items, Pack, PackItems, Packs}
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc._

object PacksController extends Controller {

  val packForm = Form(
    mapping("name" -> nonEmptyText)(formToPack)(packToForm)
  )

  private def formToPack: (String) => Pack = {
    Pack(Option.empty, _)
  }

  private def packToForm: (Pack) => Option[(String)] = {
    pack => Option.apply(pack.name)
  }

  def list() = Action {
    val packs = Packs.list
    Ok(views.html.packs.list(packs, packForm))
  }

  def view(id: Long) = Action {
    Packs.get(id).fold(NotFound: Result)(pack => {
      val itemsInPack = PackItems.itemsInPack(id)
      val itemForm = ItemsController.itemForm
      Ok(views.html.packs.view(pack, itemsInPack, itemForm))
    })
  }

  def create() = Action { implicit request =>
    packForm.bindFromRequest.fold(

      hasErrors = packForm => {
        val packs = Packs.list
        BadRequest(views.html.packs.list(packs, packForm))
      },

      success = pack => {
        Packs.create(pack)
        Redirect(routes.PacksController.list())
      })
  }

  def delete(id: Long) = Action {
    Packs.delete(id)
    Redirect(routes.PacksController.list())
  }

  def createAndAddItem(packId: Long) = Action { implicit request =>
    Packs.get(packId).fold(NotFound: Result)(pack => itemForm.bindFromRequest.fold(

      hasErrors = itemForm => {
        val itemsInPack = PackItems.itemsInPack(packId)
        BadRequest(views.html.packs.view(pack, itemsInPack, itemForm))
      },

      success = item => {
        val itemId = Items.create(item).id.get
        PackItems.addItemToPack(itemId, packId)
        Redirect(routes.PacksController.view(packId))
      }
    ))
  }

  def removeItem(packId: Long, itemId: Long) = Action {
    PackItems.removeItemFromPack(itemId, packId)
    Redirect(routes.PacksController.view(packId))
  }
}


text:
package net.finmath.montecarlo.assetderivativevaluation.models;

import java.util.Arrays;
import java.util.Map;

import net.finmath.montecarlo.RandomVariableFactory;
import net.finmath.montecarlo.RandomVariableFromArrayFactory;
import net.finmath.montecarlo.model.AbstractProcessModel;
import net.finmath.montecarlo.process.MonteCarloProcess;
import net.finmath.stochastic.RandomVariable;

/**
 * This class implements a Black Scholes Model, that is, it provides the drift and volatility specification
 * and performs the calculation of the numeraire (consistent with the dynamics, i.e. the drift).
 *
 * The model is
 * \[
 * 	dS = r S dt + \sigma S dW, \quad S(0) = S_{0},
 * \]
 * \[
 * 	dN = r N dt, \quad N(0) = N_{0},
 * \]
 *
 * The class provides the model of S to an <code>{@link net.finmath.montecarlo.process.MonteCarloProcess}</code> via the specification of
 * \( f = exp \), \( \mu = r - \frac{1}{2} \sigma^2 \), \( \lambda_{1,1} = \sigma \), i.e.,
 * of the SDE
 * \[
 * 	dX = \mu dt + \lambda_{1,1} dW, \quad X(0) = \log(S_{0}),
 * \]
 * with \( S = f(X) \). See {@link net.finmath.montecarlo.process.MonteCarloProcess} for the notation.
 *
 * @author Christian Fries
 * @see net.finmath.montecarlo.process.MonteCarloProcess The interface for numerical schemes.
 * @see net.finmath.montecarlo.model.ProcessModel The interface for models provinding parameters to numerical schemes.
 * @version 1.0
 */
public class BlackScholesModel extends AbstractProcessModel {

	private final RandomVariableFactory randomVariableFactory;

	private final RandomVariable initialValue;
	private final RandomVariable riskFreeRate;
	private final RandomVariable volatility;

	// Cache for arrays provided though AbstractProcessModel
	private final RandomVariable[]	initialState;
	private final RandomVariable[]	drift;
	private final RandomVariable[]	factorLoadings;

	/**
	 * Create a Black-Scholes specification implementing AbstractProcessModel.
	 *
	 * @param initialValue Spot value.
	 * @param riskFreeRate The risk free rate.
	 * @param volatility The log volatility.
	 * @param randomVariableFactory The random variable factory used to create random variables from constants.
	 */
	public BlackScholesModel(
			final RandomVariable initialValue,
			final RandomVariable riskFreeRate,
			final RandomVariable volatility,
			final RandomVariableFactory randomVariableFactory) {
		super();

		this.initialValue = initialValue;
		this.volatility = volatility;
		this.riskFreeRate	= riskFreeRate;
		this.randomVariableFactory = randomVariableFactory;

		// Cache
		initialState = new RandomVariable[] { initialValue.log() };
		drift = new RandomVariable[] { riskFreeRate.sub(volatility.squared().div(2)) };
		factorLoadings = new RandomVariable[] { volatility };
	}

	/**
	 * Create a Monte-Carlo simulation using given time discretization.
	 *
	 * @param initialValue Spot value.
	 * @param riskFreeRate The risk free rate.
	 * @param volatility The log volatility.
	 * @param randomVariableFactory The random variable factory used to create random variables from constants.
	 */
	public BlackScholesModel(
			final double initialValue,
			final double riskFreeRate,
			final double volatility,
			final RandomVariableFactory randomVariableFactory) {
		this(randomVariableFactory.createRandomVariable(initialValue), randomVariableFactory.createRandomVariable(riskFreeRate), randomVariableFactory.createRandomVariable(volatility), randomVariableFactory);
	}

	/**
	 * Create a Black-Scholes model from given parameters.
	 *
	 * @param initialValue Spot value.
	 * @param riskFreeRate The risk free rate.
	 * @param volatility The log volatility.
	 */
	public BlackScholesModel(
			final double initialValue,
			final double riskFreeRate,
			final double volatility) {
		this(initialValue, riskFreeRate, volatility, new RandomVariableFromArrayFactory());
	}

	@Override
	public RandomVariable[] getInitialState(MonteCarloProcess process) {
		return initialState;
	}

	@Override
	public RandomVariable[] getDrift(final MonteCarloProcess process, final int timeIndex, final RandomVariable[] realizationAtTimeIndex, final RandomVariable[] realizationPredictor) {
		return drift;
	}

	@Override
	public RandomVariable[] getFactorLoading(final MonteCarloProcess process, final int timeIndex, final int component, final RandomVariable[] realizationAtTimeIndex) {
		return factorLoadings;
	}

	@Override
	public RandomVariable applyStateSpaceTransform(MonteCarloProcess process, int timeIndex, final int componentIndex, final RandomVariable randomVariable) {
		return randomVariable.exp();
	}

	@Override
	public RandomVariable applyStateSpaceTransformInverse(final MonteCarloProcess process, final int timeIndex, final int componentIndex, final RandomVariable randomVariable) {
		return randomVariable.log();
	}

	@Override
	public RandomVariable getNumeraire(MonteCarloProcess process, final double time) {
		return riskFreeRate.mult(time).exp();
	}

	@Override
	public int getNumberOfComponents() {
		return 1;
	}

	@Override
	public int getNumberOfFactors() {
		return 1;
	}

	@Override
	public RandomVariable getRandomVariableForConstant(final double value) {
		return randomVariableFactory.createRandomVariable(value);
	}

	@Override
	public BlackScholesModel getCloneWithModifiedData(final Map<String, Object> dataModified) {
		/*
		 * Determine the new model parameters from the provided parameter map.
		 */
		final double	newInitialValue	= dataModified.get("initialValue") != null	? ((Number)dataModified.get("initialValue")).doubleValue() 	: initialValue.getAverage();
		final double	newRiskFreeRate	= dataModified.get("riskFreeRate") != null	? ((Number)dataModified.get("riskFreeRate")).doubleValue()	: getRiskFreeRate().getAverage();
		final double	newVolatility	= dataModified.get("volatility") != null	? ((Number)dataModified.get("volatility")).doubleValue()	: getVolatility().getAverage();

		return new BlackScholesModel(newInitialValue, newRiskFreeRate, newVolatility, randomVariableFactory);
	}

	/**
	 * Return the initial value of this model.
	 *
	 * @return the initial value of this model.
	 */
	@Override
	public RandomVariable[] getInitialValue(final MonteCarloProcess process) {
		return new RandomVariable[] { initialValue };
	}

	/**
	 * Returns the risk free rate parameter of this model.
	 *
	 * @return Returns the riskFreeRate.
	 */
	public RandomVariable getRiskFreeRate() {
		return riskFreeRate;
	}

	/**
	 * Returns the volatility parameter of this model.
	 *
	 * @return Returns the volatility.
	 */
	public RandomVariable getVolatility() {
		return factorLoadings[0];
	}

	@Override
	public String toString() {
		return "BlackScholesModel [initialValue=" + initialValue + ", riskFreeRate=" + riskFreeRate + ", volatility="
				+ volatility + ", randomVariableFactory=" + randomVariableFactory + ", initialState="
				+ Arrays.toString(initialState) + ", drift=" + Arrays.toString(drift) + ", factorLoadings="
				+ Arrays.toString(factorLoadings) + "]";
	}
}


text:
(function (factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(["require", "exports"], factory);
    }
})(function (require, exports) {
    "use strict";
    /**
     * @abstract
     */
    var ActivatorBase = (function () {
        function ActivatorBase() {
        }
        /**
         * @abstract
         * @param {?} ev
         * @param {?} activatableEle
         * @param {?} startCoord
         * @return {?}
         */
        ActivatorBase.prototype.clickAction = function (ev, activatableEle, startCoord) { };
        /**
         * @abstract
         * @param {?} ev
         * @param {?} activatableEle
         * @param {?} startCoord
         * @return {?}
         */
        ActivatorBase.prototype.downAction = function (ev, activatableEle, startCoord) { };
        /**
         * @abstract
         * @param {?} ev
         * @param {?} activatableEle
         * @param {?} startCoord
         * @return {?}
         */
        ActivatorBase.prototype.upAction = function (ev, activatableEle, startCoord) { };
        /**
         * @abstract
         * @param {?} animated
         * @return {?}
         */
        ActivatorBase.prototype.clearState = function (animated) { };
        return ActivatorBase;
    }());
    exports.ActivatorBase = ActivatorBase;
    /**
     * @param {?} ev
     * @param {?} activatableEle
     * @return {?}
     */
    function isActivatedDisabled(ev, activatableEle) {
        if (!activatableEle || !activatableEle.parentNode) {
            return true;
        }
        if (!ev) {
            return false;
        }
        if (ev.defaultPrevented) {
            return true;
        }
        var /** @type {?} */ targetEle = ev.target;
        for (var /** @type {?} */ i = 0; i < 4; i++) {
            if (!targetEle) {
                break;
            }
            if (targetEle.hasAttribute('disable-activated')) {
                return true;
            }
            targetEle = targetEle.parentElement;
        }
        return false;
    }
    exports.isActivatedDisabled = isActivatedDisabled;
});
//# sourceMappingURL=activator-base.js.map


text:
package luddite

import (
	"fmt"
	"io"

	"gopkg.in/SpirentOrion/trace.v2"
	"gopkg.in/yaml.v2"
)

const (
	TraceKindAWS     = "aws"
	TraceKindProcess = "process"
	TraceKindRequest = "request"
	TraceKindWorker  = "worker"
)

var recorders = make(map[string]trace.Recorder)

func RegisterTraceRecorder(name string, recorder trace.Recorder) {
	if name == "" {
		panic("empty trace recorder name")
	}
	if recorder == nil {
		panic("nil trace recorder")
	}
	if _, ok := recorders[name]; ok {
		panic(fmt.Sprintf("%s trace recorder registered twice", name))
	}
	recorders[name] = recorder
}

// yamlRecorder is included in luddite for backwards compatibility with v1 of
// github.com/SpirentOrion/trace since v2 of that package no longer supports
// YAML directly.
type yamlRecorder struct {
	io.Writer
}

func (r *yamlRecorder) Record(s *trace.Span) error {
	buf, err := yaml.Marshal(s)
	if err != nil {
		return err
	}

	fmt.Fprintln(r, "---") // document separator
	_, err = r.Write(buf)
	return err
}


text:
{% if paginator.total_pages > 1 %}

    {% if paginator.previous_page %}
      ← Newer Posts
    {% endif %}

    {% if paginator.next_page %}
      Older Posts →
    {% endif %}

{% endif %}


text:
@implementation CCMServer

- (id)initWithURL:(NSURL *)anUrl andProjectNames:(NSArray *)projectNames
{
	[super init];
	url = [anUrl retain];
	projects = [[NSMutableDictionary alloc] init];
    for(NSString *name in projectNames)
		[projects setObject:[[[CCMProject alloc] initWithName:name] autorelease] forKey:name];
	return self;
}

- (void)dealloc
{
	[url release];
	[projects release];
	[super dealloc];
}

- (NSURL *)url
{
	return url;
}

- (NSArray *)projects
{
	return [projects allValues];
}

- (CCMProject *)projectNamed:(NSString *)name
{
	return [projects objectForKey:name];
}

@end


text:
package com.fionapet.business.repository;

import com.fionapet.business.entity.TrprescriptionTemplate;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springside.modules.test.spring.SpringTransactionalTestCase;

import java.util.List;

/**
 * 药方模版
* Created by tom on 2016-07-31 16:36:24.
 */
@ContextConfiguration(locations = {"/META-INF/spring/applicationContext.xml"})
public class TrprescriptionTemplateDaoTest extends SpringTransactionalTestCase {

    @Autowired
    private TrprescriptionTemplateDao trprescriptionTemplateDao;

    @Test
    public void findAll(){
        List<TrprescriptionTemplate> trprescriptionTemplates = trprescriptionTemplateDao.findAllBy();

        Assert.assertNotNull(trprescriptionTemplates);

        Assert.assertEquals(trprescriptionTemplates.size(), 37);
    }
}


text:
> Adapter to make User compatible with Doctrine ORM

[![Build Status](https://travis-ci.org/BenGorUser/DoctrineORMBridge.svg?branch=master)](https://travis-ci.org/BenGorUser/DoctrineORMBridge)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/BenGorUser/DoctrineORMBridge/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/BenGorUser/DoctrineORMBridge/?branch=master)
[![Total Downloads](https://poser.pugx.org/bengor-user/doctrine-orm-bridge/downloads)](https://packagist.org/packages/bengor-user/doctrine-orm-bridge/)
[![Latest Stable Version](https://poser.pugx.org/bengor-user/doctrine-orm-bridge/v/stable.svg)](https://packagist.org/packages/bengor-user/doctrine-orm-bridge/)
[![Latest Unstable Version](https://poser.pugx.org/bengor-user/doctrine-orm-bridge/v/unstable.svg)](https://packagist.org/packages/bengor-user/doctrine-orm-bridge/)

##Requirements
PHP >= 5.5

##Installation
The easiest way to install this component is using [Composer][6]
```bash
$ composer require bengor-user/doctrine-orm-bridge
```

##Documentation
All the documentation is stored inside the [user library](https://github.com/BenGorUser/User/blob/master/docs/index.md).

##Tests
This library is completely tested by **[PHPSpec][1], SpecBDD framework for PHP**.

Run the following command to launch tests:
```bash
$ vendor/bin/phpspec run -fpretty
```

##Contributing
If you have any doubt or maybe you want to share some opinion, you can use our **Gitter** chat.

[![Join the chat at https://gitter.im/BenGorUser/User](https://badges.gitter.im/BenGorUser/User.svg)](https://gitter.im/BenGorUser/User?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

BenGorUser uses [Crowdin][7] as tool to manage translations so, please help us translating your favorite language
via this service. Pull requests about translations will not be accepted.

[![Crowdin](https://d322cqt584bo4o.cloudfront.net/bengoruser/localized.svg)](https://crowdin.com/project/bengoruser)

This library follows PHP coding standards, so pull requests need to execute the Fabien Potencier's [PHP-CS-Fixer][5].
Furthermore, if the PR creates some not-PHP file remember that you have to put the license header manually. In order
to simplify we provide a Composer script that wraps all the commands related with this process.
```bash
$ composer run-script cs
```

There is also a policy for contributing to this project. Pull requests must be explained step by step to make the
review process easy in order to accept and merge them. New methods or code improvements must come paired with
[PHPSpec][1] tests.

If you would like to contribute it is a good point to follow Symfony contribution standards, so please read the
[Contributing Code][2] in the project documentation. If you are submitting a pull request, please follow the guidelines
in the [Submitting a Patch][3] section and use the [Pull Request Template][4].

##Credits
This library is created by:
>
**@benatespina** - [benatespina@gmail.com](mailto:benatespina@gmail.com)<br>
**@gorkalaucirica** - [gorka.lauzirika@gmail.com](mailto:gorka.lauzirika@gmail.com)

##Licensing Options
[![License](https://poser.pugx.org/bengor-user/doctrine-orm-bridge/license.svg)](https://github.com/BenGorUser/DoctrineORMBridge/blob/master/LICENSE)

[1]: http://www.phpspec.net/
[2]: http://symfony.com/doc/current/contributing/code/index.html
[3]: http://symfony.com/doc/current/contributing/code/patches.html#check-list
[4]: http://symfony.com/doc/current/contributing/code/patches.html#make-a-pull-request
[5]: http://cs.sensiolabs.org/
[6]: http://getcomposer.org
[7]: https://crowdin.com/


text:
class SIRTFIContactPerson < Sequel::Model
  many_to_one :contact
  many_to_one :entity_descriptor
  many_to_one :role_descriptor

  def validate
    super
    validates_presence %i[contact created_at updated_at]
  end
end