text:
class NotificationServices::SlackService < NotificationService
  CHANNEL_NAME_REGEXP = /^#[a-z\d_-]+$/
  LABEL = "slack"
  FIELDS += [
    [:service_url, {
      placeholder: 'Slack Hook URL (https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXX)',
      label:       'Hook URL'
    }],
    [:room_id, {
      placeholder: '#general',
      label:       'Notification channel',
      hint:        'If empty Errbit will use the default channel for the webook'
    }]
  ]

  # Make room_id optional in case users want to use the default channel
  # setup on Slack when creating the webhook
  def check_params
    if service_url.blank?
      errors.add :service_url, "You must specify your Slack Hook url"
    end

    if room_id.present? && !CHANNEL_NAME_REGEXP.match(room_id)
      errors.add :room_id, "Slack channel name must be lowercase, with no space, special character, or periods."
    end
  end

  def message_for_slack(problem)
    "[#{problem.app.name}][#{problem.environment}][#{problem.where}]: #{problem.error_class} #{problem.url}"
  end

  def post_payload(problem)
    {
      username:    "Errbit",
      icon_url:    "https://raw.githubusercontent.com/errbit/errbit/master/docs/notifications/slack/errbit.png",
      channel:     room_id,
      attachments: [
        {
          fallback:   message_for_slack(problem),
          title:      problem.message.to_s.truncate(100),
          title_link: problem.url,
          text:       problem.where,
          color:      "#D00000",
          mrkdwn_in:  ["fields"],
          fields:     post_payload_fields(problem)
        }
      ]
    }.compact.to_json # compact to remove empty channel in case it wasn't selected by user
  end

  def create_notification(problem)
    HTTParty.post(
      service_url,
      body:    post_payload(problem),
      headers: {
        'Content-Type' => 'application/json'
      }
    )
  end

  def configured?
    service_url.present?
  end

private

  def post_payload_fields(problem)
    [
      { title: "Application", value: problem.app.name, short: true },
      { title: "Environment", value: problem.environment, short: true },
      { title: "Times Occurred", value: problem.notices_count.try(:to_s),
        short: true },
      { title: "First Noticed", value: problem.first_notice_at.try(:to_s, :db),
        short: true },
      { title: "Backtrace", value: backtrace_lines(problem), short: false }
    ]
  end

  def backtrace_line(line)
    path = line.decorated_path.gsub(%r{</?strong>}, '')
    "#{path}#{line.file_name}:#{line.number} → #{line.method}\n"
  end

  def backtrace_lines(problem)
    notice = NoticeDecorator.new problem.notices.last
    return unless notice
    backtrace = notice.backtrace
    return unless backtrace

    output = ''
    backtrace.lines[0..4].each { |line| output << backtrace_line(line) }
    "```#{output}```"
  end
end


text:
FROM python:2.7.9-slim

RUN pip install coverage pytest nose mock

redpajama_set_name: RedPajamaGithub


text:
import re
import h5py
import contextlib
import os
import errno
import re
from time import sleep
import logging
import numpy as np

from . import fs
from . import localfs
from ..utils import instance

logger = logging.getLogger(__name__)

class FileSystemException(fs.FileSystemException):
    """
    Base class for generic HDF5 file system exceptions.
    """

    pass

class LockedError(FileSystemException):
    """
    Device has been locked by someone else.
    """

try:
    unicode
except NameError:
    unicode = str

# Fixed-length dtype's
flen_unicode_dtype = unicode
flen_bytes_dtype = bytes
flen_opaque_dtype = np.void

# Variable-length dtype's
vlen_unicode_dtype = h5py.special_dtype(vlen=unicode)
vlen_bytes_dtype = h5py.special_dtype(vlen=bytes)
vlen_opaque_dtype = h5py.special_dtype(vlen=np.void)

def prepare_h5string(s, raiseExtended=True, useOpaqueDataType=False):
    """
    Convert to Variable-length string (array or scalar).
    Uses UTF-8 encoding when possible.

    Args:
        s: string or array of strings
           string types: unicode, bytes, fixed-length numpy
        raiseExtended(bool): raise decoding error
        useOpaqueDataType(bool): save as opaque instead of
                                 bytes on decoding error
    Returns:
        np.ndarray: dtype is vlen_bytes_dtype, vlen_unicode_dtype
                    or flen_opaque_dtype
    Raises:
        UnicodeDecodeError: extended ASCII encoding
    """
    try:
        # Attempt decoding (not done with vlen_unicode_dtype)
        np.array(s, dtype=flen_unicode_dtype)
    except UnicodeDecodeError:
        # Reason: at least one byte-string with non-ASCII character
        #         (e.g. Latin-1 encoding)
        if raiseExtended:
            raise
        if useOpaqueDataType:
            try:
                np.array(s, dtype=flen_bytes_dtype)
            except UnicodeEncodeError:
                # Reason: at least one UTF-8 string with non-ASCII character
                # Here because: mix of unicode and non-ASCII byte strings
                s = list(map(instance.asbytes, s))
            # vlen_opaque_dtype: currenly not supported by h5py
            return np.array(s, dtype=flen_opaque_dtype)
        else:
            return np.array(s, dtype=vlen_bytes_dtype)
    else:
        return np.array(s, dtype=vlen_unicode_dtype)

def prepare_h5data(data, **kwargs):
    if instance.isstring(data):
        return prepare_h5string(data, **kwargs)
    elif instance.isstringarray(data):
        return prepare_h5string(data, **kwargs)
    else:
        return data

def is_link(fileobj, path):
    """Check whether node is h5py.SoftLink or h5py.ExternalLink

    Args:
        fileobj(File)
        path(str)
    Returns:
        bool
    """
    try:
        lnk = fileobj.get(path, default=None, getlink=True)
    except (KeyError, RuntimeError):
        return False
    else:
        return isinstance(lnk, (h5py.SoftLink, h5py.ExternalLink))

def is_internal_link(fileobj, path):
    """Check whether node is h5py.SoftLink or h5py.ExternalLink

    Args:
        fileobj(File)
        path(str)
    Returns:
        bool
    """
    try:
        lnk = fileobj.get(path, default=None, getlink=True)
    except (KeyError, RuntimeError):
        return False
    else:
        return isinstance(lnk, h5py.SoftLink)

def is_external_link(fileobj, path):
    """Check whether node is h5py.SoftLink or h5py.ExternalLink

    Args:
        fileobj(File)
        path(str)
    Returns:
        bool
    """
    try:
        lnk = fileobj.get(path, default=None, getlink=True)
    except (KeyError, RuntimeError):
        return False
    else:
        return isinstance(lnk, h5py.ExternalLink)

def dereference_link(fileobj, path):
    """Dereference h5py.SoftLink or h5py.ExternalLink
    Args:
        fileobj(File)
        path(str)
    Returns:
        device(str)
        path(str)
    """
    try:
        lnk = fileobj.get(path, default=None, getlink=True)
    except (KeyError, RuntimeError):
        return None, None
    else:
        if isinstance(lnk, h5py.SoftLink):
            # device = fileobj[path].file.filename
            device = fileobj.filename
            dest = lnk.path  # this can be relative to "path"
        elif isinstance(lnk, h5py.ExternalLink):
            device = lnk.filename
            dest = lnk.path
        else:
            device, dest = None, None
        return device, dest

def is_reference(fileobj, path):
    """Check whether node is h5py.Reference

    Args:
        fileobj(File)
        path(str)
    Returns:
        bool
    """
    try:
        lnk = fileobj.get(path, default=None)
    except (KeyError, RuntimeError):
        return False
    else:
        try:
            return h5py.check_dtype(ref=lnk.dtype) == h5py.Reference and lnk.ndim == 0
        except AttributeError:
            return False

def dereference(fileobj, path):
    """Dereference an h5py.Reference

    Args:
        fileobj(File)
        path(str)
    Returns:
        device(str)
        path(str)
    """
    if is_reference(fileobj, path):
        ref = fileobj[path][()]
        dest = fileobj[ref]
        return dest.file.filename, dest.name
    else:
        return None, None

class Enum(dict):
    def __getattr__(self, key):
        return self[key]

h5errnames = ["SIGERR", "TRUNCERR", "EEXIST", "OPENERR"]
h5errno = Enum({k: -i for i, k in enumerate(h5errnames, 1)})
h5errcodes = {v: k for k, v in h5errno.items()}

def h5py_errno(err):
    if not errno.errorcode.get(err.errno, None):
        errmsg = str(err)
        m = re.search("errno = ([0-9]+)", errmsg)
        if m:
            return int(m.groups()[0])
        if "file signature not found" in errmsg:
            return h5errno.SIGERR
        elif "unable to truncate a file which is already open" in errmsg:
            return h5errno.TRUNCERR
        elif "file exists" in errmsg:
            return h5errno.EEXIST
        elif "file is already open for read-only" in errmsg:
            return h5errno.OPENERR
    return err.errno

