text:
import inspect
import math
import pprint
import sys
import warnings
from collections.abc import Iterable
from collections.abc import Mapping
from collections.abc import Sized
from decimal import Decimal
from itertools import filterfalse
from numbers import Number

from more_itertools.more import always_iterable

import _pytest._code
from _pytest import deprecated
from _pytest.compat import STRING_TYPES
from _pytest.outcomes import fail

BASE_TYPE = (type, STRING_TYPES)

def _non_numeric_type_error(value, at):
    at_str = " at {}".format(at) if at else ""
    return TypeError(
        "cannot make approximate comparisons to non-numeric values: {!r} {}".format(
            value, at_str
        )
    )

# builtin pytest.approx helper

class ApproxBase:
    """
    Provide shared utilities for making approximate comparisons between numbers
    or sequences of numbers.
    """

    # Tell numpy to use our `__eq__` operator instead of its.
    __array_ufunc__ = None
    __array_priority__ = 100

    def __init__(self, expected, rel=None, abs=None, nan_ok=False):
        __tracebackhide__ = True
        self.expected = expected
        self.abs = abs
        self.rel = rel
        self.nan_ok = nan_ok
        self._check_type()

    def __repr__(self):
        raise NotImplementedError

    def __eq__(self, actual):
        return all(
            a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
        )

    __hash__ = None

    def __ne__(self, actual):
        return not (actual == self)

    def _approx_scalar(self, x):
        return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)

    def _yield_comparisons(self, actual):
        """
        Yield all the pairs of numbers to be compared.  This is used to
        implement the `__eq__` method.
        """
        raise NotImplementedError

    def _check_type(self):
        """
        Raise a TypeError if the expected value is not a valid type.
        """
        # This is only a concern if the expected value is a sequence.  In every
        # other case, the approx() function ensures that the expected value has
        # a numeric type.  For this reason, the default is to do nothing.  The
        # classes that deal with sequences should reimplement this method to
        # raise if there are any non-numeric elements in the sequence.
        pass

def _recursive_list_map(f, x):
    if isinstance(x, list):
        return list(_recursive_list_map(f, xi) for xi in x)
    else:
        return f(x)

class ApproxNumpy(ApproxBase):
    """
    Perform approximate comparisons where the expected value is numpy array.
    """

    def __repr__(self):
        list_scalars = _recursive_list_map(self._approx_scalar, self.expected.tolist())
        return "approx({!r})".format(list_scalars)

    def __eq__(self, actual):
        import numpy as np

        # self.expected is supposed to always be an array here

        if not np.isscalar(actual):
            try:
                actual = np.asarray(actual)
            except:  # noqa
                raise TypeError("cannot compare '{}' to numpy.ndarray".format(actual))

        if not np.isscalar(actual) and actual.shape != self.expected.shape:
            return False

        return ApproxBase.__eq__(self, actual)

    def _yield_comparisons(self, actual):
        import numpy as np

        # `actual` can either be a numpy array or a scalar, it is treated in
        # `__eq__` before being passed to `ApproxBase.__eq__`, which is the
        # only method that calls this one.

        if np.isscalar(actual):
            for i in np.ndindex(self.expected.shape):
                yield actual, self.expected[i].item()
        else:
            for i in np.ndindex(self.expected.shape):
                yield actual[i].item(), self.expected[i].item()

class ApproxMapping(ApproxBase):
    """
    Perform approximate comparisons where the expected value is a mapping with
    numeric values (the keys can be anything).
    """

    def __repr__(self):
        return "approx({!r})".format(
            {k: self._approx_scalar(v) for k, v in self.expected.items()}
        )

    def __eq__(self, actual):
        if set(actual.keys()) != set(self.expected.keys()):
            return False

        return ApproxBase.__eq__(self, actual)

    def _yield_comparisons(self, actual):
        for k in self.expected.keys():
            yield actual[k], self.expected[k]

    def _check_type(self):
        __tracebackhide__ = True
        for key, value in self.expected.items():
            if isinstance(value, type(self.expected)):
                msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n  full mapping={}"
                raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))
            elif not isinstance(value, Number):
                raise _non_numeric_type_error(self.expected, at="key={!r}".format(key))

class ApproxSequencelike(ApproxBase):
    """
    Perform approximate comparisons where the expected value is a sequence of
    numbers.
    """

    def __repr__(self):
        seq_type = type(self.expected)
        if seq_type not in (tuple, list, set):
            seq_type = list
        return "approx({!r})".format(
            seq_type(self._approx_scalar(x) for x in self.expected)
        )

    def __eq__(self, actual):
        if len(actual) != len(self.expected):
            return False
        return ApproxBase.__eq__(self, actual)

    def _yield_comparisons(self, actual):
        return zip(actual, self.expected)

    def _check_type(self):
        __tracebackhide__ = True
        for index, x in enumerate(self.expected):
            if isinstance(x, type(self.expected)):
                msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n  full sequence: {}"
                raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))
            elif not isinstance(x, Number):
                raise _non_numeric_type_error(
                    self.expected, at="index {}".format(index)
                )

class ApproxScalar(ApproxBase):
    """
    Perform approximate comparisons where the expected value is a single number.
    """

    DEFAULT_ABSOLUTE_TOLERANCE = 1e-12
    DEFAULT_RELATIVE_TOLERANCE = 1e-6

    def __repr__(self):
        """
        Return a string communicating both the expected value and the tolerance
        for the comparison being made, e.g. '1.0 +- 1e-6'.  Use the unicode
        plus/minus symbol if this is python3 (it's too hard to get right for
        python2).
        """
        if isinstance(self.expected, complex):
            return str(self.expected)

        # Infinities aren't compared using tolerances, so don't show a
        # tolerance.
        if math.isinf(self.expected):
            return str(self.expected)

        # If a sensible tolerance can't be calculated, self.tolerance will
        # raise a ValueError.  In this case, display '???'.
        try:
            vetted_tolerance = "{:.1e}".format(self.tolerance)
        except ValueError:
            vetted_tolerance = "???"

        return "{} \u00b1 {}".format(self.expected, vetted_tolerance)

    def __eq__(self, actual):
        """
        Return true if the given value is equal to the expected value within
        the pre-specified tolerance.
        """
        if _is_numpy_array(actual):
            # Call ``__eq__()`` manually to prevent infinite-recursion with
            # numpy<1.13.  See #3748.
            return all(self.__eq__(a) for a in actual.flat)

        # Short-circuit exact equality.
        if actual == self.expected:
            return True

        # Allow the user to control whether NaNs are considered equal to each
        # other or not.  The abs() calls are for compatibility with complex
        # numbers.
        if math.isnan(abs(self.expected)):
            return self.nan_ok and math.isnan(abs(actual))

        # Infinity shouldn't be approximately equal to anything but itself, but
        # if there's a relative tolerance, it will be infinite and infinity
        # will seem approximately equal to everything.  The equal-to-itself
        # case would have been short circuited above, so here we can just
        # return false if the expected value is infinite.  The abs() call is
        # for compatibility with complex numbers.
        if math.isinf(abs(self.expected)):
            return False

        # Return true if the two numbers are within the tolerance.
        return abs(self.expected - actual) <= self.tolerance

    __hash__ = None

    @property
    def tolerance(self):
        """
        Return the tolerance for the comparison.  This could be either an
        absolute tolerance or a relative tolerance, depending on what the user
        specified or which would be larger.
        """

        def set_default(x, default):
            return x if x is not None else default

        # Figure out what the absolute tolerance should be.  ``self.abs`` is
        # either None or a value specified by the user.
        absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)

        if absolute_tolerance < 0:
            raise ValueError(
                "absolute tolerance can't be negative: {}".format(absolute_tolerance)
            )
        if math.isnan(absolute_tolerance):
            raise ValueError("absolute tolerance can't be NaN.")

        # If the user specified an absolute tolerance but not a relative one,
        # just return the absolute tolerance.
        if self.rel is None:
            if self.abs is not None:
                return absolute_tolerance

        # Figure out what the relative tolerance should be.  ``self.rel`` is
        # either None or a value specified by the user.  This is done after
        # we've made sure the user didn't ask for an absolute tolerance only,
        # because we don't want to raise errors about the relative tolerance if
        # we aren't even going to use it.
        relative_tolerance = set_default(
            self.rel, self.DEFAULT_RELATIVE_TOLERANCE
        ) * abs(self.expected)

        if relative_tolerance < 0:
            raise ValueError(
                "relative tolerance can't be negative: {}".format(absolute_tolerance)
            )
        if math.isnan(relative_tolerance):
            raise ValueError("relative tolerance can't be NaN.")

        # Return the larger of the relative and absolute tolerances.
        return max(relative_tolerance, absolute_tolerance)

class ApproxDecimal(ApproxScalar):
    """
    Perform approximate comparisons where the expected value is a decimal.
    """

    DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
    DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")

