text:
"""Utilities helpful for game analysis"""
from collections import abc
import contextlib
import functools
import inspect
import itertools
import json
import math
import operator
import random
import signal
import string
import sys
import threading
import warnings

import numpy as np
from numpy.lib import stride_tricks
import scipy.special as sps
from scipy import optimize

_TINY = np.finfo(float).tiny
# This is the maximum integer that can be exactly represented as a float
_MAX_INT_FLOAT = 2 ** (np.finfo(float).nmant - 1)
_SIMPLEX_BIG = 1 / np.finfo(float).resolution
# XXX A lot of these are candidates for cython

def prod(collection):
    """Product of all elements in the collection"""
    return functools.reduce(operator.mul, collection)

def comb(n, k):
    """Return n choose k

    This function works on arrays, and will properly return a python integer
    object if the number is too large to be stored in a 64 bit integer.
    """
    # pylint: disable-msg=invalid-name
    res = np.rint(sps.comb(n, k, False))
    if np.all(res < _MAX_INT_FLOAT):  # pylint: disable=no-else-return
        return res.astype(int)
    elif isinstance(n, abc.Iterable) or isinstance(k, abc.Iterable):
        broad = np.broadcast(np.asarray(n), np.asarray(k))
        res = np.empty(broad.shape, dtype=object)
        res.flat = [sps.comb(n_, k_, True) for n_, k_ in broad]
        return res
    else:
        return sps.comb(n, k, True)

def comb_inv(cmb, k):
    """Return the inverse of `comb`

    Given a number of combinations, and the size of subset we're choosing,
    compute the integer lower bound, i.e. return n* such that `comb(n*, k) <=
    cmb < comb(n* + 1, k)`.
    """
    # pylint: disable-msg=invalid-name
    n = np.empty(np.broadcast(cmb, k).shape, int)
    na = n.view()
    na.shape = (n.size,)
    cmba = np.broadcast_to(cmb, n.size)
    ka = np.broadcast_to(k, n.size)
    step = ka.copy()
    mask = step > 0
    na[~mask] = 0
    na[mask] = np.ceil((ka[mask] / np.e * cmba[mask] ** (1 / ka[mask])).astype(float))

    # If we didn't approximate the lower bound, then there are at most k values
    # to check. This does a poor mans binary search with some wasted effort,
    # however for small k, it's negligible, and we see performance improvements
    # over linear search in general.
    while np.any(mask):
        valid = comb(na[mask] + step[mask], ka[mask]) <= cmba[mask]

        inc = mask.copy()
        inc[mask] = valid
        na[inc] += step[inc]

        red = mask.copy()
        red[mask] = ~valid
        step[red] //= 2

        mask = step > 0
    if n.ndim == 0:  # pylint: disable=no-else-return
        return n.item()
    else:
        return n

def game_size(players, strategies):
    """Number of profiles in a symmetric game with players and strategies"""
    return comb(np.asarray(players) + strategies - 1, players)

def game_size_inv(size, players):
    """Inverse of game_size

    Given a game size and a number of players, return a lower bound on the
    number of strategies s* such that game_size(players, s*) <= size <
    game_size(players, s* + 1)`.
    """
    return comb_inv(size, players) - players + 1

def repeat(iterable, reps):
    """Repeat each element of iterable reps times"""
    return itertools.chain.from_iterable(
        itertools.repeat(e, r) for e, r in zip(iterable, reps)
    )

def acomb(n, k, repetition=False):
    """Compute an array of all n choose k options

    The result will be an array shape (m, n) where m is n choose k optionally
    with repetitions."""
    # pylint: disable-msg=invalid-name
    if repetition:  # pylint: disable=no-else-return
        return _acombr(n, k)
    else:
        return _acomb(n, k)

def _acombr(n, k):
    """Combinations with repetitions"""
    # pylint: disable-msg=invalid-name
    # This uses dynamic programming to compute everything
    num = sps.comb(n, k, repetition=True, exact=True)
    grid = np.zeros((num, n), dtype=int)
    memoized = {}

    # This recursion breaks if asking for numbers that are too large (stack
    # overflow), but the order to fill n and k is predictable, it may be better
    # to to use a for loop.
    def fill_region(n, k, region):
        """Recursively fill a region"""
        if n == 1:
            region[0, 0] = k
            return
        elif k == 0:
            region.fill(0)
            return
        if (n, k) in memoized:
            np.copyto(region, memoized[n, k])
            return
        memoized[n, k] = region
        o = 0
        for ki in range(k, -1, -1):
            n_ = n - 1
            k_ = k - ki
            m = sps.comb(n_, k_, repetition=True, exact=True)
            region[o : o + m, 0] = ki
            fill_region(n_, k_, region[o : o + m, 1:])
            o += m

    fill_region(n, k, grid)
    return grid

def _acomb(n, k):
    """Combinations"""
    # pylint: disable-msg=invalid-name
    if k == 0:
        return np.zeros((1, n), bool)

    # This uses dynamic programming to compute everything
    num = sps.comb(n, k, exact=True)
    grid = np.empty((num, n), dtype=bool)
    memoized = {}

    # This recursion breaks if asking for numbers that are too large (stack
    # overflow), but the order to fill n and k is predictable, it may be better
    # to to use a for loop.
    def fill_region(n, k, region):
        """Recursively fill a region"""
        if n <= k:
            region.fill(True)
            return
        elif k == 1:
            region.fill(False)
            np.fill_diagonal(region, True)
            return
        if (n, k) in memoized:
            np.copyto(region, memoized[n, k])
            return

        memoized[n, k] = region
        trues = sps.comb(n - 1, k - 1, exact=True)
        region[:trues, 0] = True
        fill_region(n - 1, k - 1, region[:trues, 1:])
        region[trues:, 0] = False
        fill_region(n - 1, k, region[trues:, 1:])

    fill_region(n, k, grid)
    return grid

def acartesian2(*arrays):
    """Array cartesian product in 2d

    Produces a new ndarray that has the cartesian product of every row in the
    input arrays. The number of columns is the sum of the number of columns in
    each input. The number of rows is the product of the number of rows in each
    input.

    Arguments
    ---------
    *arrays : [ndarray (xi, s)]
    """
    rows = prod(a.shape[0] for a in arrays)
    columns = sum(a.shape[1] for a in arrays)
    dtype = arrays[0].dtype  # should always have at least one role
    check(all(a.dtype == dtype for a in arrays), "all arrays must have the same dtype")

    result = np.zeros((rows, columns), dtype)
    pre_row = 1
    post_row = rows
    pre_column = 0
    for array in arrays:
        length, width = array.shape
        post_row //= length
        post_column = pre_column + width
        view = result[:, pre_column:post_column]
        view.shape = (pre_row, -1, post_row, width)
        np.copyto(view, array[:, None])
        pre_row *= length
        pre_column = post_column

    return result

def simplex_project(array):
    """Return the projection onto the simplex"""
    array = np.asarray(array, float)
    check(not np.isnan(array).any(), "can't project nan onto simplex: {}", array)
    # This fails for really large values, so we normalize the array so the
    # largest element has absolute value at most _SIMPLEX_BIG
    array = np.clip(array, -_SIMPLEX_BIG, _SIMPLEX_BIG)
    size = array.shape[-1]
    sort = -np.sort(-array, -1)
    rho = (1 - sort.cumsum(-1)) / np.arange(1, size + 1)
    inds = size - 1 - np.argmax((rho + sort > 0)[..., ::-1], -1)
    rho.shape = (-1, size)
    lam = rho[np.arange(rho.shape[0]), inds.flat]
    lam.shape = array.shape[:-1] + (1,)
    return np.maximum(array + lam, 0)

def multinomial_mode(p, n):
    """Compute the mode of n samples from multinomial distribution p.

    Notes
    -----
    Algorithm from [3]_, notation follows [4]_.

    .. [3] Finucan 1964. The mode of a multinomial distribution.
    .. [4] Gall 2003. Determination of the modes of a Multinomial distribution.
    """
    # pylint: disable-msg=invalid-name
    p = np.asarray(p, float)
    mask = p > 0
    result = np.zeros(p.size, int)

    p = p[mask]
    f = p * (n + p.size / 2)
    k = f.astype(int)
    f -= k
    n0 = k.sum()
    if n0 < n:
        q = (1 - f) / (k + 1)
        for _ in range(n0, n):
            a = q.argmin()
            k[a] += 1
            f[a] -= 1
            q[a] = (1 - f[a]) / (k[a] + 1)
    elif n0 > n:
        with np.errstate(divide="ignore"):
            q = f / k
            for _ in range(n, n0):
                a = q.argmin()
                k[a] -= 1
                f[a] += 1
                q[a] = f[a] / k[a]

    result[mask] = k
    return result

def geometric_histogram(num, prob):
    """Return the histogram of n draws from a geometric distribution

    This function computes values from the same distribution as
    `np.bincount(np.random.geometric(prob, num) - 1)` but does so more
    efficiently.
    """
    check(num > 0, "must take at least one sample")
    check(0 < prob <= 1, "must use a valid probability in (0, 1]")
    results = []
    # This is a rough upper bound on the expectation of the extreme value of
    # num geometrics with probability prob
    inc = math.ceil((np.log(num) + 1) * (1 / prob - 0.5)) + 1
    while num > 0:
        res = np.random.multinomial(num, prob * (1 - prob) ** np.arange(inc))
        results.append(res[:-1])
        num = res[-1]
    # Remove trailing zeros
    last = results.pop()
    results.append(last[: np.flatnonzero(last)[-1] + 1])
    return np.concatenate(results)

def axis_to_elem(array, axis=-1):
    """Converts an axis of an array into a unique element

    In general, this returns a copy of the array, unless the data is
    contiguous. This usually requires that the last axis is the one being
    merged.

    Parameters
    ----------
    array : ndarray
        The array to convert an axis to a view.
    axis : int, optional
        The axis to convert into a single element. Defaults to the last axis.
    """
    array = np.asarray(array)
    # ascontiguousarray will make a copy if necessary
    axis_at_end = np.ascontiguousarray(np.rollaxis(array, axis, array.ndim))
    new_shape = axis_at_end.shape
    elems = axis_at_end.view([("axis", array.dtype, new_shape[-1:])])
    elems.shape = new_shape[:-1]
    return elems

def axis_from_elem(array, axis=-1):
    """Converts and array of axis elements back to an axis"""
    return np.rollaxis(array["axis"], -1, axis)

def hash_array(array):
    """Hash an array"""
    return _HashArray(array)

class _HashArray(object):  # pylint: disable=too-few-public-methods
    """A hashed array object"""

    def __init__(self, array):
        self.array = np.asarray(array)
        self.array.setflags(write=False)
        self._hash = hash(self.array.tobytes())

    def __hash__(self):
        return self._hash

    def __eq__(self, othr):
        # pylint: disable-msg=protected-access
        return self._hash == othr._hash and np.all(self.array == othr.array)

def iunique(iterable):
    """Return an iterable of unique items ordered by first occurrence"""
    seen = set()
    for item in iterable:
        if item not in seen:
            seen.add(item)
            yield item