class h5FileIO(object):
    """Context manager to open HDF5 file with retries"""

    def __init__(self, path, retries=25, backoff_factor=0.4, **openparams):
        self._handle = None
        self.path = path
        self.retries = retries
        self.backoff_factor = backoff_factor
        self.openparams = openparams

    def __enter__(self):
        self._handle = self._open()
        return self._handle

    def __exit__(self, *args):
        if self._handle:
            self._handle.close()
            self._handle = None

    def _open(self):
        # Open file which is locked by another process:
        #   r   : OK (lock=r), EAGAIN(lock=r+/w/x/a)
        #   r+/w: EAGAIN
        #   x/a : EEXIST
        # Open file which is locked by the same process (possibly another thread):
        #   r : OK
        #   r+: OK(lock=r+/w/x/a), OPENERR(lock=r)
        #   w : TRUNCERR
        #   x : EEXIST
        #   a : EEXIST(lock=r), OK(lock=r+/w/x/a)
        if self.openparams["mode"] == "r":
            os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"
        else:
            os.environ["HDF5_USE_FILE_LOCKING"] = "TRUE"
        path = self.path
        for _ in range(self.retries):
            try:
                return h5py.File(path, **self.openparams)
            except IOError as err:
                code = h5py_errno(err)
                if code == errno.ENOENT:
                    raise fs.Missing(path)
                elif code == errno.EISDIR:
                    raise fs.NotAFile(path)
                elif code in [errno.EAGAIN, h5errno.OPENERR, h5errno.TRUNCERR]:
                    pass  # try again
                elif code in [errno.EEXIST, h5errno.EEXIST]:
                    if self.openparams["mode"] in ["x", "w-"]:
                        raise
                    # try again
                else:
                    raise
            sleep(self.backoff_factor)
        raise LockedError(path)

class h5Device(localfs.Path):
    """Proxy to HDF5 file"""

    def __init__(self, path, mode="a", **kwargs):
        """
        Args:
            path(str):
            mode(Optional(str)):
                r    : open (error when not existing), read
                r+   : open (error when not existing), read/write
                w    : create (truncate existing), read/write
                x/w- : create (error when existing), read/write
                a    : create (append when existing), read/write
        """
        if mode not in ("r", "r+", "w", "x", "w-", "a"):
            raise ValueError("Invalid mode {}".format(repr(mode)))
        self.openparams = kwargs
        self.openparams["mode"] = mode
        super(h5Device, self).__init__(path, **kwargs)

    @contextlib.contextmanager
    def _fopen(self, **openparams):
        # msg = '{} ({})'.format(self.path,openparams)
        # logger.debug('Open '+msg)
        # try:
        with h5FileIO(self.path, **openparams) as f:
            yield f
        # finally:
        #    logger.debug('Close '+msg)

    def _openparams_defaults(self, openparams):
        super(h5Device, self)._openparams_defaults(openparams)
        defaultmode = self.openparams["mode"]
        mode = openparams["mode"]

        if defaultmode == "r":
            # read-only
            mode = defaultmode
        elif defaultmode == "r+" and mode not in ["r", "r+"]:
            # deny new device
            mode = defaultmode
        elif defaultmode in ["x", "w-"] and mode not in ["r", "x", "w-"]:
            # allow new device (error when existing)
            mode = defaultmode
        elif defaultmode == "w" and mode not in ["r", "w", "a"]:
            # allow new device (overwrite when existing)
            mode = defaultmode
        elif defaultmode == "a" and mode not in ["r", "a"]:
            # allow new device (append when existing)
            mode = defaultmode

        openparams["mode"] = mode

    @fs.onclose
    def remove(self, **kwargs):
        super(h5Device, self).remove(**kwargs)

    @property
    def mode(self):
        return self.openparams["mode"]

class Path(fs.Path):
    """Proxy to HDF5 path"""

    def __init__(self, path, h5file=None, **kwargs):
        h5file, path = self._split_path(str(path), device=h5file)
        if not path.startswith(self.sep):
            path = self.sep + path
        self.path = path
        if not isinstance(h5file, h5Device):
            if not h5file:
                raise ValueError(
                    'Specify HDF5 file as Path("h5file:/...") or Path("/...",h5file=...)'
                )
            h5file = h5Device(h5file, **kwargs)
        self._h5file = h5file
        super(Path, self).__init__(**kwargs)

    def factory(self, path):
        cls = self.factorycls
        if isinstance(path, cls):
            return path
        else:
            device, path = self._split_path(path, device=self.device)
            return cls(path, h5file=device, **self.factory_kwargs)

    @property
    def openparams(self):
        return self.device.openparams

    @openparams.setter
    def openparams(self, value):
        self.device.openparams = value

    def _openparams_defaults(self, createparams):
        super(Path, self)._openparams_defaults(createparams)
        defaultmode = self.openparams["mode"]
        createparams["nodemode"] = createparams["mode"]

        # if createparams['nodemode']=='r':
        #    import traceback
        #    print ''
        #    traceback.print_stack()

        # Device access mode (will be further restricted by h5Device)
        if defaultmode == "w":
            # Do not truncate device when opening files
            createparams["mode"] = "a"

    @contextlib.contextmanager
    def _fopen(self, **createparams):
        openparams = {
            k: createparams.pop(k) for k in self.openparams if k in createparams
        }
        nodemode = createparams.pop("nodemode")

        with self.h5open(**openparams) as f:
            node = f.get(self.path, default=None)
            if node:
                if nodemode == "w-" or nodemode == "x":
                    raise fs.AlreadyExists(self.location)
                if nodemode == "w":
                    if createparams:
                        if isinstance(node, h5py.Group):
                            raise fs.NotAFile(self.location)
                    else:
                        if isinstance(node, h5py.Dataset):
                            raise fs.NotADirectory(self.location)
                    try:
                        del f[self.path]
                    except KeyError:
                        pass
                    node = None
                # r,r+,a: nothing to do
            if node:
                if createparams:
                    raise fs.AlreadyExists(self.location)
            else:
                if nodemode.startswith("r"):
                    raise fs.Missing(self.location)
                parent = self.parent
                node = f.get(parent.path, default=None)
                if not node:
                    raise fs.MissingParentDirectory(self.location)
                node = node.create_dataset(self.name, **createparams)
            yield node

    @contextlib.contextmanager
    def h5open(self, **openparams):
        with self.device.open(**openparams) as f:
            yield f

    def isopen(self):
        return self.device.isopen()

    def h5remove(self):
        self.device.remove()

    @property
    def exists(self):
        # For links: destination exists
        try:
            with self.h5open(mode="r") as f:
                if self.islink:
                    dest = self.linkdest()
                    if dest is None:
                        return False
                    else:
                        return dest.exists
                else:
                    return self.path in f
        except (IOError, fs.FileSystemException):
            return False

    @property
    def lexists(self):
        # For links: link exists
        try:
            with self.h5open(mode="r") as f:
                return self.path in f
        except IOError:
            return False

    @property
    def isdir(self):
        try:
            with self.h5open(mode="r") as f:
                node = f.get(self.path, default=None)
                return isinstance(node, h5py.Group)
        except IOError:
            return False

    @property
    def isfile(self):
        try:
            with self.h5open(mode="r") as f:
                node = f.get(self.path, default=None)
                return isinstance(node, h5py.Dataset)
        except IOError:
            return False

    @property
    def device(self):
        return self._h5file

    @property
    def devsep(self):
        return "::"

    def devsplit(self, path):
        n = len(self.devsep)
        pattern = "\.[^{}]+{}".format(re.escape(self.sep), re.escape(self.devsep))
        a = 0
        lst = []
        for m in re.finditer(pattern, path):
            b = m.end()
            add = path[a : b - n]
            if add:
                lst.append(add)
            a = b
        add = path[a:]
        lst.append(add)
        return lst
        # return path.split(self.devsep)

    def listdir(self, recursive=False, depth=0):
        with self.h5open() as f:
            root = f.get(self.path, default=None)
            if isinstance(root, h5py.Group):
                for k in root.keys():
                    yield self[k]

    @property
    def sep(self):
        return "/"

    def mkdir(self, recursive=True, force=True):
        with self.h5open() as f:
            if self._mkdir_prepare(recursive=recursive, force=force):
                return self
            parent = self.parent
            if recursive:
                node = parent
                lst = []
                while not node.exists:
                    lst.append(node)
                    node = node.parent
                for node in reversed(lst):
                    f.create_group(node.path)
            else:
                if not parent.exists:
                    raise fs.MissingParentDirectory(parent.location)
            f.create_group(self.path)
            return self

    def move(self, dest, force=False, rename=False):
        with self.h5open() as f:
            dest = self._copy_move_prepare(dest, force=force, rename=rename)
            if dest.exists and force:
                dest.remove(recursive=True)
            if self.device == dest.device:
                try:
                    # h5py does not have a `rename` so use
                    # the next best thing
                    f.move(self.path, dest.path)
                except ValueError:
                    dest = self._move_copyrenamedel(dest)
            else:
                dest = self._move_copyrenamedel(dest)
            dest._copymove_relink(self, dest)
            return self.factory(dest)

    def _copymove_relink(self, source, dest):
        # Softlink in HDF5 are absolute, so relink all links below self
        # that point to a destination below self (including self)
        if self.is_external_link:
            return
        for path in self.listdir():
            path._copymove_relink(source, dest)
        if self.islink:
            linkdest = self.linkdest()
            if source.common(linkdest) == source:
                self.remove()
                self.link(dest[source.relpath(linkdest.path)])

    def copy(self, dest, force=False, follow=False, dereference=False):
        with self.h5open() as fsource:
            dest = self._copy_move_prepare(dest, force=force)
            if dest.exists and force:
                dest.remove(recursive=True)
            if self.islink and not follow:
                # just copy the link itself
                dest.link(self.linkdest())
            else:
                with dest.h5open() as fdest:
                    # RuntimeError: softlink to external link
                    fsource.copy(
                        self.path,
                        fdest[dest.parent.path],
                        name=dest.name,
                        expand_soft=dereference,
                        expand_external=dereference,
                    )
                    dest._copymove_relink(self, dest)
            return self.factory(dest)

    def remove(self, recursive=False):
        with self.h5open() as f:
            if self.islink:
                if recursive:
                    node = self.linkdest()
                    if node:
                        node.remove(recursive=True)
                del f[self.path]
            elif self.exists:
                if self.isdir:
                    if not recursive:
                        if list(self.listdir()):
                            raise fs.DirectoryIsNotEmpty(self.location)
                if self.path == self.sep:
                    self.h5remove()
                else:
                    del f[self.path]

    def stats(self, follow=True):
        if follow == False:
            raise ValueError("Hdf5 links do not have attributes themselves")
        with self.open(mode="r") as node:
            return dict(node.attrs)

    def get_stat(self, key, default=None, follow=True):
        if follow == False:
            raise ValueError("Hdf5 links do not have attributes themselves")
        try:
            with self.open(mode="r") as node:
                return node.attrs.get(instance.asunicode(key), default=default)
        except fs.Missing:
            return default

    def pop_stat(self, key, default=None, follow=True):
        if follow == False:
            raise ValueError("Hdf5 links do not have attributes themselves")
        try:
            with self.open(mode="r") as node:
                return node.attrs.pop(instance.asunicode(key), default=default)
        except fs.Missing:
            return default

    def update_stats(self, prepare_kwargs=None, **stats):
        with self.open() as node:
            if prepare_kwargs is None:
                prepare_kwargs = {}
            stats = {
                instance.asunicode(k): prepare_h5data(v, **prepare_kwargs)
                for k, v in stats.items()
            }
            node.attrs.update(stats)

    @contextlib.contextmanager
    def openstats(self, follow=True, **openparams):
        if follow == False:
            raise ValueError("Hdf5 links do not have attributes themselves")
        with self.open(**openparams) as node:
            yield node.attrs

    def link(self, dest, soft=True):
        with self.h5open() as f:
            base = self.parent
            lnkname = self.name

            destpath = self.sibling(dest)
            if destpath.device == self.device:
                if soft:
                    dest = base.relpath(self._getpath(dest))

                    # Remove '..' because it is not supported:
                    # https://support.hdfgroup.org/HDF5/doc/UG/HDF5_Users_Guide-Responsive%20HTML5/index.html#t=HDF5_Users_Guide%2FGroups%2FHDF5_Groups.htm%23IX_soft_links
                    if ".." in dest:
                        # This does not work either:
                        # lst = dest.split(self.sep)
                        # i = len(lst) - lst[::-1].index('..')
                        # base = base[self.sep.join(lst[:i])]
                        # dest = base.relpath(destpath.path)
                        # lnkname = base.relpath(self.path)

                        # Use absolute path instead:
                        dest = destpath.path
                    dest = h5py.SoftLink(dest)
                else:
                    dest = f[destpath.path]
            else:
                dest = h5py.ExternalLink(str(destpath.device), destpath.path)
            f[base.path][lnkname] = dest
            return self.factory(self)

    @property
    def islink(self):
        with self.h5open(mode="r") as f:
            if is_link(f, self.path):
                return True
            else:
                return is_reference(f, self.path)

    @property
    def is_internal_link(self):
        with self.h5open(mode="r") as f:
            return is_internal_link(f, self.path)

    @property
    def is_external_link(self):
        with self.h5open(mode="r") as f:
            return is_external_link(f, self.path)

    def linkdest(self, follow=False):
        if not self.root.exists:
            return None
        with self.h5open(mode="r") as f:
            device, path = dereference_link(f, self.path)
            if path is None:
                device, path = dereference(f, self.path)
            if path and device == self.device:
                dest = self.factory(self.abspath(path))
            elif path and device:
                dest = self.factory(device + self.devsep + path)
            else:
                dest = None
            if follow:
                dest = self._link_follow(dest)
            return dest

    def _contentinfo(self):
        contentinfo = ""
        if self.isfile:
            with self.open(mode="r") as node:
                dtype = node.dtype
                specialdtype = h5py.check_dtype(vlen=node.dtype)
                if node.ndim == 0:
                    if specialdtype == str or specialdtype == unicode:
                        contentinfo = " = {}".format(node[()])
                    else:
                        if specialdtype is not None:
                            dtype = specialdtype
                        contentinfo = " = {} ({})".format(node[()], dtype)
                else:
                    if specialdtype is not None:
                        dtype = specialdtype
                    shape = "x".join(list(map(str, node.shape)))
                    contentinfo = " = {} ({})".format(dtype, shape)
        return contentinfo

    def read(self):
        with self.open(mode="r") as node:
            try:
                return node.asstr()[()]
            except Exception:
                return node[()]

    def write(self, **kwargs):
        return self.mkfile(**kwargs)

    def mkfile(self, data=None, attributes=None, prepare_kwargs=None, **params):
        if prepare_kwargs is None:
            prepare_kwargs = {}
        if data is not None:
            params["data"] = prepare_h5data(data, **prepare_kwargs)
        with self.open(**params) as dset:
            if attributes:
                for k, v in attributes.items():
                    dset.attrs[k] = prepare_h5data(v, **prepare_kwargs)
        return self

    @property
    def dtype(self):
        with self.open(mode="r") as node:
            try:
                return node.dtype
            except AttributeError:
                return None

    @property
    def shape(self):
        with self.open(mode="r") as node:
            try:
                return node.shape
            except AttributeError:
                return None

    @property
    def ndim(self):
        with self.open(mode="r") as node:
            try:
                return node.ndim
            except AttributeError:
                return None

    @property
    def size(self):
        with self.open(mode="r") as node:
            try:
                return node.size
            except AttributeError:
                return None