def approx(expected, rel=None, abs=None, nan_ok=False):
    """
    Assert that two numbers (or two sets of numbers) are equal to each other
    within some tolerance.

    Due to the `intricacies of floating-point arithmetic`__, numbers that we
    would intuitively expect to be equal are not always so::

        >>> 0.1 + 0.2 == 0.3
        False

    __ https://docs.python.org/3/tutorial/floatingpoint.html

    This problem is commonly encountered when writing tests, e.g. when making
    sure that floating-point values are what you expect them to be.  One way to
    deal with this problem is to assert that two floating-point numbers are
    equal to within some appropriate tolerance::

        >>> abs((0.1 + 0.2) - 0.3) < 1e-6
        True

    However, comparisons like this are tedious to write and difficult to
    understand.  Furthermore, absolute comparisons like the one above are
    usually discouraged because there's no tolerance that works well for all
    situations.  ``1e-6`` is good for numbers around ``1``, but too small for
    very big numbers and too big for very small ones.  It's better to express
    the tolerance as a fraction of the expected value, but relative comparisons
    like that are even more difficult to write correctly and concisely.

    The ``approx`` class performs floating-point comparisons using a syntax
    that's as intuitive as possible::

        >>> from pytest import approx
        >>> 0.1 + 0.2 == approx(0.3)
        True

    The same syntax also works for sequences of numbers::

        >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
        True

    Dictionary *values*::

        >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
        True

    ``numpy`` arrays::

        >>> import numpy as np                                                          # doctest: +SKIP
        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
        True

    And for a ``numpy`` array against a scalar::

        >>> import numpy as np                                         # doctest: +SKIP
        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
        True

    By default, ``approx`` considers numbers within a relative tolerance of
    ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
    This treatment would lead to surprising results if the expected value was
    ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
    To handle this case less surprisingly, ``approx`` also considers numbers
    within an absolute tolerance of ``1e-12`` of its expected value to be
    equal.  Infinity and NaN are special cases.  Infinity is only considered
    equal to itself, regardless of the relative tolerance.  NaN is not
    considered equal to anything by default, but you can make it be equal to
    itself by setting the ``nan_ok`` argument to True.  (This is meant to
    facilitate comparing arrays that use NaN to mean "no data".)

    Both the relative and absolute tolerances can be changed by passing
    arguments to the ``approx`` constructor::

        >>> 1.0001 == approx(1)
        False
        >>> 1.0001 == approx(1, rel=1e-3)
        True
        >>> 1.0001 == approx(1, abs=1e-3)
        True

    If you specify ``abs`` but not ``rel``, the comparison will not consider
    the relative tolerance at all.  In other words, two numbers that are within
    the default relative tolerance of ``1e-6`` will still be considered unequal
    if they exceed the specified absolute tolerance.  If you specify both
    ``abs`` and ``rel``, the numbers will be considered equal if either
    tolerance is met::

        >>> 1 + 1e-8 == approx(1)
        True
        >>> 1 + 1e-8 == approx(1, abs=1e-12)
        False
        >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
        True

    If you're thinking about using ``approx``, then you might want to know how
    it compares to other good ways of comparing floating-point numbers.  All of
    these algorithms are based on relative and absolute tolerances and should
    agree for the most part, but they do have meaningful differences:

    - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``:  True if the relative
      tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
      tolerance is met.  Because the relative tolerance is calculated w.r.t.
      both ``a`` and ``b``, this test is symmetric (i.e.  neither ``a`` nor
      ``b`` is a "reference value").  You have to specify an absolute tolerance
      if you want to compare to ``0.0`` because there is no tolerance by
      default.  Only available in python>=3.5.  `More information...`__

      __ https://docs.python.org/3/library/math.html#math.isclose

    - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
      between ``a`` and ``b`` is less that the sum of the relative tolerance
      w.r.t. ``b`` and the absolute tolerance.  Because the relative tolerance
      is only calculated w.r.t. ``b``, this test is asymmetric and you can
      think of ``b`` as the reference value.  Support for comparing sequences
      is provided by ``numpy.allclose``.  `More information...`__

      __ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html

    - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
      are within an absolute tolerance of ``1e-7``.  No relative tolerance is
      considered and the absolute tolerance cannot be changed, so this function
      is not appropriate for very large or very small numbers.  Also, it's only
      available in subclasses of ``unittest.TestCase`` and it's ugly because it
      doesn't follow PEP8.  `More information...`__

      __ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual

    - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
      tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
      Because the relative tolerance is only calculated w.r.t. ``b``, this test
      is asymmetric and you can think of ``b`` as the reference value.  In the
      special case that you explicitly specify an absolute tolerance but not a
      relative tolerance, only the absolute tolerance is considered.

    .. warning::

       .. versionchanged:: 3.2

       In order to avoid inconsistent behavior, ``TypeError`` is
       raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
       The example below illustrates the problem::

           assert approx(0.1) > 0.1 + 1e-10  # calls approx(0.1).__gt__(0.1 + 1e-10)
           assert 0.1 + 1e-10 > approx(0.1)  # calls approx(0.1).__lt__(0.1 + 1e-10)

       In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
       to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
       comparison. This is because the call hierarchy of rich comparisons
       follows a fixed behavior. `More information...`__

       __ https://docs.python.org/3/reference/datamodel.html#object.__ge__
    """

    # Delegate the comparison to a class that knows how to deal with the type
    # of the expected value (e.g. int, float, list, dict, numpy.array, etc).
    #
    # The primary responsibility of these classes is to implement ``__eq__()``
    # and ``__repr__()``.  The former is used to actually check if some
    # "actual" value is equivalent to the given expected value within the
    # allowed tolerance.  The latter is used to show the user the expected
    # value and tolerance, in the case that a test failed.
    #
    # The actual logic for making approximate comparisons can be found in
    # ApproxScalar, which is used to compare individual numbers.  All of the
    # other Approx classes eventually delegate to this class.  The ApproxBase
    # class provides some convenient methods and overloads, but isn't really
    # essential.

    __tracebackhide__ = True

    if isinstance(expected, Decimal):
        cls = ApproxDecimal
    elif isinstance(expected, Number):
        cls = ApproxScalar
    elif isinstance(expected, Mapping):
        cls = ApproxMapping
    elif _is_numpy_array(expected):
        cls = ApproxNumpy
    elif (
        isinstance(expected, Iterable)
        and isinstance(expected, Sized)
        and not isinstance(expected, STRING_TYPES)
    ):
        cls = ApproxSequencelike
    else:
        raise _non_numeric_type_error(expected, at=None)

    return cls(expected, rel, abs, nan_ok)

def _is_numpy_array(obj):
    """
    Return true if the given object is a numpy array.  Make a special effort to
    avoid importing numpy unless it's really necessary.
    """
    import sys

    np = sys.modules.get("numpy")
    if np is not None:
        return isinstance(obj, np.ndarray)
    return False

# builtin pytest.raises helper

def raises(expected_exception, *args, **kwargs):
    r"""
    Assert that a code block/function call raises ``expected_exception``
    or raise a failure exception otherwise.

    :kwparam match: if specified, a string containing a regular expression,
        or a regular expression object, that is tested against the string
        representation of the exception using ``re.search``. To match a literal
        string that may contain `special characters`__, the pattern can
        first be escaped with ``re.escape``.

    __ https://docs.python.org/3/library/re.html#regular-expression-syntax

    :kwparam message: **(deprecated since 4.1)** if specified, provides a custom failure message
        if the exception is not raised. See :ref:`the deprecation docs <raises message deprecated>` for a workaround.

    .. currentmodule:: _pytest._code

    Use ``pytest.raises`` as a context manager, which will capture the exception of the given
    type::

        >>> with raises(ZeroDivisionError):
        ...    1/0

    If the code block does not raise the expected exception (``ZeroDivisionError`` in the example
    above), or no exception at all, the check will fail instead.

    You can also use the keyword argument ``match`` to assert that the
    exception matches a text or regex::

        >>> with raises(ValueError, match='must be 0 or None'):
        ...     raise ValueError("value must be 0 or None")

        >>> with raises(ValueError, match=r'must be \d+$'):
        ...     raise ValueError("value must be 42")

    The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
    details of the captured exception::

        >>> with raises(ValueError) as exc_info:
        ...     raise ValueError("value must be 42")
        >>> assert exc_info.type is ValueError
        >>> assert exc_info.value.args[0] == "value must be 42"

    .. deprecated:: 4.1

        In the context manager form you may use the keyword argument
        ``message`` to specify a custom failure message that will be displayed
        in case the ``pytest.raises`` check fails. This has been deprecated as it
        is considered error prone as users often mean to use ``match`` instead.
        See :ref:`the deprecation docs <raises message deprecated>` for a workaround.

    .. note::

       When using ``pytest.raises`` as a context manager, it's worthwhile to
       note that normal context manager rules apply and that the exception
       raised *must* be the final line in the scope of the context manager.
       Lines of code after that, within the scope of the context manager will
       not be executed. For example::

           >>> value = 15
           >>> with raises(ValueError) as exc_info:
           ...     if value > 10:
           ...         raise ValueError("value must be <= 10")
           ...     assert exc_info.type is ValueError  # this will not execute

       Instead, the following approach must be taken (note the difference in
       scope)::

           >>> with raises(ValueError) as exc_info:
           ...     if value > 10:
           ...         raise ValueError("value must be <= 10")
           ...
           >>> assert exc_info.type is ValueError

    **Using with** ``pytest.mark.parametrize``

    When using :ref:`pytest.mark.parametrize ref`
    it is possible to parametrize tests such that
    some runs raise an exception and others do not.

    See :ref:`parametrizing_conditional_raising` for an example.

    **Legacy form**

    It is possible to specify a callable by passing a to-be-called lambda::

        >>> raises(ZeroDivisionError, lambda: 1/0)
        <ExceptionInfo ...>

    or you can specify an arbitrary callable with arguments::

        >>> def f(x): return 1/x
        ...
        >>> raises(ZeroDivisionError, f, 0)
        <ExceptionInfo ...>
        >>> raises(ZeroDivisionError, f, x=0)
        <ExceptionInfo ...>

    The form above is fully supported but discouraged for new code because the
    context manager form is regarded as more readable and less error-prone.

    .. note::
        Similar to caught exception objects in Python, explicitly clearing
        local references to returned ``ExceptionInfo`` objects can
        help the Python interpreter speed up its garbage collection.

        Clearing those references breaks a reference cycle
        (``ExceptionInfo`` --> caught exception --> frame stack raising
        the exception --> current frame stack --> local variables -->
        ``ExceptionInfo``) which makes Python keep all objects referenced
        from that cycle (including all local variables in the current
        frame) alive until the next cyclic garbage collection run. See the
        official Python ``try`` statement documentation for more detailed
        information.

    """
    __tracebackhide__ = True
    for exc in filterfalse(
        inspect.isclass, always_iterable(expected_exception, BASE_TYPE)
    ):
        msg = (
            "exceptions must be old-style classes or"
            " derived from BaseException, not %s"
        )
        raise TypeError(msg % type(exc))

    message = "DID NOT RAISE {}".format(expected_exception)
    match_expr = None

    if not args:
        if "message" in kwargs:
            message = kwargs.pop("message")
            warnings.warn(deprecated.RAISES_MESSAGE_PARAMETER, stacklevel=2)
        if "match" in kwargs:
            match_expr = kwargs.pop("match")
        if kwargs:
            msg = "Unexpected keyword arguments passed to pytest.raises: "
            msg += ", ".join(sorted(kwargs))
            raise TypeError(msg)
        return RaisesContext(expected_exception, message, match_expr)
    elif isinstance(args[0], str):
        warnings.warn(deprecated.RAISES_EXEC, stacklevel=2)
        code, = args
        assert isinstance(code, str)
        frame = sys._getframe(1)
        loc = frame.f_locals.copy()
        loc.update(kwargs)
        # print "raises frame scope: %r" % frame.f_locals
        try:
            code = _pytest._code.Source(code).compile(_genframe=frame)
            exec(code, frame.f_globals, loc)
            # XXX didn't mean f_globals == f_locals something special?
            #     this is destroyed here ...
        except expected_exception:
            return _pytest._code.ExceptionInfo.from_current()
    else:
        func = args[0]
        try:
            func(*args[1:], **kwargs)
        except expected_exception:
            return _pytest._code.ExceptionInfo.from_current()
    fail(message)