def random_strings(min_length, max_length=None, digits=string.ascii_lowercase):
    """Return a random string

    Parameters
    ----------
    min_length : int
        The minimum length string to return.
    max_length : int, optional
        The maximum length string to return. If None or unspecified, this is
        the same as min_length.
    num : int, optional
        The number of strings to return. If None or unspecified this returns a
        single string, otherwise it returns a generator with length `num`.
    digits : str, optional
        The optional digits to select from.
    """
    if max_length is None:
        max_length = min_length
    check(min_length <= max_length, "max_length can't be less than min_length")
    while True:
        length = random.randint(min_length, max_length)
        yield "".join(random.choice(digits) for _ in range(length))

def prefix_strings(prefix, num):
    """Returns a list of prefixed integer strings"""
    padding = int(math.log10(max(num - 1, 1))) + 1
    return ("{}{:0{:d}d}".format(prefix, i, padding) for i in range(num))

def is_sorted(iterable, *, key=None, reverse=False, strict=False):
    """Returns true if iterable is sorted

    Parameters
    ----------
    iterable : iterable
        The iterable to check for sorted-ness.
    key : x -> y, optional
        Apply mapping function key to iterable prior to checking. This can be
        done before calling, but this ensures identical calls as sorted.
    reverse : bool, optional
    `key` and `reverse` function as they for `sorted`"""
    if key is not None:
        iterable = map(key, iterable)

    ait, bit = itertools.tee(iterable)
    next(bit, None)  # Don't throw error if empty

    if strict and reverse:  # pylint: disable=no-else-return
        return all(a > b for a, b in zip(ait, bit))
    elif reverse:
        return all(a >= b for a, b in zip(ait, bit))
    elif strict:
        return all(a < b for a, b in zip(ait, bit))
    else:
        return all(a <= b for a, b in zip(ait, bit))

def allequal_perm(aarr, barr):
    """Test if two arrays are equal for any permutation of their first axis

    Parameters
    ----------
    aarr, barr : array_like
        Identically sized arrays. This will determine if any permutation of
        their first axis will make them equal.
    """
    aarr, barr = map(np.asarray, [aarr, barr])
    check(aarr.shape == barr.shape, "can only compare identically sized arrays")
    auniq, acounts = np.unique(
        axis_to_elem(aarr.reshape(aarr.shape[0], -1)), return_counts=True
    )
    buniq, bcounts = np.unique(
        axis_to_elem(barr.reshape(barr.shape[0], -1)), return_counts=True
    )
    return np.all(acounts == bcounts) and np.all(auniq == buniq)

def allclose_perm(aarr, barr, **kwargs):
    """allclose but for any permutation of aarr and barr

    Parameters
    ----------
    aarr, barr : array_like
        Identically sized arrays of floats. This will determine if any
        permutation of their first axis will make `allclose` true.
    kwargs
        Additional arguments to pass to `isclose`.
    """
    aarr, barr = map(np.asarray, [aarr, barr])
    check(aarr.shape == barr.shape, "can only compare identically sized arrays")
    isclose = np.isclose(aarr[:, None], barr, **kwargs)
    isclose.shape = isclose.shape[:2] + (-1,)
    return isclose[optimize.linear_sum_assignment(~isclose.all(2))].all()

def check(condition, message, *args, **kwargs):
    """Check state and raise exception if not valid"""
    if not condition:
        raise ValueError(message.format(*args, **kwargs))

def memoize(member_function):
    """Memoize computation of single object functions"""
    check(
        len(inspect.signature(member_function).parameters) == 1,
        "can only memoize single object functions",
    )

    @functools.wraps(member_function)
    def new_member_function(obj):
        """Memoized member function"""
        name = "__{}_{}".format(member_function.__name__, obj.__class__.__name__)
        if not hasattr(obj, name):
            setattr(obj, name, member_function(obj))
        return getattr(obj, name)

    return new_member_function

def deprecated(func):
    """Mark a function as deprecated"""

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        """Deprecated function"""
        warnings.warn(
            "Call to deprecated function {}.".format(func.__name__),
            category=DeprecationWarning,
            stacklevel=2,
        )
        return func(*args, **kwargs)

    return wrapped

def subsequences(iterable, seq=2):
    """Return subsequences of an iterable

    Each element in the generator will be a tuple of `seq` elements that were
    ordered in the iterable.
    """
    iters = itertools.tee(iterable, seq)
    for i, itr in enumerate(iters):
        for _ in range(i):
            next(itr, None)
    return zip(*iters)

def asubsequences(array, seq=2, axis=0):
    """Return sub-sequences of an array

    This returns a new array with leading dimension `seq` representing a length
    `seq` sub-sequence of the input array. The following dimensions are
    preserved except for `axis`, which is `seq - 1` shorter due to edge
    effects. This method returns a view, so no data copying happens.

    Parameters
    ----------
    array : ndarray
        Array to take subsequences over.
    seq : int, optional
        Length of subsequences to take.
    axis : int, optional
        The axis to treat as the sequence to take sub-sequences of.
    """
    new_shape = list(array.shape)
    new_shape[axis] -= seq - 1
    return stride_tricks.as_strided(
        array, shape=[seq] + new_shape, strides=(array.strides[axis],) + array.strides
    )

def _raise_handler(exception):
    """Create handler for exception"""

    def handler(_signum, _frame):
        """Raise timeout error"""
        raise exception

    return handler

def _timeout_context(seconds, exception):
    """Timeout context manager that works in parent or child thread"""
    if seconds is None or seconds <= 0:  # pylint: disable=no-else-return
        return _noop()
    elif threading.current_thread() == threading.main_thread():
        return _timeout_context_main(seconds, exception)
    else:
        return _timeout_context_child(seconds, exception)

@contextlib.contextmanager
def _noop():
    """Noop for irrelevant time"""
    yield

@contextlib.contextmanager
def _timeout_context_main(seconds, exception):
    """Timeout context manager for main thread"""
    old = signal.signal(signal.SIGALRM, _raise_handler(exception))
    signal.setitimer(signal.ITIMER_REAL, seconds)
    yield
    signal.setitimer(signal.ITIMER_REAL, 0)
    signal.signal(signal.SIGALRM, old)

@contextlib.contextmanager
def _timeout_context_child(seconds, exception):
    """Timeout context manager for child thread"""
    timedout = threading.Event()
    complete = threading.Event()

    def globaltrace(_frame, why, _arg):  # pragma: no cover
        """Global trace to set local trace"""
        if why == "call":  # pylint: disable=no-else-return
            return localtrace
        else:
            return None

    def localtrace(_frame, why, _arg):  # pragma: no cover
        """Local trace to check for timeout"""
        if complete.is_set():  # pylint: disable=no-else-return
            return None
        elif timedout.is_set() and why == "line":
            complete.set()
            raise exception
        else:
            return localtrace

    timer = threading.Timer(seconds, timedout.set)
    timer.start()
    sys.settrace(globaltrace)
    yield
    # These are executed, but coverage misses them, potentially due to messing
    # with the trace
    complete.set()  # pragma: no cover
    timer.cancel()  # pragma: no cover