text:
package com.hhua.android.producthunt.adapters;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.hhua.android.producthunt.R;
import com.hhua.android.producthunt.activities.UserActivity;
import com.hhua.android.producthunt.models.Comment;
import com.hhua.android.producthunt.models.User;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by ahua on 12/18/15.
 */
public class CommentsArrayAdapter extends ArrayAdapter<Comment> {

    public CommentsArrayAdapter(Context context, List<Comment> comments) {
        super(context, android.R.layout.simple_list_item_1, comments);
    }

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        final Comment comment = getItem(position);

        if (convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_comment, parent, false);
        }

        TextView tvCommenterDescription = (TextView) convertView.findViewById(R.id.tvCommenterDescription);
        TextView tvCommentBody = (TextView) convertView.findViewById(R.id.tvCommentBody);
        TextView tvCommentCreatedAt = (TextView) convertView.findViewById(R.id.tvCommentCreatedAt);

        String description = "<b>" + comment.getUser().getName() + "</b> " + " - " + comment.getUser().getHeadline();
        tvCommenterDescription.setText(Html.fromHtml(description));
        tvCommentBody.setText(Html.fromHtml(comment.getBody()));
        tvCommentCreatedAt.setText(comment.getCreatedAt());

        ImageView ivCommenterAvatar = (ImageView) convertView.findViewById(R.id.ivCommenterAvatar);
        ivCommenterAvatar.setImageResource(0);

        Picasso.with(getContext()).load(comment.getUser().getMediumProfileImageUrl()).fit().into(ivCommenterAvatar);
        ivCommenterAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User commenter = comment.getUser();
                if (commenter != null) {
                    int userId = commenter.getId();
                    Intent intent = new Intent(getContext(), UserActivity.class);
                    intent.putExtra(User.USER_ID_MESSAGE, userId);

                    parent.getContext().startActivity(intent);
                }
            }
        });

        ListView lvChildComments = (ListView) convertView.findViewById(R.id.lvChildComments);
        CommentsArrayAdapter commentsArrayAdapter = new CommentsArrayAdapter(getContext(), comment.getChildComments());
        lvChildComments.setAdapter(commentsArrayAdapter);

        return convertView;
    }
}


text:
<?php

namespace Project3\WebsiteBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ContactControllerControllerTest extends WebTestCase
{
}


text:
# Essential Shortcuts - Search Everywhere

Search everywhere by name combines go to type, symbol, actions and file in one menu.

<shortcut id="Search Everywhere">Ctrl+T</shortcut>

`Escape` to cancel.

Covered in more detail in next section


text:
package org.keycloak.testsuite.hok;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED;

import java.io.IOException;
import java.net.URI;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.hamcrest.Matchers;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.junit.*;
import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.common.util.KeystoreUtil;
import org.keycloak.crypto.Algorithm;
import org.keycloak.events.Details;
import org.keycloak.events.EventType;
import org.keycloak.jose.jws.JWSHeader;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.jose.jws.crypto.HashUtils;
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
import org.keycloak.protocol.oidc.utils.OIDCResponseType;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.representations.RefreshToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.oidc.TokenMetadataRepresentation;
import org.keycloak.testsuite.AbstractKeycloakTest;
import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.drone.Different;
import org.keycloak.testsuite.oauth.RefreshTokenTest;
import org.keycloak.testsuite.util.ClientManager;
import org.keycloak.testsuite.util.MutualTLSUtils;
import org.keycloak.testsuite.util.KeycloakModelUtils;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.UserInfoClientUtil;
import org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse;
import org.keycloak.testsuite.util.WaitUtils;
import org.keycloak.util.JsonSerialization;
import org.openqa.selenium.WebDriver;