raises.Exception = fail.Exception

class RaisesContext:
    def __init__(self, expected_exception, message, match_expr):
        self.expected_exception = expected_exception
        self.message = message
        self.match_expr = match_expr
        self.excinfo = None

    def __enter__(self):
        self.excinfo = _pytest._code.ExceptionInfo.for_later()
        return self.excinfo

    def __exit__(self, *tp):
        __tracebackhide__ = True
        if tp[0] is None:
            fail(self.message)
        self.excinfo.__init__(tp)
        suppress_exception = issubclass(self.excinfo.type, self.expected_exception)
        if self.match_expr is not None and suppress_exception:
            self.excinfo.match(self.match_expr)
        return suppress_exception


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  def after_sign_in_path_for(resource)
    deals_path
  end

end

redpajama_set_name: RedPajamaGithub


text:
class Solution(object):
    def countRangeSum(self, nums, lower, upper):
        """
        :type nums: List[int]
        :type lower: int
        :type upper: int
        :rtype: int
        """
        def countAndMergeSort(sums, start, end, lower, upper):
            if end - start <= 1:  # The size of range [start, end) less than 2 is always with count 0.
                return 0
            mid = start + (end - start) / 2
            count = countAndMergeSort(sums, start, mid, lower, upper) + \
                    countAndMergeSort(sums, mid, end, lower, upper)
            j, k, r = mid, mid, mid
            tmp = []
            for i in xrange(start, mid):
                # Count the number of range sums that lie in [lower, upper].
                while k < end and sums[k] - sums[i] < lower:
                    k += 1
                while j < end and sums[j] - sums[i] <= upper:
                    j += 1
                count += j - k

                # Merge the two sorted arrays into tmp.
                while r < end and sums[r] < sums[i]:
                    tmp.append(sums[r])
                    r += 1
                tmp.append(sums[i])
            # Copy tmp back to sums.
            sums[start:start+len(tmp)] = tmp
            return count

        sums = [0] * (len(nums) + 1)
        for i in xrange(len(nums)):
            sums[i + 1] = sums[i] + nums[i]
        return countAndMergeSort(sums, 0, len(sums), lower, upper)

# Divide and Conquer solution.
class Solution2(object):
    def countRangeSum(self, nums, lower, upper):
        """
        :type nums: List[int]
        :type lower: int
        :type upper: int
        :rtype: int
        """
        def countAndMergeSort(sums, start, end, lower, upper):
            if end - start <= 0:  # The size of range [start, end] less than 2 is always with count 0.
                return 0

            mid = start + (end - start) / 2
            count = countAndMergeSort(sums, start, mid, lower, upper) + \
                    countAndMergeSort(sums, mid + 1, end, lower, upper)
            j, k, r = mid + 1, mid + 1, mid + 1
            tmp = []
            for i in xrange(start, mid + 1):
                # Count the number of range sums that lie in [lower, upper].
                while k <= end and sums[k] - sums[i] < lower:
                    k += 1
                while j <= end and sums[j] - sums[i] <= upper:
                    j += 1
                count += j - k

                # Merge the two sorted arrays into tmp.
                while r <= end and sums[r] < sums[i]:
                    tmp.append(sums[r])
                    r += 1
                tmp.append(sums[i])

            # Copy tmp back to sums
            sums[start:start+len(tmp)] = tmp
            return count

        sums = [0] * (len(nums) + 1)
        for i in xrange(len(nums)):
            sums[i + 1] = sums[i] + nums[i]
        return countAndMergeSort(sums, 0, len(sums) - 1, lower, upper)


text:
/*===- InstrProfilingPlatformOther.c - Profile data default platform ------===*\
|*
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|* See https://llvm.org/LICENSE.txt for license information.
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|*
\*===----------------------------------------------------------------------===*/

#if !defined(__APPLE__) && !defined(__linux__) && !defined(__FreeBSD__) &&     \
    !(defined(__sun__) && defined(__svr4__)) && !defined(__NetBSD__) &&        \
    !defined(_WIN32)

#include <stddef.h>

#include "InstrProfiling.h"

static const __llvm_profile_data *DataFirst = NULL;
static const __llvm_profile_data *DataLast = NULL;
static const char *NamesFirst = NULL;
static const char *NamesLast = NULL;
static uint64_t *CountersFirst = NULL;
static uint64_t *CountersLast = NULL;
static uint32_t *OrderFileFirst = NULL;

static const void *getMinAddr(const void *A1, const void *A2) {
  return A1 < A2 ? A1 : A2;
}

static const void *getMaxAddr(const void *A1, const void *A2) {
  return A1 > A2 ? A1 : A2;
}

/*!
 * \brief Register an instrumented function.
 *
 * Calls to this are emitted by clang with -fprofile-instr-generate.  Such
 * calls are only required (and only emitted) on targets where we haven't
 * implemented linker magic to find the bounds of the sections.
 */
COMPILER_RT_VISIBILITY
void __llvm_profile_register_function(void *Data_) {
  /* TODO: Only emit this function if we can't use linker magic. */
  const __llvm_profile_data *Data = (__llvm_profile_data *)Data_;
  if (!DataFirst) {
    DataFirst = Data;
    DataLast = Data + 1;
    CountersFirst = Data->CounterPtr;
    CountersLast = (uint64_t *)Data->CounterPtr + Data->NumCounters;
    return;
  }

  DataFirst = (const __llvm_profile_data *)getMinAddr(DataFirst, Data);
  CountersFirst = (uint64_t *)getMinAddr(CountersFirst, Data->CounterPtr);

  DataLast = (const __llvm_profile_data *)getMaxAddr(DataLast, Data + 1);
  CountersLast = (uint64_t *)getMaxAddr(
      CountersLast, (uint64_t *)Data->CounterPtr + Data->NumCounters);
}

COMPILER_RT_VISIBILITY
void __llvm_profile_register_names_function(void *NamesStart,
                                            uint64_t NamesSize) {
  if (!NamesFirst) {
    NamesFirst = (const char *)NamesStart;
    NamesLast = (const char *)NamesStart + NamesSize;
    return;
  }
  NamesFirst = (const char *)getMinAddr(NamesFirst, NamesStart);
  NamesLast =
      (const char *)getMaxAddr(NamesLast, (const char *)NamesStart + NamesSize);
}