class _Timeout(object):  # pylint: disable=too-few-public-methods
    """Timeout class"""

    def __init__(self, seconds, exception):
        self._create = functools.partial(_timeout_context, seconds, exception)
        self._seconds = seconds
        self._exception = exception
        self._context = None

    def __enter__(self):
        self._context = self._create()
        self._context.__enter__()  # pylint: disable=no-member

    def __exit__(self, typ, value, traceback):
        self._context.__exit__(typ, value, traceback)  # pylint: disable=no-member
        self._context = None

    def __call__(self, func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            """Wrapped function"""
            with self._create():
                return func(*args, **kwargs)

        return wrapped

def timeout(seconds=None, exception=TimeoutError):
    """Timeout code

    A TimeoutError is raised if code doesn't finish within seconds. The result
    can be used as a decorator or as a context manager. This will work in child
    threads, but as a significant performance hit.

    Parameters
    ----------
    seconds : int, optional
        The number of seconds until timeout. If omitted, no timeout is used,
        and this is essentially a no op
    exception : Exception, optional
        The exception to raise. IF omitted, a generic TimeoutError is used.
    """
    return _Timeout(seconds, exception)

def iloads(jstring, **kwargs):
    """Load a string as a generator of json objects"""
    decoder = json.JSONDecoder(**kwargs)
    idx = json.decoder.WHITESPACE.match(jstring, 0).end()
    while idx < len(jstring):
        obj, end = decoder.raw_decode(jstring, idx)
        yield obj
        idx = json.decoder.WHITESPACE.match(jstring, end).end()

def iload(jfp, **kwargs):
    """Load a file as a generator of json objects"""
    return iloads(jfp.read(), **kwargs)


text:
id: bad87fee1348bd9aed108826
title: Націлення на конкретний дочірній елемент за допомогою jQuiery
challengeType: 6
forumTopicId: 18315
required:
  -
    link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css'
dashedName: target-a-specific-child-of-an-element-using-jquery
---

# --description--

Ви вже бачили, чому id атрибути такі зручні в націленні завдяки селекторам jOuery. Але ви не завжди працюватимете з такими лаконічними id.

На щастя, jQuery має деякі інші хитрощі для націлювання на правильні елементи.

jQuery використовує селектори CSS для націлювання на елементи. Значення `target:nth-child(n)` селектора CSS дає змогу виділити всі n-ні елементи з цільовим класом або типом елементу.

Ось як варто надавати третьому елементу у кожному джерелі класу руху:

```js
$(".target:nth-child(3)").addClass("animated bounce");
```

Кожен другий дочірній елемент у джерелі має бути рухливим. Ви мусите виділити дочірні елементи як `target` клас.

# --hints--

Другий елемент у ваших `target` елементах має бути рухливим.

```js
assert(
  $('.target:nth-child(2)').hasClass('animated') &&
    $('.target:nth-child(2)').hasClass('bounce')
);
```

Рухатись мають тільки два елементи.

```js
assert($('.animated.bounce').length === 2);
```

Варто скористатися селектором `:nth-child()` щоб змінювати ці елементи.

```js
assert(code.match(/\:nth-child\(/g));
```

Щоб додати ці класи до елемента використовуйте тільки jQuery.

```js
assert(
  code.match(/\$\(".target:nth-child\(2\)"\)/g) ||
    code.match(/\$\('.target:nth-child\(2\)'\)/g) ||
    code.match(/\$\(".target"\).filter\(":nth-child\(2\)"\)/g) ||
    code.match(/\$\('.target'\).filter\(':nth-child\(2\)'\)/g)
);
```

# --seed--

## --seed-contents--

```html
<script>
  $(document).ready(function() {
    $("#target1").css("color", "red");
    $("#target1").prop("disabled", true);
    $("#target4").remove();
    $("#target2").appendTo("#right-well");
    $("#target5").clone().appendTo("#left-well");
    $("#target1").parent().css("background-color", "red");
    $("#right-well").children().css("color", "orange");

  });
</script>

<!-- Only change code above this line -->

<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>
  <div class="row">
    <div class="col-xs-6">
      <h4>#left-well</h4>
      <div class="well" id="left-well">
        <button class="btn btn-default target" id="target1">#target1</button>
        <button class="btn btn-default target" id="target2">#target2</button>
        <button class="btn btn-default target" id="target3">#target3</button>
      </div>
    </div>
    <div class="col-xs-6">
      <h4>#right-well</h4>
      <div class="well" id="right-well">
        <button class="btn btn-default target" id="target4">#target4</button>
        <button class="btn btn-default target" id="target5">#target5</button>
        <button class="btn btn-default target" id="target6">#target6</button>
      </div>
    </div>
  </div>
</div>
```

# --solutions--

```html
<script>
  $(document).ready(function() {
    $("#target1").css("color", "red");
    $("#target1").prop("disabled", true);
    $("#target4").remove();
    $("#target2").appendTo("#right-well");
    $("#target5").clone().appendTo("#left-well");
    $("#target1").parent().css("background-color", "red");
    $("#right-well").children().css("color", "orange");
    $(".target:nth-child(2)").addClass("animated bounce");
  });
</script>

<!-- Only change code above this line -->

<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>
  <div class="row">
    <div class="col-xs-6">
      <h4>#left-well</h4>
      <div class="well" id="left-well">
        <button class="btn btn-default target" id="target1">#target1</button>
        <button class="btn btn-default target" id="target2">#target2</button>
        <button class="btn btn-default target" id="target3">#target3</button>
      </div>
    </div>
    <div class="col-xs-6">
      <h4>#right-well</h4>
      <div class="well" id="right-well">
        <button class="btn btn-default target" id="target4">#target4</button>
        <button class="btn btn-default target" id="target5">#target5</button>
        <button class="btn btn-default target" id="target6">#target6</button>
      </div>
    </div>
  </div>
</div>
```

redpajama_set_name: RedPajamaGithub


text:
SilverTick.TodosController = Ember.ArrayController.extend({
actions: {
createTodo: function() {
// Get the todo title set by the "New Todo" text field
var title = this.get('newTitle');
if (!title) { return false; }
if (!title.trim()) { return; }
// Create the new Todo model
var todo = this.store.createRecord('todo', {
title: title,
isCompleted: false
});
// Clear the "New Todo" text field
this.set('newTitle', '');
// Save the new model
todo.save();
},
},
remaining: function() {
return this.filterBy('isCompleted', false).get('length');
}.property('@each.isCompleted'),
inflection: function() {
var remaining = this.get('remaining');
return remaining === 1 ? 'item' : 'items';
}.property('remaining')

});


text:
<?php

namespace Magento\Customer\Controller;

use Magento\Framework\App\RequestInterface;

/**
 * Customer address controller
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
abstract class Address extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;

    /**
     * @var \Magento\Framework\Data\Form\FormKey\Validator
     */
    protected $_formKeyValidator;

    /**
     * @var \Magento\Customer\Api\AddressRepositoryInterface
     */
    protected $_addressRepository;

    /**
     * @var \Magento\Customer\Model\Metadata\FormFactory
     */
    protected $_formFactory;

    /**
     * @var \Magento\Customer\Api\Data\AddressInterfaceFactory
     */
    protected $addressDataFactory;

    /**
     * @var \Magento\Customer\Api\Data\RegionInterfaceFactory
     */
    protected $regionDataFactory;

    /**
     * @var \Magento\Framework\Reflection\DataObjectProcessor
     */
    protected $_dataProcessor;

    /**
     * @var \Magento\Framework\Api\DataObjectHelper
     */
    protected $dataObjectHelper;

    /**
     * @var \Magento\Framework\Controller\Result\ForwardFactory
     */
    protected $resultForwardFactory;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
     * @param \Magento\Customer\Model\Metadata\FormFactory $formFactory
     * @param \Magento\Customer\Api\AddressRepositoryInterface $addressRepository
     * @param \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory
     * @param \Magento\Customer\Api\Data\RegionInterfaceFactory $regionDataFactory
     * @param \Magento\Framework\Reflection\DataObjectProcessor $dataProcessor
     * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
     * @param \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
        \Magento\Customer\Model\Metadata\FormFactory $formFactory,
        \Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
        \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory,
        \Magento\Customer\Api\Data\RegionInterfaceFactory $regionDataFactory,
        \Magento\Framework\Reflection\DataObjectProcessor $dataProcessor,
        \Magento\Framework\Api\DataObjectHelper $dataObjectHelper,
        \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->_customerSession = $customerSession;
        $this->_formKeyValidator = $formKeyValidator;
        $this->_formFactory = $formFactory;
        $this->_addressRepository = $addressRepository;
        $this->addressDataFactory = $addressDataFactory;
        $this->regionDataFactory = $regionDataFactory;
        $this->_dataProcessor = $dataProcessor;
        $this->dataObjectHelper = $dataObjectHelper;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Retrieve customer session object
     *
     * @return \Magento\Customer\Model\Session
     */
    protected function _getSession()
    {
        return $this->_customerSession;
    }

    /**
     * Check customer authentication
     *
     * @param RequestInterface $request
     * @return \Magento\Framework\App\ResponseInterface
     */
    public function dispatch(RequestInterface $request)
    {
        if (!$this->_getSession()->authenticate()) {
            $this->_actionFlag->set('', 'no-dispatch', true);
        }
        return parent::dispatch($request);
    }

    /**
     * @param string $route
     * @param array $params
     * @return string
     */
    protected function _buildUrl($route = '', $params = [])
    {
        /** @var \Magento\Framework\UrlInterface $urlBuilder */
        $urlBuilder = $this->_objectManager->create('Magento\Framework\UrlInterface');
        return $urlBuilder->getUrl($route, $params);
    }
}


text:
<?php

namespace ZF2Base\View\Helper;

use Zend\View\Helper\AbstractHelper;

class Formatar extends AbstractHelper {

    /**
     * Formatar plugin
     *
     * @var ZF2Base\Controller\Plugin\Formatar
     */
    protected $pluginFormatar;

    /**
     * Returns the formatar plugin controller
     *
     * @return Helper\Formatar
     */
    public function __invoke($valor = null) {
        $this->getPluginFormatar();
        if ($valor == null){
            return $this;
        }
        return $valor;

    }

    /**
     * Returna CEP formatado via plugin controller
     *
     * @param  string|null $cep
     * @return string|Plugin\Formatar
     */
    public function cep($cep) {
        return $this->pluginFormatar->cep($cep);
    }

    /**
     * Returna CPF formatado via plugin controller
     *
     * @param  string|null $cpf
     * @return string|Plugin\Formatar
     */
    public function cpf($cpf) {
        return $this->pluginFormatar->cpf($cpf);
    }

    /**
     * Returna CNPJ formatado via plugin controller
     *
     * @param  string|null $cnpj
     * @return string|Plugin\Formatar
     */
    public function cnpj($cnpj) {
        return $this->pluginFormatar->cnpj($cnpj);
    }

    /**
     * Returna número de telefone formatado via plugin controller
     *
     * @param  string|null $telefone
     * @return string|Plugin\Formatar
     */
    function telefone($numero) {
        return $this->pluginFormatar->telefone($numero);
    }

    /**
     * Get plugin Formatar
     *
     * @return ZF2Base\Controller\Plugin\Formatar
     */
    protected function getPluginFormatar() {
        if (null === $this->pluginFormatar) {
            $this->setPluginFormatar(new \ZF2Base\Controller\Plugin\Formatar());
        }
        return $this->pluginFormatar;
    }

    /**
     * Set plugin Formatar
     *
     * @return AbstractHelper
     */
    protected function setPluginFormatar(\ZF2Base\Controller\Plugin\Formatar $pluginFormatar) {
        $this->pluginFormatar = $pluginFormatar;
        return $this;
    }

}


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

namespace LionFire.Wpf
{
    public class ThemeInjector
    {
        public static void SetTheme(object control, string themeName)
        {
            if (control == null) return;
            if (control.GetType().FullName == "Xceed.Wpf.AvalonDock.DockingManager")
            {
                var typeName = "Xceed.Wpf.AvalonDock.Themes." + themeName;
                //var assemblyName = "Xceed.Wpf.AvalonDock.Themes.VS2013";
                //Type type = Type.GetType(typeName); // TODO - use
            }
            // ENH
            //Vs2013DarkTheme;
        }
    }

}


text:
package org.apache.hadoop.metrics2.sink.timeline.availability;

import com.google.gson.Gson;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.retry.BoundedExponentialBackoffRetry;
import org.apache.hadoop.metrics2.sink.timeline.AbstractTimelineMetricsSink;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.powermock.api.easymock.PowerMock.createNiceMock;
import static org.powermock.api.easymock.PowerMock.expectNew;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;

@RunWith(PowerMockRunner.class)
@PrepareForTest({AbstractTimelineMetricsSink.class, URL.class, HttpURLConnection.class, MetricCollectorHAHelper.class})
public class MetricCollectorHATest {

  @Test
  public void findCollectorUsingZKTest() throws Exception {
    InputStream is = createNiceMock(InputStream.class);
    HttpURLConnection connection = createNiceMock(HttpURLConnection.class);
    URL url = createNiceMock(URL.class);
    MetricCollectorHAHelper haHelper = createNiceMock(MetricCollectorHAHelper.class);

    expectNew(URL.class, "http://localhost1:2181/ws/v1/timeline/metrics/livenodes").andReturn(url).anyTimes();
    expectNew(URL.class, "http://localhost2:2181/ws/v1/timeline/metrics/livenodes").andReturn(url).anyTimes();
    expect(url.openConnection()).andReturn(connection).anyTimes();
    expect(connection.getInputStream()).andReturn(is).anyTimes();
    expect(connection.getResponseCode()).andThrow(new IOException()).anyTimes();
    expect(haHelper.findLiveCollectorHostsFromZNode()).andReturn(
      new ArrayList<String>() {{
        add("h2");
        add("h3");
      }});

    replayAll();
    TestTimelineMetricsSink sink = new TestTimelineMetricsSink(haHelper);
    sink.init();

    String host = sink.findPreferredCollectHost();

    verifyAll();

    Assert.assertNotNull(host);
    Assert.assertEquals("h2", host);

  }

  @Test
  public void testEmbeddedModeCollectorZK() throws Exception {

    BoundedExponentialBackoffRetry retryPolicyMock = PowerMock.createMock(BoundedExponentialBackoffRetry.class);
    expectNew(BoundedExponentialBackoffRetry.class, 1000, 10000, 1).andReturn(retryPolicyMock);

    CuratorZookeeperClient clientMock = PowerMock.createMock(CuratorZookeeperClient.class);
    expectNew(CuratorZookeeperClient.class, "zkQ", 10000, 2000, null, retryPolicyMock)
      .andReturn(clientMock);

    clientMock.start();
    expectLastCall().once();

    clientMock.close();
    expectLastCall().once();

    ZooKeeper zkMock = PowerMock.createMock(ZooKeeper.class);
    expect(clientMock.getZooKeeper()).andReturn(zkMock).once();

    expect(zkMock.exists("/ambari-metrics-cluster", false)).andReturn(null).once();

    replayAll();
    MetricCollectorHAHelper metricCollectorHAHelper = new MetricCollectorHAHelper("zkQ", 1, 1000);
    Collection<String> liveInstances = metricCollectorHAHelper.findLiveCollectorHostsFromZNode();
    verifyAll();
    Assert.assertTrue(liveInstances.isEmpty());
  }