public class HoKTest extends AbstractTestRealmKeycloakTest {
    // KEYCLOAK-6771 Certificate Bound Token
    // https://tools.ietf.org/html/draft-ietf-oauth-mtls-08#section-3

    @Drone
    @Different
    protected WebDriver driver2;

    private static final List<String> CLIENT_LIST = Arrays.asList("test-app", "named-test-app", "service-account-client");

    public static class HoKAssertEvents extends AssertEvents {

        public HoKAssertEvents(AbstractKeycloakTest ctx) {
            super(ctx);
        }

        private final String defaultRedirectUri = "https://localhost:8543/auth/realms/master/app/auth";

        @Override
        public ExpectedEvent expectLogin() {
            return expect(EventType.LOGIN)
                    .detail(Details.CODE_ID, isCodeId())
                    //.detail(Details.USERNAME, DEFAULT_USERNAME)
                    //.detail(Details.AUTH_METHOD, OIDCLoginProtocol.LOGIN_PROTOCOL)
                    //.detail(Details.AUTH_TYPE, AuthorizationEndpoint.CODE_AUTH_TYPE)
                    .detail(Details.REDIRECT_URI, defaultRedirectUri)
                    .detail(Details.CONSENT, Details.CONSENT_VALUE_NO_CONSENT_REQUIRED)
                    .session(isUUID());
        }
    }

    @Rule
    public HoKAssertEvents events = new HoKAssertEvents(this);

    @Override
    public void configureTestRealm(RealmRepresentation testRealm) {
        // override due to effects caused by enabling TLS
        for (String clientId : CLIENT_LIST) addRedirectUrlForTls(testRealm, clientId);

        // for token introspection
        configTestRealmForTokenIntrospection(testRealm);
    }

    @BeforeClass
    public static void checkIfTLSIsTurnedOn() {
        Assume.assumeTrue(AUTH_SERVER_SSL_REQUIRED);
    }

    private void addRedirectUrlForTls(RealmRepresentation testRealm, String clientId) {
        for (ClientRepresentation client : testRealm.getClients()) {
            if (client.getClientId().equals(clientId)) {
                URI baseUri = URI.create(client.getRedirectUris().get(0));
                URI redir = URI.create("https://localhost:" + System.getProperty("auth.server.https.port", "8543") + baseUri.getRawPath());
                client.getRedirectUris().add(redir.toString());
                break;
            }
        }
    }

    private void configTestRealmForTokenIntrospection(RealmRepresentation testRealm) {
        ClientRepresentation confApp = KeycloakModelUtils.createClient(testRealm, "confidential-cli");
        confApp.setSecret("secret1");
        confApp.setServiceAccountsEnabled(Boolean.TRUE);

        ClientRepresentation serviceAccountApp = KeycloakModelUtils.createClient(testRealm, "service-account-client");
        serviceAccountApp.setSecret("secret1");
        serviceAccountApp.setServiceAccountsEnabled(Boolean.TRUE);

        ClientRepresentation pubApp = KeycloakModelUtils.createClient(testRealm, "public-cli");
        pubApp.setPublicClient(Boolean.TRUE);

        UserRepresentation user = new UserRepresentation();
        user.setUsername("no-permissions");
        CredentialRepresentation credential = new CredentialRepresentation();
        credential.setType("password");
        credential.setValue("password");
        List<CredentialRepresentation> creds = new ArrayList<>();
        creds.add(credential);
        user.setCredentials(creds);
        user.setEnabled(Boolean.TRUE);
        List<String> realmRoles = new ArrayList<>();
        realmRoles.add("user");
        user.setRealmRoles(realmRoles);
        testRealm.getUsers().add(user);
    }

    // enable HoK Token as default
    @Before
    public void enableHoKToken() {
        // Enable MTLS HoK Token
        for (String clientId : CLIENT_LIST) enableHoKToken(clientId);
    }