COMPILER_RT_VISIBILITY
const __llvm_profile_data *__llvm_profile_begin_data(void) { return DataFirst; }
COMPILER_RT_VISIBILITY
const __llvm_profile_data *__llvm_profile_end_data(void) { return DataLast; }
COMPILER_RT_VISIBILITY
const char *__llvm_profile_begin_names(void) { return NamesFirst; }
COMPILER_RT_VISIBILITY
const char *__llvm_profile_end_names(void) { return NamesLast; }
COMPILER_RT_VISIBILITY
uint64_t *__llvm_profile_begin_counters(void) { return CountersFirst; }
COMPILER_RT_VISIBILITY
uint64_t *__llvm_profile_end_counters(void) { return CountersLast; }
/* TODO: correctly set up OrderFileFirst. */
COMPILER_RT_VISIBILITY
uint32_t *__llvm_profile_begin_orderfile(void) { return OrderFileFirst; }

COMPILER_RT_VISIBILITY
ValueProfNode *__llvm_profile_begin_vnodes(void) {
  return 0;
}
COMPILER_RT_VISIBILITY
ValueProfNode *__llvm_profile_end_vnodes(void) { return 0; }

COMPILER_RT_VISIBILITY ValueProfNode *CurrentVNode = 0;
COMPILER_RT_VISIBILITY ValueProfNode *EndVNode = 0;

#endif


text:
SELECT
  count_past_partitions = 6 and count_future_partitions = 0
FROM
  sql_range_partitions
WHERE
  table_name='test_sql_range_partitions_quarter_maxvalue'
;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hanc.Common
{
    /// <summary>
    /// Models with this attribute will be auto loaded into HancContext
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class HancModel : Attribute
    {
    }
}

namespace Hanc.Common.Data
{
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyModel;
    using Microsoft.DotNet.InternalAbstractions;
    using System.Reflection;

    /// <summary>
    /// Default DbContext
    /// </summary>
    public class HancContext : DbContext
    {
        public HancContext(DbContextOptions<HancContext> options) : base(options)
        {}

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Use reflection to load all the data models with the HancModel attribute
            var entityMethod = typeof(ModelBuilder).GetMethod("Entity", true);
            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var assemblies = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId);

            foreach (var assembly in assemblies)
            {
                var ass = Assembly.Load(assembly);

                var entityTypes = ass
                  .GetTypes()
                  .Where(t =>
                    t.GetTypeInfo().GetCustomAttributes(typeof(HancModel), inherit: true)
                    .Any());

                foreach (var type in entityTypes)
                {
                    entityMethod.MakeGenericMethod(type)
                      .Invoke(modelBuilder, new object[] { });
                }
            }

            base.OnModelCreating(modelBuilder);
        }
    }

    /// <summary>
    /// Used for retreiving generic methods using reflection
    /// </summary>
    public static class TypeExtensions
    {
        public static MethodInfo GetMethod(this Type type, string name, bool generic)
        {
            if (type != null || !String.IsNullOrEmpty(name))
            {
                return type.GetMethods().FirstOrDefault(method => method.Name == name && method.IsGenericMethod == generic);
            }
            else {
                throw new ArgumentNullException();
            }
        }
    }
}

namespace Hanc.Common.Options
{
    /// <summary>
    /// The options pattern uses custom options classes to represent a group of related settings.
    /// See Startup.cs and ValuesController.cs for implimentation code
    /// </summary>
    public class SecretOptions
    {
        public SecretOptions()
        {
            MacSecret = "default_secret";
        }
        public string MacSecret { get; set; }
        public string AppId { get; set; }
        public bool RequireApiAuthToken { get; set; }
    }
}


text:
FactoryGirl.define do
  factory :invoiceable_order, class: Spree::Order do
    user
    bill_address
    ship_address
    completed_at nil
    email { user.email }
    state 'confirm'
    store

    transient do
      line_items_count 1
      line_items_price 10
      shipment_cost 100
      shipping_method_filter Spree::ShippingMethod::DISPLAY_ON_FRONT_END
    end

    after(:create) do |order, evaluator|
      create_list(:line_item, evaluator.line_items_count, order: order, price: evaluator.line_items_price)
      order.line_items.reload

      create(:shipment, order: order, cost: evaluator.shipment_cost)
      order.shipments.reload
      order.next
    end
  end
end


text:
'*
'* This file is part of the TwitterVB software
'* Copyright (c) 2009, Duane Roelands <duane@getTwitterVB.com>
'* All rights reserved.
'*
'* TwitterVB is a port of the Twitterizer library <http://code.google.com/p/twitterizer/>
'* Copyright (c) 2008, Patrick "Ricky" Smith <ricky@digitally-born.com>
'* All rights reserved.
'*
'* Redistribution and use in source and binary forms, with or without modification, are
'* permitted provided that the following conditions are met:
'*
'* - Redistributions of source code must retain the above copyright notice, this list
'*   of conditions and the following disclaimer.
'* - Redistributions in binary form must reproduce the above copyright notice, this list
'*   of conditions and the following disclaimer in the documentation and/or other
'*   materials provided with the distribution.
'* - Neither the name of TwitterVB nor the names of its contributors may be
'*   used to endorse or promote products derived from this software without specific
'*   prior written permission.
'*
'* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
'* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
'* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
'* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
'* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
'* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
'* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
'* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
'* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
'* POSSIBILITY OF SUCH DAMAGE.
'*
Namespace Integration.Twitter.TwitterVB2

    ''' <summary>
    ''' An individual Twitter user.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class TwitterUser
        Inherits XmlObjectBase

#Region "Private Members"
        Private _ID As Int64
        Private _ScreenName As String = String.Empty
        Private _CreatedAt As DateTime
        Private _Description As String = String.Empty
        Private _FavoritesCount As Int64
        Private _FriendsCount As Int64
        Private _FollowersCount As Int64
        Private _Location As String = String.Empty
        Private _Name As String = String.Empty
        Private _Notifications As Boolean
        Private _ProfileBackgroundColor As String = String.Empty
        Private _ProfileBackgroundImageUrl As String = String.Empty
        Private _ProfileImageUrl As String = String.Empty
        Private _ProfileLinkColor As String = String.Empty
        Private _ProfileSidebarBorderColor As String = String.Empty
        Private _ProfileSidebarFillColor As String = String.Empty
        Private _ProfileTextColor As String = String.Empty
        Private _Protected As Boolean
        Private _Status As TwitterStatus = Nothing
        Private _StatusesCount As Int64
        Private _TimeZone As String = String.Empty
        Private _Url As String = String.Empty
        Private _UTCOffset As String = String.Empty
        Private _Verified As Boolean
#End Region

#Region "Public Properties"

        ''' <summary>
        ''' The ID of the user.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ID() As Int64
            Get
                Return _ID
            End Get
            Set(ByVal value As Int64)
                _ID = value
            End Set
        End Property

        ''' <summary>
        ''' The screen name of the user
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ScreenName() As String
            Get
                Return _ScreenName
            End Get
            Set(ByVal value As String)
                _ScreenName = value
            End Set
        End Property

        ''' <summary>
        ''' When the user account was created.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>
        ''' This value is UTC time.
        ''' </remarks>
        Public Property CreatedAt() As DateTime
            Get
                Return _CreatedAt
            End Get
            Set(ByVal value As DateTime)
                _CreatedAt = value
            End Set
        End Property

        ''' <summary>
        ''' When the user account was created.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>
        ''' This value is local time.
        ''' <para/>
        ''' This property is read-only because it is generated in TwitterVB, rather than the Twitter API.
        ''' </remarks>
        Public ReadOnly Property CreatedAtLocalTime() As DateTime
            Get
                Return _CreatedAt.ToLocalTime
            End Get
        End Property

        ''' <summary>
        ''' The description field from the user's profile.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Description() As String
            Get
                Return _Description
            End Get
            Set(ByVal value As String)
                _Description = value
            End Set
        End Property

        ''' <summary>
        ''' How many tweets the user has marked as a favorite.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property FavoritesCount() As Int64
            Get
                Return _FavoritesCount
            End Get
            Set(ByVal value As Int64)
                _FavoritesCount = value
            End Set
        End Property

        ''' <summary>
        ''' How many people this user is following.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property FriendsCount() As Int64
            Get
                Return _FriendsCount
            End Get
            Set(ByVal value As Int64)
                _FriendsCount = value
            End Set
        End Property

        ''' <summary>
        ''' How many people are following this user.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property FollowersCount() As Int64
            Get
                Return _FollowersCount
            End Get
            Set(ByVal value As Int64)
                _FollowersCount = value
            End Set
        End Property

        ''' <summary>
        ''' The location from the user's profile.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>
        ''' This contains no reliable data; it's just a text field.
        ''' </remarks>
        Public Property Location() As String
            Get
                Return _Location
            End Get
            Set(ByVal value As String)
                _Location = value
            End Set
        End Property

        ''' <summary>
        ''' The full name of the user.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>
        ''' This data may not be reliable, since the user can type anything (or nothing at all) here.
        ''' </remarks>
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value
            End Set
        End Property

        ''' <summary>
        ''' Whether or not the user has device notifications active.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Notifications() As Boolean
            Get
                Return _Notifications
            End Get
            Set(ByVal value As Boolean)
                _Notifications = value
            End Set
        End Property

        ''' <summary>
        ''' The background color on the user's profile.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileBackgroundColor() As String
            Get
                Return _ProfileBackgroundColor
            End Get
            Set(ByVal value As String)
                _ProfileBackgroundColor = value
            End Set
        End Property

        ''' <summary>
        ''' The Url of the user's profile background image.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileBackgroundImageUrl() As String
            Get
                Return _ProfileBackgroundImageUrl
            End Get
            Set(ByVal value As String)
                _ProfileBackgroundImageUrl = value
            End Set
        End Property

        ''' <summary>
        ''' The user's profile image.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileImageUrl() As String
            Get
                Return _ProfileImageUrl
            End Get
            Set(ByVal value As String)
                _ProfileImageUrl = value
            End Set
        End Property

        ''' <summary>
        ''' The user's profile link color.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileLinkColor() As String
            Get
                Return _ProfileLinkColor
            End Get
            Set(ByVal value As String)
                _ProfileLinkColor = value
            End Set
        End Property

        ''' <summary>
        ''' The user's profile sidebar border color.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileSidebarBorderColor() As String
            Get
                Return _ProfileSidebarBorderColor
            End Get
            Set(ByVal value As String)
                _ProfileSidebarBorderColor = value
            End Set
        End Property

        ''' <summary>
        ''' The user's profile sidebar fill color.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileSidebarFillColor() As String
            Get
                Return _ProfileSidebarFillColor
            End Get
            Set(ByVal value As String)
                _ProfileSidebarFillColor = value
            End Set
        End Property

        ''' <summary>
        ''' The user's profile text color.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property ProfileTextColor() As String
            Get
                Return _ProfileTextColor
            End Get
            Set(ByVal value As String)
                _ProfileTextColor = value
            End Set
        End Property

        ''' <summary>
        ''' Whether or not this user's tweets are protected.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property [Protected]() As Boolean
            Get
                Return _Protected
            End Get
            Set(ByVal value As Boolean)
                _Protected = value
            End Set
        End Property

        ''' <summary>
        ''' A <c>TwitterStatus</c> object representing the user's last tweet.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Status() As TwitterStatus
            Get
                Return _Status
            End Get
            Set(ByVal value As TwitterStatus)
                _Status = value
            End Set
        End Property

        ''' <summary>
        ''' The number of tweets the user has posted.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property StatusesCount() As Int64
            Get
                Return _StatusesCount
            End Get
            Set(ByVal value As Int64)
                _StatusesCount = value
            End Set
        End Property

        ''' <summary>
        ''' The user's time zone
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>
        ''' This contains no reliable data; it's just a text field.
        ''' </remarks>
        Public Property TimeZone() As String
            Get
                Return _TimeZone
            End Get
            Set(ByVal value As String)
                _TimeZone = value
            End Set
        End Property

        ''' <summary>
        ''' The Url in the user's profile.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Url() As String
            Get
                Return _Url
            End Get
            Set(ByVal value As String)
                _Url = value
            End Set
        End Property

        ''' <summary>
        ''' The amount of time, in seconds, between the user's timezone and UTC time.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property UTCOffset() As String
            Get
                Return _UTCOffset
            End Get
            Set(ByVal value As String)
                _UTCOffset = value
            End Set
        End Property

        ''' <summary>
        ''' Whether or not the user is a verified user.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Verified() As Boolean
            Get
                Return _Verified
            End Get
            Set(ByVal value As Boolean)
                _Verified = value
            End Set
        End Property