  @Test
  public void findCollectorUsingKnownCollectorTest() throws Exception {
    HttpURLConnection connection = createNiceMock(HttpURLConnection.class);
    URL url = createNiceMock(URL.class);
    MetricCollectorHAHelper haHelper = createNiceMock(MetricCollectorHAHelper.class);

    Gson gson = new Gson();
    ArrayList<String> output = new ArrayList<>();
    output.add("h1");
    output.add("h2");
    output.add("h3");
    InputStream is = IOUtils.toInputStream(gson.toJson(output));

    expectNew(URL.class, "http://localhost1:2181/ws/v1/timeline/metrics/livenodes").andReturn(url).anyTimes();
    expectNew(URL.class, "http://localhost2:2181/ws/v1/timeline/metrics/livenodes").andReturn(url).anyTimes();
    expect(url.openConnection()).andReturn(connection).anyTimes();
    expect(connection.getInputStream()).andReturn(is).anyTimes();
    expect(connection.getResponseCode()).andReturn(200).anyTimes();

    replayAll();
    TestTimelineMetricsSink sink = new TestTimelineMetricsSink(haHelper);
    sink.init();

    String host = sink.findPreferredCollectHost();
    Assert.assertNotNull(host);
    Assert.assertEquals("h3", host);

    verifyAll();
  }

  private class TestTimelineMetricsSink extends AbstractTimelineMetricsSink {
    MetricCollectorHAHelper testHelper;

    TestTimelineMetricsSink(MetricCollectorHAHelper haHelper) {
      testHelper = haHelper;
    }

    @Override
    protected void init() {
      super.init();
      this.collectorHAHelper = testHelper;
    }

    @Override
    protected synchronized String findPreferredCollectHost() {
      return super.findPreferredCollectHost();
    }

    @Override
    protected String getCollectorUri(String host) {
      return null;
    }

    @Override
    protected String getCollectorProtocol() {
      return "http";
    }

    @Override
    protected String getCollectorPort() {
      return "2181";
    }

    @Override
    protected int getTimeoutSeconds() {
      return 10;
    }

    @Override
    protected String getZookeeperQuorum() {
      return "localhost1:2181";
    }

    @Override
    protected Collection<String> getConfiguredCollectorHosts() {
      return Arrays.asList("localhost1",  "localhost2");
    }

    @Override
    protected String getHostname() {
      return "h1";
    }
  }
}


text:
.ps-container > .ps-scrollbar-y-rail {
    display: none;
    position: absolute;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    opacity: 0;
    -webkit-transition: background-color .1s linear,opacity .1s linear;
    -moz-transition: background-color .1s linear,opacity .1s linear;
    -o-transition: background-color .1s linear,opacity .1s linear;
    transition: background-color .1s linear,opacity .1s linear;
    right: 1px;
    width: 7px;
}

.ps-container:hover > .ps-scrollbar-x-rail,
.ps-container:hover > .ps-scrollbar-y-rail {
    opacity: .6;
}

.ps-container:hover > .ps-scrollbar-y-rail:hover {
    background-color: #eee;
    opacity: .9;
}

.ps-container.ps-active-x > .ps-scrollbar-x-rail,
.ps-container.ps-active-y > .ps-scrollbar-y-rail {
    display: block;
    background-color: transparent;
    z-index: 10002;
}

.ps-container > .ps-scrollbar-y-rail > .ps-scrollbar-y {
    position: absolute;
    background-color: #777;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    -webkit-transition: background-color .1s linear;
    -moz-transition: background-color .1s linear;
    -o-transition: background-color .1s linear;
    transition: background-color .1s linear;
    right: 0;
    width: 7px;
}

textarea {
    font-size: 14px;
    font-family: Consolas;
}


text:
package installer

import (
	"fmt"
	"net/http"
	gpath "path"
	"reflect"
	"strings"
	"time"

	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/conversion"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/apiserver/pkg/endpoints"
	"k8s.io/apiserver/pkg/endpoints/discovery"
	"k8s.io/apiserver/pkg/endpoints/handlers"
	"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
	"k8s.io/apiserver/pkg/endpoints/metrics"
	"k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/registry/rest"

	"github.com/emicklei/go-restful"
)

// NB: the contents of this file should mostly be a subset of the functionality
// in "k8s.io/apiserver/pkg/endpoints".  It would be nice to eventual figure out
// a way to not have to recreate/copy a bunch of the structure from the normal API
// installer, so that this trivially tracks changes to the main installer.

// MetricsAPIGroupVersion is similar to "k8s.io/apiserver/pkg/endpoints".APIGroupVersion,
// except that it installs the metrics REST handlers, which use wildcard resources
// and subresources.
//
// This basically only serves the limitted use case required by the metrics API server --
// the only verb accepted is GET (and perhaps WATCH in the future).
type MetricsAPIGroupVersion struct {
	DynamicStorage rest.Storage

	*endpoints.APIGroupVersion
}

// InstallREST registers the dynamic REST handlers into a restful Container.
// It is expected that the provided path root prefix will serve all operations.  Root MUST
// NOT end in a slash.  It should mirror InstallREST in the plain APIGroupVersion.
func (g *MetricsAPIGroupVersion) InstallREST(container *restful.Container) error {
	installer := g.newDynamicInstaller()
	ws := installer.NewWebService()

	registrationErrors := installer.Install(ws)
	lister := g.ResourceLister
	if lister == nil {
		return fmt.Errorf("must provide a dynamic lister for dynamic API groups")
	}
	versionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, lister)
	versionDiscoveryHandler.AddToWebService(ws)
	container.Add(ws)
	return utilerrors.NewAggregate(registrationErrors)
}

// newDynamicInstaller is a helper to create the installer.  It mirrors
// newInstaller in APIGroupVersion.
func (g *MetricsAPIGroupVersion) newDynamicInstaller() *MetricsAPIInstaller {
	prefix := gpath.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)
	installer := &MetricsAPIInstaller{
		group:             g,
		prefix:            prefix,
		minRequestTimeout: g.MinRequestTimeout,
	}

	return installer
}

// MetricsAPIInstaller is a specialized API installer for the metrics API.
// It is intended to be fully compliant with the Kubernetes API server conventions,
// but serves wildcard resource/subresource routes instead of hard-coded resources
// and subresources.
type MetricsAPIInstaller struct {
	group             *MetricsAPIGroupVersion
	prefix            string // Path prefix where API resources are to be registered.
	minRequestTimeout time.Duration

	// TODO: do we want to embed a normal API installer here so we can serve normal
	// endpoints side by side with dynamic ones (from the same API group)?
}

// Install installs handlers for API resources.
func (a *MetricsAPIInstaller) Install(ws *restful.WebService) (errors []error) {
	errors = make([]error, 0)

	err := a.registerResourceHandlers(a.group.DynamicStorage, ws)
	if err != nil {
		errors = append(errors, fmt.Errorf("error in registering custom metrics resource: %v", err))
	}

	return errors
}

// NewWebService creates a new restful webservice with the api installer's prefix and version.
func (a *MetricsAPIInstaller) NewWebService() *restful.WebService {
	ws := new(restful.WebService)
	ws.Path(a.prefix)
	// a.prefix contains "prefix/group/version"
	ws.Doc("API at " + a.prefix)
	// Backwards compatibility, we accepted objects with empty content-type at V1.
	// If we stop using go-restful, we can default empty content-type to application/json on an
	// endpoint by endpoint basis
	ws.Consumes("*/*")
	mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
	ws.Produces(append(mediaTypes, streamMediaTypes...)...)
	ws.ApiVersion(a.group.GroupVersion.String())

	return ws
}

// registerResourceHandlers registers the resource handlers for custom metrics.
// Compared to the normal installer, this plays fast and loose a bit, but should still
// follow the API conventions.
func (a *MetricsAPIInstaller) registerResourceHandlers(storage rest.Storage, ws *restful.WebService) error {
	context := a.group.Context

	optionsExternalVersion := a.group.GroupVersion
	if a.group.OptionsExternalVersion != nil {
		optionsExternalVersion = *a.group.OptionsExternalVersion
	}

	mapping, err := a.restMapping()
	if err != nil {
		return err
	}

	fqKindToRegister, err := a.getResourceKind(storage)
	if err != nil {
		return err
	}

	kind := fqKindToRegister.Kind

	lister := storage.(rest.Lister)
	list := lister.NewList()
	listGVKs, _, err := a.group.Typer.ObjectKinds(list)
	if err != nil {
		return err
	}
	versionedListPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind(listGVKs[0].Kind))
	if err != nil {
		return err
	}
	versionedList := indirectArbitraryPointer(versionedListPtr)

	versionedListOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind("ListOptions"))
	if err != nil {
		return err
	}

	ctxFn := func(req *http.Request) request.Context {
		if ctx, ok := context.Get(req); ok {
			return request.WithUserAgent(ctx, req.Header.Get("User-Agent"))
		}
		return request.WithUserAgent(request.NewContext(), req.Header.Get("User-Agent"))
	}

	scope := mapping.Scope
	nameParam := ws.PathParameter("name", "name of the described resource").DataType("string")
	resourceParam := ws.PathParameter("resource", "the name of the resource").DataType("string")
	subresourceParam := ws.PathParameter("subresource", "the name of the subresource").DataType("string")

	// metrics describing non-namespaced objects (e.g. nodes)
	rootScopedParams := []*restful.Parameter{
		resourceParam,
		nameParam,
		subresourceParam,
	}
	rootScopedPath := "{resource}/{name}/{subresource}"

	// metrics describing namespaced objects (e.g. pods)
	namespaceParam := ws.PathParameter(scope.ArgumentName(), scope.ParamDescription()).DataType("string")
	namespacedParams := []*restful.Parameter{
		namespaceParam,
		resourceParam,
		nameParam,
		subresourceParam,
	}
	namespacedPath := scope.ParamName() + "/{" + scope.ArgumentName() + "}/{resource}/{name}/{subresource}"

	namespaceSpecificPath := scope.ParamName() + "/{" + scope.ArgumentName() + "}/metrics/{name}"
	namespaceSpecificParams := []*restful.Parameter{
		namespaceParam,
		nameParam,
	}

	mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
	allMediaTypes := append(mediaTypes, streamMediaTypes...)
	ws.Produces(allMediaTypes...)

	reqScope := handlers.RequestScope{
		ContextFunc:     ctxFn,
		Serializer:      a.group.Serializer,
		ParameterCodec:  a.group.ParameterCodec,
		Creater:         a.group.Creater,
		Convertor:       a.group.Convertor,
		Copier:          a.group.Copier,
		Typer:           a.group.Typer,
		UnsafeConvertor: a.group.UnsafeConvertor,

		// TODO: This seems wrong for cross-group subresources. It makes an assumption that a subresource and its parent are in the same group version. Revisit this.
		Resource:    a.group.GroupVersion.WithResource("*"),
		Subresource: "*",
		Kind:        fqKindToRegister,

		MetaGroupVersion: metav1.SchemeGroupVersion,
	}
	if a.group.MetaGroupVersion != nil {
		reqScope.MetaGroupVersion = *a.group.MetaGroupVersion
	}

	// we need one path for namespaced resources, one for non-namespaced resources
	doc := "list custom metrics describing an object or objects"
	reqScope.Namer = MetricsNaming{
		handlers.ContextBasedNaming{
			GetContext:         ctxFn,
			SelfLinker:         a.group.Linker,
			ClusterScoped:      true,
			SelfLinkPathPrefix: a.prefix + "/",
		},
	}

	rootScopedHandler := metrics.InstrumentRouteFunc("LIST", "custom-metrics", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))

	// install the root-scoped route
	rootScopedRoute := ws.GET(rootScopedPath).To(rootScopedHandler).
		Doc(doc).
		Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
		Operation("list"+kind).
		Produces(allMediaTypes...).
		Returns(http.StatusOK, "OK", versionedList).
		Writes(versionedList)
	if err := addObjectParams(ws, rootScopedRoute, versionedListOptions); err != nil {
		return err
	}
	addParams(rootScopedRoute, rootScopedParams)
	ws.Route(rootScopedRoute)

	// install the namespace-scoped route
	reqScope.Namer = MetricsNaming{
		handlers.ContextBasedNaming{
			GetContext:         ctxFn,
			SelfLinker:         a.group.Linker,
			ClusterScoped:      false,
			SelfLinkPathPrefix: gpath.Join(a.prefix, scope.ParamName()) + "/",
		},
	}
	namespacedHandler := metrics.InstrumentRouteFunc("LIST", "custom-metrics-namespaced", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))
	namespacedRoute := ws.GET(namespacedPath).To(namespacedHandler).
		Doc(doc).
		Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
		Operation("listNamespaced"+kind).
		Produces(allMediaTypes...).
		Returns(http.StatusOK, "OK", versionedList).
		Writes(versionedList)
	if err := addObjectParams(ws, namespacedRoute, versionedListOptions); err != nil {
		return err
	}
	addParams(namespacedRoute, namespacedParams)
	ws.Route(namespacedRoute)

	// install the special route for metrics describing namespaces (last b/c we modify the context func)
	reqScope.ContextFunc = ctxFn
	reqScope.Namer = MetricsNaming{
		handlers.ContextBasedNaming{
			GetContext:         ctxFn,
			SelfLinker:         a.group.Linker,
			ClusterScoped:      false,
			SelfLinkPathPrefix: gpath.Join(a.prefix, scope.ParamName()) + "/",
		},
	}
	namespaceSpecificHandler := metrics.InstrumentRouteFunc("LIST", "custom-metrics-for-namespace", restfulListResource(lister, nil, reqScope, false, a.minRequestTimeout))
	namespaceSpecificRoute := ws.GET(namespaceSpecificPath).To(namespaceSpecificHandler).
		Doc(doc).
		Param(ws.QueryParameter("pretty", "If 'true', then the output is pretty printed.")).
		Operation("read"+kind+"ForNamespace").
		Produces(allMediaTypes...).
		Returns(http.StatusOK, "OK", versionedList).
		Writes(versionedList)
	if err := addObjectParams(ws, namespaceSpecificRoute, versionedListOptions); err != nil {
		return err
	}
	addParams(namespaceSpecificRoute, namespaceSpecificParams)
	ws.Route(namespaceSpecificRoute)

	return nil
}