    private void enableHoKToken(String clientId) {
        // Enable MTLS HoK Token
        ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), clientId);
        ClientRepresentation clientRep = clientResource.toRepresentation();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseMtlsHoKToken(true);
        clientResource.update(clientRep);
    }

    // Authorization Code Flow
    // Bind HoK Token

    @Test
    public void accessTokenRequestWithClientCertificate() throws Exception {
        oauth.doLogin("test-user@localhost", "password");
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        AccessTokenResponse response;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            response = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Success Pattern
        expectSuccessfulResponseFromTokenEndpoint(sessionId, codeId, response);
        verifyHoKTokenDefaultCertThumbPrint(response);
    }

    @Test
    public void accessTokenRequestWithoutClientCertificate() throws Exception {
        oauth.doLogin("test-user@localhost", "password");
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        AccessTokenResponse response;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
            response = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Error Pattern
        assertEquals(400, response.getStatusCode());
        assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError());
        assertEquals("Client Certification missing for MTLS HoK Token Binding", response.getErrorDescription());
    }

    private void expectSuccessfulResponseFromTokenEndpoint(String sessionId, String codeId, AccessTokenResponse response) throws Exception {
        assertEquals(200, response.getStatusCode());

        Assert.assertThat(response.getExpiresIn(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
        Assert.assertThat(response.getRefreshExpiresIn(), allOf(greaterThanOrEqualTo(1750), lessThanOrEqualTo(1800)));

        assertEquals("Bearer", response.getTokenType());

        String expectedKid = oauth.doCertsRequest("test").getKeys()[0].getKeyId();

        JWSHeader header = new JWSInput(response.getAccessToken()).getHeader();
        assertEquals("RS256", header.getAlgorithm().name());
        assertEquals("JWT", header.getType());
        assertEquals(expectedKid, header.getKeyId());
        assertNull(header.getContentType());

        header = new JWSInput(response.getIdToken()).getHeader();
        assertEquals("RS256", header.getAlgorithm().name());
        assertEquals("JWT", header.getType());
        assertEquals(expectedKid, header.getKeyId());
        assertNull(header.getContentType());

        header = new JWSInput(response.getRefreshToken()).getHeader();
        assertEquals("HS256", header.getAlgorithm().name());
        assertEquals("JWT", header.getType());
        assertNull(header.getContentType());

        AccessToken token = oauth.verifyToken(response.getAccessToken());

        assertEquals(findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId(), token.getSubject());
        Assert.assertNotEquals("test-user@localhost", token.getSubject());

        assertEquals(sessionId, token.getSessionState());

        assertEquals(2, token.getRealmAccess().getRoles().size());
        assertTrue(token.getRealmAccess().isUserInRole("user"));

        assertEquals(1, token.getResourceAccess(oauth.getClientId()).getRoles().size());
        assertTrue(token.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user"));

        EventRepresentation event = events.expectCodeToToken(codeId, sessionId).assertEvent();
        assertEquals(token.getId(), event.getDetails().get(Details.TOKEN_ID));
        assertEquals(oauth.parseRefreshToken(response.getRefreshToken()).getId(), event.getDetails().get(Details.REFRESH_TOKEN_ID));
        assertEquals(sessionId, token.getSessionState());
    }

    // verify HoK Token - Token Refresh

    @Test
    public void refreshTokenRequestByHoKRefreshTokenByOtherClient() throws Exception {
        // first client user login
        oauth.doLogin("test-user@localhost", "password");
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        AccessTokenResponse tokenResponse = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            tokenResponse = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        verifyHoKTokenDefaultCertThumbPrint(tokenResponse);
        String refreshTokenString = tokenResponse.getRefreshToken();

        // second client user login
        OAuthClient oauth2 = new OAuthClient();
        oauth2.init(driver2);
        oauth2.doLogin("john-doh@localhost", "password");
        String code2 = oauth2.getCurrentQuery().get(OAuth2Constants.CODE);
        AccessTokenResponse tokenResponse2 = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithOtherKeyStoreAndTrustStore()) {
            tokenResponse2 = oauth2.doAccessTokenRequest(code2, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        verifyHoKTokenOtherCertThumbPrint(tokenResponse2);

        // token refresh by second client by first client's refresh token
        AccessTokenResponse response = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithOtherKeyStoreAndTrustStore()) {
            response = oauth2.doRefreshTokenRequest(refreshTokenString, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Error Pattern
        assertEquals(401, response.getStatusCode());
        assertEquals(OAuthErrorException.UNAUTHORIZED_CLIENT, response.getError());
        assertEquals("Client certificate missing, or its thumbprint and one in the refresh token did NOT match", response.getErrorDescription());
    }

    @Test
    public void refreshTokenRequestByHoKRefreshTokenWithClientCertificate() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        AccessTokenResponse tokenResponse = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            tokenResponse = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        verifyHoKTokenDefaultCertThumbPrint(tokenResponse);
        AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
        String refreshTokenString = tokenResponse.getRefreshToken();
        RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);
        EventRepresentation tokenEvent = events.expectCodeToToken(codeId, sessionId).assertEvent();

        Assert.assertNotNull(refreshTokenString);
        assertEquals("Bearer", tokenResponse.getTokenType());
        Assert.assertThat(token.getExpiration() - getCurrentTime(), allOf(greaterThanOrEqualTo(200), lessThanOrEqualTo(350)));
        int actual = refreshToken.getExpiration() - getCurrentTime();
        Assert.assertThat(actual, allOf(greaterThanOrEqualTo(1799 - RefreshTokenTest.ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(1800 + RefreshTokenTest.ALLOWED_CLOCK_SKEW)));
        assertEquals(sessionId, refreshToken.getSessionState());

        setTimeOffset(2);

        AccessTokenResponse response = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            response = oauth.doRefreshTokenRequest(refreshTokenString, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Success Pattern
        expectSuccessfulResponseFromTokenEndpoint(response, sessionId, token, refreshToken, tokenEvent);
        verifyHoKTokenDefaultCertThumbPrint(response);
    }

    @Test
    public void refreshTokenRequestByRefreshTokenWithoutClientCertificate() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String sessionId = loginEvent.getSessionId();
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        AccessTokenResponse tokenResponse = null;
        tokenResponse = oauth.doAccessTokenRequest(code, "password");

        verifyHoKTokenDefaultCertThumbPrint(tokenResponse);
        AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
        String refreshTokenString = tokenResponse.getRefreshToken();
        RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);

        Assert.assertNotNull(refreshTokenString);
        assertEquals("Bearer", tokenResponse.getTokenType());
        Assert.assertThat(token.getExpiration() - getCurrentTime(), allOf(greaterThanOrEqualTo(200), lessThanOrEqualTo(350)));
        int actual = refreshToken.getExpiration() - getCurrentTime();
        Assert.assertThat(actual, allOf(greaterThanOrEqualTo(1799 - RefreshTokenTest.ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(1800 + RefreshTokenTest.ALLOWED_CLOCK_SKEW)));
        assertEquals(sessionId, refreshToken.getSessionState());

        setTimeOffset(2);

        AccessTokenResponse response = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
            response = oauth.doRefreshTokenRequest(refreshTokenString, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Error Pattern
        assertEquals(401, response.getStatusCode());
        assertEquals(OAuthErrorException.UNAUTHORIZED_CLIENT, response.getError());
        assertEquals("Client certificate missing, or its thumbprint and one in the refresh token did NOT match", response.getErrorDescription());
    }

    private void expectSuccessfulResponseFromTokenEndpoint(AccessTokenResponse response, String sessionId, AccessToken token, RefreshToken refreshToken, EventRepresentation tokenEvent) {
        expectSuccessfulResponseFromTokenEndpoint(oauth, "test-user@localhost", response, sessionId, token, refreshToken, tokenEvent);
    }

    private void expectSuccessfulResponseFromTokenEndpoint(OAuthClient oauth, String username, AccessTokenResponse response, String sessionId, AccessToken token, RefreshToken refreshToken, EventRepresentation tokenEvent) {
        AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
        RefreshToken refreshedRefreshToken = oauth.parseRefreshToken(response.getRefreshToken());
        if (refreshedToken.getCertConf() != null) {
            log.warnf("refreshed access token's cnf-x5t#256 = %s", refreshedToken.getCertConf().getCertThumbprint());
            log.warnf("refreshed refresh token's cnf-x5t#256 = %s", refreshedRefreshToken.getCertConf().getCertThumbprint());
        }

        assertEquals(200, response.getStatusCode());

        assertEquals(sessionId, refreshedToken.getSessionState());
        assertEquals(sessionId, refreshedRefreshToken.getSessionState());

        Assert.assertThat(response.getExpiresIn(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
        Assert.assertThat(refreshedToken.getExpiration() - getCurrentTime(), allOf(greaterThanOrEqualTo(250 - RefreshTokenTest.ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(300 + RefreshTokenTest.ALLOWED_CLOCK_SKEW)));

        Assert.assertThat(refreshedToken.getExpiration() - token.getExpiration(), allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));
        Assert.assertThat(refreshedRefreshToken.getExpiration() - refreshToken.getExpiration(), allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

        Assert.assertNotEquals(token.getId(), refreshedToken.getId());
        Assert.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId());

        assertEquals("Bearer", response.getTokenType());

        assertEquals(findUserByUsername(adminClient.realm("test"), username).getId(), refreshedToken.getSubject());
        Assert.assertNotEquals(username, refreshedToken.getSubject());

        assertEquals(2, refreshedToken.getRealmAccess().getRoles().size());
        Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole("user"));

        assertEquals(1, refreshedToken.getResourceAccess(oauth.getClientId()).getRoles().size());
        Assert.assertTrue(refreshedToken.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user"));

        EventRepresentation refreshEvent = events.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).user(AssertEvents.isUUID()).assertEvent();
        Assert.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID));
        Assert.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID));

        setTimeOffset(0);
    }

    // verify HoK Token - Get UserInfo

    @Test
    public void getUserInfoByHoKAccessTokenWithClientCertificate() throws Exception {
        // get an access token
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        AccessTokenResponse tokenResponse = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            tokenResponse = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        verifyHoKTokenDefaultCertThumbPrint(tokenResponse);
        events.expectCodeToToken(codeId, sessionId).assertEvent();

        // execute the access token to get UserInfo with token binded client certificate in mutual authentication TLS
        ClientBuilder clientBuilder = ClientBuilder.newBuilder();
        KeyStore keystore = null;
        keystore = KeystoreUtil.loadKeyStore(MutualTLSUtils.DEFAULT_KEYSTOREPATH, MutualTLSUtils.DEFAULT_KEYSTOREPASSWORD);
        clientBuilder.keyStore(keystore, MutualTLSUtils.DEFAULT_KEYSTOREPASSWORD);
        Client client = clientBuilder.build();
        WebTarget userInfoTarget = null;
        Response response = null;
        try {
            userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
            response = userInfoTarget.request().header(HttpHeaders.AUTHORIZATION, "Bearer " + tokenResponse.getAccessToken()).get();
            testSuccessfulUserInfoResponse(response);
        } finally {
            response.close();
            client.close();
        }

    }

    @Test
    public void getUserInfoByHoKAccessTokenWithoutClientCertificate() throws Exception {
        // get an access token
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        AccessTokenResponse tokenResponse = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            tokenResponse = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        verifyHoKTokenDefaultCertThumbPrint(tokenResponse);
        events.expectCodeToToken(codeId, sessionId).assertEvent();

        // execute the access token to get UserInfo without token binded client certificate in mutual authentication TLS
        ClientBuilder clientBuilder = ClientBuilder.newBuilder();
        Client client = clientBuilder.build();
        WebTarget userInfoTarget = null;
        Response response = null;
        try {
            userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
            response = userInfoTarget.request().header(HttpHeaders.AUTHORIZATION, "Bearer " + tokenResponse.getAccessToken()).get();
            assertEquals(401, response.getStatus());
        } finally {
            response.close();
            client.close();
        }

    }

    private void testSuccessfulUserInfoResponse(Response response) {
        events.expect(EventType.USER_INFO_REQUEST)
                .session(Matchers.notNullValue(String.class))
                .detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN)
                .detail(Details.USERNAME, "test-user@localhost")
                .detail(Details.SIGNATURE_REQUIRED, "false")
                .assertEvent();
        UserInfoClientUtil.testSuccessfulUserInfoResponse(response, "test-user@localhost", "test-user@localhost");
    }

    // verify HoK Token - Back Channel Logout

    @Test
    public void postLogoutByHoKRefreshTokenWithClientCertificate() throws Exception {
        String refreshTokenString = execPreProcessPostLogout();

        CloseableHttpResponse response = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
            response = oauth.doLogout(refreshTokenString, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Success Pattern
        assertThat(response, org.keycloak.testsuite.util.Matchers.statusCodeIsHC(Status.NO_CONTENT));
        assertNotNull(testingClient.testApp().getAdminLogoutAction());
    }

    @Test
    public void postLogoutByHoKRefreshTokenWithoutClientCertificate() throws Exception {
        String refreshTokenString = execPreProcessPostLogout();

        CloseableHttpResponse response = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
            response = oauth.doLogout(refreshTokenString, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        // Error Pattern
        assertEquals(401, response.getStatusLine().getStatusCode());
    }

    private String execPreProcessPostLogout() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        oauth.clientSessionState("client-session");
        AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
        verifyHoKTokenDefaultCertThumbPrint(tokenResponse);

        return tokenResponse.getRefreshToken();
    }

    // Hybrid Code Flow : response_type = code id_token
    // Bind HoK Token

    @Test
    public void accessTokenRequestWithClientCertificateInHybridFlowWithCodeIDToken() throws Exception {
        String nonce = "ckw938gnspa93dj";
        ClientManager.realm(adminClient.realm("test")).clientId("test-app").standardFlow(true).implicitFlow(true);
        oauth.clientId("test-app");
        oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
        oauth.nonce(nonce);

        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        OAuthClient.AuthorizationEndpointResponse authzResponse = new OAuthClient.AuthorizationEndpointResponse(oauth, true);
        Assert.assertNotNull(authzResponse.getSessionState());
        List<IDToken> idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent);
        for (IDToken idToken : idTokens) {
            Assert.assertEquals(nonce, idToken.getNonce());
            Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState());
        }
    }

    protected List<IDToken> testAuthzResponseAndRetrieveIDTokens(OAuthClient.AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) {
        Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE));

        // IDToken from the authorization response
        Assert.assertNull(authzResponse.getAccessToken());
        String idTokenStr = authzResponse.getIdToken();
        IDToken idToken = oauth.verifyIDToken(idTokenStr);

        // Validate "c_hash"
        Assert.assertNull(idToken.getAccessTokenHash());
        Assert.assertNotNull(idToken.getCodeHash());
        Assert.assertEquals(idToken.getCodeHash(), HashUtils.oidcHash(Algorithm.RS256, authzResponse.getCode()));

        // IDToken exchanged for the code
        IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent);

        return Arrays.asList(idToken, idToken2);
    }

    @Test
    public void testIntrospectHoKAccessToken() throws Exception {
        // get an access token with client certificate in mutual authenticate TLS
        // mimic Client
        oauth.doLogin("test-user@localhost", "password");
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        AccessTokenResponse accessTokenResponse = null;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
           accessTokenResponse = oauth.doAccessTokenRequest(code, "password", client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        // Do token introspection
        // mimic Resource Server
        String tokenResponse;
        try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
            tokenResponse = oauth.introspectTokenWithClientCredential("confidential-cli", "secret1", "access_token", accessTokenResponse.getAccessToken(), client);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
        JWSInput jws = new JWSInput(accessTokenResponse.getAccessToken());
        AccessToken at = jws.readJsonContent(AccessToken.class);
        jws = new JWSInput(accessTokenResponse.getRefreshToken());
        RefreshToken rt = jws.readJsonContent(RefreshToken.class);
        String certThumprintFromAccessToken = at.getCertConf().getCertThumbprint();
        String certThumprintFromRefreshToken = rt.getCertConf().getCertThumbprint();
        String certThumprintFromTokenIntrospection = rep.getCertConf().getCertThumbprint();
        String certThumprintFromBoundClientCertificate = MutualTLSUtils.getThumbprintFromDefaultClientCert();

        assertTrue(rep.isActive());
        assertEquals("test-user@localhost", rep.getUserName());
        assertEquals("test-app", rep.getClientId());
        assertEquals(loginEvent.getUserId(), rep.getSubject());

        assertEquals(certThumprintFromTokenIntrospection, certThumprintFromBoundClientCertificate);
        assertEquals(certThumprintFromBoundClientCertificate, certThumprintFromAccessToken);
        assertEquals(certThumprintFromAccessToken, certThumprintFromRefreshToken);

    }

    @Test
    public void serviceAccountWithClientCertificate() throws Exception {
        oauth.clientId("service-account-client");

        AccessTokenResponse response;

        Supplier<CloseableHttpClient> previous = oauth.getHttpClient();

        try {
            // Request without HoK should fail
            oauth.httpClient(MutualTLSUtils::newCloseableHttpClientWithoutKeyStoreAndTrustStore);
            response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1");
            assertEquals(400, response.getStatusCode());
            assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError());
            assertEquals("Client Certification missing for MTLS HoK Token Binding", response.getErrorDescription());

            // Request with HoK - success
            oauth.httpClient(MutualTLSUtils::newCloseableHttpClientWithDefaultKeyStoreAndTrustStore);
            response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1");
            assertEquals(200, response.getStatusCode());

            // Success Pattern
            verifyHoKTokenCertThumbPrint(response, MutualTLSUtils.getThumbprintFromDefaultClientCert(), false);
        }  catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } finally {
            oauth.httpClient(previous);
        }
    }

    private void verifyHoKTokenDefaultCertThumbPrint(AccessTokenResponse response) throws Exception {
        verifyHoKTokenCertThumbPrint(response, MutualTLSUtils.getThumbprintFromDefaultClientCert(), true);
    }

    private void verifyHoKTokenOtherCertThumbPrint(AccessTokenResponse response) throws Exception {
        verifyHoKTokenCertThumbPrint(response, MutualTLSUtils.getThumbprintFromOtherClientCert(), true);
    }

    private void verifyHoKTokenCertThumbPrint(AccessTokenResponse response, String certThumbPrint, boolean checkRefreshToken) {
        JWSInput jws = null;
        AccessToken at = null;
        try {
            jws = new JWSInput(response.getAccessToken());
            at = jws.readJsonContent(AccessToken.class);
        } catch (JWSInputException e) {
            Assert.fail(e.toString());
        }
        assertTrue(MessageDigest.isEqual(certThumbPrint.getBytes(), at.getCertConf().getCertThumbprint().getBytes()));

        if (checkRefreshToken) {
            RefreshToken rt = null;
            try {
                jws = new JWSInput(response.getRefreshToken());
                rt = jws.readJsonContent(RefreshToken.class);
            } catch (JWSInputException e) {
                Assert.fail(e.toString());
            }
            assertTrue(MessageDigest.isEqual(certThumbPrint.getBytes(), rt.getCertConf().getCertThumbprint().getBytes()));
        }
    }
}