#End Region

        ''' <summary>
        ''' Creates a new <c>TwitterUser</c> object.
        ''' </summary>
        ''' <param name="UserNode">An <c>XmlNode</c> from the Twitter API response representing a user.</param>
        ''' <remarks></remarks>
        Public Sub New(ByVal UserNode As System.Xml.XmlNode)
            Me.ID = XmlInt64_Get(UserNode("id"))
            Me.ScreenName = XmlString_Get(UserNode("screen_name"))
            Me.CreatedAt = XmlDate_Get(UserNode("created_at"))
            Me.Description = XmlString_Get(UserNode("description"))
            Me.FavoritesCount = XmlInt64_Get(UserNode("favourites_count"))
            Me.FollowersCount = XmlInt64_Get(UserNode("followers_count"))
            Me.FriendsCount = XmlInt64_Get(UserNode("friends_count"))
            Me.Location = XmlString_Get(UserNode("location"))
            Me.Name = XmlString_Get(UserNode("name"))
            Me.Notifications = XmlBoolean_Get(UserNode("notifications"))
            Me.ProfileBackgroundColor = XmlString_Get(UserNode("profile_background_color"))
            Me.ProfileBackgroundImageUrl = XmlString_Get(UserNode("profile_background_image_url"))
            Me.ProfileImageUrl = XmlString_Get(UserNode("profile_image_url"))
            Me.ProfileLinkColor = XmlString_Get(UserNode("profile_link_color"))
            Me.ProfileSidebarBorderColor = XmlString_Get(UserNode("profile_sidebar_border_color"))
            Me.ProfileSidebarFillColor = XmlString_Get(UserNode("profile_sidebar_fill_color"))
            Me.ProfileTextColor = XmlString_Get(UserNode("profile_text_color"))
            Me.Protected = XmlBoolean_Get(UserNode("protected"))
            If UserNode("status") IsNot Nothing Then
                Me.Status = New TwitterStatus(UserNode("status"))
            End If
            Me.StatusesCount = XmlInt64_Get(UserNode("statuses_count"))
            Me.TimeZone = XmlString_Get(UserNode("time_zone"))
            Me.Url = XmlString_Get(UserNode("url"))
            Me.UTCOffset = XmlString_Get(UserNode("utc_offset"))
            Me.Verified = XmlBoolean_Get(UserNode("verified"))
        End Sub

        ''' <summary>
        ''' Default constructor
        ''' </summary>
        ''' <remarks></remarks>
        ''' <exclude/>
        Public Sub New()
        End Sub
    End Class
End Namespace


text:
<!doctype html>

    <meta charset="utf-8">

    <title>JavaScript is Like Ruby</title>

    <meta name="description" content="">
    <meta name="author" content="Trey Hunner">

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

    <link rel="stylesheet" href="css/reveal.css">
    <link rel="stylesheet" href="css/theme/truthful.css" id="theme">

    <link rel="stylesheet" href="lib/css/github.css">

JavaScript

Slightly more like Ruby

            Trey Hunner / @treyhunner

            My name is Trey.  I do front-end web development and I only know enough Ruby to be dangerous.

            I'm going to show you some new JavaScript features that you can start using today to make your JavaScript code a little more readable.

ECMAScript History

                Edition
                Release Date
                Browser Support
                a.k.a.

              3
              Dec. 1999
              All
              ES3

              5
              Dec. 2009
              IE 9, FF 4, Chrome 7
              ES5

              6
              June 2015
              Not supported yet
              ES2015

            ECMAScript is the language specification that JavaScript is based on.

            In this presentation I'm going to show off features that were added in ECMAScript 6, also known as ECMAScript 2015.

            I will be going a little quickly, so you probably won't catch everything but hopefully you'll learn something new.

            ECMAScript 6 isn't supported by browsers, but you **can** start using it today...

Use next generation JavaScript, today.

            You just need to use Babel.

            Babel allows you to compile your ES6 code down to ES5 code, which is understood by all modern web browsers.

            This is a pre-compilation process, which is kind of like the pre-compilation step necessary for using something like CoffeeScript.

Fat Arrows

people.each do |person|
  puts person.name
end

people.forEach(person => {
  console.log(person.name);
});

              Our first new feature is fat arrows.

              Fat arrows are a new shortened function syntax.

              Here, as you can see, we've lost the parenthesis around our single argument and we've lost the word function.

Fat Arrows

  users.select {|u| u.is_active}.map(&:name).sort

  users.filter(u => u.isActive).map(u => u.name).sort();

              Fat arrow functions have an even shorter syntax.

              Here in addition to losing the parenthesis and the word function, we've also lost the curly braces and the return statement.

              In addition to being easier on the eyes, fat arrow functions inherit the "this" binding of their outer scope.

              For anyone who has wrestled with JavaScript function binding, that's a really big deal.

Template Strings

date = Time.now
puts "The year is #{date.year}"

let date = new Date();
console.log(`The year is ${date.getFullYear()}`);

              With Template strings you can now do string interpolation in JavaScript.

              You create template strings using backticks and they act kind of like Ruby's double-quoted strings.

              Remember that these backticks notate strings.  This is not executing commands like backticks do in Ruby.

Template Strings

poem = 'Programming is fun
Except for syntax errors
Missing curly brace'

let poem = `Programming is fun
Except for syntax errors
Missing curly brace`;

              Template strings also allow you to make multi-line strings, the same way all strings work in Ruby.

Classes

class Point
  def initialize(x, y)
    @x = x
    @y = y
  end
  def to_s
    "(#{@x}, #{@y})"
  end
end

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return `(${this.x}, ${this.y})`;
  }
}

              JavaScript now has a class notation which is somewhat similar to the one used by CoffeeScript.

              Of course no class implementation is complete without a good foot gun.  So JavaScript also supports...

Subclasses

class ColorPoint < Point
  def initialize(x, y, color)
    super(x, y)
    @color = color
  end
  def to_s
    "#{super()} in #{@color}"
  end
end

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y);
    this.color = color;
  }
  toString() {
    return `${super.toString()} in ${this.color}`;
  }
}

              Inheritance!

              So we can use extends to inherit classes and super to call methods in a parent class.

              Under the hood, this is equivalent to the prototype inheritance which is already supported by JavaScript.

Rest

def say(phrase, *folks)
  folks.each{|folk| puts "#{folk} said \"#{phrase}\""}
end