// This magic incantation returns *ptrToObject for an arbitrary pointer
func indirectArbitraryPointer(ptrToObject interface{}) interface{} {
	return reflect.Indirect(reflect.ValueOf(ptrToObject)).Interface()
}

// getResourceKind returns the external group version kind registered for the given storage object.
func (a *MetricsAPIInstaller) getResourceKind(storage rest.Storage) (schema.GroupVersionKind, error) {
	object := storage.New()
	fqKinds, _, err := a.group.Typer.ObjectKinds(object)
	if err != nil {
		return schema.GroupVersionKind{}, err
	}

	// a given go type can have multiple potential fully qualified kinds.  Find the one that corresponds with the group
	// we're trying to register here
	fqKindToRegister := schema.GroupVersionKind{}
	for _, fqKind := range fqKinds {
		if fqKind.Group == a.group.GroupVersion.Group {
			fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
			break
		}

		// TODO: keep rid of extensions api group dependency here
		// This keeps it doing what it was doing before, but it doesn't feel right.
		if fqKind.Group == "extensions" && fqKind.Kind == "ThirdPartyResourceData" {
			fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
		}
	}
	if fqKindToRegister.Empty() {
		return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, a.group.GroupVersion)
	}
	return fqKindToRegister, nil
}

// restMapping returns rest mapper for the resource provided by DynamicStorage.
func (a *MetricsAPIInstaller) restMapping() (*meta.RESTMapping, error) {
	// subresources must have parent resources, and follow the namespacing rules of their parent.
	// So get the storage of the resource (which is the parent resource in case of subresources)
	fqKindToRegister, err := a.getResourceKind(a.group.DynamicStorage)
	if err != nil {
		return nil, fmt.Errorf("unable to locate fully qualified kind for mapper resource for dynamic storage: %v", err)
	}
	return a.group.Mapper.RESTMapping(fqKindToRegister.GroupKind(), fqKindToRegister.Version)
}

func addParams(route *restful.RouteBuilder, params []*restful.Parameter) {
	for _, param := range params {
		route.Param(param)
	}
}

// addObjectParams converts a runtime.Object into a set of go-restful Param() definitions on the route.
// The object must be a pointer to a struct; only fields at the top level of the struct that are not
// themselves interfaces or structs are used; only fields with a json tag that is non empty (the standard
// Go JSON behavior for omitting a field) become query parameters. The name of the query parameter is
// the JSON field name. If a description struct tag is set on the field, that description is used on the
// query parameter. In essence, it converts a standard JSON top level object into a query param schema.
func addObjectParams(ws *restful.WebService, route *restful.RouteBuilder, obj interface{}) error {
	sv, err := conversion.EnforcePtr(obj)
	if err != nil {
		return err
	}
	st := sv.Type()
	switch st.Kind() {
	case reflect.Struct:
		for i := 0; i < st.NumField(); i++ {
			name := st.Field(i).Name
			sf, ok := st.FieldByName(name)
			if !ok {
				continue
			}
			switch sf.Type.Kind() {
			case reflect.Interface, reflect.Struct:
			case reflect.Ptr:
				// TODO: This is a hack to let metav1.Time through. This needs to be fixed in a more generic way eventually. bug #36191
				if (sf.Type.Elem().Kind() == reflect.Interface || sf.Type.Elem().Kind() == reflect.Struct) && strings.TrimPrefix(sf.Type.String(), "*") != "metav1.Time" {
					continue
				}
				fallthrough
			default:
				jsonTag := sf.Tag.Get("json")
				if len(jsonTag) == 0 {
					continue
				}
				jsonName := strings.SplitN(jsonTag, ",", 2)[0]
				if len(jsonName) == 0 {
					continue
				}

				var desc string
				if docable, ok := obj.(documentable); ok {
					desc = docable.SwaggerDoc()[jsonName]
				}
				route.Param(ws.QueryParameter(jsonName, desc).DataType(typeToJSON(sf.Type.String())))
			}
		}
	}
	return nil
}

// TODO: this is incomplete, expand as needed.
// Convert the name of a golang type to the name of a JSON type
func typeToJSON(typeName string) string {
	switch typeName {
	case "bool", "*bool":
		return "boolean"
	case "uint8", "*uint8", "int", "*int", "int32", "*int32", "int64", "*int64", "uint32", "*uint32", "uint64", "*uint64":
		return "integer"
	case "float64", "*float64", "float32", "*float32":
		return "number"
	case "metav1.Time", "*metav1.Time":
		return "string"
	case "byte", "*byte":
		return "string"
	case "v1.DeletionPropagation", "*v1.DeletionPropagation":
		return "string"

	// TODO: Fix these when go-restful supports a way to specify an array query param:
	// https://github.com/emicklei/go-restful/issues/225
	case "[]string", "[]*string":
		return "string"
	case "[]int32", "[]*int32":
		return "integer"

	default:
		return typeName
	}
}

// An interface to see if an object supports swagger documentation as a method
type documentable interface {
	SwaggerDoc() map[string]string
}

// MetricsNaming is similar to handlers.ContextBasedNaming, except that it handles
// polymorphism over subresources.
type MetricsNaming struct {
	handlers.ContextBasedNaming
}

// GenerateLink returns the appropriate path and query to locate an object by its canonical path.
func (n MetricsNaming) GenerateLink(req *http.Request, obj runtime.Object) (uri string, err error) {
	requestInfo, ok := request.RequestInfoFrom(n.GetContext(req))
	if !ok {
		return "", fmt.Errorf("missing requestInfo")
	}

	if requestInfo.Resource != "metrics" {
		n.SelfLinkPathSuffix += "/" + requestInfo.Subresource
	}

	// since this is not a pointer receiver, it's ok to modify it here
	// (since we copy around every method call)
	if n.ClusterScoped {
		n.SelfLinkPathPrefix += requestInfo.Resource + "/"
		return n.ContextBasedNaming.GenerateLink(req, obj)
	}

	return n.ContextBasedNaming.GenerateLink(req, obj)
}