text:
status

network

tests


text:
package org.elasticsearch.action.fieldcaps;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.OriginalIndices;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.single.shard.SingleShardRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

public class FieldCapabilitiesIndexRequest extends SingleShardRequest<FieldCapabilitiesIndexRequest> {

    private final String[] fields;
    private final OriginalIndices originalIndices;

    // For serialization
    FieldCapabilitiesIndexRequest(StreamInput in) throws IOException {
        super(in);
        fields = in.readStringArray();
        originalIndices = OriginalIndices.readOriginalIndices(in);
    }

    FieldCapabilitiesIndexRequest(String[] fields, String index, OriginalIndices originalIndices) {
        super(index);
        if (fields == null || fields.length == 0) {
            throw new IllegalArgumentException("specified fields can't be null or empty");
        }
        this.fields = fields;
        assert index != null;
        this.index(index);
        this.originalIndices = originalIndices;
    }

    public String[] fields() {
        return fields;
    }

    @Override
    public String[] indices() {
        return originalIndices.indices();
    }

    @Override
    public IndicesOptions indicesOptions() {
        return originalIndices.indicesOptions();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeStringArray(fields);
        OriginalIndices.writeOriginalIndices(originalIndices, out);
    }

    @Override
    public ActionRequestValidationException validate() {
        return null;
    }
}


text:
import * as React from 'react';
import './style.css';

import FooterContainer from './Components';

class Footer extends React.Component<{}, {}> {
  render() {
    return (
        <FooterContainer />
    );
  }
}

export default Footer;


text:
package autosteamgifts

import autosteamgifts.background.GameRating
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class Game(
    val id: String,
    val name: String,
    val steamUrl: Option[String],
    val imageUrl: Option[String]
  ) {

  lazy val steamId = steamUrl map { URLs.steamIdFromSteamUrl }

  lazy val rating: Future[Double] =
    Future(steamId)
      .collect { case Some(steamId) => steamId }
      .flatMap { GameRating.get }

  override def equals(other: Any): Boolean = {
    other match {
      case otherGame: Game => this.id == otherGame.id
      case _ => false
    }
  }

  override def hashCode(): Int = id.hashCode()
}


text:
#region License
//    Copyright 2012 Julien Lebosquain
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
#endregion
using GammaJul.ReSharper.ForTea.Tree;
using JetBrains.ReSharper.Feature.Services.SelectEmbracingConstruct;
using JetBrains.ReSharper.Psi.Tree;

namespace GammaJul.ReSharper.ForTea.Services.Selection {

	public class T4NodeSelection : TreeNodeSelection<IT4File> {

		public override ISelectedRange Parent {
			get {
				ITreeNode parentNode = TreeNode.Parent;
				return parentNode == null ? null : new T4NodeSelection(FileNode, parentNode);
			}
		}

		public T4NodeSelection(IT4File fileNode, ITreeNode node)
			: base(fileNode, node) {
		}

	}

}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28645_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SAMPLE PROGRAM:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">LOGGING COMPANY: WELL STATUS: COMPANY ENGINEER: WELLSITE SUPERVISOR: COMPANY GEOLOGIST:
WELLSITE GEOLOGIST:

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Schlumbergcr
Awaiting Completion
Travis Lancr
Dave Edwards, Chris Calamc En'c Ewoniuk
Scott Strahm

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Caught: Examined: Saved:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Very good to excellent


text:
package com.raulh82vlc.topratemovies.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.transition.Slide;
import android.transition.Transition;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.raulh82vlc.topratemovies.R;
import com.raulh82vlc.topratemovies.models.Constants;
import com.raulh82vlc.topratemovies.models.FilmDetailsJSONEntity;
import com.raulh82vlc.topratemovies.models.FilmJSONEntity;
import com.raulh82vlc.topratemovies.widgets.CompatUtils;
import com.raulh82vlc.topratemovies.widgets.TransitionFlowAdapter;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Raul Hernandez Lopez on 22/02/2015.
 * CardView where the further details are filled
 */

public class CardFilmDetailsActivity extends BaseActivity implements View.OnClickListener {

    // constant
    private static final String TAG_DETAIL = "FilmDetails";

    @InjectView(R.id.imgExtended)
    ImageView imgExtended;
    @InjectView(R.id.txtTitle)
    TextView txtTitle;
    @InjectView(R.id.txtYear)
    TextView txtYear;
    @InjectView(R.id.txtMetaScore)
    TextView txtMetaScore;
    @InjectView(R.id.txtGenres)
    TextView txtGenres;
    @InjectView(R.id.txtPlot)
    TextView txtPlot;
    @InjectView(R.id.txtWriters)
    TextView txtWriters;
    @InjectView(R.id.txtDirectors)
    TextView txtDirectors;
    @InjectView(R.id.card_film_detail)
    CardView cardFilmDetail;
    @InjectView(R.id.toolbar_id)
    Toolbar mToolbar;
    @InjectView(R.id.scroll_id)
    ScrollView mScrollView;
    @InjectView(R.id.frame_layout)
    FrameLayout mFrameLayout;
    @InjectView(R.id.imgRetryCard)
    ImageButton imgRetryCard;