function say(phrase, ...folks) {
  folks.forEach(folk => console.log(`${folk} said "${phrase}"`));
}

              The *rest* operator is kind of like Ruby's splat operator.

              When defining a function, we can use the rest operator (notated by three dots) to capture the rest of our function arguments.

Spread

people = ["Bigelow", "Quil", "Trady Blix", "Lara"]
shout("hello world", *people)

people = ["Bigelow", "Quil", "Trady Blix", "Lara"];
shout("hello world", ...people);

              The spread operator is also like the splat operator.

              When calling a function, we can use the spread operator to place an array of items into *separate* arguments in a function call.

Combine Arrays

first = [1, 2]
second = [3, 4]
combined = first + second

var first = [1, 2];
var second = [3, 4];
var combined = [...first, ...second];

              You can also use the spread operator to unpack one array inside of another array.  This allows us to combine arrays easily.

              So in this example `combined` would be the array `[1, 2, 3, 4]`.

Default Arguments

def greet(name = 'there')
  puts "Hello #{name}!"
end

function greet(name='there') {
  console.log(`Hello ${name}!`);
}

            JavaScript functions can now have default argument values.

            This **does not** mean JavaScript has keyword arguments.  It doesn't.  These are just default values for positional arguments.

Array Destructuring

x, y = [1, 2]

[x, y] = [1, 2];

              With array destructuring, you can unpack arrays into multiple variables.

              You can also use this for multiple assignment and for swapping variables.

Object Destructuring

emoji = {category: "people", char: "😁", name: "smile"}
character, name = emoji.values_at(:char, :name)

let emoji = {category: "people", char: "😁", name: "smile"};
let {name, char: character} = emoji;

              There's also an object destructuring syntax.  This is a little bit awkward in Ruby but this is probably also considered to be a code smell in the Ruby world.

              Temporary variables are probably a little more common JavaScript, so this can actually be a pretty useful feature.

Go Forth and Babel

Learn ES2015: https://babeljs.io/docs/learn-es2015/

Try it out: http://babeljs.io/repl

            If you write JavaScript and you're not already sold on a JavaScript pre-processor like CoffeeScript, I think you should seriously consider Babel.

            If you're interested in learning more about Babel or trying it out right from your web browser, you should really check out the Babel website.

Final

            Trey Hunner / @treyhunner

            Web consultant available for hire

            http://truthful.technology

            Any questions?


text:
package org.wso2.carbon.apimgt.impl.publishers;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIPublisher;
import org.wso2.carbon.apimgt.api.model.APIStore;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException;
import org.wso2.carbon.apimgt.impl.importexport.ExportFormat;
import org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI;
import org.wso2.carbon.apimgt.impl.importexport.utils.APIImportExportUtil;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;

/**
 * This class handles all the Publisher functionality when publishing an API to an external WSO2 Store.
 * When publishing an API to an external store, this uses ImportExportAPI service to export the API with advertise_only
 * property true and uses the APIs Import Publisher REST API in external store to import and publish the API. To remove
 * an API from external store, this class uses the API DELETE Publisher REST API of external store.
 */
public class WSO2APIPublisher implements APIPublisher {

    private static final Log log = LogFactory.getLog(WSO2APIPublisher.class);

    /**
     * Publish an API to External Store.
     *
     * @param api   API to publish
     * @param store External APIStore
     * @return Whether API publish is successful or not
     * @throws APIManagementException If an error occurs while publishing API to external store
     */
    @Override
    public boolean publishToStore(API api, APIStore store) throws APIManagementException {

        evaluateCredentialsAndEndpointURL(store);
        if (log.isDebugEnabled()) {
            log.debug("Publishing API: " + api.getId().getApiName() + " version: " + api.getId().getVersion()
                    + " to external store: " + store.getName());
        }
        //Export API as an advertised only API as a zipped file
        File file = exportAPIArchive(api);
        //Call the Admin REST API of external Store to publish the exported advertised only API
        CloseableHttpResponse response = importAPIToExternalStore(file, store, Boolean.FALSE);
        return evaluateImportAPIResponse(response);
    }

    /**
     * Check if external store endpoint and credentials are not blank.
     *
     * @param store APIStore configurations
     * @throws APIManagementException If either one of the credentials and endpoint URL is blank
     */
    private void evaluateCredentialsAndEndpointURL(APIStore store) throws APIManagementException {

        if (StringUtils.isBlank(store.getEndpoint()) || StringUtils.isBlank(store.getUsername())
                || StringUtils.isBlank(store.getPassword())) {
            String msg = "External APIStore endpoint URL or credentials are not defined. " +
                    "Cannot proceed with publishing API to the APIStore - " + store.getDisplayName();
            throw new APIManagementException(msg);
        }
    }

    /**
     * Exports API as an advertised API using APIImportExportManager.
     *
     * @param api API artifact to import
     * @return API archive
     * @throws APIManagementException If an error occurs while exporting API.
     */
    private File exportAPIArchive(API api) throws APIManagementException {

        File apiArchive;
        String tenantDomain = null;
        int tenantId;

        try {
            // Get tenant domain and ID to generate the original DevPortal URL (redirect URL) for the original Store
            tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(
                    api.getId().getProviderName()));
            tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);