func restfulListResource(r rest.Lister, rw rest.Watcher, scope handlers.RequestScope, forceWatch bool, minRequestTimeout time.Duration) restful.RouteFunction {
	return func(req *restful.Request, res *restful.Response) {
		handlers.ListResource(r, rw, scope, forceWatch, minRequestTimeout)(res.ResponseWriter, req.Request)
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package framework.interpreter;

import framework.commands.CommandFactory;
import framework.game.Game;
import framework.game.JSONFactory;

/**
 *
 * @author Marcos
 */
public abstract class Interpreter {
    Game g;
    public Interpreter(Game g) {
        this.g = g;
    }

    public String interpretar() {
        //<editor-fold defaultstate="collapsed" desc="Itera sobre todos os comandos e verifica se algum é igual ao digitado ou sugere o comando mais próximo">
        String comando = Game.getInputStream().getInput();
        String comand = comando.split(" ")[0];
        String closestCommand = "";
        int hashInput = comand.hashCode();
        int hashRead = 0;
        int closestHashRead = Integer.MAX_VALUE;
        String comandoEncontrado = "";
        for (String key : JSONFactory.getCommands().keySet()) {
            hashRead = key.hashCode();
            if (hashRead == hashInput) {
                //sai do loop
                closestHashRead = 0;
                comandoEncontrado = key;
                break;
            }
            //Procura o comando mais próximo ao digitado pelo usuário pelo hash do String digitado
            if (Math.min(closestHashRead, Math.abs(hashRead - hashInput)) != closestHashRead) {
                closestHashRead = Math.min(closestHashRead, Math.abs(hashRead - hashInput));
                closestCommand = key;
            }
        }
//</editor-fold>
        if (closestHashRead == 0) { //O comando achado é o comando digitado
            CommandFactory.getCommand(comandoEncontrado, comando).execute(comandoEncontrado, comando);
        } else { //Sugere o comando mais próximo
            Game.getPrinterStream().print("O comando digitado foi " + comand + " e não foi reconhecido. Você quis dizer " + closestCommand + "?");
        }
        return null;
    }
}


text:
using System;
using BenchmarkDotNet.Configs;

namespace BenchmarkDotNet.Attributes
{
    public class KeepBenchmarkFilesAttribute : Attribute, IConfigSource
    {
        public bool Value { get; }
        public IConfig Config { get; }

        public KeepBenchmarkFilesAttribute(bool value = true)
        {
            Value = value;
            Config = ManualConfig.CreateEmpty().KeepBenchmarkFiles(value);
        }
    }
}


text:
package kieker.analysis.architecture.recovery;

import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;

import kieker.analysis.architecture.recovery.events.CallEvent;
import kieker.analysis.architecture.recovery.events.OperationEvent;
import kieker.analysis.architecture.recovery.signature.AbstractSignatureProcessor;
import kieker.analysis.architecture.recovery.signature.NullSignatureProcessor;
import kieker.common.record.flow.IFlowRecord;
import kieker.common.record.flow.trace.TraceMetadata;
import kieker.common.record.flow.trace.operation.AfterOperationEvent;
import kieker.common.record.flow.trace.operation.AfterOperationFailedEvent;
import kieker.common.record.flow.trace.operation.BeforeOperationEvent;
import kieker.common.record.flow.trace.operation.CallOperationEvent;

import teetime.framework.AbstractConsumerStage;
import teetime.framework.OutputPort;

/**
 * Produce operation and operation call events based on flow records. This stage requires structurally intact traces.
 *
 * @author Reiner Jung
 * @since 1.15
 */
public class OperationAndCallGeneratorStage extends AbstractConsumerStage<IFlowRecord> {

	private final Map<Long, TraceData> traceDataMap = new ConcurrentHashMap<>();

	private final OutputPort<OperationEvent> operationOutputPort = this.createOutputPort(OperationEvent.class);
	private final OutputPort<CallEvent> callOutputPort = this.createOutputPort(CallEvent.class);
	private final boolean createEntryCall;

	private final AbstractSignatureProcessor processor;

	/**
	 * Create stage.
	 *
	 * @param createEntryCall
	 *            if true, create a call for the implied call from external
	 * @param processor
	 *            signature processor to be used to interpret component and operation signatures
	 */
	public OperationAndCallGeneratorStage(final boolean createEntryCall, final AbstractSignatureProcessor processor) {
		super();
		this.createEntryCall = createEntryCall;
		this.processor = processor;
	}

	/**
	 * Create stage.
	 *
	 * @param createEntryCall
	 *            if true, create a call for the implied call from external
	 */
	public OperationAndCallGeneratorStage(final boolean createEntryCall) {
		this(createEntryCall, new NullSignatureProcessor(false));
	}

	@Override
	protected void execute(final IFlowRecord element) {
		if (element instanceof TraceMetadata) {
			this.processTraceMetadata((TraceMetadata) element);
		} else if (element instanceof BeforeOperationEvent) {
			this.processBeforeOperationEvent((BeforeOperationEvent) element);
		} else if (element instanceof AfterOperationFailedEvent) {
			this.processAfterOperationFailedEvent((AfterOperationFailedEvent) element);
		} else if (element instanceof AfterOperationEvent) {
			this.processAfterOperationEvent((AfterOperationEvent) element);
		} else if (element instanceof CallOperationEvent) {
			this.logger.error("Received CallOperationEvent which cannot be handled by the {}. Sanitize the trace before processing it.",
					this.getClass().getSimpleName());
		}
	}

	private void processTraceMetadata(final TraceMetadata traceMetadata) {
		this.traceDataMap.put(traceMetadata.getTraceId(), new TraceData(traceMetadata, new Stack<OperationEvent>()));
	}

	private void processBeforeOperationEvent(final BeforeOperationEvent beforeOperationEvent) {
		final TraceData traceData = this.traceDataMap.get(beforeOperationEvent.getTraceId());

		this.processor.processSignatures(beforeOperationEvent.getClassSignature(),
				beforeOperationEvent.getOperationSignature());

		final OperationEvent newEvent = new OperationEvent(traceData.getMetadata().getHostname(),
				this.processor.getComponentSignature(),
				this.processor.getOperationSignature());
		if (!traceData.getOperationStack().empty()) {
			this.operationOutputPort.send(newEvent);
		} else {
			if (this.createEntryCall) {
				final OperationEvent triggerEvent = new OperationEvent("external", "<unknown>", "<unknown>");
				this.operationOutputPort.send(triggerEvent);
				this.operationOutputPort.send(newEvent);
				traceData.getOperationStack().push(triggerEvent);
				traceData.getStartTimeStack().push(Instant.ofEpochSecond(0, beforeOperationEvent.getTimestamp()));
			} else {
				this.operationOutputPort.send(newEvent);
			}
		}
		traceData.getOperationStack().push(newEvent);
		traceData.getStartTimeStack().push(Instant.ofEpochSecond(0, beforeOperationEvent.getTimestamp()));
	}

	private void processAfterOperationEvent(final AfterOperationEvent afterOperationEvent) {
		final TraceData traceData = this.traceDataMap.get(afterOperationEvent.getTraceId());
		final Stack<OperationEvent> stack = traceData.getOperationStack();
		if (!stack.isEmpty()) {
			final OperationEvent lastEvent = stack.pop();

			this.processor.processSignatures(afterOperationEvent.getClassSignature(), afterOperationEvent.getOperationSignature());

			if (!lastEvent.getComponentSignature().equals(this.processor.getComponentSignature())
					|| !lastEvent.getOperationSignature().equals(this.processor.getOperationSignature())) {
				this.logger.error("Broken trace, expected {}:{}, but got {}:{}",
						lastEvent.getComponentSignature(),
						lastEvent.getOperationSignature(),
						this.processor.getComponentSignature(),
						this.processor.getOperationSignature());
			}
			if (stack.isEmpty()) { // trace is complete
				this.traceDataMap.remove(afterOperationEvent.getTraceId());
			} else {
				final OperationEvent previousEvent = stack.peek();
				final Instant end = Instant.ofEpochSecond(0, afterOperationEvent.getTimestamp());
				this.callOutputPort.send(new CallEvent(previousEvent, lastEvent, Duration.between(traceData.getStartTimeStack().pop(), end)));
			}
		} else {
			this.logger.error("Trace stack error. AfterOperationEvent without a previous BeforeOperationEvent, found {}:{}",
					afterOperationEvent.getClassSignature(), afterOperationEvent.getOperationSignature());
		}
	}

	/**
	 * A failed event indicates the end of a trace. Thus, the stack becomes invalid.
	 *
	 * @param afterOperationFailedEvent
	 *            failed event to be processed
	 */
	private void processAfterOperationFailedEvent(final AfterOperationFailedEvent afterOperationFailedEvent) {
		final TraceData traceData = this.traceDataMap.get(afterOperationFailedEvent.getTraceId());
		final Stack<OperationEvent> stack = traceData.getOperationStack();
		if (!stack.isEmpty()) {
			final OperationEvent lastEvent = stack.pop();
			if (!stack.isEmpty()) {
				final OperationEvent previousEvent = stack.peek();
				final Instant end = Instant.ofEpochSecond(0, afterOperationFailedEvent.getTimestamp());
				this.callOutputPort.send(new CallEvent(previousEvent, lastEvent, Duration.between(traceData.getStartTimeStack().pop(), end)));
			}
		}
		this.traceDataMap.remove(afterOperationFailedEvent.getTraceId());
	}

	public OutputPort<CallEvent> getCallOutputPort() {
		return this.callOutputPort;
	}

	public OutputPort<OperationEvent> getOperationOutputPort() {
		return this.operationOutputPort;
	}

	/**
	 *
	 * @author Reiner Jung
	 * @since 1.15
	 */
	private final class TraceData {

		private final TraceMetadata metadata;
		private final Stack<OperationEvent> operationStack;
		private final Stack<Instant> startTimeStack;

		private TraceData(final TraceMetadata metadata, final Stack<OperationEvent> operationStack) {
			this.metadata = metadata;
			this.operationStack = operationStack;
			this.startTimeStack = new Stack<>();
		}

		public TraceMetadata getMetadata() {
			return this.metadata;
		}

		public Stack<OperationEvent> getOperationStack() {
			return this.operationStack;
		}

		public Stack<Instant> getStartTimeStack() {
			return this.startTimeStack;
		}

	}
}


text:
lightweight document generator for Asp.net WebApi.
view [sample code](https://github.com/BehroozBahrameh/Documenter/tree/master/src/Sample) generated [Documenter markdown](https://github.com/BehroozBahrameh/Documenter/wiki/Sample-code-generated-markdown)

By default Documenter generate markdown documentation  but you can develop your owned appender.

```csharp
	var generator = Rocket.Web.Documenter.Core.DocumentHelper();
	generator.Generate(GlobalConfiguration.Configuration);

```

MarkdownAppneder generate text file in root of project `in api_document_{datetime}.txt` format

## Custom Appender
To develop your owned appender, you must implement **IDocumenterAppender** interface.

```csharp
    public class MyDocumenterAppender : IDocumenterAppender
    {
		void Create(IEnumerable<ApiDocument> models){
			...
		}
    }
```

Create method get collection of ApiDocument object, each ApiDocument object is a your project api-controller action,

```csharp
	public class ApiDocument
    {
        public string Url { get; set; }	//Url of action
        public string Method { get; set; } //GET, POST or ...
        public IEnumerable<string[]> UrlProperties { get; set; } //Query strings
        public IEnumerable<string[]> RequestProperties { get; set; } //Body properties
        public string RequestBodyJson { get; set; } //Sample JSON of body object
        public IEnumerable<string[]> ResponseProperties { get; set; } //Response properties
        public string ResponseJson { get; set; } //Sample JSON of response object
    }
```

##Install via Nuget

 `PM> Install-Package Rocket.Web.Documenter.Core`


text:
<?php
require_once __DIR__ . '/../TestHelper.php';

class Braintree_OAuthTest extends PHPUnit_Framework_TestCase
{
    protected $gateway;

    public function setUp()
    {
        $this->gateway = new Braintree_Gateway(array(
            'clientId' => 'client_id$development$integration_client_id',
            'clientSecret' => 'client_secret$development$integration_client_secret'
        ));
    }

    public function testMapInvalidGrantCodeToOldError()
    {
        $result = $this->_buildResult(array(
            'code' => '93801',
            'message' => 'Invalid grant: code not found'
        ));

        $this->gateway->oauth()->_mapError($result);

        $this->assertEquals($result->error, 'invalid_grant');
        $this->assertEquals($result->errorDescription, 'code not found');
    }

    public function testMapInvalidCredentialsCodeToOldError()
    {
        $result = $this->_buildResult(array(
            'code' => '93802',
            'message' => 'Invalid credentials: wrong client id or secret'
        ));

        $this->gateway->oauth()->_mapError($result);

        $this->assertEquals($result->error, 'invalid_credentials');
        $this->assertEquals($result->errorDescription, 'wrong client id or secret');
    }

    public function testMapInvalidScopeCodeToOldError()
    {
        $result = $this->_buildResult(array(
            'code' => '93803',
            'message' => 'Invalid scope: scope is invalid'
        ));

        $this->gateway->oauth()->_mapError($result);

        $this->assertEquals($result->error, 'invalid_scope');
        $this->assertEquals($result->errorDescription, 'scope is invalid');
    }

    protected function _buildResult($error)
    {
        return new Braintree_Result_Error(array(
            'errors' => array(
                'errors' => array(),
                'credentials' => array(
                    'errors' => array($error)
                )
            )
        ));
    }
}


text:
unless defined?(Motion::Project::Config)
  raise "This file must be required within a RubyMotion project Rakefile."
end

require "ProMotion/version"

Motion::Project::App.setup do |app|

  # Dir.glob(File.join(File.dirname(__FILE__), "ProMotion/**/*.rb")).each do |file|
  #   app.files.unshift(file)
  # end
  app.files = Dir.glob(File.join(File.dirname(__FILE__), 'ProMotion/**/*.rb')) | app.files
  app.files = Dir.glob(File.join(File.dirname(__FILE__), 'ProMotion/helpers/**/*.rb')) | app.files
  app.files = Dir.glob(File.join(File.dirname(__FILE__), 'ProMotion/modules/**/*.rb')) | app.files
  app.files = Dir.glob(File.join(File.dirname(__FILE__), 'ProMotion/ext/**/*.rb')) | app.files

end


text:
module Rspec
  module Visual
    VERSION = "0.0.2"
  end
end


text:
{% extends "spirit/_base.html" %}

{% load i18n %}

{% block title %}{% trans "Mods" %}{% endblock %}

{% block content %}

    {% include "spirit/admin/_nav_menu.html" with active="users" %}

{% trans "Mods" %}

    {% include "spirit/user/admin/_list.html" with active_tab="mods" %}

{% endblock %}


text:
<?php

require_once __DIR__.'/vendor/autoload.php';

$app = require __DIR__.'/web/config/kernel.php';
require __DIR__.'/web/config/kernel-oauth.php';

require __DIR__.'/web/src/controllers/controllers.php';

define('VERSION', 'V2/');

$app->run();


text:
@interface SJDYPlaybackListViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SJDYDataProvider *dataProvider;
@property (nonatomic, strong) NSMutableArray<SJVideoModel *> *list;
@property (nonatomic, strong) id<SJDYDemoPlayer> curPlayer;

@property (nonatomic, strong, nullable) id<MCSPrefetchTask> prePrefetchTask;
@property (nonatomic, strong, nullable) id<MCSPrefetchTask> nextPrefetchTask;
@end

@implementation SJDYPlaybackListViewController
- (BOOL)shouldAutorotate {
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self _setupViews];
    [self _setupMediaCacheServer];
    [self _setupTableView];
}

- (void)dealloc {
    [_prePrefetchTask cancel];
    [_nextPrefetchTask cancel];
}

// 当用户暂停时, 将不会调用播放
- (void)playIfNeeded {
    if ( !_curPlayer.isUserPaused ) [_curPlayer play];
}

// 暂停播放. 如果该方法调用之前用户已暂停播放了, 当执行此操作时不会影响用户暂停态
- (void)pause {
    if ( !_curPlayer.isPaused ) [_curPlayer pause];
}

#pragma mark -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [SJDYTableViewCell cellWithTableView:tableView indexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(SJDYTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSURL *playbackURL = [SJMediaCacheServer.shared playbackURLWithURL:_list[indexPath.row].URL];
    [cell.player configureWithURL:playbackURL];
    __weak typeof(self) _self = self;
    cell.player.allowsPlayback = ^BOOL(id<SJDYDemoPlayer>  _Nonnull player) {
        __strong typeof(_self) self = _self;
        if ( self == nil ) return NO;
        return [self.delegate canPerformPlayForListViewController:self];
    };
    if ( _curPlayer == nil ) {
        _curPlayer = cell.player;
    }
    [_prePrefetchTask cancel];
    [_nextPrefetchTask cancel];
    _prePrefetchTask = [self _prefetchTaskWithIndex:indexPath.row - 1];
    _nextPrefetchTask = [self _prefetchTaskWithIndex:indexPath.row + 1];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.view.bounds.size.height;
}

- (BOOL)prefersHomeIndicatorAutoHidden {
    return YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self _checkVisibleCells];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ( !decelerate ) [self _checkVisibleCells];
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [self _checkVisibleCells];
}

