text:
This example shows how to use Ladybug's sunpath and sunlightHours analysis to identify which part of the buildings around Central Park needs to be removed so the park can see more than 4 hours of sunlight on Dec. 21st. Building geometries are generated using @it pluging for Grasshopper.

This file has been submitted by [mostaphaRoudsari](https://github.com/mostaphaRoudsari)

[Check out this example on Hydra!](http://hydrashare.github.io/hydra/viewer?owner=mostaphaRoudsari&fork=hydra_1&id=Central_Park_Shadow_Study)
### Tags
Grasshopper, Ladybug, Central Park, Shadow, Minimum sunlight, OpenData, @it
### Thumbnail
![Screenshot](https://raw.githubusercontent.com/mostaphaRoudsari/hydra/master/Central_Park_Shadow_Study/thumbnail.png)


text:
package ch.qos.logback.classic.turbo;

import org.slf4j.Marker;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.spi.LifeCycle;

/**
 * TurboFilter is a specialized filter with a decide method that takes a bunch
 * of parameters instead of a single event object. The latter is cleaner but
 * the first is much more performant.
 *

 * For more information about turbo filters, please refer to the online manual at
 * http://logback.qos.ch/manual/filters.html#TurboFilter
 *
 * @author Ceki Gulcu
 */
public abstract class TurboFilter extends ContextAwareBase implements LifeCycle {

    private String name;
    boolean start = false;

    /**
     * Make a decision based on the multiple parameters passed as arguments.
     * The returned value should be one of {@link FilterReply#DENY},
     * {@link FilterReply#NEUTRAL}, or {@link FilterReply#ACCEPT}.

     * @param marker
     * @param logger
     * @param level
     * @param format
     * @param params
     * @param t
     * @return
     */
    public abstract FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t);

    public void start() {
        this.start = true;
    }

    public boolean isStarted() {
        return this.start;
    }

    public void stop() {
        this.start = false;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

redpajama_set_name: RedPajamaGithub


text:
const express = require('express');
const router = express.Router();
const { Student, Course, Checkin } = require('../server/models')

router.get('/:id/checkins', (req, res) => {
  Checkin.findAll({
    where: {
      courseId: req.params.id
    }
  }).then(arr => res.send(arr))
})

router.get('/:id', (req, res) => {
  Course.findAll({
    where: {
      id: req.params.id
    }
  }).then(arr => res.send(arr))
})

router.get('/', (req, res) => {
  Course.findAll().then(arr => res.send(arr))
})

module.exports = router;


text:
class Shpotify < Formula
  desc "Command-line interface for Spotify on a Mac"
  homepage "https://harishnarayanan.org/projects/shpotify/"
  url "https://github.com/hnarayanan/shpotify/archive/2.1.tar.gz"
  sha256 "b41d8798687be250d0306ac0c5a79420fa46619c5954286711a5d63c86a6c071"
  license "MIT"
  head "https://github.com/hnarayanan/shpotify.git"

  def install
    bin.install "spotify"
  end

  test do
    system "#{bin}/spotify"
  end
end


text:
package com.hazelcast.map.impl.operation;

import com.hazelcast.map.impl.MapDataSerializerHook;
import com.hazelcast.monitor.impl.LocalMapStatsImpl;
import com.hazelcast.spi.PartitionAwareOperation;
import com.hazelcast.spi.ReadonlyOperation;

public class MapIsEmptyOperation extends MapOperation implements PartitionAwareOperation, ReadonlyOperation {

    private boolean empty;

    public MapIsEmptyOperation(String name) {
        super(name);
    }

    public MapIsEmptyOperation() {
    }

    public void run() {
        empty = recordStore.isEmpty();
        if (mapContainer.getMapConfig().isStatisticsEnabled()) {
            LocalMapStatsImpl localMapStatsImpl = mapServiceContext.getLocalMapStatsProvider()
                    .getLocalMapStatsImpl(name);
            localMapStatsImpl.incrementOtherOperations();
        }
    }

    @Override
    public Object getResponse() {
        return empty;
    }

    @Override
    public int getId() {
        return MapDataSerializerHook.IS_EMPTY;
    }
}


text:
"""
Wraps multiple ways to communicate over SSH.
"""

from typing import Type
from typing import Optional
from typing import Tuple
from typing import List
from typing import Union
from typing import cast

have_paramiko = False

try:
    import paramiko

    have_paramiko = True
except ImportError:
    pass

# Depending on your version of Paramiko, it may cause a deprecation
# warning on Python 2.6.
# Ref: https://bugs.launchpad.net/paramiko/+bug/392973

import os
import re
import time
import subprocess
import logging
import warnings

from os.path import split as psplit
from os.path import join as pjoin

from libcloud.utils.logging import ExtraLogFormatter
from libcloud.utils.py3 import StringIO
from libcloud.utils.py3 import b

__all__ = [
    "BaseSSHClient",
    "ParamikoSSHClient",
    "ShellOutSSHClient",
    "SSHCommandTimeoutError",
]

SUPPORTED_KEY_TYPES_URL = "https://libcloud.readthedocs.io/en/latest/compute/deployment.html#supported-private-ssh-key-types"  # NOQA

class SSHCommandTimeoutError(Exception):
    """
    Exception which is raised when an SSH command times out.
    """

    def __init__(self, cmd, timeout, stdout=None, stderr=None):
        # type: (str, float, Optional[str], Optional[str]) -> None
        self.cmd = cmd
        self.timeout = timeout
        self.stdout = stdout
        self.stderr = stderr

        self.message = "Command didn't finish in %s seconds" % (timeout)
        super(SSHCommandTimeoutError, self).__init__(self.message)

    def __repr__(self):
        return '<SSHCommandTimeoutError: cmd="%s",timeout=%s)>' % (
            self.cmd,
            self.timeout,
        )

    def __str__(self):
        return self.__repr__()

class BaseSSHClient(object):
    """
    Base class representing a connection over SSH/SCP to a remote node.
    """

    def __init__(
        self,
        hostname,  # type: str
        port=22,  # type: int
        username="root",  # type: str
        password=None,  # type: Optional[str]
        key=None,  # type: Optional[str]
        key_files=None,  # type: Optional[Union[str, List[str]]]
        timeout=None,  # type: Optional[float]
    ):
        """
        :type hostname: ``str``
        :keyword hostname: Hostname or IP address to connect to.

        :type port: ``int``
        :keyword port: TCP port to communicate on, defaults to 22.

        :type username: ``str``
        :keyword username: Username to use, defaults to root.

        :type password: ``str``
        :keyword password: Password to authenticate with or a password used
                           to unlock a private key if a password protected key
                           is used.

        :param key: Deprecated in favor of ``key_files`` argument.

        :type key_files: ``str`` or ``list``
        :keyword key_files: A list of paths to the private key files to use.
        """
        if key is not None:
            message = (
                'You are using deprecated "key" argument which has '
                'been replaced with "key_files" argument'
            )
            warnings.warn(message, DeprecationWarning)

            # key_files has precedent
            key_files = key if not key_files else key_files

        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = password
        self.key_files = key_files
        self.timeout = timeout

    def connect(self):
        # type: () -> bool
        """
        Connect to the remote node over SSH.

        :return: True if the connection has been successfully established,
                 False otherwise.
        :rtype: ``bool``
        """
        raise NotImplementedError("connect not implemented for this ssh client")

    def put(self, path, contents=None, chmod=None, mode="w"):
        # type: (str, Optional[Union[str, bytes]], Optional[int], str) -> str
        """
        Upload a file to the remote node.

        :type path: ``str``
        :keyword path: File path on the remote node.

        :type contents: ``str``
        :keyword contents: File Contents.

        :type chmod: ``int``
        :keyword chmod: chmod file to this after creation.

        :type mode: ``str``
        :keyword mode: Mode in which the file is opened.

        :return: Full path to the location where a file has been saved.
        :rtype: ``str``
        """
        raise NotImplementedError("put not implemented for this ssh client")

    def putfo(self, path, fo=None, chmod=None):
        """
        Upload file like object to the remote server.

        :param path: Path to upload the file to.
        :type path: ``str``

        :param fo: File like object to read the content from.
        :type fo: File handle or file like object.

        :type chmod: ``int``
        :keyword chmod: chmod file to this after creation.

        :return: Full path to the location where a file has been saved.
        :rtype: ``str``
        """
        raise NotImplementedError("putfo not implemented for this ssh client")

    def delete(self, path):
        # type: (str) -> bool
        """
        Delete/Unlink a file on the remote node.

        :type path: ``str``
        :keyword path: File path on the remote node.

        :return: True if the file has been successfully deleted, False
                 otherwise.
        :rtype: ``bool``
        """
        raise NotImplementedError("delete not implemented for this ssh client")

    def run(self, cmd, timeout=None):
        # type: (str, Optional[float]) -> Tuple[str, str, int]
        """
        Run a command on a remote node.

        :type cmd: ``str``
        :keyword cmd: Command to run.

        :return ``list`` of [stdout, stderr, exit_status]
        """
        raise NotImplementedError("run not implemented for this ssh client")

    def close(self):
        # type: () -> bool
        """
        Shutdown connection to the remote node.

        :return: True if the connection has been successfully closed, False
                 otherwise.
        :rtype: ``bool``
        """
        raise NotImplementedError("close not implemented for this ssh client")

    def _get_and_setup_logger(self):
        # type: () -> logging.Logger
        logger = logging.getLogger("libcloud.compute.ssh")
        path = os.getenv("LIBCLOUD_DEBUG")

        if path:
            handler = logging.FileHandler(path)
            handler.setFormatter(ExtraLogFormatter())
            logger.addHandler(handler)
            logger.setLevel(logging.DEBUG)

        return logger

class ParamikoSSHClient(BaseSSHClient):
    """
    A SSH Client powered by Paramiko.
    """

    # Maximum number of bytes to read at once from a socket
    CHUNK_SIZE = 4096

    # How long to sleep while waiting for command to finish (to prevent busy
    # waiting)
    SLEEP_DELAY = 0.2

    def __init__(
        self,
        hostname,  # type: str
        port=22,  # type: int
        username="root",  # type: str
        password=None,  # type: Optional[str]
        key=None,  # type: Optional[str]
        key_files=None,  # type: Optional[Union[str, List[str]]]
        key_material=None,  # type: Optional[str]
        timeout=None,  # type: Optional[float]
        keep_alive=None,  # type: Optional[int]
        use_compression=False,  # type: bool
    ):
        """
        Authentication is always attempted in the following order:

        - The key passed in (if key is provided)
        - Any key we can find through an SSH agent (only if no password and
          key is provided)
        - Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (only if no
          password and key is provided)
        - Plain username/password auth, if a password was given (if password is
          provided)

        :param keep_alive: Optional keep alive internal (in seconds) to use.
        :type keep_alive: ``int``

        :param use_compression: True to use compression.
        :type use_compression: ``bool``
        """
        if key_files and key_material:
            raise ValueError(
                ("key_files and key_material arguments are " "mutually exclusive")
            )

        super(ParamikoSSHClient, self).__init__(
            hostname=hostname,
            port=port,
            username=username,
            password=password,
            key=key,
            key_files=key_files,
            timeout=timeout,
        )

        self.key_material = key_material
        self.keep_alive = keep_alive
        self.use_compression = use_compression

        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.logger = self._get_and_setup_logger()

        # This object is lazily created on first SFTP operation (e.g. put()
        # method call)
        self.sftp_client = None

    def connect(self):
        conninfo = {
            "hostname": self.hostname,
            "port": self.port,
            "username": self.username,
            "allow_agent": False,
            "look_for_keys": False,
        }

        if self.password:
            conninfo["password"] = self.password

        if self.key_files:
            conninfo["key_filename"] = self.key_files

        if self.key_material:
            conninfo["pkey"] = self._get_pkey_object(
                key=self.key_material, password=self.password
            )

        if not self.password and not (self.key_files or self.key_material):
            conninfo["allow_agent"] = True
            conninfo["look_for_keys"] = True

        if self.timeout:
            conninfo["timeout"] = self.timeout

        # This is a workaround for paramiko only supporting key files in
        # format staring with "BEGIN RSA PRIVATE KEY".
        # If key_files are provided and a key looks like a PEM formatted key
        # we try to convert it into a format supported by paramiko
        if (
            self.key_files
            and not isinstance(self.key_files, (list, tuple))
            and os.path.isfile(self.key_files)
        ):
            with open(self.key_files, "r") as fp:
                key_material = fp.read()

            try:
                pkey = self._get_pkey_object(key=key_material, password=self.password)
            except paramiko.ssh_exception.PasswordRequiredException as e:
                raise e
            except Exception:
                pass
            else:
                # It appears key is valid, but it was passed in in an invalid
                # format. Try to use the converted key directly
                del conninfo["key_filename"]
                conninfo["pkey"] = pkey

        extra = {
            "_hostname": self.hostname,
            "_port": self.port,
            "_username": self.username,
            "_timeout": self.timeout,
        }

        if self.password:
            extra["_auth_method"] = "password"
        else:
            extra["_auth_method"] = "key_file"

            if self.key_files:
                extra["_key_file"] = self.key_files

        self.logger.debug("Connecting to server", extra=extra)

        self.client.connect(**conninfo)
        return True

    def put(self, path, contents=None, chmod=None, mode="w"):
        extra = {"_path": path, "_mode": mode, "_chmod": chmod}
        self.logger.debug("Uploading file", extra=extra)

        sftp = self._get_sftp_client()

        # less than ideal, but we need to mkdir stuff otherwise file() fails
        head, tail = psplit(path)

        if path[0] == "/":
            sftp.chdir("/")
        else:
            # Relative path - start from a home directory (~)
            sftp.chdir(".")

        for part in head.split("/"):
            if part != "":
                try:
                    sftp.mkdir(part)
                except IOError:
                    # so, there doesn't seem to be a way to
                    # catch EEXIST consistently *sigh*
                    pass
                sftp.chdir(part)

        cwd = sftp.getcwd()
        cwd = self._sanitize_cwd(cwd=cwd)

        ak = sftp.file(tail, mode=mode)
        ak.write(contents)
        if chmod is not None:
            ak.chmod(chmod)
        ak.close()

        file_path = self._sanitize_file_path(cwd=cwd, file_path=path)
        return file_path

    def putfo(self, path, fo=None, chmod=None):
        """
        Upload file like object to the remote server.

        Unlike put(), this method operates on file objects and not directly on
        file content which makes it much more efficient for large files since
        it utilizes pipelining.
        """
        extra = {"_path": path, "_chmod": chmod}
        self.logger.debug("Uploading file", extra=extra)

        sftp = self._get_sftp_client()

        # less than ideal, but we need to mkdir stuff otherwise file() fails
        head, tail = psplit(path)

        if path[0] == "/":
            sftp.chdir("/")
        else:
            # Relative path - start from a home directory (~)
            sftp.chdir(".")

        for part in head.split("/"):
            if part != "":
                try:
                    sftp.mkdir(part)
                except IOError:
                    # so, there doesn't seem to be a way to
                    # catch EEXIST consistently *sigh*
                    pass
                sftp.chdir(part)

        cwd = sftp.getcwd()
        cwd = self._sanitize_cwd(cwd=cwd)

        sftp.putfo(fo, path)
        if chmod is not None:
            ak = sftp.file(tail)
            ak.chmod(chmod)
            ak.close()

        file_path = self._sanitize_file_path(cwd=cwd, file_path=path)
        return file_path

    def delete(self, path):
        extra = {"_path": path}
        self.logger.debug("Deleting file", extra=extra)

        sftp = self.client.open_sftp()
        sftp.unlink(path)
        sftp.close()
        return True

    def run(self, cmd, timeout=None):
        # type: (str, Optional[float]) -> Tuple[str, str, int]
        """
        Note: This function is based on paramiko's exec_command()
        method.

        :param timeout: How long to wait (in seconds) for the command to
                        finish (optional).
        :type timeout: ``float``
        """
        extra1 = {"_cmd": cmd}
        self.logger.debug("Executing command", extra=extra1)

        # Use the system default buffer size
        bufsize = -1

        transport = self._get_transport()

        chan = transport.open_session()

        start_time = time.time()
        chan.exec_command(cmd)

        stdout = StringIO()
        stderr = StringIO()

        # Create a stdin file and immediately close it to prevent any
        # interactive script from hanging the process.
        stdin = chan.makefile("wb", bufsize)
        stdin.close()

        # Receive all the output
        # Note #1: This is used instead of chan.makefile approach to prevent
        # buffering issues and hanging if the executed command produces a lot
        # of output.
        #
        # Note #2: If you are going to remove "ready" checks inside the loop
        # you are going to have a bad time. Trying to consume from a channel
        # which is not ready will block for indefinitely.
        exit_status_ready = chan.exit_status_ready()

        if exit_status_ready:
            # It's possible that some data is already available when exit
            # status is ready
            stdout.write(self._consume_stdout(chan).getvalue())
            stderr.write(self._consume_stderr(chan).getvalue())

        while not exit_status_ready:
            current_time = time.time()
            elapsed_time = current_time - start_time

            if timeout and (elapsed_time > timeout):
                # TODO: Is this the right way to clean up?
                chan.close()

                stdout_str = stdout.getvalue()  # type: str
                stderr_str = stderr.getvalue()  # type: str
                raise SSHCommandTimeoutError(
                    cmd=cmd, timeout=timeout, stdout=stdout_str, stderr=stderr_str
                )

            stdout.write(self._consume_stdout(chan).getvalue())
            stderr.write(self._consume_stderr(chan).getvalue())

            # We need to check the exist status here, because the command could
            # print some output and exit during this sleep below.
            exit_status_ready = chan.exit_status_ready()

            if exit_status_ready:
                break

            # Short sleep to prevent busy waiting
            time.sleep(self.SLEEP_DELAY)

        # Receive the exit status code of the command we ran.
        status = chan.recv_exit_status()  # type: int

        stdout_str = stdout.getvalue()
        stderr_str = stderr.getvalue()

        extra2 = {"_status": status, "_stdout": stdout_str, "_stderr": stderr_str}
        self.logger.debug("Command finished", extra=extra2)

        result = (stdout_str, stderr_str, status)  # type: Tuple[str, str, int]
        return result

    def close(self):
        self.logger.debug("Closing server connection")

        if self.client:
            self.client.close()

        if self.sftp_client:
            self.sftp_client.close()

        return True

    def _consume_stdout(self, chan):
        """
        Try to consume stdout data from chan if it's receive ready.
        """
        stdout = self._consume_data_from_channel(
            chan=chan, recv_method=chan.recv, recv_ready_method=chan.recv_ready
        )
        return stdout

    def _consume_stderr(self, chan):
        """
        Try to consume stderr data from chan if it's receive ready.
        """
        stderr = self._consume_data_from_channel(
            chan=chan,
            recv_method=chan.recv_stderr,
            recv_ready_method=chan.recv_stderr_ready,
        )
        return stderr

    def _consume_data_from_channel(self, chan, recv_method, recv_ready_method):
        """
        Try to consume data from the provided channel.

        Keep in mind that data is only consumed if the channel is receive
        ready.
        """
        result = StringIO()
        result_bytes = bytearray()

        if recv_ready_method():
            data = recv_method(self.CHUNK_SIZE)
            result_bytes += b(data)

            while data:
                ready = recv_ready_method()

                if not ready:
                    break

                data = recv_method(self.CHUNK_SIZE)
                result_bytes += b(data)

        # We only decode data at the end because a single chunk could contain
        # a part of multi byte UTF-8 character (whole multi bytes character
        # could be split over two chunks)
        result.write(result_bytes.decode("utf-8", errors="ignore"))
        return result

    def _get_pkey_object(self, key, password=None):
        """
        Try to detect private key type and return paramiko.PKey object.

        # NOTE: Paramiko only supports key in PKCS#1 PEM format.
        """
        key_types = [
            (paramiko.RSAKey, "RSA"),
            (paramiko.DSSKey, "DSA"),
            (paramiko.ECDSAKey, "EC"),
        ]

        paramiko_version = getattr(paramiko, "__version__", "0.0.0")
        paramiko_version = tuple([int(c) for c in paramiko_version.split(".")])

        if paramiko_version >= (2, 2, 0):
            # Ed25519 is only supported in paramiko >= 2.2.0
            key_types.append((paramiko.ed25519key.Ed25519Key, "Ed25519"))

        for cls, key_type in key_types:
            # Work around for paramiko not recognizing keys which start with
            # "----BEGIN PRIVATE KEY-----"
            # Since key is already in PEM format, we just try changing the
            # header and footer
            key_split = key.strip().splitlines()
            if (
                key_split[0] == "-----BEGIN PRIVATE KEY-----"
                and key_split[-1] == "-----END PRIVATE KEY-----"
            ):
                key_split[0] = "-----BEGIN %s PRIVATE KEY-----" % (key_type)
                key_split[-1] = "-----END %s PRIVATE KEY-----" % (key_type)

                key_value = "\n".join(key_split)
            else:
                # Already a valid key, us it as is
                key_value = key

            try:
                key = cls.from_private_key(StringIO(key_value), password)
            except paramiko.ssh_exception.PasswordRequiredException as e:
                raise e
            except (paramiko.ssh_exception.SSHException, AssertionError) as e:
                if "private key file checkints do not match" in str(e).lower():
                    msg = (
                        "Invalid password provided for encrypted key. "
                        "Original error: %s" % (str(e))
                    )
                    # Indicates invalid password for password protected keys
                    raise paramiko.ssh_exception.SSHException(msg)

                # Invalid key, try other key type
                pass
            else:
                return key

        msg = (
            "Invalid or unsupported key type (only RSA, DSS, ECDSA and"
            " Ed25519 keys"
            " in PEM format are supported). For more information on "
            " supported key file types, see %s" % (SUPPORTED_KEY_TYPES_URL)
        )
        raise paramiko.ssh_exception.SSHException(msg)

    def _sanitize_cwd(self, cwd):
        # type: (str) -> str
        # getcwd() returns an invalid path when executing commands on Windows
        # so we need a special case for that scenario
        # For example, we convert /C:/Users/Foo -> C:/Users/Foo
        if re.match(r"^\/\w\:.*$", str(cwd)):
            cwd = str(cwd[1:])

        return cwd

    def _sanitize_file_path(self, cwd, file_path):
        # type: (str, str) -> str
        """
        Sanitize the provided file path and ensure we always return an
        absolute path, even if relative path is passed to to this function.
        """

        if file_path[0] in ["/", "\\"] or re.match(r"^\w\:.*$", file_path):
            # If it's an absolute path we return path as is
            # NOTE: We assume it's a Windows absolute path if it's starts with
            # a drive letter - e.g. C:\\..., D:\\, etc. or with \
            pass
        else:
            if re.match(r"^\w\:.*$", cwd):
                # Windows path
                file_path = cwd + "\\" + file_path
            else:
                file_path = pjoin(cwd, file_path)

        return file_path

    def _get_transport(self):
        """
        Return transport object taking into account keep alive and compression
        options passed to the constructor.
        """
        transport = self.client.get_transport()

        if self.keep_alive:
            transport.set_keepalive(self.keep_alive)

        if self.use_compression:
            transport.use_compression(compress=True)

        return transport

    def _get_sftp_client(self):
        """
        Create SFTP client from the underlying SSH client.

        This method tries to re-use the existing self.sftp_client (if it
        exists) and it also tries to verify the connection is opened and if
        it's not, it will try to re-establish it.
        """
        if not self.sftp_client:
            self.sftp_client = self.client.open_sftp()

        sftp_client = self.sftp_client

        # Verify the connection is still open, if it's not, try to
        # re-establish it.
        # We do that, by calling listdir(). If it returns "Socket is closed"
        # error we assume the connection is closed and we try to re-establish
        # it.
        try:
            sftp_client.listdir(".")
        except OSError as e:
            if "socket is closed" in str(e).lower():
                self.sftp_client = self.client.open_sftp()
            elif "no such file" in str(e).lower():
                # Not a fatal exception, means connection is still open
                pass
            else:
                raise e

        return self.sftp_client

class ShellOutSSHClient(BaseSSHClient):
    """
    This client shells out to "ssh" binary to run commands on the remote
    server.

    Note: This client should not be used in production.
    """

    def __init__(
        self,
        hostname,  # type: str
        port=22,  # type: int
        username="root",  # type: str
        password=None,  # type: Optional[str]
        key=None,  # type: Optional[str]
        key_files=None,  # type: Optional[str]
        timeout=None,  # type: Optional[float]
    ):
        super(ShellOutSSHClient, self).__init__(
            hostname=hostname,
            port=port,
            username=username,
            password=password,
            key=key,
            key_files=key_files,
            timeout=timeout,
        )
        if self.password:
            raise ValueError("ShellOutSSHClient only supports key auth")

        child = subprocess.Popen(
            ["ssh"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        child.communicate()

        if child.returncode == 127:
            raise ValueError("ssh client is not available")

        self.logger = self._get_and_setup_logger()

    def connect(self):
        """
        This client doesn't support persistent connections establish a new
        connection every time "run" method is called.
        """
        return True

    def run(self, cmd, timeout=None):
        return self._run_remote_shell_command([cmd])

    def put(self, path, contents=None, chmod=None, mode="w"):
        if mode == "w":
            redirect = ">"
        elif mode == "a":
            redirect = ">>"
        else:
            raise ValueError("Invalid mode: " + mode)

        cmd = ['echo "%s" %s %s' % (contents, redirect, path)]
        self._run_remote_shell_command(cmd)
        return path

    def putfo(self, path, fo=None, chmod=None):
        content = fo.read()
        return self.put(path=path, contents=content, chmod=chmod)

    def delete(self, path):
        cmd = ["rm", "-rf", path]
        self._run_remote_shell_command(cmd)
        return True

    def close(self):
        return True

    def _get_base_ssh_command(self):
        # type: () -> List[str]
        cmd = ["ssh"]

        if self.key_files:
            self.key_files = cast(str, self.key_files)
            cmd += ["-i", self.key_files]

        if self.timeout:
            cmd += ["-oConnectTimeout=%s" % (self.timeout)]

        cmd += ["%s@%s" % (self.username, self.hostname)]

        return cmd

    def _run_remote_shell_command(self, cmd):
        # type: (List[str]) -> Tuple[str, str, int]
        """
        Run a command on a remote server.

        :param      cmd: Command to run.
        :type       cmd: ``list`` of ``str``

        :return: Command stdout, stderr and status code.
        :rtype: ``tuple``
        """
        base_cmd = self._get_base_ssh_command()
        full_cmd = base_cmd + [" ".join(cmd)]

        self.logger.debug('Executing command: "%s"' % (" ".join(full_cmd)))

        child = subprocess.Popen(
            full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        stdout, stderr = child.communicate()

        stdout_str = cast(str, stdout)
        stderr_str = cast(str, stdout)

        return (stdout_str, stderr_str, child.returncode)

class MockSSHClient(BaseSSHClient):
    pass

SSHClient = ParamikoSSHClient  # type: Type[BaseSSHClient]
if not have_paramiko:
    SSHClient = MockSSHClient  # type: ignore


text:
Opening Ports for Kaltura
===========

There are different ways to open ports, I will focus on a particular way I like, and works the best for me.

**Opening ports on Centos 6.5 using the console / terminal**

Open `/etc/sysconfig/iptables` using vi or nano.

Edit this file to have something equal this:
(where the lines between line breaks are the new lines added.)

```
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 25 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 2049 -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 2049 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 111 -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 111 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 9312 -j ACCEPT

-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
```

Now restart the service:

```
service iptables restart
```

**IMPORTANT NOTE:** This setup is to install all-in-one kaltura on a single server, if you would use a cluster installation, you can configure each firewall with the relevant ports for each server.


text:
package com.hp.ov.sdk.rest.reflect;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.apache.commons.lang3.StringUtils;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface QueryParam {

    String key() default StringUtils.EMPTY;

}


text:
package com.google.gerrit.client.reviewdb;

import com.google.gwtorm.client.Access;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.PrimaryKey;
import com.google.gwtorm.client.Query;
import com.google.gwtorm.client.ResultSet;

public interface AccountExternalIdAccess extends
    Access<AccountExternalId, AccountExternalId.Key> {
  @PrimaryKey("key")
  AccountExternalId get(AccountExternalId.Key key) throws OrmException;

  @Query("WHERE accountId = ?")
  ResultSet<AccountExternalId> byAccount(Account.Id id) throws OrmException;

  @Query("WHERE accountId = ? AND emailAddress = ?")
  ResultSet<AccountExternalId> byAccountEmail(Account.Id id, String email)
      throws OrmException;

  @Query("WHERE emailAddress = ?")
  ResultSet<AccountExternalId> byEmailAddress(String email) throws OrmException;

  @Query("WHERE emailAddress >= ? AND emailAddress <= ? ORDER BY emailAddress LIMIT ?")
  ResultSet<AccountExternalId> suggestByEmailAddress(String emailA,
      String emailB, int limit) throws OrmException;
}


text:
package org.apache.wiki.auth;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.wiki.api.core.Engine;
import org.apache.wiki.api.core.Session;
import org.apache.wiki.api.exceptions.WikiException;
import org.apache.wiki.api.spi.Wiki;
import org.apache.wiki.auth.authorize.WebAuthorizer;
import org.apache.wiki.auth.authorize.WebContainerAuthorizer;
import org.apache.wiki.auth.login.AnonymousLoginModule;
import org.apache.wiki.auth.login.CookieAssertionLoginModule;
import org.apache.wiki.auth.login.CookieAuthenticationLoginModule;
import org.apache.wiki.auth.login.UserDatabaseLoginModule;
import org.apache.wiki.auth.login.WebContainerCallbackHandler;
import org.apache.wiki.auth.login.WebContainerLoginModule;
import org.apache.wiki.auth.login.WikiCallbackHandler;
import org.apache.wiki.event.WikiEventListener;
import org.apache.wiki.event.WikiEventManager;
import org.apache.wiki.event.WikiSecurityEvent;
import org.apache.wiki.util.ClassUtil;
import org.apache.wiki.util.TextUtil;
import org.apache.wiki.util.TimedCounterList;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Default implementation for {@link AuthenticationManager}
 *
 * {@inheritDoc}
 *
 * @since 2.3
 */
public class DefaultAuthenticationManager implements AuthenticationManager {

    /** How many milliseconds the logins are stored before they're cleaned away. */
    private static final long LASTLOGINS_CLEANUP_TIME = 10 * 60 * 1_000L; // Ten minutes

    private static final long MAX_LOGIN_DELAY = 20 * 1_000L; // 20 seconds

    private static final Logger LOG = LogManager.getLogger( DefaultAuthenticationManager.class );

    /** Empty Map passed to JAAS {@link #doJAASLogin(Class, CallbackHandler, Map)} method. */
    protected static final Map< String, String > EMPTY_MAP = Collections.unmodifiableMap( new HashMap<>() );

    /** Class (of type LoginModule) to use for custom authentication. */
    protected Class< ? extends LoginModule > m_loginModuleClass = UserDatabaseLoginModule.class;

    /** Options passed to {@link LoginModule#initialize(Subject, CallbackHandler, Map, Map)};
     * initialized by {@link #initialize(Engine, Properties)}. */
    protected final Map< String, String > m_loginModuleOptions = new HashMap<>();

    /** The default {@link LoginModule} class name to use for custom authentication. */
    private static final String DEFAULT_LOGIN_MODULE = "org.apache.wiki.auth.login.UserDatabaseLoginModule";

    /** Empty principal set. */
    private static final Set<Principal> NO_PRINCIPALS = new HashSet<>();

    /** Static Boolean for lazily-initializing the "allows assertions" flag */
    private boolean m_allowsCookieAssertions = true;

    private boolean m_throttleLogins = true;

    /** Static Boolean for lazily-initializing the "allows cookie authentication" flag */
    private boolean m_allowsCookieAuthentication;

    private Engine m_engine;

    /** If true, logs the IP address of the editor */
    private boolean m_storeIPAddress = true;

    /** Keeps a list of the usernames who have attempted a login recently. */
    private final TimedCounterList< String > m_lastLoginAttempts = new TimedCounterList<>();

    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize( final Engine engine, final Properties props ) throws WikiException {
        m_engine = engine;
        m_storeIPAddress = TextUtil.getBooleanProperty( props, PROP_STOREIPADDRESS, m_storeIPAddress );

        // Should we allow cookies for assertions? (default: yes)
        m_allowsCookieAssertions = TextUtil.getBooleanProperty( props, PROP_ALLOW_COOKIE_ASSERTIONS,true );

        // Should we allow cookies for authentication? (default: no)
        m_allowsCookieAuthentication = TextUtil.getBooleanProperty( props, PROP_ALLOW_COOKIE_AUTH, false );

        // Should we throttle logins? (default: yes)
        m_throttleLogins = TextUtil.getBooleanProperty( props, PROP_LOGIN_THROTTLING, true );

        // Look up the LoginModule class
        final String loginModuleClassName = TextUtil.getStringProperty( props, PROP_LOGIN_MODULE, DEFAULT_LOGIN_MODULE );
        try {
            m_loginModuleClass = ClassUtil.findClass( "", loginModuleClassName );
        } catch( final ClassNotFoundException e ) {
            LOG.error( e.getMessage(), e );
            throw new WikiException( "Could not instantiate LoginModule class.", e );
        }

        // Initialize the LoginModule options
        initLoginModuleOptions( props );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isContainerAuthenticated() {
        try {
            final Authorizer authorizer = m_engine.getManager( AuthorizationManager.class ).getAuthorizer();
            if ( authorizer instanceof WebContainerAuthorizer ) {
                 return ( ( WebContainerAuthorizer )authorizer ).isContainerAuthorized();
            }
        } catch ( final WikiException e ) {
            // It's probably ok to fail silently...
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean login( final HttpServletRequest request ) throws WikiSecurityException {
        final HttpSession httpSession = request.getSession();
        final Session session = SessionMonitor.getInstance( m_engine ).find( httpSession );
        final AuthenticationManager authenticationMgr = m_engine.getManager( AuthenticationManager.class );
        final AuthorizationManager authorizationMgr = m_engine.getManager( AuthorizationManager.class );
        CallbackHandler handler = null;
        final Map< String, String > options = EMPTY_MAP;

        // If user not authenticated, check if container logged them in, or if there's an authentication cookie
        if ( !session.isAuthenticated() ) {
            // Create a callback handler
            handler = new WebContainerCallbackHandler( m_engine, request );

            // Execute the container login module, then (if that fails) the cookie auth module
            Set< Principal > principals = authenticationMgr.doJAASLogin( WebContainerLoginModule.class, handler, options );
            if ( principals.size() == 0 && authenticationMgr.allowsCookieAuthentication() ) {
                principals = authenticationMgr.doJAASLogin( CookieAuthenticationLoginModule.class, handler, options );
            }

            // If the container logged the user in successfully, tell the Session (and add all the Principals)
            if ( principals.size() > 0 ) {
                fireEvent( WikiSecurityEvent.LOGIN_AUTHENTICATED, getLoginPrincipal( principals ), session );
                for( final Principal principal : principals ) {
                    fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, principal, session );
                }

                // Add all appropriate Authorizer roles
                injectAuthorizerRoles( session, authorizationMgr.getAuthorizer(), request );
            }
        }

        // If user still not authenticated, check if assertion cookie was supplied
        if ( !session.isAuthenticated() && authenticationMgr.allowsCookieAssertions() ) {
            // Execute the cookie assertion login module
            final Set< Principal > principals = authenticationMgr.doJAASLogin( CookieAssertionLoginModule.class, handler, options );
            if ( principals.size() > 0 ) {
                fireEvent( WikiSecurityEvent.LOGIN_ASSERTED, getLoginPrincipal( principals ), session);
            }
        }

        // If user still anonymous, use the remote address
        if( session.isAnonymous() ) {
            final Set< Principal > principals = authenticationMgr.doJAASLogin( AnonymousLoginModule.class, handler, options );
            if( principals.size() > 0 ) {
                fireEvent( WikiSecurityEvent.LOGIN_ANONYMOUS, getLoginPrincipal( principals ), session );
                return true;
            }
        }

        // If by some unusual turn of events the Anonymous login module doesn't work, login failed!
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean login( final Session session, final HttpServletRequest request, final String username, final String password ) throws WikiSecurityException {
        if ( session == null ) {
            LOG.error( "No wiki session provided, cannot log in." );
            return false;
        }

        // Protect against brute-force password guessing if configured to do so
        if ( m_throttleLogins ) {
            delayLogin( username );
        }

        final CallbackHandler handler = new WikiCallbackHandler( m_engine, null, username, password );

        // Execute the user's specified login module
        final Set< Principal > principals = doJAASLogin( m_loginModuleClass, handler, m_loginModuleOptions );
        if( principals.size() > 0 ) {
            fireEvent(WikiSecurityEvent.LOGIN_AUTHENTICATED, getLoginPrincipal( principals ), session );
            for ( final Principal principal : principals ) {
                fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, principal, session );
            }

            // Add all appropriate Authorizer roles
            injectAuthorizerRoles( session, m_engine.getManager( AuthorizationManager.class ).getAuthorizer(), null );

            return true;
        }
        return false;
    }

    /**
     *  This method builds a database of login names that are being attempted, and will try to delay if there are too many requests coming
     *  in for the same username.
     *

     *  The current algorithm uses 2^loginattempts as the delay in milliseconds, i.e. at 10 login attempts it'll add 1.024 seconds to the login.
     *
     *  @param username The username that is being logged in
     */
    private void delayLogin( final String username ) {
        try {
            m_lastLoginAttempts.cleanup( LASTLOGINS_CLEANUP_TIME );
            final int count = m_lastLoginAttempts.count( username );

            final long delay = Math.min( 1L << count, MAX_LOGIN_DELAY );
            LOG.debug( "Sleeping for " + delay + " ms to allow login." );
            Thread.sleep( delay );

            m_lastLoginAttempts.add( username );
        } catch( final InterruptedException e ) {
            // FALLTHROUGH is fine
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void logout( final HttpServletRequest request ) {
        if( request == null ) {
            LOG.error( "No HTTP reqest provided; cannot log out." );
            return;
        }

        final HttpSession session = request.getSession();
        final String sid = ( session == null ) ? "(null)" : session.getId();
        LOG.debug( "Invalidating Session for session ID= {}", sid );
        // Retrieve the associated Session and clear the Principal set
        final Session wikiSession = Wiki.session().find( m_engine, request );
        final Principal originalPrincipal = wikiSession.getLoginPrincipal();
        wikiSession.invalidate();

        // Remove the wikiSession from the WikiSession cache
        Wiki.session().remove( m_engine, request );

        // We need to flush the HTTP session too
        if( session != null ) {
            session.invalidate();
        }

        // Log the event
        fireEvent( WikiSecurityEvent.LOGOUT, originalPrincipal, null );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean allowsCookieAssertions() {
        return m_allowsCookieAssertions;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean allowsCookieAuthentication() {
        return m_allowsCookieAuthentication;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Set< Principal > doJAASLogin( final Class< ? extends LoginModule > clazz,
                                         final CallbackHandler handler,
                                         final Map< String, String > options ) throws WikiSecurityException {
        // Instantiate the login module
        final LoginModule loginModule;
        try {
            loginModule = ClassUtil.buildInstance( clazz );
        } catch( final ReflectiveOperationException e ) {
            throw new WikiSecurityException( e.getMessage(), e );
        }

        // Initialize the LoginModule
        final Subject subject = new Subject();
        loginModule.initialize( subject, handler, EMPTY_MAP, options );

        // Try to log in:
        boolean loginSucceeded = false;
        boolean commitSucceeded = false;
        try {
            loginSucceeded = loginModule.login();
            if( loginSucceeded ) {
                commitSucceeded = loginModule.commit();
            }
        } catch( final LoginException e ) {
            // Login or commit failed! No principal for you!
        }

        // If we successfully logged in & committed, return all the principals
        if( loginSucceeded && commitSucceeded ) {
            return subject.getPrincipals();
        }
        return NO_PRINCIPALS;
    }

    // events processing .......................................................

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized void addWikiEventListener( final WikiEventListener listener ) {
        WikiEventManager.addWikiEventListener( this, listener );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized void removeWikiEventListener( final WikiEventListener listener ) {
        WikiEventManager.removeWikiEventListener( this, listener );
    }

    /**
     * Initializes the options Map supplied to the configured LoginModule every time it is invoked. The properties and values extracted from
     * jspwiki.properties are of the form jspwiki.loginModule.options.<var>param</var> = <var>value</var>, where
     * <var>param</var> is the key name, and <var>value</var> is the value.
     *
     * @param props the properties used to initialize JSPWiki
     * @throws IllegalArgumentException if any of the keys are duplicated
     */
    private void initLoginModuleOptions( final Properties props ) {
        for( final Object key : props.keySet() ) {
            final String propName = key.toString();
            if( propName.startsWith( PREFIX_LOGIN_MODULE_OPTIONS ) ) {
                // Extract the option name and value
                final String optionKey = propName.substring( PREFIX_LOGIN_MODULE_OPTIONS.length() ).trim();
                if( !optionKey.isEmpty() ) {
                    final String optionValue = props.getProperty( propName );

                    // Make sure the key is unique before stashing the key/value pair
                    if ( m_loginModuleOptions.containsKey( optionKey ) ) {
                        throw new IllegalArgumentException( "JAAS LoginModule key " + propName + " cannot be specified twice!" );
                    }
                    m_loginModuleOptions.put( optionKey, optionValue );
                }
            }
        }
    }

    /**
     * After successful login, this method is called to inject authorized role Principals into the Session. To determine which roles
     * should be injected, the configured Authorizer is queried for the roles it knows about by calling  {@link Authorizer#getRoles()}.
     * Then, each role returned by the authorizer is tested by calling {@link Authorizer#isUserInRole(Session, Principal)}. If this
     * check fails, and the Authorizer is of type WebAuthorizer, the role is checked again by calling
     * {@link WebAuthorizer#isUserInRole(HttpServletRequest, Principal)}). Any roles that pass the test are injected into the Subject by
     * firing appropriate authentication events.
     *
     * @param session the user's current Session
     * @param authorizer the Engine's configured Authorizer
     * @param request the user's HTTP session, which may be null
     */
    private void injectAuthorizerRoles( final Session session, final Authorizer authorizer, final HttpServletRequest request ) {
        // Test each role the authorizer knows about
        for( final Principal role : authorizer.getRoles() ) {
            // Test the Authorizer
            if( authorizer.isUserInRole( session, role ) ) {
                fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, role, session );
                LOG.debug( "Added authorizer role {}.", role.getName() );
            // If web authorizer, test the request.isInRole() method also
            } else if ( request != null && authorizer instanceof WebAuthorizer ) {
                final WebAuthorizer wa = ( WebAuthorizer )authorizer;
                if ( wa.isUserInRole( request, role ) ) {
                    fireEvent( WikiSecurityEvent.PRINCIPAL_ADD, role, session );
                    LOG.debug( "Added container role {}.",role.getName() );
                }
            }
        }
    }

}


text:
package com.example.android.networkconnect;

import android.net.NetworkInfo;
import android.support.annotation.IntDef;

/**
 * Sample interface containing bare minimum methods needed for an asynchronous task
 * to update the UI Context.
 */

public interface DownloadCallback {
    interface Progress {
        int ERROR = -1;
        int CONNECT_SUCCESS = 0;
        int GET_INPUT_STREAM_SUCCESS = 1;
        int PROCESS_INPUT_STREAM_IN_PROGRESS = 2;
        int PROCESS_INPUT_STREAM_SUCCESS = 3;
    }

    /**
     * Indicates that the callback handler needs to update its appearance or information based on
     * the result of the task. Expected to be called from the main thread.
     */
    void updateFromDownload(String result);

    /**
     * Get the device's active network status in the form of a NetworkInfo object.
     */
    NetworkInfo getActiveNetworkInfo();

    /**
     * Indicate to callback handler any progress update.
     * @param progressCode must be one of the constants defined in DownloadCallback.Progress.
     * @param percentComplete must be 0-100.
     */
    void onProgressUpdate(int progressCode, int percentComplete);

    /**
     * Indicates that the download operation has finished. This method is called even if the
     * download hasn't completed successfully.
     */
    void finishDownloading();

}


text:
class Redis;module Search;module Amplifier

  class GoogleTranslator
    extend Helpers::Config
    include Helpers::Config
    class Job
      @queue = :redis_search_amplifier
      def self.perform(klass,id)
        p 'todo'
      end
    end

  end

end;end;end


text:
package com.example.android.pmdb;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements Callback {

    private static final String DETAILFRAGMENT_TAG = "DFTAG";

    Toolbar toolbar;
    boolean mTwoPane;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if(findViewById(R.id.movie_detail_container) != null) {
            mTwoPane = true;
            if(savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.movie_detail_container, new MovieDetailActivityFragment(), DETAILFRAGMENT_TAG)
                        .commit();
            }
        } else {
            mTwoPane = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected(Movie movie) {
        if(!mTwoPane) {
            Intent intent = new Intent(getApplicationContext(), MovieDetailActivity.class)
                    .putExtra(Movie.class.getName(), movie);
            startActivity(intent);
        } else {
            Bundle args = new Bundle();
            args.putParcelable(Movie.class.getName(), movie);

            MovieDetailActivityFragment movieDetailActivityFragment = new MovieDetailActivityFragment();
            movieDetailActivityFragment.setArguments(args);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.movie_detail_container, movieDetailActivityFragment, DETAILFRAGMENT_TAG)
                    .commit();
        }
    }

    public void expandOverview(View view) {
        TextView overviewText = (TextView) findViewById(R.id.overview);
        overviewText.setMaxLines(Integer.MAX_VALUE);
        overviewText.setEllipsize(null);
    }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { Service251Service } from './service-251.service';

describe('Service251Service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Service251Service]
    });
  });

  it('should ...', inject([Service251Service], (service: Service251Service) => {
    expect(service).toBeTruthy();
  }));
});


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Post
 *
 * @ORM\Table(name="post")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
 */
class Post
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="publicationDate", type="datetime")
     */
    private $publicationDate;

    /**
     * @var bool
     *
     * @ORM\Column(name="publish", type="boolean")
     */
    private $publish;

    /**
     * @var bool
     *
     * @ORM\Column(name="mathematics", type="boolean")
     */
    private $mathematics;

    /**
     * @var string
     *
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(name="slug", type="string", length=255, unique=true)
     */
    private $slug;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="abstract", type="text")
     */
    private $abstract;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="text")
     */
    private $content;

    /**
     * @var PostVote
     *
     * @ORM\OneToMany(targetEntity="PostVote", mappedBy="post")
     */
    private $votes;

    /**
     * @var PostComment
     *
     * @ORM\OneToMany(targetEntity="PostComment", mappedBy="post")
     */
    private $comments;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(nullable=false)
     */
    private $author;

    /**
     * @var Tag
     *
     * @ORM\ManyToMany(targetEntity="Tag", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $tags;

    public function __construct() {
        $this->publicationDate = new \DateTime();
        $this->mathematics = false;
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set publicationDate
     *
     * @param \DateTime $publicationDate
     *
     * @return Post
     */
    public function setPublicationDate($publicationDate)
    {
        $this->publicationDate = $publicationDate;

        return $this;
    }

    /**
     * Get publicationDate
     *
     * @return \DateTime
     */
    public function getPublicationDate()
    {
        return $this->publicationDate;
    }

    /**
     * Set publish
     *
     * @param boolean $publish
     *
     * @return Post
     */
    public function setPublish($publish)
    {
        $this->publish = $publish;

        return $this;
    }

    /**
     * Get publish
     *
     * @return bool
     */
    public function getPublish()
    {
        return $this->publish;
    }

    /**
     * Set abstract
     *
     * @param string $abstract
     *
     * @return Post
     */
    public function setAbstract($abstract)
    {
        $this->abstract = $abstract;

        return $this;
    }

    /**
     * Get abstract
     *
     * @return string
     */
    public function getAbstract()
    {
        return $this->abstract;
    }

    /**
     * Set content
     *
     * @param string $content
     *
     * @return Post
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set slug
     *
     * @param string $slug
     *
     * @return Post
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Post
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set mathematics
     *
     * @param boolean $mathematics
     *
     * @return Post
     */
    public function setMathematics($mathematics)
    {
        $this->mathematics = $mathematics;

        return $this;
    }

    /**
     * Get mathematics
     *
     * @return boolean
     */
    public function getMathematics()
    {
        return $this->mathematics;
    }

    /**
     * Set author
     *
     * @param \AppBundle\Entity\User $author
     *
     * @return Post
     */
    public function setAuthor(\AppBundle\Entity\User $author = null)
    {
        $this->author = $author;

        return $this;
    }

    /**
     * Get author
     *
     * @return \AppBundle\Entity\User
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Add tag
     *
     * @param \AppBundle\Entity\Tag $tag
     *
     * @return Post
     */
    public function addTag(\AppBundle\Entity\Tag $tag)
    {
        $this->tags[] = $tag;

        return $this;
    }

    /**
     * Remove tag
     *
     * @param \AppBundle\Entity\Tag $tag
     */
    public function removeTag(\AppBundle\Entity\Tag $tag)
    {
        $this->tags->removeElement($tag);
    }

    /**
     * Get tags
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Add vote
     *
     * @param \AppBundle\Entity\PostVote $vote
     *
     * @return Post
     */
    public function addVote(\AppBundle\Entity\PostVote $vote)
    {
        $this->votes[] = $vote;

        return $this;
    }

    /**
     * Remove vote
     *
     * @param \AppBundle\Entity\PostVote $vote
     */
    public function removeVote(\AppBundle\Entity\PostVote $vote)
    {
        $this->votes->removeElement($vote);
    }

    /**
     * Get votes
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getVotes()
    {
        return $this->votes;
    }

    /**
     * Add comment
     *
     * @param \AppBundle\Entity\PostComment $comment
     *
     * @return Post
     */
    public function addComment(\AppBundle\Entity\PostComment $comment)
    {
        $this->comments[] = $comment;

        return $this;
    }

    /**
     * Remove comment
     *
     * @param \AppBundle\Entity\PostComment $comment
     */
    public function removeComment(\AppBundle\Entity\PostComment $comment)
    {
        $this->comments->removeElement($comment);
    }

    /**
     * Get comments
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComments()
    {
        return $this->comments;
    }
}


text:
{% extends 'layout.html' %}

{% block page_title %}{{ action_name }} Article{% endblock %}

{% block content %}
	{% include 'article_form.html' %}
{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="aj_template_layout_homepage" pattern="/layout/{name}">
        <default key="_controller">AJTemplateLayoutBundle:Default:index</default>
    </route>
</routes>


text:
PORTNAME=	netperf
PORTVERSION=	2.1pl3
CATEGORIES=	benchmarks
MASTER_SITES=	ftp://ftp.cup.hp.com/dist/networking/benchmarks/netperf/

PATCH_SITES=	ftp://ftp.kame.net/pub/kame/misc/
PATCHFILES=	netperf-21pl3-20000721.diff.gz
PATCH_DIST_STRIP=	-p1

MAINTAINER=	sumikawa@kame.net

MAKEFILE=	makefile
MAN1=		netperf.1 netserver.1
MINSTALL=	${INSTALL} ${COPY} -o ${MANOWN} -g ${MANGRP} -m ${MANMODE}

post-install:
	strip ${PREFIX}/netperf/netperf
	strip ${PREFIX}/netperf/netserver
	${MINSTALL} ${WRKSRC}/netperf.man ${PREFIX}/man/man1/netperf.1
	${MINSTALL} ${WRKSRC}/netserver.man ${PREFIX}/man/man1/netserver.1
.if !defined(NOPORTDOCS)
	${MKDIR} ${PREFIX}/share/doc/netperf
	${MINSTALL} ${WRKSRC}/netperf.ps ${PREFIX}/share/doc/netperf
	gzip -9nf ${PREFIX}/share/doc/netperf/netperf.ps
.endif

.include <bsd.port.mk>


text:
package com.formkiq.vision.pdf;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Holder class for {@link PdfTokenOperator} and {@link List} of
 * {@link PdfTokenOperand}.
 *
 */
public class PdfToken {

    /** {@link PdfTokenOperator}. */
	private PdfTokenOperator operator;
	/** {@link List} of {@link PdfTokenOperand}. */
	private List<PdfTokenOperand> operands;

	/**
	 * constructor.
	 */
	public PdfToken() {
	}

	/**
	 * constructor.
	 * @param op {@link PdfTokenOperator}
	 */
	public PdfToken(final PdfTokenOperator op) {
		this();
		this.operator = op;
	}

	/**
	 * @return {@link PdfTokenOperator}
	 */
	public PdfTokenOperator getOperator() {
		return this.operator;
	}

	/**
	 * @param op {@link PdfTokenOperator}
	 */
	public void setOperator(final PdfTokenOperator op) {
		this.operator = op;
	}

	/**
	 * @return {@link List} of {@link PdfTokenOperand}
	 */
	public List<PdfTokenOperand> getOperands() {
		return this.operands;
	}

	/**
	 * @param list {@link List} of {@link PdfTokenOperand}
	 */
	public void setOperands(final List<PdfTokenOperand> list) {
		this.operands = list;
	}

    @Override
    public String toString() {
        return this.operator + ": " + this.operands.stream()
                .map(s -> s.toString()).collect(Collectors.joining(","));
    }
}


text:
import os

from django.core.management import call_command
from rest_framework import serializers

from kolibri.core.auth.models import Facility
from kolibri.core.logger.csv_export import CSV_EXPORT_FILENAMES
from kolibri.core.tasks.decorators import register_task
from kolibri.core.tasks.permissions import IsAdminForJob
from kolibri.core.tasks.validation import JobValidator
from kolibri.utils import conf

def get_filepath(log_type, facility_id):
    facility = Facility.objects.get(id=facility_id)
    logs_dir = os.path.join(conf.KOLIBRI_HOME, "log_export")
    if not os.path.isdir(logs_dir):
        os.mkdir(logs_dir)
    filepath = os.path.join(
        logs_dir,
        CSV_EXPORT_FILENAMES[log_type].format(facility.name, facility.id[:4]),
    )
    return filepath

class ExportLogCSVValidator(JobValidator):
    facility = serializers.PrimaryKeyRelatedField(
        queryset=Facility.objects.all(), required=False
    )

    def validate(self, data):
        facility = data.get("facility", None)
        if facility is None and "user" in self.context:
            facility = self.context["user"].facility
        elif facility is None:
            raise serializers.ValidationError(
                "Facility must be specified when no user is available."
            )

        return {
            "facility_id": facility.id,
            "args": [facility.id],
        }

def _exportlogcsv(log_type, facility_id):
    filepath = get_filepath(log_type, facility_id)
    call_command(
        "exportlogs",
        log_type=log_type,
        output_file=filepath,
        facility=facility_id,
        overwrite=True,
    )

@register_task(
    validator=ExportLogCSVValidator,
    track_progress=True,
    permission_classes=[IsAdminForJob],
)
def exportsessionlogcsv(
    facility_id,
):
    """
    Dumps in csv format the content session logs.

    :param: facility.
    """
    _exportlogcsv("session", facility_id)

@register_task(
    validator=ExportLogCSVValidator,
    track_progress=True,
    permission_classes=[IsAdminForJob],
)
def exportsummarylogcsv(
    facility_id,
):
    """
    Dumps in csv format the content summary logs.

    :param: facility.
    """
    _exportlogcsv("summary", facility_id)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>case-studies</artifactId>
        <groupId>org.glassfish.javaeetutorial</groupId>
        <version>7.0.5</version>
    </parent>
    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>dukes-tutoring</artifactId>
    <packaging>pom</packaging>
    <name>dukes-tutoring</name>
    <modules>
        <module>dukes-tutoring-war</module>
        <module>dukes-tutoring-common</module>
    </modules>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <skip>true</skip>
                    <executable>${glassfish.home}/bin/asadmin${glassfish.executables.suffix}</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?php

class Google_Service_AndroidEnterprise_Permission extends Google_Model
{
  public $description;
  public $kind;
  public $name;
  public $permissionId;

  public function setDescription($description)
  {
    $this->description = $description;
  }
  public function getDescription()
  {
    return $this->description;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  public function setPermissionId($permissionId)
  {
    $this->permissionId = $permissionId;
  }
  public function getPermissionId()
  {
    return $this->permissionId;
  }
}


text:
use sys::{self, VALUE};

use super::{CheckResult, FromRuby, ToRuby, ToRubyResult};
use super::super::{inspect};

impl<T: FromRuby> FromRuby for Vec<T> {
    type Checked = Vec<T::Checked>;

    fn from_ruby(value: VALUE) -> CheckResult<Self::Checked> {
        if unsafe { sys::RB_TYPE_P(value, sys::T_ARRAY) } {
            // Make sure we can actually do the conversions for the values.
            let len = unsafe { sys::RARRAY_LEN(value) };
            let mut checked = Vec::with_capacity(len as usize);

            for i in 0..len {
                let val = unsafe { sys::rb_ary_entry(value, i) };
                match T::from_ruby(val) {
                    Ok(v) => checked.push(v),
                    Err(e) => type_error!(format!("Failed to convert {}, element {} has the wrong type: {}", inspect(value), i, e)),
                }
            }

            Ok(checked)
        } else {
            type_error!(value, "an array")
        }
    }

    fn from_checked(checked: Self::Checked) -> Self {
        checked.into_iter().map(T::from_checked).collect()
    }
}

impl<T: ToRuby> ToRuby for Vec<T> {
    fn to_ruby(self) -> ToRubyResult {
        let ary = unsafe { sys::rb_ary_new_capa(self.len() as isize) };
        for item in self {
            unsafe { sys::rb_ary_push(ary, item.to_ruby()?); }
        }
        Ok(ary)
    }
}


text:
package estivate.core.ast;

import lombok.Data;

@Data
public abstract class QueryAST {

}


text:
#include <cms/ExceptionListener.h>

using namespace cms;

////////////////////////////////////////////////////////////////////////////////
ExceptionListener::~ExceptionListener() {

}


text:
/*
 * TransportCapacitySort
 * Bonial International GmbH
 * written by Jan Max Tiedemann @ 2017
 *
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE.txt', which is part of this source code package.
 */

// Import external libaries
const _ = require('underscore');
const numeral = require('numeral');
const JSONStream = require('JSONStream');
const clear = require('clear');
const fs = require('fs');

// Result array (makes results easy so sort)
var count_results = [];
var distinct_results = [];

// Metrics Variables
var entry_count = 0;
var data_count = 0;

// Count by transport type
var car_count = 0;
var plane_count = 0;
var train_count = 0;

// Arrays for Transport types (needed to keep track of the distint models)
var cars = [];
var planes = [];
var trains = [];

// this function can be used as a filter on an array and will only return unique items
function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}

if (process.argv.length > 3 || process.argv.length == 2) {
  console.log("Usage: node index.js <file spath>");
  return;
}

// Path to input file
var path = process.argv[2];

// Init JSONStream (reads only the important parts (only the transports array) of the file)
var json = JSONStream.parse('transports.*');

// setup data recive event
json.on('data', (data) => {
  // On each entry increase entry count by 1
  entry_count++;

  // Every 100k entries give a hint how its going
  if ((entry_count - 1) % 1e5 == 0 && (entry_count - 1) != 0) {
    console.log("Parsed \t" + numeral(entry_count).format('0.0a') + " entries");
    console.log("Cars: " + cars.length + "\t | Trains: " + trains.length + "\t | Planes: " + planes.length);
  }

  // Every 10m clean the memory (requires gc to be accessible)
  if ((entry_count - 1) % 1e7 == 0 && (entry_count - 1) != 0) {

    // this works by fitering out every dupicate in every array and then running the garbage collector
    // This is not nessesary but i will otherwise pollute your ram and might run out of heap memory
    console.time('cleanup')
    console.log("Reducing car array");
    var cars_before = cars.length;
    cars = cars.filter(onlyUnique);
    console.log("Reducing trains array");
    var trains_before = trains.length;
    trains = trains.filter(onlyUnique);
    console.log("Reducing planes array");
    var planes_before = planes.length;
    planes = planes.filter(onlyUnique);
    console.log("Comencing Garbage Collection...");
    global.gc();
    console.timeEnd('cleanup')
    console.log("Reduced car array size by: " + numeral(100-((cars_before-cars.length)/cars_before*10)).format('0.0') + "%");
    console.log("Reduced train array size by: " + numeral(100-((trains_before-trains.length)/trains_before*10)).format('0.0')  + "%");
    console.log("Reduced plane array size by: " + numeral(100-((planes_before-planes.length)/planes_before*10)).format('0.0')  + "%");
  }
  // As the type of a json object in this example can be determinded by looking for certian magic values
  // this is done here and the values are calucated as given in the instruction
  if (_.has(data, 'b-passenger-capacity')){
    planes.push(data.model);
    plane_count += (data["b-passenger-capacity"]+data["e-passenger-capacity"]);
  } else if (_.has(data, 'number-wagons')) {
    trains.push(data.model);
    train_count += (data["number-wagons"] * data["w-passenger-capacity"]);
  } else {
    cars.push(data.model);
    car_count += data["passenger-capacity"];
  }
});

// This function does the final calulaitons for distinct and prints the results
function processData() {
  // Clear console
  clear();
  console.time('distinct');

  // add results to arrays
  count_results.push({
      "name": 'cars',
      "capacity": car_count
  });
  count_results.push({
      "name": 'trains',
      "capacity": train_count
  });
  count_results.push({
      "name": 'planes',
      "capacity": plane_count
  });
  console.log("Sorting count_results...");
  count_results.sort((kek, kek1) => {
      return kek1.capacity - kek.capacity;
  })

  console.log("Seatching for distinct_cars")
  var distinct_cars = cars.filter(onlyUnique).length
  console.log("Seatching for distinct_trains")
  var distinct_trains = trains.filter(onlyUnique).length
  console.log("Seatching for distinct_trains")
  var distinct_planes = planes.filter(onlyUnique).length

  // add results to array
  distinct_results.push({
      "name": 'distinct_cars',
      "capacity": distinct_cars
  });
  distinct_results.push({
      "name": 'distinct_trains',
      "capacity": distinct_trains
  });
  distinct_results.push({
      "name": 'distinct_planes',
      "capacity": distinct_planes
  });

  console.log("Sorting distinct_results...");
  distinct_results.sort((kek, kek1) => {
      return kek1.capacity - kek.capacity;
  })

  console.timeEnd('distinct');
  console.timeEnd('loadingData');

  // Print results
  console.log("Capacity by transport class");
  for (var i = 0; i < count_results.length; i++) {
      console.log("["+(i+1)+"]: " +count_results[i].name + ": " + count_results[i].capacity);
  }
  console.log();
  console.log("Distinct transport entitys");
  for (var i = 0; i < distinct_results.length; i++) {
      console.log("["+(i+1)+"]: " +distinct_results[i].name + ": " + distinct_results[i].capacity);
  }
}

// acctual start of processing
console.time('loadingData');
// Create a file reading stream
var readStream = fs.createReadStream(path);

// call final processing on EOF
readStream.on('end', () => {
  processData();
})

// Pipe read data to json stream
readStream.pipe(json);


text:
<?php

class CallbackOptionsTestCase extends PradoGenericSelenium2Test
{
	function test()
	{
		$base='ctl0_Content_';
		$this->url("active-controls/index.php?page=CallbackOptionsTest");
		$this->assertSourceContains("TCallbackOptions Test");

		$this->assertText("label1", "Label 1");
		$this->assertText("label2", "Label 2");
		$this->assertText("label3", "Label 3");

		$this->byId("{$base}button1")->click();
		$this->pause(800);
		$this->assertText("label1", "Button 1 has returned");
		$this->assertText("label2", "Label 2");
		$this->assertText("label3", "Label 3");

		$this->byId("{$base}button2")->click();
		$this->pause(800);
		$this->assertText("label1", "Button 1 has returned");
		$this->assertText("label2", "Button 2 has returned");
		$this->assertText("label3", "Label 3");

		$this->byId("{$base}button3")->click();
		$this->pause(800);
		$this->assertText("label1", "Button 1 has returned");
		$this->assertText("label2", "Button 2 has returned");
		$this->assertText("label3", "Button 3 has returned");
	}
}


text:
namespace Microsoft.AspNetCore.Server.HttpSys;

/// <summary>
/// This exposes the Http.Sys HTTP_REQUEST_INFO extensibility point as opaque data for the caller to interperate.
/// <see href="https://docs.microsoft.com/en-us/windows/win32/api/http/ns-http-http_request_v2"/>,
/// <see href="https://docs.microsoft.com/en-us/windows/win32/api/http/ns-http-http_request_info"/>
/// </summary>
public interface IHttpSysRequestInfoFeature
{
    /// <summary>
    /// A collection of the HTTP_REQUEST_INFO for the current request. The integer represents the identifying
    /// HTTP_REQUEST_INFO_TYPE enum value. The Memory is opaque bytes that need to be interperted in the format
    /// specified by the enum value.
    /// </summary>
    public IReadOnlyDictionary<int, ReadOnlyMemory<byte>> RequestInfo { get; }
}


text:
<!DOCTYPE html>

{{template "head.html" .PageMetaData}}

	{{template "header.html" .PageMetaData}}

Supplying young businesses since 1908

From a child's first business to the most cutting edge stands, LSS is ready to support you with ingredients, supplies
					and advertising supplies.

Sales

Shop

Members

	{{template "footer.html"}}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { WorkbasketListToolbarComponent } from './workbasket-list-toolbar.component';
import { Component, DebugElement, EventEmitter, Input, Output } from '@angular/core';
import { Actions, NgxsModule, ofActionDispatched, Store } from '@ngxs/store';
import { Observable, of } from 'rxjs';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { WorkbasketState } from '../../../shared/store/workbasket-store/workbasket.state';
import { WorkbasketService } from '../../../shared/services/workbasket/workbasket.service';
import { DomainService } from '../../../shared/services/domain/domain.service';
import { CreateWorkbasket } from '../../../shared/store/workbasket-store/workbasket.actions';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { Direction, Sorting, WorkbasketQuerySortParameter } from '../../../shared/models/sorting';
import { ACTION } from '../../../shared/models/action';
import { TaskanaType } from '../../../shared/models/taskana-type';
import { MatIconModule } from '@angular/material/icon';
import { MatDialogModule } from '@angular/material/dialog';
import { RouterTestingModule } from '@angular/router/testing';
import { RequestInProgressService } from '../../../shared/services/request-in-progress/request-in-progress.service';

const getDomainFn = jest.fn().mockReturnValue(true);
const domainServiceMock: Partial<DomainService> = {
  getDomains: getDomainFn,
  getSelectedDomain: jest.fn().mockReturnValue(of('A'))
};

@Component({ selector: 'taskana-administration-import-export', template: '' })
class ImportExportStub {
  @Input() currentSelection: TaskanaType;
  @Input() parentComponent;
}

@Component({ selector: 'taskana-shared-sort', template: '' })
class SortStub {
  @Input() sortingFields: Map<WorkbasketQuerySortParameter, string>;
  @Input() defaultSortBy: WorkbasketQuerySortParameter;
  @Output() performSorting = new EventEmitter<Sorting<WorkbasketQuerySortParameter>>();
}

@Component({ selector: 'taskana-shared-workbasket-filter', template: '' })
class FilterStub {
  @Input() isExpanded = false;
}

const requestInProgressServiceSpy = jest.fn().mockImplementation(() => jest.fn().mockReturnValue(of()));

describe('WorkbasketListToolbarComponent', () => {
  let fixture: ComponentFixture<WorkbasketListToolbarComponent>;
  let debugElement: DebugElement;
  let component: WorkbasketListToolbarComponent;
  let store: Store;
  let actions$: Observable<any>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        NgxsModule.forRoot([WorkbasketState]),
        NoopAnimationsModule,
        MatIconModule,
        MatDialogModule
      ],
      declarations: [WorkbasketListToolbarComponent, ImportExportStub, SortStub, FilterStub],
      providers: [
        { provide: DomainService, useValue: domainServiceMock },
        { provide: RequestInProgressService, useValue: requestInProgressServiceSpy },
        WorkbasketService
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(WorkbasketListToolbarComponent);
    debugElement = fixture.debugElement;
    component = fixture.debugElement.componentInstance;
    store = TestBed.inject(Store);
    actions$ = TestBed.inject(Actions);
    component.action = ACTION.COPY;
    fixture.detectChanges();
  }));

  it('should create the component', () => {
    expect(component).toBeTruthy();
  });

  /* Typescript */

  it('should dispatch CreateWorkbasket when addWorkbasket is called', async((done) => {
    component.action = ACTION.COPY;
    let actionDispatched = false;
    actions$.pipe(ofActionDispatched(CreateWorkbasket)).subscribe(() => (actionDispatched = true));
    component.addWorkbasket();
    expect(actionDispatched).toBe(true);
  }));

  it('should not dispatch action in addWorkbasket when action is CREATE', async((done) => {
    component.action = ACTION.CREATE;
    let actionDispatched = false;
    actions$.pipe(ofActionDispatched(CreateWorkbasket)).subscribe(() => (actionDispatched = true));
    component.addWorkbasket();
    expect(actionDispatched).toBe(false);
  }));

  it('should emit value when sorting is called', (done) => {
    const mockSort: Sorting<WorkbasketQuerySortParameter> = {
      'sort-by': WorkbasketQuerySortParameter.KEY,
      order: Direction.ASC
    };
    let sort: Sorting<WorkbasketQuerySortParameter> = undefined;
    component.performSorting.subscribe((sortBy: Sorting<WorkbasketQuerySortParameter>) => {
      sort = sortBy;
      done();
    });
    component.sorting(mockSort);
    expect(sort).toMatchObject(mockSort);
  });

  /* HTML */

  it('should call AddWorkbasket() when add-workbasket button is clicked', async () => {
    const button = debugElement.nativeElement.querySelector('.workbasket-list-toolbar__add-button');
    expect(button).toBeTruthy();
    expect(button.textContent).toContain('add');
    expect(button.textContent).toContain('Add');
    component.addWorkbasket = jest.fn().mockImplementation();
    button.click();
    expect(component.addWorkbasket).toHaveBeenCalled();
  });

  it('should display import-export component', () => {
    expect(debugElement.nativeElement.querySelector('taskana-administration-import-export')).toBeTruthy();
  });

  it('should display sort component', () => {
    expect(debugElement.nativeElement.querySelector('taskana-shared-sort')).toBeTruthy();
  });

  it('should display filter component', () => {
    expect(debugElement.nativeElement.querySelector('taskana-shared-workbasket-filter')).toBeTruthy();
  });

  it('should show expanded filter component only when filter button is clicked', () => {
    const button = debugElement.nativeElement.querySelector('.filter__filter-button');
    expect(button).toBeTruthy();
    button.click();
    fixture.detectChanges();
    expect(component.isExpanded).toBe(true);
    expect(button.textContent).toBe('keyboard_arrow_up');
    button.click();
    fixture.detectChanges();
    expect(component.isExpanded).toBe(false);
    expect(button.textContent).toBe('keyboard_arrow_down');
  });
});