            //Export API as an archive file and set it as a multipart entity in the request
            ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
            apiArchive = importExportAPI.exportAPI(api.getUuid(), api.getId().getName(), api.getId().getVersion(),
                    String.valueOf(api.getRevisionId()), api.getId().getProviderName(), Boolean.TRUE, ExportFormat.JSON,
                    Boolean.TRUE, Boolean.TRUE, Boolean.FALSE,
                    getExternalStoreRedirectURLForAPI(tenantId, api.getUuid()));
            if (log.isDebugEnabled()) {
                log.debug("API successfully exported to file: " + apiArchive.getName());
            }
        } catch (APIImportExportException e) {
            String errorMessage = "Error while exporting API: " + api.getId().getApiName() + " version: "
                    + api.getId().getVersion();
            throw new APIManagementException(errorMessage, e);
        } catch (UserStoreException e) {
            String errorMessage =
                    "Error while getting tenantId for tenant domain: " + tenantDomain + " when exporting API:" + api
                            .getId().getApiName() + " version: " + api.getId().getVersion();
            throw new APIManagementException(errorMessage, e);
        }
        return apiArchive;
    }

    /**
     * Imports an API to external Store by calling Admin import API REST service. If overwrite is true, then the API
     * which is already published in external store will be updated.
     *
     * @param apiArchive API zipped file
     * @param store      external store to import
     * @param overwrite  whether to import or update APII
     * @return HTTP Response whether import is successful or not
     * @throws APIManagementException If an error occurs while importing API.
     */
    private CloseableHttpResponse importAPIToExternalStore(File apiArchive, APIStore store, Boolean overwrite)
            throws APIManagementException {

        MultipartEntityBuilder multipartEntityBuilder;
        String storeEndpoint = null;
        CloseableHttpClient httpclient;
        URIBuilder uriBuilder;
        HttpPost httppost;
        CloseableHttpResponse httpResponse;

        try {
            multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addPart(APIConstants.RestApiConstants.IMPORT_API_ARCHIVE_FILE,
                    new FileBody(apiArchive));
            //Get Publisher REST API apis/import endpoint from given store endpoint
            storeEndpoint = getPublisherRESTURLFromStoreURL(store.getEndpoint())
                    + APIConstants.RestApiConstants.REST_API_PUBLISHER_API_IMPORT_RESOURCE;
            httpclient = getHttpClient(storeEndpoint);
            uriBuilder = new URIBuilder(storeEndpoint);
            //Add preserveProvider query parameter false
            uriBuilder.addParameter(APIConstants.RestApiConstants.IMPORT_API_PRESERVE_PROVIDER, Boolean.FALSE.toString());
            uriBuilder.addParameter(APIConstants.RestApiConstants.IMPORT_API_OVERWRITE, overwrite.toString());

            httppost = new HttpPost(uriBuilder.build());
            httppost.setEntity(multipartEntityBuilder.build());

            //Set Authorization Header of external store admin
            httppost.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader(store));
            if (log.isDebugEnabled()) {
                log.debug("Invoking Admin REST API of external store: " + storeEndpoint + " to import API archive: "
                        + apiArchive.getName());
            }
            //Call import API of external store
            httpResponse = httpclient.execute(httppost);
        } catch (URISyntaxException e) {
            String errorMessage = "Error while building URI for store endpoint: " + storeEndpoint;
            log.error(errorMessage, e);
            throw new APIManagementException(errorMessage, e);
        } catch (IOException e) {
            String errorMessage = "Error while importing to external Store: " + storeEndpoint;
            log.error(errorMessage, e);
            throw new APIManagementException(errorMessage, e);
        } finally {
            FileUtils.deleteQuietly(apiArchive);
        }
        return httpResponse;
    }

    /**
     * Get actual store host URL (without the path name) from the given store endpoint URL.
     *
     * @param storeEndpoint Store endpoint URL given in configuration (Eg:https://localhost:9443)
     * @return Actual store host URL (Eg:https://localhost:9443)
     * @throws APIManagementException If a malformed store endpoint is provided
     */
    private String getStoreHostURLFromEndpoint(String storeEndpoint) throws APIManagementException {

        try {
            URL storeURL = new URL(storeEndpoint);
            int port = storeURL.getPort();
            String host = storeURL.getHost();
            String protocol = storeURL.getProtocol();
            storeURL = new URL(protocol, host, port, StringUtils.EMPTY);
            return storeURL.toString();
        } catch (MalformedURLException e) {
            String errorMessage = "Error while getting Store host URL of external store due to provided malformed Store "
                    + "endpoint URL: " + storeEndpoint;
            log.error(errorMessage, e);
            throw new APIManagementException(errorMessage, e);
        }
    }

    /**
     * Get Publisher REST API URL from given Store Endpoint URL assuming that given Store endpoint URL is similar to
     * "http://localhost:9763/store.
     *
     * @param storeEndpoint Store endpoint URL with "/store" context
     * @return Publisher REST API URL of external store
     */
    private String getPublisherRESTURLFromStoreURL(String storeEndpoint) throws APIManagementException {

        //Get Publisher REST API endpoint from given store endpoint
        return getStoreHostURLFromEndpoint(storeEndpoint)
                .concat(APIConstants.RestApiConstants.REST_API_PUBLISHER_CONTEXT_FULL_1);
    }

    /**
     * Get Basic Authorization header for external store admin credentials.
     *
     * @param store External Store config
     * @return Base64 encoded Basic Authorization header
     */
    private String getBasicAuthorizationHeader(APIStore store) {

        //Set Authorization Header of external store admin
        byte[] encodedAuth = Base64
                .encodeBase64((store.getUsername() + ":" + store.getPassword()).getBytes(StandardCharsets.ISO_8859_1));
        return APIConstants.AUTHORIZATION_HEADER_BASIC + StringUtils.SPACE + new String(encodedAuth);
    }

    /**
     * Check whether successful response is received for API Import service call.
     *
     * @param response HTTP response received for API Import request
     * @return Successful or not
     * @throws APIManagementException If an error occurs while checking the response
     */
    private Boolean evaluateImportAPIResponse(CloseableHttpResponse response) throws APIManagementException {

        HttpEntity entity;
        String responseString;
        try {
            //If API is imported successfully, return true
            entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            //release all resources held by the responseHttpEntity
            EntityUtils.consume(entity);
            if (evaluateResponseStatus(response)
                    && StringUtils.containsIgnoreCase(responseString, APIConstants.RestApiConstants.IMPORT_API_SUCCESS)) {
                if (log.isDebugEnabled()) {
                    log.debug("Import API service call received successful response: " + responseString);
                }
                return true;
            } else {
                String errorMessage = "Import API service call received unsuccessful response: " + responseString
                        + " status: " + response.getStatusLine().getStatusCode();
                log.error(errorMessage);
                throw new APIManagementException(errorMessage);
            }
        } catch (IOException e) {
            String errorMessage = "Error while evaluating HTTP response";
            throw new APIManagementException(errorMessage, e);
        } finally {
            closeHTTPResponse(response);
        }
    }

    /**
     * Check whether HTTP Response code is 200 OK.
     *
     * @param response HTTP Response
     * @return whether status code matches or not.
     */
    private Boolean evaluateResponseStatus(CloseableHttpResponse response) {

        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_OK;
    }

    /**
     * Close HTTP Response to ensure correct deallocate of system resources
     *
     * @param response CloseableHttpResponse
     * @throws APIManagementException If an error occurs while closing response
     */
    private void closeHTTPResponse(CloseableHttpResponse response) throws APIManagementException {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                String errorMessage = "Error occurred while closing the buffers reader.";
                log.error(errorMessage, e);
                throw new APIManagementException(errorMessage, e);
            }
        }
    }

    /**
     * Update API in external store.
     *
     * @param api   API to update
     * @param store External APIStore
     * @return Whether API update is successful or nor
     * @throws APIManagementException If an error occurs while updating API in external store
     */
    @Override
    public boolean updateToStore(API api, APIStore store) throws APIManagementException {

        evaluateCredentialsAndEndpointURL(store);
        if (log.isDebugEnabled()) {
            log.debug("Updating API: " + api.getId().getApiName() + " version: " + api.getId().getVersion()
                    + " to external store: " + store.getName());
        }
        //Export API as an advertised only API as a zipped file
        File file = exportAPIArchive(api);
        //Call the Admin REST API of external Store to publish the exported advertised only API
        CloseableHttpResponse response = importAPIToExternalStore(file, store, Boolean.TRUE);
        return evaluateImportAPIResponse(response);
    }

    /**
     * Publish API to external Store.
     *
     * @param apiId APIIdentifier
     * @param store External APIStore
     * @return Whether API is successfully deleted or not
     * @throws APIManagementException If an error occurs while deleting API from external store
     */
    @Override
    public boolean deleteFromStore(APIIdentifier apiId, APIStore store) throws APIManagementException {

        CloseableHttpResponse httpResponse = null;
        evaluateCredentialsAndEndpointURL(store);
        if (log.isDebugEnabled()) {
            log.debug("Delete API: " + apiId.getApiName() + " version: " + apiId.getVersion()
                    + " from external store: " + store.getName());
        }
        String apiUUID = getAPIUUID(store, apiId);
        if (apiUUID != null) {
            //Get Publisher REST endpoint from given store endpoint
            String storeEndpoint = getPublisherRESTURLFromStoreURL(store.getEndpoint())
                    + APIConstants.RestApiConstants.REST_API_PUB_RESOURCE_PATH_APIS + "/" + apiUUID;
            //Delete API
            try {
                CloseableHttpClient httpclient = getHttpClient(storeEndpoint);
                HttpDelete httpDelete = new HttpDelete(storeEndpoint);
                //Set Authorization Header of external store admin
                httpDelete.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader(store));
                //Call import API of external store
                httpResponse = httpclient.execute(httpDelete);
                if (evaluateResponseStatus(httpResponse)) {
                    if (log.isDebugEnabled()) {
                        log.debug("API: " + apiId.getApiName() + " version: " + apiId.getVersion()
                                + " removed from external store: " + store.getName() + " successfully");
                    }
                    return true;
                } else {
                    HttpEntity entity = httpResponse.getEntity();
                    String responseString = EntityUtils.toString(entity);
                    //release all resources held by the responseHttpEntity
                    EntityUtils.consume(entity);
                    String errorMessage = "API Delete service call received unsuccessful response status: "
                            + httpResponse.getStatusLine().getStatusCode() + " response: " + responseString;
                    throw new APIManagementException(errorMessage);
                }
            } catch (IOException e) {
                String errorMessage = "Error while deleting API UUID: " + apiUUID + " from external store: "
                        + store.getName();
                log.error(errorMessage, e);
                throw new APIManagementException(errorMessage, e);
            } finally {
                closeHTTPResponse(httpResponse);
            }
        } else {
            String errorMessage = "API: " + apiId.getApiName() + " version: " + apiId.getVersion()
                    + " does not exist in external store: " + store.getName();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
    }

    /**
     * Check whether API exists in external Store.
     *
     * @param api   API to check existence of
     * @param store External API Store
     * @return Whether API is available or not
     * @throws APIManagementException If an error occurs while checking existence of API in external store
     */
    @Override
    public boolean isAPIAvailable(API api, APIStore store) throws APIManagementException {

        evaluateCredentialsAndEndpointURL(store);
        if (log.isDebugEnabled()) {
            log.debug("Check if API: " + api.getId().getApiName() + " version: " + api.getId().getVersion()
                    + " available in external store: " + store.getName());
        }
        return getAPIUUID(store, api.getId()) != null;
    }

    /**
     * Publish new version of an existing API to external Store.
     *
     * @param api     API to create new version of
     * @param store   External APIStore
     * @param version New Version
     * @return If creating new version is successful or not
     * @throws APIManagementException If an error occurs while creating new version.
     */
    @Override
    public boolean createVersionedAPIToStore(API api, APIStore store, String version) throws APIManagementException {
        //We do not perform a separate call for creating a new version. Import API REST API is used for creating the
        //new versioned API as well.
        return publishToStore(api, store);
    }

    /**
     * Get API published to external Store by calling search API REST service in external store's publisher component.
     * If API exists, a non empty UUID will be returned.
     *
     * @param store         External Store
     * @param apiIdentifier API ID of the API to retrieve
     * @return UUID of the published API
     * @throws APIManagementException If an error occurs while searching the API in external store.
     */
    private String getAPIUUID(APIStore store, APIIdentifier apiIdentifier) throws APIManagementException {

        String apiUUID;
        CloseableHttpResponse httpResponse = null;
        //Get Publisher REST endpoint from given store endpoint
        String storeEndpoint = getPublisherRESTURLFromStoreURL(store.getEndpoint())
                + APIConstants.RestApiConstants.REST_API_PUB_RESOURCE_PATH_APIS;
        try {
            CloseableHttpClient httpclient = getHttpClient(storeEndpoint);
            URIBuilder uriBuilder = new URIBuilder(storeEndpoint);
            String searchQuery = APIConstants.RestApiConstants.PUB_SEARCH_API_QUERY_PARAMS_NAME + "\""
                    + apiIdentifier.getApiName() + "\"" + StringUtils.SPACE
                    + APIConstants.RestApiConstants.PUB_SEARCH_API_QUERY_PARAMS_VERSION + "\""
                    + apiIdentifier.getVersion() + "\"";
            uriBuilder.addParameter(APIConstants.RestApiConstants.REST_API_PUB_SEARCH_API_QUERY, searchQuery);
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            //Set Authorization Header of external store admin
            httpGet.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader(store));

            //Call Publisher REST API of external store
            httpResponse = httpclient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String responseString = EntityUtils.toString(entity);
            //release all resources held by the responseHttpEntity
            EntityUtils.consume(entity);
            if (evaluateResponseStatus(httpResponse)) {
                JSONParser parser = new JSONParser();
                JSONObject responseJson = (JSONObject) parser.parse(responseString);
                long apiListResultCount =
                        (long) responseJson.get(APIConstants.RestApiConstants.PUB_API_LIST_RESPONSE_PARAMS_COUNT);
                if (apiListResultCount == 1) {
                    JSONArray apiList =
                            (JSONArray) responseJson.get(APIConstants.RestApiConstants.PUB_API_LIST_RESPONSE_PARAMS_LIST);
                    JSONObject apiJson = (JSONObject) apiList.get(0);
                    apiUUID = (String) apiJson.get(APIConstants.RestApiConstants.PUB_API_RESPONSE_PARAMS_ID);
                    if (log.isDebugEnabled()) {
                        log.debug("API: " + apiIdentifier.getApiName() + " version: " + apiIdentifier.getVersion()
                                + " exists in external store: " + store.getName() + " with UUID: " + apiUUID);
                    }
                    return apiUUID;
                } else if (apiListResultCount > 1) {
                    //Duplicate APIs exists
                    String errorMessage = "Duplicate APIs exists in external store for API name:"
                            + apiIdentifier.getApiName() + " version: " + apiIdentifier.getVersion();
                    log.error(errorMessage);
                    throw new APIManagementException(errorMessage);
                }
                //Response count is 0. Hence API does not exists in external store.
                if (log.isDebugEnabled()) {
                    log.debug("API: " + apiIdentifier.getApiName() + " version: " + apiIdentifier.getVersion()
                            + " does not exists in external store: " + store.getName());
                }
            } else {
                String errorMessage = "API Search service call received unsuccessful response with status: "
                        + httpResponse.getStatusLine().getStatusCode() + " response: " + responseString;
                log.error(errorMessage);
                throw new APIManagementException(errorMessage);
            }
        } catch (ParseException e) {
            String errorMessage = "Error while reading API response from external store for API: "
                    + apiIdentifier.getApiName() + " version:" + apiIdentifier.getVersion();
            log.error(errorMessage, e);
            throw new APIManagementException(errorMessage, e);
        } catch (IOException e) {
            String errorMessage = "Error while getting API UUID from external store for API: "
                    + apiIdentifier.getApiName() + " version:" + apiIdentifier.getVersion();
            log.error(errorMessage, e);
            throw new APIManagementException(errorMessage, e);
        } catch (URISyntaxException e) {
            String errorMessage = "Error while building URI for store endpoint: " + storeEndpoint;
            log.error(errorMessage, e);
            throw new APIManagementException(errorMessage, e);
        } finally {
            closeHTTPResponse(httpResponse);
        }
        return null;
    }

    /**
     * Get APIProvider instance for the logged in user.
     *
     * @return APIProvider instance
     * @throws APIManagementException If an error occurs while getting APIProvider instance
     */
    protected APIProvider getLoggedInUserProvider() throws APIManagementException {
        //Get APIProvider instance for logged in user
        return APIManagerFactory.getInstance().getAPIProvider(getLoggedInUsername());
    }

    /**
     * Get logged in username.
     *
     * @return username
     */
    protected String getLoggedInUsername() {

        return CarbonContext.getThreadLocalCarbonContext().getUsername();
    }

    /**
     * Get redirect URL for external stores. (This is the URL displayed in the published APIs in external Store)
     *
     * @param tenantId tenant ID
     * @return Redirect URL
     * @throws APIManagementException If an error occurs while getting redirect URL.
     */
    private String getExternalStoreRedirectURL(int tenantId) throws APIManagementException {

        UserRegistry registry;
        String redirectURL;
        redirectURL = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration()
                .getFirstProperty(APIConstants.EXTERNAL_API_STORES + "." + APIConstants.EXTERNAL_API_STORES_STORE_URL);

        if (redirectURL != null) {
            return redirectURL;
        }
        try {
            registry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceSystemRegistry(tenantId);
            if (registry.resourceExists(APIConstants.EXTERNAL_API_STORES_LOCATION)) {
                Resource resource = registry.get(APIConstants.EXTERNAL_API_STORES_LOCATION);
                String content = new String((byte[]) resource.getContent());
                OMElement element = AXIOMUtil.stringToOM(content);
                OMElement storeURL = element.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORES_STORE_URL));
                if (storeURL != null) {
                    redirectURL = storeURL.getText();
                } else {
                    String msg = "Store URL element is missing in External APIStores configuration";
                    log.error(msg);
                    throw new APIManagementException(msg);
                }
            }
            return redirectURL;
        } catch (RegistryException e) {
            String msg = "Error while retrieving External Stores Configuration from registry";
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (XMLStreamException e) {
            String msg = "Malformed XML found in the External Stores Configuration resource";
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    }

    /**
     * Get External store redirecting URL for the API
     *
     * @param tenantId Tenant Id
     * @param apiId    API UUID of the API to redirect
     * @return Exact redirect URL for the API in external store
     */
    private String getExternalStoreRedirectURLForAPI(int tenantId, String apiId) throws APIManagementException {

        String redirectURL = getExternalStoreRedirectURL(tenantId);
        if (redirectURL.split(APIConstants.EXTERNAL_API_DEVPORTAL_URL_REGEX).length == 0) {
            return redirectURL;
        }
        return redirectURL.split(APIConstants.EXTERNAL_API_DEVPORTAL_URL_REGEX)[0]
                + APIConstants.RestApiConstants.REST_API_PUB_RESOURCE_PATH_APIS + "/" + apiId;
    }

    /**
     * Get HTTP Client for service endpoint port and protocol.
     *
     * @param storeEndpoint service endpoint URL Eg: http://localhost:9763/api/am/admin/v0.16/import/api
     *                      Eg: http://localhost:9763/api/am/publisher/v0.16
     * @return HTTP Client
     * @throws APIManagementException If an error occurs due to malformed URL.
     */
    protected CloseableHttpClient getHttpClient(String storeEndpoint) throws APIManagementException {

        try {
            URL storeURL = new URL(storeEndpoint);
            int externalStorePort = storeURL.getPort();
            String externalStoreProtocol = storeURL.getProtocol();
            return (CloseableHttpClient) APIUtil.getHttpClient(externalStorePort, externalStoreProtocol);
        } catch (MalformedURLException e) {
            throw new APIManagementException("Error while initializing HttpClient due to malformed URL", e);
        }
    }
}