#pragma mark - mark

- (void)_checkVisibleCells {
    SJDYTableViewCell *target = nil;
    CGRect max = CGRectZero;
    for ( SJDYTableViewCell *cell in _tableView.visibleCells ) {
        CGRect intersection = [cell intersectionWithView:_tableView insets:UIEdgeInsetsZero];
        if ( intersection.size.height > max.size.height ) {
            target = cell;
            max = intersection;
        }
    }

    if ( target == nil )
        return;

    id<SJDYDemoPlayer> cur = target.player;
    if ( cur != _curPlayer ) {
        [_curPlayer pause];
    }

    _curPlayer = cur;

    if ( !_curPlayer.isUserPaused ) {
        [_curPlayer play];
    }
}

#pragma mark -

- (void)_setupViews {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = UIColor.blackColor;
    self.view.clipsToBounds = YES;
    _list = NSMutableArray.alloc.init;
    _dataProvider = SJDYDataProvider.alloc.init;
}

- (void)_setupTableView {
    _tableView = [UITableView.alloc initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = UIColor.blackColor;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.pagingEnabled = YES;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];

    [SJDYTableViewCell registerWithTableView:_tableView];

    // 请求列表数据
    //      模拟请求网络数据
    __weak typeof(self) _self = self;
    [_tableView sj_setupRefreshingWithPageSize:20 beginPageNum:1 refreshingBlock:^(__kindof UIScrollView * _Nonnull scrollView, NSInteger requestPageNum) {
        __strong typeof(_self) self = _self;
        if ( !self ) return;

        // 模拟延迟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.dataProvider playbackListWithPageNum:self.tableView.sj_pageNum pageSize:self.tableView.sj_pageSize completionHandler:^(NSArray<SJVideoModel *> * _Nullable list, NSError * _Nullable error) {
                __strong typeof(_self) self = _self;
                if ( !self ) return;
                if ( error ) {
                    // error
                    NSLog(@"%@", error);
                    return;
                }
                // 如果是请求首页的数据, 即下拉
                if ( self.tableView.sj_pageNum == self.tableView.sj_beginPageNum ) {
                    // 下拉刷新时, 清理播放数据
                    [self.curPlayer stop];
                    self.curPlayer = nil;
                    [self.list removeAllObjects];
                }

                // 添加到播放列表中, 刷新列表
                [self.list addObjectsFromArray:list];
                [self.tableView reloadData];
                [self.tableView sj_endRefreshingWithItemCount:list.count];
                [self _checkVisibleCells];
            }];
        });
    }];

    [_tableView sj_exeHeaderRefreshingAnimated:NO]; // 执行头部刷新
}

// 配置边播边缓存模块
- (void)_setupMediaCacheServer {
    // 开启控制台log
    SJMediaCacheServer.shared.enabledConsoleLog = YES;
    SJMediaCacheServer.shared.resolveAssetIdentifier = ^NSString * _Nonnull(NSURL * _Nonnull URL) {
        // 由于demo中同一个视频的URL后面的参数不一样, 为保证引用相同的缓存文件, 这里删除了URL后面的所有参数
        // 例如:
        //      - https://dh2.v.netease.com/2017/cg/fxtpty.mp4?id=0&key=value
        //      - https://dh2.v.netease.com/2017/cg/fxtpty.mp4?id=1
        //      这两个URL后面的参数不同, 但它们代表了同一个视频, 为保证引用相同的缓存文件, 这里需删除后面的所有参数, 保证返回的字符串一致
        return [URL.absoluteString stringByDeletingPathExtension];
    };
}

#pragma mark -

// 预加载指定位置的某个资源`1M`的内容
- (nullable id<MCSPrefetchTask>)_prefetchTaskWithIndex:(NSInteger)index {
    if ( index < 0 || index >= _list.count )
        return nil;
    return [SJMediaCacheServer.shared prefetchWithURL:_list[index].URL preloadSize:1 * 1024 * 1024];
}
@end


text:
from django.contrib import admin
from .models import Artist
from django.conf import settings
from bs4 import BeautifulSoup
from django.utils.translation import ugettext_lazy as _

class ArtistAdmin(admin.ModelAdmin):
    model = Artist
    list_display = ['first_name', 'last_name', 'id_number', 'created_date', 'gender', 'email']
    list_filter = ['created_date', 'gender']
    search_fields = ['first_name', 'last_name', 'id_number', 'email', 'payment']
admin.site.register(Artist, ArtistAdmin)


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/appBarLayoutBinding"
        layout="@layout/view_centered_appbar_binding" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/inAppPurchasesContentContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/inAppPurchasesRecycler"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                app:layout_constraintBottom_toTopOf="@id/inAppPurchasesConsumeAllAction"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/inAppPurchasesConsumeAllAction"
                style="@style/Widget.AppTheme.Button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="16dp"
                android:text="@string/debug_purchase_consume_all_action"
                android:theme="@style/ThemeOverlay.Violet"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@id/inAppPurchasesRecycler" />
        </androidx.constraintlayout.widget.ConstraintLayout>

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/inAppPurchaseEmpty"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/debug_purchase_empty"
            android:textAppearance="?textAppearanceBody1" />

        <include
            android:id="@+id/inAppPurchaseError"
            layout="@layout/error_no_connection_with_button_binding"
            android:visibility="gone" />

        <include
            android:id="@+id/inAppPurchaseProgressBar"
            layout="@layout/progress_bar_on_empty_screen"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </FrameLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
using Ploeh.AutoFixture.Xunit;

namespace FusionMVVM.Tests
{
    public class CustomInlineAutoDataAttribute : InlineAutoDataAttribute
    {
        public CustomInlineAutoDataAttribute(params object[] values)
            : base(new CustomAutoDataAttribute(), values)
        {
        }
    }
}


text:
package gov.nih.nci.cagrid.workflow.test.system.steps;

import java.io.File;
import java.io.FileOutputStream;
import java.rmi.RemoteException;

import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;

import workflowmanagementfactoryservice.WorkflowOutputType;
import workflowmanagementfactoryservice.WorkflowPortType;
import workflowmanagementfactoryservice.WorkflowStatusType;

import gov.nih.nci.cagrid.testing.system.haste.Step;
import gov.nih.nci.cagrid.workflow.factory.client.TavernaWorkflowServiceClient;

public class CheckTavernaWorkflowServiceStep extends Step {

	private final EndpointReferenceType twsEPR;
	private static final String SCUFL_FILE = "resources/input/input.t2flow";
	//private static final String OUTPUT_FILE = "resources/output/output.xml";
	private static final String OUTPUT_FILE = System.getProperty("java.io.tmpdir")
		+ System.getProperty("file.separator") + "output.xml";
	private static final WorkflowPortType[] INPUTS = {
		new WorkflowPortType("fish","TavernaWorkflowService"),
		new WorkflowPortType("soup", " Test Successful")};