    // variable
    private int ranking = 0;
    private String mNameOfFilm = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        startAllTransitions();

        setContentView(R.layout.card_film_details_view);
        ActivityCompat.postponeEnterTransition(this);
        ButterKnife.inject(this);
        setSupportActionBar(mToolbar);
        ViewCompat.setTransitionName(imgExtended, Constants.A_NAME_IMG);

        if (getIntent().getExtras() != null) {
            Bundle extra = getIntent().getExtras();
            String nameOfFilm = extra.getString(Constants.A_NAME_FILM);
            setmNameOfFilm(nameOfFilm);
            ranking = extra.getInt(Constants.A_RANKING);
            // now start the transition
            ActivityCompat.startPostponedEnterTransition(this);
            if (isInternetConnectionAvailable()) {
                getTopRatedFilms(nameOfFilm);
            } else {
                seeToast(getString(R.string.try_again));
                imgRetryCard.setVisibility(View.VISIBLE);
                imgRetryCard.setOnClickListener(this);
            }
        }
    }

    /**
     * Method getTopRatedFilms
     * this does the getting from the network's API
     * then fills all corresponding model entities
     * and does the UI settings for providing the info corresponding
     * to each aspect of the film
     *
     * @param iFilmName
     */
    private void getTopRatedFilms(final String iFilmName) {
        getWebServicesApiCalls().getFilmsByName(iFilmName, new Callback<List<FilmDetailsJSONEntity>>() {
            @Override
            public void success(List<FilmDetailsJSONEntity> filmDetails, Response response) {
                if (filmDetails != null && filmDetails.size() > 0) {
                    // Getting the instance of the object from the array returned by the API

                    final FilmDetailsJSONEntity filmDetail = filmDetails.get(0);
                    if (filmDetail != null && !TextUtils.isEmpty(filmDetail.getTitle()) && !TextUtils.isEmpty(filmDetail.getUrlIMDB())) {
                        fillInfo(filmDetail);
                    } else {
                        seeToast(getString(R.string.error_server) + " " + iFilmName);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    /**
     * Method fillInfo
     * all written info is filled
     *
     * @param filmDetail
     */
    private void fillInfo(FilmDetailsJSONEntity filmDetail) {
        fillColors();
        /* Setting Film info for the card view */
        txtTitle.setText(filmDetail.getTitle());
        txtMetaScore.setText("Score: " + filmDetail.getMetascore());

        txtYear.setText("Year: " + filmDetail.getYear());
        txtPlot.setText(filmDetail.getPlot());
        /* Now the collections composed info */
        // Writers
        String aWriters = "Writers: ";
        aWriters += filmDetail.getToString(filmDetail.getWriters());
        txtWriters.setText(aWriters);
        // Genres
        txtGenres.setText(filmDetail.getToStringGenres());
        // Directors
        String aDirectors = "Directors: ";
        aDirectors += filmDetail.getToString(filmDetail.getDirectors());
        txtDirectors.setText(aDirectors);

        fillImage(filmDetail);
    }

    /**
     * Method fillColors
     * colors of each row are drawn
     * and the highlight effect of the score
     */
    private void fillColors() {
        // Setting color
        if (ranking % 2 == 1) {
            cardFilmDetail.setCardBackgroundColor(getResources().getColor(R.color.primary));
        } else {
            cardFilmDetail.setCardBackgroundColor(getResources().getColor(R.color.primary_dark));
        }
        txtMetaScore.setBackgroundColor(getResources().getColor(R.color.accent));
    }

    /**
     * Method fillInfo
     * all written info is filled
     *
     * @param filmDetail
     */
    private void fillImage(FilmDetailsJSONEntity filmDetail) {

        // Finally the image loaded by Universal Image Loader library
        final String titleOfFilm = filmDetail.getTitle();

        // Load image, decode it to Bitmap and return Bitmap to callback
        ImageLoader.getInstance().displayImage(filmDetail.getUrlPoster(), imgExtended, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                // Do whatever you want with Bitmap
                Palette.generateAsync(loadedImage, new Palette.PaletteAsyncListener() {
                    public void onGenerated(Palette palette) {
                        applyPalette(palette, titleOfFilm);
                    }
                });
            }
        });
    }

    /**
     * Method applyPalette
     * takes the principal colors and  set the toolbar
     * muted color as well as the fade in and starts to pospone the transaction
     *
     * @param iPalette    input palette
     * @param titleOfFilm
     */
    private void applyPalette(Palette iPalette, String titleOfFilm) {

        if (iPalette != null) {
            int primaryDark = getResources().getColor(R.color.primary_dark);
            int primary = getResources().getColor(R.color.primary);
            mToolbar.setBackgroundColor(iPalette.getMutedColor(primary));
            CompatUtils.setToolBarColor(getWindow(), iPalette.getDarkMutedColor(primaryDark));
            startScrollFadeIn(titleOfFilm);
            ActivityCompat.startPostponedEnterTransition(this);
        }
    }

    /**
     * Method startScrollFadeIn
     * starts the scroll setting the components
     * and adding the scroll listener when changing it
     *
     * @param titleOfFilm
     */
    private void startScrollFadeIn(final String titleOfFilm) {

        setComponentFeatures(titleOfFilm);

        mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                setComponentFeatures(titleOfFilm);
            }
        });
    }

    /**
     * Method setComponentFeatures
     * sets the dynamic translation in y-axis
     * when users moves the scroll
     * then calculates the alpha from the color
     * sets colors and the title in the tootbar
     *
     * @param titleOfFilm
     */
    private void setComponentFeatures(String titleOfFilm) {
        int scrollY = mScrollView.getScrollY();
        imgExtended.setTranslationY(-scrollY / 2);
        ColorDrawable background = (ColorDrawable) mToolbar.getBackground();
        int padding = mScrollView.getPaddingTop();
        double alphaColor = (1 - (((double) padding - (double) scrollY) / (double) padding)) * 255.0;
        alphaColor = alphaColor < 0 ? 0 : alphaColor;
        alphaColor = alphaColor > 255 ? 255 : alphaColor;

        background.setAlpha((int) alphaColor);
        mFrameLayout.setBackgroundColor(background.getColor());
        float scrollRatio = (float) (alphaColor / 255f);
        int titleColor = getItsAlphaColor(Color.WHITE, scrollRatio);
        mToolbar.setTitleTextColor(titleColor);
        mToolbar.setTitle(titleOfFilm);
    }

    /**
     * Method getItsAlphaColor
     * if API 21 then effects are settled
     *
     * @param iColor      alpha of a color
     * @param scrollRatio float variant
     */
    private int getItsAlphaColor(int iColor, float scrollRatio) {
        return Color.argb((int) (scrollRatio * 255f), Color.red(iColor), Color.green(iColor), Color.blue(iColor));
    }

    /**
     * Method startAllTransitions
     * if API 21 then effects are settled
     */
    private void startAllTransitions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Slide transition = new Slide();
            transition.excludeTarget(android.R.id.statusBarBackground, true);
            getWindow().setEnterTransition(transition);
            getWindow().setReturnTransition(transition);
        }
    }

    /**
     * Method startDetailsActivity
     * handles and launches the parameters to the Intent
     * with its corresponding transition
     *
     * @param context                 Activity which should be launched (own CardFilmDetailsActivity)
     * @param transitionFromPrevImage view
     * @param iFilm                   data structure which corresponds to the Film Entity itself
     */
    public static void startDetailsActivity(Activity context, View transitionFromPrevImage, FilmJSONEntity iFilm) {
        Intent aIntentDetails = new Intent(context, CardFilmDetailsActivity.class);
        aIntentDetails.putExtra(Constants.A_NAME_FILM, iFilm.getTitle());
        aIntentDetails.putExtra(Constants.A_NAME_IMG, iFilm.getUrlPoster());
        aIntentDetails.putExtra(Constants.A_RANKING, iFilm.getRanking());

        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(context, transitionFromPrevImage, Constants.A_NAME_IMG);
        ActivityCompat.startActivity(context, aIntentDetails, optionsCompat.toBundle());
    }

    @Override
    public void onBackPressed() {
        fallbackActionBar();
        super.onBackPressed();
    }

    /**
     * Method fallbackActionBar
     * restores the action bar when back pressed
     */
    private void fallbackActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mToolbar != null) {
                if (getWindow() != null
                        && getWindow().getReturnTransition() != null) {
                    getWindow().getReturnTransition().addListener(new TransitionFlowAdapter() {
                        @Override
                        public void onTransitionEnd(Transition transition) {
                            if (mToolbar != null) {
                                mToolbar.setTitleTextColor(Color.WHITE);
                                if (mToolbar.getBackground() != null)
                                    mToolbar.getBackground().setAlpha(255);
                            }
                        }
                    });
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.imgRetryCard:
                if(isInternetConnectionAvailable()) {
                    getTopRatedFilms(mNameOfFilm);
                    imgRetryCard.setVisibility(View.GONE);
                }
                else
                {
                    seeToast(getString(R.string.try_again));
                }
                break;
        }
    }

    public void setmNameOfFilm(String mNameOfFilm) {
        this.mNameOfFilm = mNameOfFilm;
    }
}