text:
<configuration>

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
		</encoder>
	</appender>

	<root level="info">
		<appender-ref ref="STDOUT"/>
	</root>

	<logger name="com.github.kerubistan" level="info"/>

</configuration>


text:
using System;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using log4net.Config;

namespace PowerShellTools.Common.Logging
{
    public class LogManager
    {
        private static bool _initialized;
        private const string ResourceName = "PowerShellTools.Common.Logging.logging.xml";
        private static readonly string PoshToolsAppPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"PowerShell Tools for Visual Studio");
        private static readonly string LogConfigPath = Path.Combine(PoshToolsAppPath, "logging.xml");

        public static ILog GetLogger(Type type)
        {
            Initialize();

            return new Log(log4net.LogManager.GetLogger(type));
        }

        private static void Initialize()
        {
            if (_initialized) return;

            if (!File.Exists(LogConfigPath))
            {
                Directory.CreateDirectory(PoshToolsAppPath);
                var assembly = Assembly.GetExecutingAssembly();

                using (var stream = assembly.GetManifestResourceStream(ResourceName))
                using (var reader = new StreamReader(stream))
                {
                    var result = reader.ReadToEnd();
                    using (var writer = new StreamWriter(LogConfigPath))
                    {
                        writer.Write(result);
                    }
                }
            }

            XmlConfigurator.ConfigureAndWatch(new FileInfo(LogConfigPath));

            _initialized = true;
        }

        public static void SetLoggingLevel(string levelString)
        {
            Initialize();
            if (!File.Exists(LogConfigPath)) return;

            var document = XDocument.Load(LogConfigPath);
            if (document.Root == null) return;
            var root = document.Root.Element("root");
            if (root == null) return;
            var level = root.Element("level");
            if (level == null) return;
            var levelValue = level.Attribute("value");
            if (levelValue == null) return;
            levelValue.SetValue(levelString);

            document.Save(LogConfigPath);
        }

    }
}


text:
package com.gmail.socraticphoenix.nebula.javasource.ast.block;

import com.gmail.socraticphoenix.nebula.javasource.ast.JavaSourceContext;

public class JavaSourceRawBlock extends AbstractJavaSourceBlock<JavaSourceRawBlock> {
    private String header;
    private String footer;

    public JavaSourceRawBlock(String header, String footer) {
        this.header = header;
        this.footer = footer;
    }

    public static JavaSourceRawBlock of(String header, String footer) {
        return new JavaSourceRawBlock(header, footer);
    }

    @Override
    public String write(int indent, JavaSourceContext context) {
        return this.writeStatements(indent, context, this.header, this.footer);
    }

}