	public CheckTavernaWorkflowServiceStep(EndpointReferenceType twsEPR) {
		this.twsEPR = twsEPR;
	}

	@Override
	public void runStep() throws RemoteException {
		assertNotNull("A non-null EPR must be passed in.", this.twsEPR);

		// Create a resource with the givne Input Scufl file.
		System.out.println("1. Creating A Resource with the given Scufl file.\n");
		File scuflDoc = new File(SCUFL_FILE);
		System.out.println(" >> SCUFL_FILE path = " + scuflDoc.getAbsolutePath());
		System.out.println(" >> ADDRESS = " + twsEPR.getAddress().toString());

		EndpointReferenceType serviceEPR;
		try {
			serviceEPR = TavernaWorkflowServiceClient.setupWorkflow(
					twsEPR.getAddress().toString(), scuflDoc.getAbsolutePath(), "TEST", null);
			assertNotNull("ERROR : The resource EPR is null.", serviceEPR);

			// Start the workflow with the input parameters.
			System.out.println("\n2. Starting the workflow.\n");
			WorkflowStatusType status = TavernaWorkflowServiceClient.startWorkflow (INPUTS, serviceEPR);

			assertTrue("Submitted workflow was not started.",status.equals(WorkflowStatusType.Active)
					|| status.equals(WorkflowStatusType.Pending)
					|| status.equals(WorkflowStatusType.Done));
			System.out.println(" >> Workflow status is :" + status.getValue() + "\n");

			// Check the status of the Workflow..
			System.out.println("3. Checking the status of the workflow.\n");
			status = TavernaWorkflowServiceClient.getStatus(serviceEPR);
			System.out.println(" >> Workflow status is :" + status.getValue() + "\n");

			// Subscribing to the resource property..
			System.out.println("4. Waiting 30 mins for the workflow to complete.\n");
			//TavernaWorkflowServiceClient.subscribeRP(serviceEPR, 60);
			for(int i=0; (i<180 && !status.equals(WorkflowStatusType.Done)); i++)
			{
				Thread.sleep(10000);
				status = TavernaWorkflowServiceClient.getStatus(serviceEPR);
			}

			assertTrue("Submitted workflow was not Completed.", status.equals(WorkflowStatusType.Done));
			System.out.println(" >> Workflow status is :" + status.getValue() + "\n");

			//Get the output of the Workflow..
			System.out.println("5. Getting the output of the Workflow.\n");
			WorkflowOutputType output = TavernaWorkflowServiceClient.getOutput(serviceEPR);

			FileOutputStream out = new FileOutputStream(new File(OUTPUT_FILE));
			out.write((output.getOutput(0).getValue()).getBytes());
			out.flush();
			out.close();
			System.out.println(" >> Output File located at:" + (new File(OUTPUT_FILE)).getAbsolutePath() + "\n");
			System.out.println("\n\n >> Output : " + output.getOutput(0).getValue() + "\n");

			//System.out.println("result: " + output.getOutputFile()[0]);
			assertNotNull("The output of the workflow is null.", output);
			assertNotNull("The output of the workflow is null.",output.getOutput(0).getValue());

		} catch (MalformedURIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


text:
var wdCapture = require('../main');

var port = 8000;
var server = setupPageServer();
server.listen(port);

createBrowser(onBrowserReady);

function onBrowserReady (err, browser) {
    wdCapture(browser, 'http://localhost:' + port, onRead);

    function onRead (err, res) {
        if (err) {
            console.error('ERR', err);
        }

        if (res) {
            console.log('result', res);
        }

        browser.takeScreenshot(onScreenshotComplete);

        function onScreenshotComplete (err, res) {
            browser.quit();

            if (err) {
                console.error(err);
            }
            else {
                require('fs').writeFile(__dirname + '/ex-1/screenshot.png', res, 'base64', function (err) {
                    if(err) { console.error(err); }
                });
            }

            server.close();
        }
    }
}

function createBrowser (callback) {
    var wd = require('wd');
    var browser = wd.remote({
        hostname: '127.0.0.1',
        port: 4444,
    });

    var caps = {
        browserName: 'chrome'
    };

    browser.init(caps, onInit);

    function onInit () {
        browser.setWindowSize(540, 500, onSizeReady);
    }

    function onSizeReady () {
        var timeout = 5000;
        browser.setAsyncScriptTimeout(timeout, onTimeoutReady);
    }

    function onTimeoutReady () {
        callback(null, browser);
    }
}

function setupPageServer () {
    var http = require('http');
    var fs = require('fs');

    return http.createServer(function (req, res) {
        fs.createReadStream(__dirname + '/ex-1/index.html').pipe(res);
    });
}


text:
module Dialers
  class RequestOptions
    attr_accessor :url, :http_method, :query_params, :payload, :headers
  end
end


text:
module ODRL::Rights::Constraint
     class Count < Base
       def eval(party = nil, context = nil)
         return false if !eval_constraints(party, context)
	 $session[@id]=0 if $session[@id].nil?
	 $session[@id] += 1
	 $session[@id] <= @xml.content.to_i
       end
     end
end


text:
define(function () {
var jsonrpc = {};
jsonrpc.DelayedTask = function (fn, scope, args) {
	this._fn = fn || function () {};
	this._scope = scope || undefined;
	this._args = args || [];
	this._id = null;
};

jsonrpc.DelayedTask.prototype = {
	delay: function (delay, fn, scope, args) {
		var me = this;

		this._fn = fn || this._fn;
		this._scope = scope || this._scope;
		this._args = args || this._args;
		this.cancel();
		this._id = window.setInterval(function () {
			window.clearInterval(me._id);
			me._id = null;
			me._fn.apply(me._scope, me._args);
		}, delay);
	},

	cancel: function () {
		if (this._id) {
			window.clearInterval(this._id);
			this._id = null;
		}
	}
};
jsonrpc.CallStack = function (enterFn, enterScope, exitFn, exitScope) {
	this._counter = 0;
	this._enterFn = enterFn;
	this._exitFn = exitFn;
	this._enterScope = enterScope;
	this._exitScope = exitScope;
};

jsonrpc.CallStack.prototype = {
	enter: function () {
		this._counter = (this._counter < 0 ? 1 : this._counter + 1);
		if (this._counter === 1) {
			this._enterFn.apply(this._enterScope, arguments);
		}
	},

	exit: function (fn) {
		this._counter -= 1;
		if (this._counter === 0) {
			this._exitFn.apply(this._exitScope, arguments);
		}
	}
};

jsonrpc.Observable = function () {
	this._listeners = [];
};

jsonrpc.Observable.prototype = {
	bind: function (fn, scope) {
		var token = { fn: fn, scope: scope || this };
		this._listeners.push(token);
		return token;
	},

	unbind: function (token) {
		var idx = this._listeners.indexOf(token);
		if (idx !== -1) {
			this._listeners.splice(idx, 1);
		}
	},

	trigger: function () {
		var i;
		for (i = 0; i < this._listeners.length; i += 1) {
			this._listeners[i].fn.apply(this._listeners[i].scope, arguments);
		}
	}
};
jsonrpc.JsonRpc = function (url) {
	this._url = url;
	this.loading = new jsonrpc.Observable();
	this.loaded = new jsonrpc.Observable();
	this.unhandledFailure = new jsonrpc.Observable();
	this._loadingState = new jsonrpc.CallStack(this.loading.trigger, this.loading, this.loaded.trigger, this.loaded);
	this._requests = [];
	this._batchingMilliseconds = 10;
	this._delayedTask = new jsonrpc.DelayedTask();
};

jsonrpc.JsonRpc.prototype = {
	setBatchingMilliseconds: function (value) {
		this._batchingMilliseconds = value;
	},

	call: function () {
		var args = this._getParams.apply(this, arguments);

		this._loadingState.enter();
		this._requests.push(args);

		if (this._batchingMilliseconds) {
			this._delayedTask.delay(this._batchingMilliseconds, this._sendRequests, this);
		} else {
			this._sendRequests();
		}
	},

	_sendRequests: function () {
		var me = this,
			requests = this._requests,
			data = [],
			i;

		this._requests = [];

		for (i = 0; i < requests.length; i += 1) {
			requests[i].request.id = i;
			data.push(requests[i].request);
		}

		if (data.length === 1) {
			data = data[0];
		}

		me._doJsonPost(me._url, data, function (htmlSuccess, htmlResponse) {
			var responses;
			if (htmlSuccess) {
				responses = (me._isArray(htmlResponse) ? htmlResponse : [htmlResponse]);
			} else {
				responses = [];
				for (i = 0; i < requests.length; i += 1) {
					responses[i] = { id: i, error: { message: htmlResponse } };
				}
			}
			me._handleResponses(requests, responses);
		});
	},

	_handleResponses: function (requests, responses) {
		var i, response, request;
		for (i = 0; i < responses.length; i += 1) {
			response = responses[i];
			request = requests[response.id];
			this._handleResponse(request, response);
		}
	},

	_handleResponse: function (request, response) {
		var success = !response.error,
			ret = (success ? response.result : response.error.message);

		this._loadingState.exit();

		if (success) {
			request.success.call(request.scope, ret);
		} else {
			request.failure.call(request.scope, ret);
		}
		request.callback.call(request.scope, success, ret);
	},

	_getParams: function () {
		var me = this,
			args = Array.prototype.slice.call(arguments),
			ret = {
				request: {
					jsonrpc: '2.0',
					method: args.shift()
				}
			};

		ret.request.params = [];
		while (args.length > 1 && !this._isFunction(args[0])) {
			ret.request.params.push(args.shift());
		}

		if (this._isFunction(args[0])) {
			ret.success = args[0];
			ret.scope = args[1];
		} else {
			ret.success = args[0].success;
			ret.failure = args[0].failure;
			ret.callback = args[0].callback;
			ret.scope = args[0].scope;
		}
		ret.success = ret.success || function () { return; };
		ret.failure = ret.failure || function () { me.unhandledFailure.trigger.apply(me.unhandledFailure, arguments); };
		ret.callback = ret.callback || function () { return; };

		return ret;
	},

	_isArray: function (v) {
		return Object.prototype.toString.apply(v) === '[object Array]';
	},

	_isFunction: function (v) {
		return Object.prototype.toString.apply(v) === '[object Function]';
	},

	_doJsonPost: function (url, data, callback) {
		var xhr = new XMLHttpRequest();
		xhr.open("POST", url, true);
		xhr.setRequestHeader('Content-Type', 'application/json');
		xhr.onreadystatechange = function () {
			if (xhr.readyState !== 4) {
				return;
			}

			var contentType = xhr.getResponseHeader('Content-Type');

			if (xhr.status !== 200) {
				callback(false, 'Expected HTTP response "200 OK", found "' + xhr.status + ' ' + xhr.statusText + '"');
			} else if (contentType.indexOf('application/json') !== 0) {
				callback(false, 'Expected JSON encoded response, found "' + contentType + '"');
			} else {
				callback(true, JSON.parse(this.responseText));
			}
		};
		xhr.send(JSON.stringify(data));
	}
};
return jsonrpc.JsonRpc;
});