text:
'use strict';

// Declare app level module which depends on filters, and services
var pocket = angular.module('pocket', ['pocket.services', 'pocket.controllers', 'ui.state']);

pocket.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('index', {
      url: '/home',
      templateUrl: 'partials/list.html',
      controller: 'ArticleList'
    })
    .state('index.detail', {
      templateUrl: 'partials/detail.html',
      controller: 'ArticleDetail',
      params: ['url']
    })
    .state('callback', {
      url: 'callback',
      templateUrl: 'partials/callback.html'
    });

  $urlRouterProvider.otherwise('/home');

  //$locationProvider.html5Mode(true);
});


text:
package org.apiwatch.util.errors;

public class ParseError extends Exception {

    private static final long serialVersionUID = 1L;

    public ParseError() {
        super();
    }

    public ParseError(String message, Throwable cause) {
        super(message, cause);
    }

    public ParseError(String message) {
        super(message);
    }

    public ParseError(Throwable cause) {
        super(cause);
    }

}


text:
var config = {};

if(process.env.NODE_ENV === 'production'){
  //production
  config.DB = process.env.DATABASE_URL;

}else{
  //development
  config.DB = {
    host: 'db',
    port: 5432,
    database: 'postgres',
    user: 'postgres',
    password: ''
  };
}

module.exports = config;


text:
import clr
clr.AddReference("ChronosEngine")
clr.AddReference("OpenTK")
clr.AddReference("System.Drawing")


text:
package com.davidhagar.selectiveimagery;

import com.davidhagar.selectiveimagery.model.Project;
import com.davidhagar.selectiveimagery.ui.ProjectFrame;

/**
 * Hello world!
 *
 */
public class Main
{

	public static void main(String[] args)
	{
		java.awt.EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				Project p = new Project();
				p.setupInitalProject();

				new ProjectFrame(p).setVisible(true);
			}
		});

	}
}


text:
    <title>{{ escape(data['name']) }}</title>
    <meta charset="UTF-8">

    <link rel="stylesheet" href="./libs/jquery/css/base/jquery-ui.min.css" type="text/css"/>
    <link rel="stylesheet" href="./libs/jquery/css/bootstrap/jquery-ui.min.css" type="text/css"/>
    <link rel="stylesheet" href="./libs/zTreeStyle/zTreeStyle.css" type="text/css">
    <link rel="stylesheet" href="./libs/jqGrid/css/ui.jqgrid.css" type="text/css">
    <link rel="stylesheet" href="./libs/w2ui/css/w2ui-1.3.2.min.css" type="text/css">

    <link rel="stylesheet" href="./libs/umyproto/css/jquery-umy-ui-splitter.css" type="text/css">

                    <colgroup>
                        <col style="width: 33%;">
                        <col style="width: 33%;">
                        <col style="width: 33%;">
                    </colgroup>

                                Наименование: {{ escape(data["name"]) }} Код: {{ escape(data["code"]) }}

                                Медиана 2014:   , Медиана 2015: {{ escape(str(data["price_med15"])) }}

                                Основные единицы измерения 2014:  , Основные единицы измерения 2015:  {{ escape(data["unit_mod15"]) }}

                                Выбросы по единицам измерения:

                                    {% for item in data["mod_outliers"] %}

 СМ. {{ escape(item['link'])}} - Единица измерения {{ escape(item['OKEI_name']) }}

                                    {% end%}

                                Выбросы по значениям:

                                    {% for item in data["med_outliers"] %}

 СМ. {{ escape(item['link'])}} - Цена {{ escape(item['product_price'])}}

                                    {% end%}


text:
name "m4"
default_version "1.4.17"

source url: "http://ftp.gnu.org/gnu/m4/m4-#{version}.tar.gz",
       md5: "efb2d7c7e22840947863efaedc175747"

relative_path "m4-#{version}"

build do
  env = with_standard_compiler_flags(with_embedded_path)

  command "./configure --prefix=#{install_dir}/embedded", env: env

  make "-j #{workers}", env: env
  make "-j #{workers} install", env: env
end


text:
"""Decoding functions using multiple attentions for RNN decoders.

See http://arxiv.org/abs/1606.07481

The attention mechanisms used in Neural Monkey are inherited from the
``BaseAttention`` class defined in this module.

Each attention object has the ``attention`` function which operates on the
``attention_states`` tensor.  The attention function receives the query tensor,
the decoder previous state and input, and its inner state, which could bear an
arbitrary structure of information. The default structure for this is the
``AttentionLoopStateTA``, which contains a growing array of attention
distributions and context vectors in time. That's why there is the
``initial_loop_state`` function in the ``BaseAttention`` class.

Mainly for illustration purposes, the attention objects can keep their
*histories*, which is a dictionary populated with attention distributions in
time for every decoder, that used this attention object. This is because for
example the recurrent decoder is can be run twice for each sentence - once in
the *training* mode, in which the decoder gets the reference tokens on the
input, and once in the *running* mode, in which it gets its own outputs. The
histories object is constructed *after* the decoding and its construction
should be triggered manually from the decoder by calling the ``finalize_loop``
method.
"""
from typing import NamedTuple, Dict, Optional, Any, Tuple, Union

import tensorflow as tf

from neuralmonkey.model.stateful import TemporalStateful, SpatialStateful
from neuralmonkey.model.model_part import ModelPart, FeedDict, InitializerSpecs
from neuralmonkey.dataset import Dataset

# pylint: disable=invalid-name
Attendable = Union[TemporalStateful, SpatialStateful]
AttentionLoopStateTA = NamedTuple("AttentionLoopStateTA",
                                  [("contexts", tf.TensorArray),
                                   ("weights", tf.TensorArray)])
# pylint: enable=invalid-name

def empty_attention_loop_state() -> AttentionLoopStateTA:
    """Create an empty attention loop state.

    The attention loop state is a technical object for storing the attention
    distributions and the context vectors in time. It is used with the
    ``tf.while_loop`` dynamic implementation of the decoder.

    This function returns an empty attention loop state which means there are
    two empty arrays, one for attention distributions in time, and one for
    the attention context vectors in time.
    """
    return AttentionLoopStateTA(
        contexts=tf.TensorArray(
            dtype=tf.float32, size=0, dynamic_size=True,
            name="contexts"),
        weights=tf.TensorArray(
            dtype=tf.float32, size=0, dynamic_size=True,
            name="distributions", clear_after_read=False))

def get_attention_states(encoder: Attendable) -> tf.Tensor:
    if isinstance(encoder, TemporalStateful):
        return encoder.temporal_states

    elif isinstance(encoder, SpatialStateful):
        # pylint: disable=no-member
        shape = encoder.spatial_states.get_shape().as_list()
        # pylint: enable=no-member
        return tf.reshape(encoder.spatial_states,
                          [-1, shape[1] * shape[2], shape[3]])
    else:
        raise AssertionError("Unknown encoder type")

def get_attention_mask(encoder: Attendable) -> Optional[tf.Tensor]:
    if isinstance(encoder, TemporalStateful):
        if encoder.temporal_mask is None:
            raise ValueError("The encoder temporal mask should not be none")
        return encoder.temporal_mask

    elif isinstance(encoder, SpatialStateful):
        if encoder.spatial_mask is None:
            return None

        # pylint: disable=no-member
        shape = encoder.spatial_states.get_shape().as_list()
        # pylint: enable=no-member
        return tf.reshape(encoder.spatial_mask, [-1, shape[1] * shape[2]])
    else:
        raise AssertionError("Unknown encoder type")

class BaseAttention(ModelPart):
    def __init__(self,
                 name: str,
                 save_checkpoint: str = None,
                 load_checkpoint: str = None,
                 initializers: InitializerSpecs = None) -> None:
        ModelPart.__init__(self, name, save_checkpoint, load_checkpoint,
                           initializers)

        self.query_state_size = None  # type: tf.Tensor
        self._histories = {}  # type: Dict[str, tf.Tensor]

        with self.use_scope():
            self.train_mode = tf.placeholder(tf.bool, [], "train_mode")

    @property
    def histories(self) -> Dict[str, tf.Tensor]:
        return self._histories

    def attention(self,
                  query: tf.Tensor,
                  decoder_prev_state: tf.Tensor,
                  decoder_input: tf.Tensor,
                  loop_state: Any,
                  step: tf.Tensor) -> Tuple[tf.Tensor, Any]:
        """Get context vector for a given query."""
        raise NotImplementedError("Abstract method")

    def initial_loop_state(self) -> Any:
        """Get initial loop state for the attention object."""
        raise NotImplementedError("Abstract method")

    def finalize_loop(self, key: str, last_loop_state: Any) -> None:
        raise NotImplementedError("Abstract method")

    def feed_dict(self, dataset: Dataset, train: bool = False) -> FeedDict:
        return {self.train_mode: train}

    @property
    def context_vector_size(self) -> int:
        raise NotImplementedError("Abstract property")

    def visualize_attention(self, key: str) -> None:
        if key not in self.histories:
            raise ValueError(
                "Key {} not among attention histories".format(key))

        alignments = tf.expand_dims(
            tf.transpose(self.histories[key], perm=[1, 2, 0]), -1)

        tf.summary.image(self.name, alignments,
                         collections=["summary_att_plots"], max_outputs=256)