text:
"""
Provides base classes for working with drivers
"""

import sys
import time
import hashlib
import os
import socket
import struct
import binascii

from libcloud.utils.py3 import b

import libcloud.compute.ssh
from libcloud.pricing import get_size_price
from libcloud.compute.types import NodeState, DeploymentError
from libcloud.compute.ssh import SSHClient

# @@TR: are the imports below part of the public api for this
# module? They aren't used in here ...
from libcloud.common.base import ConnectionKey, ConnectionUserAndKey
from libcloud.common.base import BaseDriver
from libcloud.httplib_ssl import LibcloudHTTPSConnection
from libcloud.common.base import LibcloudHTTPConnection
from libcloud.common.types import LibcloudError

# How long to wait for the node to come online after creating it
NODE_ONLINE_WAIT_TIMEOUT = 10 * 60

# How long to try connecting to a remote SSH server when running a deployment
# script.
SSH_CONNECT_TIMEOUT = 5 * 60

__all__ = [
    "Node",
    "NodeState",
    "NodeSize",
    "NodeImage",
    "NodeLocation",
    "NodeAuthSSHKey",
    "NodeAuthPassword",
    "NodeDriver",

    # @@TR: do the following need exporting?
    "ConnectionKey",
    "ConnectionUserAndKey",
    "LibcloudHTTPSConnection",
    "LibcloudHTTPConnection"
]

class UuidMixin(object):
    """
    Mixin class for get_uuid function.
    """

    def __init__(self):
        self._uuid = None

    def get_uuid(self):
        """Unique hash for a node, node image, or node size

        @return: C{string}

        The hash is a function of an SHA1 hash of the node, node image,
        or node size's ID and its driver which means that it should be
        unique between all objects of its type.
        In some subclasses (e.g. GoGridNode) there is no ID
        available so the public IP address is used.  This means that,
        unlike a properly done system UUID, the same UUID may mean a
        different system install at a different time

        >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
        >>> driver = DummyNodeDriver(0)
        >>> node = driver.create_node()
        >>> node.get_uuid()
        'd3748461511d8b9b0e0bfa0d4d3383a619a2bb9f'

        Note, for example, that this example will always produce the
        same UUID!
        """
        if not self._uuid:
            self._uuid = hashlib.sha1(b('%s:%s' %
                                      (self.id, self.driver.type))).hexdigest()

        return self._uuid

    @property
    def uuid(self):
        return self.get_uuid()

class Node(UuidMixin):
    """
    Provide a common interface for handling nodes of all types.

    The Node object provides the interface in libcloud through which
    we can manipulate nodes in different cloud providers in the same
    way.  Node objects don't actually do much directly themselves,
    instead the node driver handles the connection to the node.

    You don't normally create a node object yourself; instead you use
    a driver and then have that create the node for you.

    >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
    >>> driver = DummyNodeDriver(0)
    >>> node = driver.create_node()
    >>> node.public_ips[0]
    '127.0.0.3'
    >>> node.name
    'dummy-3'

    You can also get nodes from the driver's list_node function.

    >>> node = driver.list_nodes()[0]
    >>> node.name
    'dummy-1'

    the node keeps a reference to its own driver which means that we
    can work on nodes from different providers without having to know
    which is which.

    >>> driver = DummyNodeDriver(72)
    >>> node2 = driver.create_node()
    >>> node.driver.creds
    0
    >>> node2.driver.creds
    72

    Althrough Node objects can be subclassed, this isn't normally
    done.  Instead, any driver specific information is stored in the
    "extra" proproperty of the node.

    >>> node.extra
    {'foo': 'bar'}

    """

    def __init__(self, id, name, state, public_ips, private_ips,
                 driver, size=None, image=None, extra=None):
        self.id = str(id) if id else None
        self.name = name
        self.state = state
        self.public_ips = public_ips if public_ips else []
        self.private_ips = private_ips if private_ips else []
        self.driver = driver
        self.size = size
        self.image = image
        self.extra = extra or {}
        UuidMixin.__init__(self)

    # Note: getters and setters bellow are here only for backward
    # compatibility. They will be removed in the next release.

    def _set_public_ips(self, value):
        self.public_ips = value

    def _get_public_ips(self):
        return self.public_ips

    def _set_private_ips(self, value):
        self.private_ips = value

    def _get_private_ips(self):
        return self.private_ips

    public_ip = property(fget=_get_public_ips, fset=_set_public_ips)
    private_ip = property(fget=_get_private_ips, fset=_set_private_ips)

    def reboot(self):
        """Reboot this node

        @return: C{bool}

        This calls the node's driver and reboots the node

        >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
        >>> driver = DummyNodeDriver(0)
        >>> node = driver.create_node()
        >>> from libcloud.compute.types import NodeState
        >>> node.state == NodeState.RUNNING
        True
        >>> node.state == NodeState.REBOOTING
        False
        >>> node.reboot()
        True
        >>> node.state == NodeState.REBOOTING
        True
        """
        return self.driver.reboot_node(self)

    def destroy(self):
        """Destroy this node

        @return: C{bool}

        This calls the node's driver and destroys the node

        >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
        >>> driver = DummyNodeDriver(0)
        >>> from libcloud.compute.types import NodeState
        >>> node = driver.create_node()
        >>> node.state == NodeState.RUNNING
        True
        >>> node.destroy()
        True
        >>> node.state == NodeState.RUNNING
        False

        """
        return self.driver.destroy_node(self)

    def __repr__(self):
        return (('<Node: uuid=%s, name=%s, state=%s, public_ips=%s, '
                 'provider=%s ...>')
                % (self.uuid, self.name, self.state, self.public_ips,
                   self.driver.name))

class NodeSize(UuidMixin):
    """
    A Base NodeSize class to derive from.

    NodeSizes are objects which are typically returned a driver's
    list_sizes function.  They contain a number of different
    parameters which define how big an image is.

    The exact parameters available depends on the provider.

    N.B. Where a parameter is "unlimited" (for example bandwidth in
    Amazon) this will be given as 0.

    >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
    >>> driver = DummyNodeDriver(0)
    >>> size = driver.list_sizes()[0]
    >>> size.ram
    128
    >>> size.bandwidth
    500
    >>> size.price
    4
    """

    def __init__(self, id, name, ram, disk, bandwidth, price, driver):
        self.id = str(id)
        self.name = name
        self.ram = ram
        self.disk = disk
        self.bandwidth = bandwidth
        self.price = price
        self.driver = driver
        UuidMixin.__init__(self)

    def __repr__(self):
        return (('<NodeSize: id=%s, name=%s, ram=%s disk=%s bandwidth=%s '
                 'price=%s driver=%s ...>')
                % (self.id, self.name, self.ram, self.disk, self.bandwidth,
                   self.price, self.driver.name))

class NodeImage(UuidMixin):
    """
    An operating system image.

    NodeImage objects are typically returned by the driver for the
    cloud provider in response to the list_images function

    >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
    >>> driver = DummyNodeDriver(0)
    >>> image = driver.list_images()[0]
    >>> image.name
    'Ubuntu 9.10'

    Apart from name and id, there is no further standard information;
    other parameters are stored in a driver specific "extra" variable

    When creating a node, a node image should be given as an argument
    to the create_node function to decide which OS image to use.

    >>> node = driver.create_node(image=image)

    """

    def __init__(self, id, name, driver, extra=None):
        self.id = str(id)
        self.name = name
        self.driver = driver
        self.extra = extra or {}
        UuidMixin.__init__(self)

    def __repr__(self):
        return (('<NodeImage: id=%s, name=%s, driver=%s  ...>')
                % (self.id, self.name, self.driver.name))

class NodeLocation(object):
    """
    A physical location where nodes can be.

    >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
    >>> driver = DummyNodeDriver(0)
    >>> location = driver.list_locations()[0]
    >>> location.country
    'US'
    """

    def __init__(self, id, name, country, driver):
        self.id = str(id)
        self.name = name
        self.country = country
        self.driver = driver

    def __repr__(self):
        return (('<NodeLocation: id=%s, name=%s, country=%s, driver=%s>')
                % (self.id, self.name, self.country, self.driver.name))

class NodeAuthSSHKey(object):
    """
    An SSH key to be installed for authentication to a node.

    This is the actual contents of the users ssh public key which will
    normally be installed as root's public key on the node.

    >>> pubkey = '...' # read from file
    >>> from libcloud.compute.base import NodeAuthSSHKey
    >>> k = NodeAuthSSHKey(pubkey)
    >>> k
    <NodeAuthSSHKey>
    """

    def __init__(self, pubkey):
        self.pubkey = pubkey

    def __repr__(self):
        return '<NodeAuthSSHKey>'

class NodeAuthPassword(object):
    """
    A password to be used for authentication to a node.
    """
    def __init__(self, password):
        self.password = password

    def __repr__(self):
        return '<NodeAuthPassword>'

class StorageVolume(UuidMixin):
    """
    A base StorageVolume class to derive from.
    """

    def __init__(self, id, name, size, driver, extra=None):
        self.id = id
        self.name = name
        self.size = size
        self.driver = driver
        self.extra = extra
        UuidMixin.__init__(self)

    def attach(self, node, device=None):
        """
        Attach this volume to a node.

        @param      node: Node to attach volume to
        @type       node: L{Node}

        @param      device: Where the device is exposed,
                            e.g. '/dev/sdb (optional)
        @type       device: C{str}

        @returns C{bool}
        """

        return self.driver.attach_volume(node=node, volume=self, device=device)

    def detach(self):
        """
        Detach this volume from its node

        @returns C{bool}
        """

        return self.driver.detach_volume(volume=self)

    def destroy(self):
        """Destroy this storage volume.

        @returns C{bool}
        """

        return self.driver.destroy_volume(volume=self)

    def __repr__(self):
        return '<StorageVolume id=%s size=%s driver=%s>' % (
               self.id, self.size, self.driver.name)

class NodeDriver(BaseDriver):
    """
    A base NodeDriver class to derive from

    This class is always subclassed by a specific driver.  For
    examples of base behavior of most functions (except deploy node)
    see the dummy driver.

    """

    connectionCls = ConnectionKey
    name = None
    type = None
    port = None
    features = {"create_node": []}
    """
    List of available features for a driver.
        - L{create_node}
            - ssh_key: Supports L{NodeAuthSSHKey} as an authentication method
              for nodes.
            - password: Supports L{NodeAuthPassword} as an authentication
              method for nodes.
            - generates_password: Returns a password attribute on the Node
              object returned from creation.
    """

    NODE_STATE_MAP = {}

    def __init__(self, key, secret=None, secure=True, host=None, port=None,
                 api_version=None, **kwargs):
        super(NodeDriver, self).__init__(key=key, secret=secret, secure=secure,
                                         host=host, port=port,
                                         api_version=api_version, **kwargs)

    def create_node(self, **kwargs):
        """Create a new node instance.

        @keyword    name:   String with a name for this new node (required)
        @type       name:   C{str}

        @keyword    size:   The size of resources allocated to this node.
                            (required)
        @type       size:   L{NodeSize}

        @keyword    image:  OS Image to boot on node. (required)
        @type       image:  L{NodeImage}

        @keyword    location: Which data center to create a node in. If empty,
                              undefined behavoir will be selected. (optional)
        @type       location: L{NodeLocation}

        @keyword    auth:   Initial authentication information for the node
                            (optional)
        @type       auth:   L{NodeAuthSSHKey} or L{NodeAuthPassword}

        @return: The newly created node.
        @rtype: L{Node}
        """
        raise NotImplementedError(
            'create_node not implemented for this driver')

    def destroy_node(self, node):
        """Destroy a node.

        Depending upon the provider, this may destroy all data associated with
        the node, including backups.

        @param node: The node to be destroyed
        @type node: L{Node}

        @return: True if the destroy was successful, otherwise False
        @rtype: C{bool}
        """
        raise NotImplementedError(
            'destroy_node not implemented for this driver')

    def reboot_node(self, node):
        """
        Reboot a node.

        @param node: The node to be rebooted
        @type node: L{Node}

        @return: True if the reboot was successful, otherwise False
        @rtype: C{bool}
        """
        raise NotImplementedError(
            'reboot_node not implemented for this driver')

    def list_nodes(self):
        """
        List all nodes
        @return:  list of node objects
        @rtype: C{list} of L{Node}
        """
        raise NotImplementedError(
            'list_nodes not implemented for this driver')

    def list_images(self, location=None):
        """
        List images on a provider

        @keyword location: The location at which to list images
        @type location: L{NodeLocation}

        @return: list of node image objects
        @rtype: C{list} of L{NodeImage}
        """
        raise NotImplementedError(
            'list_images not implemented for this driver')

    def list_sizes(self, location=None):
        """
        List sizes on a provider

        @keyword location: The location at which to list sizes
        @type location: L{NodeLocation}

        @return: list of node size objects
        @rtype: C{list} of L{NodeSize}
        """
        raise NotImplementedError(
            'list_sizes not implemented for this driver')

    def list_locations(self):
        """
        List data centers for a provider

        @return: list of node location objects
        @rtype: C{list} of L{NodeLocation}
        """
        raise NotImplementedError(
            'list_locations not implemented for this driver')

    def deploy_node(self, **kwargs):
        """
        Create a new node, and start deployment.

        Depends on a Provider Driver supporting either using a specific
        password or returning a generated password.

        This function may raise a L{DeploymentException}, if a create_node
        call was successful, but there is a later error (like SSH failing or
        timing out).  This exception includes a Node object which you may want
        to destroy if incomplete deployments are not desirable.

        >>> from libcloud.compute.drivers.dummy import DummyNodeDriver
        >>> from libcloud.compute.deployment import ScriptDeployment
        >>> from libcloud.compute.deployment import MultiStepDeployment
        >>> from libcloud.compute.base import NodeAuthSSHKey
        >>> driver = DummyNodeDriver(0)
        >>> key = NodeAuthSSHKey('...') # read from file
        >>> script = ScriptDeployment("yum -y install emacs strace tcpdump")
        >>> msd = MultiStepDeployment([key, script])
        >>> def d():
        ...     try:
        ...         node = driver.deploy_node(deploy=msd)
        ...     except NotImplementedError:
        ...         print ("not implemented for dummy driver")
        >>> d()
        not implemented for dummy driver

        Deploy node is typically not overridden in subclasses.  The
        existing implementation should be able to handle most such.

        @inherits: L{NodeDriver.create_node}

        @keyword    deploy: Deployment to run once machine is online and
                            availble to SSH.
        @type       deploy: L{Deployment}

        @keyword    ssh_username: Optional name of the account which is used
                                  when connecting to
                                  SSH server (default is root)
        @type       ssh_username: C{str}

        @keyword    ssh_alternate_usernames: Optional list of ssh usernames to
                                             try to connect with if using the
                                             default one fails
        @type       ssh_alternate_usernames: C{list}

        @keyword    ssh_port: Optional SSH server port (default is 22)
        @type       ssh_port: C{int}

        @keyword    ssh_timeout: Optional SSH connection timeout in seconds
                                 (default is None)
        @type       ssh_timeout: C{float}

        @keyword    auth:   Initial authentication information for the node
                            (optional)
        @type       auth:   L{NodeAuthSSHKey} or L{NodeAuthPassword}

        @keyword    ssh_key: A path (or paths) to an SSH private key with which
                             to attempt to authenticate. (optional)
        @type       ssh_key: C{str} or C{list} of C{str}

        @keyword    timeout: How many seconds to wait before timing out.
                             (default is 600)
        @type       timeout: C{int}

        @keyword    max_tries: How many times to retry if a deployment fails
                               before giving up (default is 3)
        @type       max_tries: C{int}

        @keyword    ssh_interface: The interface to wait for. Default is
                                   'public_ips', other option is 'private_ips'.
        @type       ssh_interface: C{str}
        """
        if not libcloud.compute.ssh.have_paramiko:
            raise RuntimeError('paramiko is not installed. You can install ' +
                               'it using pip: pip install paramiko')

        password = None

        if 'create_node' not in self.features:
            raise NotImplementedError(
                'deploy_node not implemented for this driver')
        elif 'generates_password' not in self.features["create_node"]:
            if 'password' not in self.features["create_node"] and \
               'ssh_key' not in self.features["create_node"]:
                raise NotImplementedError(
                    'deploy_node not implemented for this driver')

            if 'auth' not in kwargs:
                value = os.urandom(16)
                kwargs['auth'] = NodeAuthPassword(binascii.hexlify(value))

            if 'ssh_key' not in kwargs:
                password = kwargs['auth'].password

        node = self.create_node(**kwargs)
        max_tries = kwargs.get('max_tries', 3)

        if 'generates_password' in self.features['create_node']:
            password = node.extra.get('password')

        ssh_interface = kwargs.get('ssh_interface', 'public_ips')

        # Wait until node is up and running and has IP assigned
        try:
            node, ip_addresses = self.wait_until_running(
                nodes=[node],
                wait_period=3, timeout=NODE_ONLINE_WAIT_TIMEOUT,
                ssh_interface=ssh_interface)[0]
        except Exception:
            e = sys.exc_info()[1]
            raise DeploymentError(node=node, original_exception=e, driver=self)

        if password:
            node.extra['password'] = password

        ssh_username = kwargs.get('ssh_username', 'root')
        ssh_alternate_usernames = kwargs.get('ssh_alternate_usernames', [])
        ssh_port = kwargs.get('ssh_port', 22)
        ssh_timeout = kwargs.get('ssh_timeout', 10)
        ssh_key_file = kwargs.get('ssh_key', None)
        timeout = kwargs.get('timeout', SSH_CONNECT_TIMEOUT)

        deploy_error = None

        for username in ([ssh_username] + ssh_alternate_usernames):
            try:
                self._connect_and_run_deployment_script(
                    task=kwargs['deploy'], node=node,
                    ssh_hostname=ip_addresses[0], ssh_port=ssh_port,
                    ssh_username=username, ssh_password=password,
                    ssh_key_file=ssh_key_file, ssh_timeout=ssh_timeout,
                    timeout=timeout, max_tries=max_tries)
            except Exception:
                # Try alternate username
                # Todo: Need to fix paramiko so we can catch a more specific
                # exception
                e = sys.exc_info()[1]
                deploy_error = e
            else:
                # Script sucesfully executed, don't try alternate username
                deploy_error = None
                break

        if deploy_error is not None:
            raise DeploymentError(node=node, original_exception=deploy_error,
                                  driver=self)

        return node

    def create_volume(self, size, name, location=None, snapshot=None):
        """
        Create a new volume.

        @param      size: Size of volume in gigabytes (required)
        @type       size: C{int}

        @keyword    name: Name of the volume to be created
        @type       name: C{str}

        @keyword    location: Which data center to create a volume in. If
                               empty, undefined behavoir will be selected.
                               (optional)
        @type       location: L{NodeLocation}

        @keyword    snapshot:  Name of snapshot from which to create the new
                               volume.  (optional)
        @type       snapshot:  C{str}

        @return: The newly created volume.
        @rtype: L{StorageVolume}
        """
        raise NotImplementedError(
            'create_volume not implemented for this driver')

    def destroy_volume(self, volume):
        """
        Destroys a storage volume.

        @param      volume: Volume to be destroyed
        @type       volume: L{StorageVolume}

        @rtype: C{bool}
        """

        raise NotImplementedError(
            'destroy_volume not implemented for this driver')

    def attach_volume(self, node, volume, device=None):
        """
        Attaches volume to node.

        @param      node: Node to attach volume to
        @type       node: L{Node}

        @param      volume: Volume to attach
        @type       volume: L{StorageVolume}

        @param      device: Where the device is exposed,
                            e.g. '/dev/sdb (optional)
        @type       device: C{str}

        @rtype: C{bool}
        """
        raise NotImplementedError('attach not implemented for this driver')

    def detach_volume(self, volume):
        """
        Detaches a volume from a node.

        @param      volume: Volume to be detached
        @type       volume: L{StorageVolume}

        @rtype: C{bool}
        """

        raise NotImplementedError('detach not implemented for this driver')

    def _wait_until_running(self, node, wait_period=3, timeout=600,
                            ssh_interface='public_ips', force_ipv4=True):
        # This is here for backward compatibility and will be removed in the
        # next major release
        return self._wait_until_running(nodes=[node], wait_period=wait_period,
                                        timeout=timeout,
                                        ssh_interface=ssh_interface,
                                        force_ipv4=force_ipv4)

    def wait_until_running(self, nodes, wait_period=3, timeout=600,
                           ssh_interface='public_ips', force_ipv4=True):
        """
        Block until the given nodes are fully booted and have an IP address
        assigned.

        @keyword    nodes: list of node instances.
        @type       nodes: C{List} of L{Node}

        @keyword    wait_period: How many seconds to between each loop
                                 iteration (default is 3)
        @type       wait_period: C{int}

        @keyword    timeout: How many seconds to wait before timing out
                             (default is 600)
        @type       timeout: C{int}

        @keyword    ssh_interface: The interface to wait for.
                                   Default is 'public_ips', other option is
                                   'private_ips'.
        @type       ssh_interface: C{str}

        @keyword    force_ipv4: Ignore ipv6 IP addresses (default is True).
        @type       force_ipv4: C{bool}

        @return: C{[(Node, ip_addresses)]} list of tuple of Node instance and
                 list of ip_address on success.

        @return: List of tuple of Node instance and list of ip_address on
                 success (node, ip_addresses).
        @rtype: C{list} of C{tuple}
        """
        def is_supported(address):
            """Return True for supported address"""
            if force_ipv4 and not is_valid_ip_address(address=address,
                                                      family=socket.AF_INET):
                return False
            return True

        def filter_addresses(addresses):
            """Return list of supported addresses"""
            return [a for a in addresses if is_supported(a)]

        start = time.time()
        end = start + timeout

        if ssh_interface not in ['public_ips', 'private_ips']:
            raise ValueError('ssh_interface argument must either be' +
                             'public_ips or private_ips')

        uuids = set([n.uuid for n in nodes])
        while time.time() < end:
            nodes = self.list_nodes()
            nodes = list([n for n in nodes if n.uuid in uuids])

            if len(nodes) > len(uuids):
                found_uuids = [n.uuid for n in nodes]
                msg = ('Unable to match specified uuids ' +
                       '(%s) with existing nodes. Found ' % (uuids) +
                       'multiple nodes with same uuid: (%s)' % (found_uuids))
                raise LibcloudError(value=msg, driver=self)

            running_nodes = [n for n in nodes if n.state == NodeState.RUNNING]
            addresses = [filter_addresses(getattr(n, ssh_interface)) for n in
                         running_nodes]
            if len(running_nodes) == len(uuids) == len(addresses):
                return list(zip(running_nodes, addresses))
            else:
                time.sleep(wait_period)
                continue

        raise LibcloudError(value='Timed out after %s seconds' % (timeout),
                            driver=self)

    def _ssh_client_connect(self, ssh_client, wait_period=1.5, timeout=300):
        """
        Try to connect to the remote SSH server. If a connection times out or
        is refused it is retried up to timeout number of seconds.

        @keyword    ssh_client: A configured SSHClient instance
        @type       ssh_client: C{SSHClient}

        @keyword    wait_period: How many seconds to wait between each loop
                                 iteration (default is 1.5)
        @type       wait_period: C{int}

        @keyword    timeout: How many seconds to wait before timing out
                             (default is 600)
        @type       timeout: C{int}

        @return: C{SSHClient} on success
        """
        start = time.time()
        end = start + timeout

        while time.time() < end:
            try:
                ssh_client.connect()
            except (IOError, socket.gaierror, socket.error):
                # Retry if a connection is refused or timeout
                # occurred
                ssh_client.close()
                time.sleep(wait_period)
                continue
            else:
                return ssh_client

        raise LibcloudError(value='Could not connect to the remote SSH ' +
                            'server. Giving up.', driver=self)

    def _connect_and_run_deployment_script(self, task, node, ssh_hostname,
                                           ssh_port, ssh_username,
                                           ssh_password, ssh_key_file,
                                           ssh_timeout, timeout, max_tries):
        ssh_client = SSHClient(hostname=ssh_hostname,
                               port=ssh_port, username=ssh_username,
                               password=ssh_password,
                               key=ssh_key_file,
                               timeout=ssh_timeout)

        # Connect to the SSH server running on the node
        ssh_client = self._ssh_client_connect(ssh_client=ssh_client,
                                              timeout=timeout)

        # Execute the deployment task
        self._run_deployment_script(task=task, node=node,
                                    ssh_client=ssh_client,
                                    max_tries=max_tries)

    def _run_deployment_script(self, task, node, ssh_client, max_tries=3):
        """
        Run the deployment script on the provided node. At this point it is
        assumed that SSH connection has already been established.

        @keyword    task: Deployment task to run on the node.
        @type       task: C{Deployment}

        @keyword    node: Node to operate one
        @type       node: C{Node}

        @keyword    ssh_client: A configured and connected SSHClient instance
        @type       ssh_client: C{SSHClient}

        @keyword    max_tries: How many times to retry if a deployment fails
                               before giving up (default is 3)
        @type       max_tries: C{int}

        @return: C{Node} Node instance on success.
        """
        tries = 0
        while tries < max_tries:
            try:
                node = task.run(node, ssh_client)
            except Exception:
                e = sys.exc_info()[1]
                tries += 1
                if tries >= max_tries:
                    e = sys.exc_info()[1]
                    raise LibcloudError(value='Failed after %d tries: %s'
                                        % (max_tries, str(e)), driver=self)
            else:
                ssh_client.close()
                return node

    def _get_size_price(self, size_id):
        return get_size_price(driver_type='compute',
                              driver_name=self.api_name,
                              size_id=size_id)

def is_private_subnet(ip):
    """
    Utility function to check if an IP address is inside a private subnet.

    @type ip: C{str}
    @keyword ip: IP address to check

    @return: C{bool} if the specified IP address is private.
    """
    priv_subnets = [{'subnet': '10.0.0.0', 'mask': '255.0.0.0'},
                    {'subnet': '172.16.0.0', 'mask': '255.240.0.0'},
                    {'subnet': '192.168.0.0', 'mask': '255.255.0.0'}]

    ip = struct.unpack('I', socket.inet_aton(ip))[0]

    for network in priv_subnets:
        subnet = struct.unpack('I', socket.inet_aton(network['subnet']))[0]
        mask = struct.unpack('I', socket.inet_aton(network['mask']))[0]

        if (ip & mask) == (subnet & mask):
            return True

    return False

def is_valid_ip_address(address, family=socket.AF_INET):
    """
    Check if the provided address is valid IPv4 or IPv6 adddress.

    @return: C{bool} True if the provided address is valid.
    """
    try:
        socket.inet_pton(family, address)
    except socket.error:
        return False
    return True

if __name__ == "__main__":
    import doctest
    doctest.testmod()


text:
using GogoKit.Services;

namespace GogoKit.Tests.Fakes
{
    public class FakeLocalizationProvider : ILocalizationProvider
    {
        public string LanguageCode { get; set; }
        public string CountryCode { get; set; }
        public string CurrencyCode { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package WiredCatsControllers;

import WiredCatsEvents.SensorEvents.EventPositionChanged;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 *
 * @author BruceCrane
 */
public class ControllerDrive extends WiredCatsController
{

    private Encoder leftEncoder;
    private Encoder rightEncoder;
    private Gyro gyro;

    private double leftEncoderDistance;
    private double rightEncoderDistance;

    private double lastLeftEncoderDistance;
    private double lastRightEncoderDistance;

    public double lastGyroValue;

    private double gyroValue;

    private Timer timer;

    public ControllerDrive(int limit)
    {
        super(limit);
        //TODO
        leftEncoder = new Encoder(3,4);  //competition: 3,4 / practice: 8,7
        rightEncoder = new Encoder(2,1); //competition: 2,1 / practice: 6,5
        gyro = new Gyro(2);

        leftEncoderDistance = 0;
        rightEncoderDistance = 0;
        lastLeftEncoderDistance = 0;
        lastRightEncoderDistance = 0;

        timer = new Timer();
        timer.start();

        lastGyroValue = 0;
        System.out.println("[WiredCats] Drive Controller Initialized.");
    }

    /**
     * Called by the EventLogger, WiredCats2415, or Autonomous mode,
     * It resets the encoder values to 0 ticks.
     */
    public void resetEncoders(){
        leftEncoder.reset();
        rightEncoder.reset();
    }

    public int getLeftTicks() { return leftEncoder.get(); }

    public int getRightTicks() { return rightEncoder.get(); }

    public double getGyro() { return gyro.getAngle(); }

    public void run() {
        leftEncoder.start();
        rightEncoder.start();

        while (true) {
            leftEncoderDistance = leftEncoder.get()/1000.0;
            rightEncoderDistance = rightEncoder.get()/1000.0;
            gyroValue = gyro.getAngle();

            if (leftEncoderDistance != lastLeftEncoderDistance ||
                   rightEncoderDistance != lastRightEncoderDistance)
            {
                lastLeftEncoderDistance = leftEncoderDistance;
                lastRightEncoderDistance = rightEncoderDistance;
                lastGyroValue = gyroValue;
                fireEvent( new EventPositionChanged(this, leftEncoderDistance, rightEncoderDistance, timer.get()));
            }

            try {
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microting.eForm;
using Microting.eForm.Dto;
using Microting.eForm.Helpers;
using Microting.eForm.Infrastructure;
using Microting.eForm.Infrastructure.Data.Entities;
using Microting.eForm.Infrastructure.Helpers;
using NUnit.Framework;

namespace eFormSDK.Integration.Base.SqlControllerTests
{
    [Parallelizable(ParallelScope.Fixtures)]
    [TestFixture]
    public class SqlControllerTestPublicSetting : DbTestFixture
    {
        private SqlController sut;
        private TestHelpers testHelpers;

        public override async Task DoSetup()
        {
            #region Setup SettingsTableContent

            DbContextHelper dbContextHelper = new DbContextHelper(ConnectionString);
            SqlController sql = new SqlController(dbContextHelper);
            await sql.SettingUpdate(Settings.token, "abc1234567890abc1234567890abcdef");
            await sql.SettingUpdate(Settings.firstRunDone, "true");
            await sql.SettingUpdate(Settings.knownSitesDone, "true");
            #endregion

            sut = new SqlController(dbContextHelper);
            sut.StartLog(new CoreBase());
            testHelpers = new TestHelpers(ConnectionString);
            await testHelpers.GenerateDefaultLanguages();
            await sut.SettingUpdate(Settings.fileLocationPicture, @"\output\dataFolder\picture\");
            await sut.SettingUpdate(Settings.fileLocationPdf, @"\output\dataFolder\pdf\");
            await sut.SettingUpdate(Settings.fileLocationJasper, @"\output\dataFolder\reports\");
        }

        #region Public Setting

        [Test]
        public async Task SQL_Setting_SettingCreateDefault_CreatesDetault()
        {
            // Arrance

            // Act
            var match = await sut.SettingCreateDefaults();
            // Assert

            Assert.True(match);

        }

        [Test]
        public async Task SQL_Setting_SetingCreate_CreatesSetting()
        {
            // Arrance

            // Act
            var match1 = await sut.SettingCreate(Settings.firstRunDone);
            var match2 = await sut.SettingCreate(Settings.logLevel);
            var match3 = await sut.SettingCreate(Settings.logLimit);
            var match4 = await sut.SettingCreate(Settings.knownSitesDone);
            var match5 = await sut.SettingCreate(Settings.fileLocationPicture);
            var match6 = await sut.SettingCreate(Settings.fileLocationPdf);
            var match7 = await sut.SettingCreate(Settings.fileLocationJasper);
            var match8 = await sut.SettingCreate(Settings.token);
            var match9 = await sut.SettingCreate(Settings.comAddressBasic);
            var match10 = await sut.SettingCreate(Settings.comAddressApi);
            var match11 = await sut.SettingCreate(Settings.comAddressPdfUpload);
            var match12 = await sut.SettingCreate(Settings.comOrganizationId);
            var match13 = await sut.SettingCreate(Settings.awsAccessKeyId);
            var match14 = await sut.SettingCreate(Settings.awsSecretAccessKey);
            var match15 = await sut.SettingCreate(Settings.awsEndPoint);
            var match16 = await sut.SettingCreate(Settings.unitLicenseNumber);
            var match17 = await sut.SettingCreate(Settings.httpServerAddress);

            // Assert
            Assert.True(match1);
            Assert.True(match2);
            Assert.True(match3);
            Assert.True(match4);
            Assert.True(match5);
            Assert.True(match6);
            Assert.True(match7);
            Assert.True(match8);
            Assert.True(match9);
            Assert.True(match10);
            Assert.True(match11);
            Assert.True(match12);
            Assert.True(match13);
            Assert.True(match14);
            Assert.True(match15);
            Assert.True(match16);
            Assert.True(match17);

            var matchb1 = await sut.SettingRead(Settings.awsAccessKeyId);
            var matchb2 = await sut.SettingRead(Settings.awsEndPoint);
            var matchb3 = await sut.SettingRead(Settings.awsSecretAccessKey);
            var matchb4 = await sut.SettingRead(Settings.comAddressApi);
            var matchb5 = await sut.SettingRead(Settings.comAddressBasic);
            var matchb6 = await sut.SettingRead(Settings.comAddressPdfUpload);
            var matchb7 = await sut.SettingRead(Settings.comOrganizationId);
            var matchb8 = await sut.SettingRead(Settings.fileLocationJasper);
            var matchb9 = await sut.SettingRead(Settings.fileLocationPdf);
            var matchb10 = await sut.SettingRead(Settings.fileLocationPicture);
            var matchb11 = await sut.SettingRead(Settings.firstRunDone);
            var matchb12 = await sut.SettingRead(Settings.httpServerAddress);
            var matchb13 = await sut.SettingRead(Settings.knownSitesDone);
            var matchb14 = await sut.SettingRead(Settings.logLevel);
            var matchb15 = await sut.SettingRead(Settings.logLimit);
            var matchb16 = await sut.SettingRead(Settings.token);
            var matchb17 = await sut.SettingRead(Settings.unitLicenseNumber);

            // Assert
            Assert.AreEqual(matchb1, "3T98EGIO4Y9H8W2");
            Assert.AreEqual(matchb2, "https://sqs.eu-central-1.amazonaws.com/564456879978/");
            Assert.AreEqual(matchb3, "098u34098uergijt3098w");
            Assert.AreEqual(matchb4, "http://srv05.microting.com");
            Assert.AreEqual(matchb5, "https://basic.microting.com");
            Assert.AreEqual(matchb6, "https://srv16.microting.com");
            Assert.AreEqual(matchb7, "64856189");
            Assert.AreEqual(matchb8, @"\output\dataFolder\reports\");
            Assert.AreEqual(matchb9, @"\output\dataFolder\pdf\");
            Assert.AreEqual(matchb10, @"\output\dataFolder\picture\");
            Assert.AreEqual(matchb11, "true");
            Assert.AreEqual(matchb12, "http://localhost:3000");
            Assert.AreEqual(matchb13, "true");
            Assert.AreEqual(matchb14, "4");
            Assert.AreEqual(matchb15, "25000");
            Assert.AreEqual(matchb16, "abc1234567890abc1234567890abcdef");
            Assert.AreEqual(matchb17, "55");

        }

        // [Test]
        // public async Task SQL_Setting_SettingRead_ReadsSetting()
        // {
        //     // Arrance
        //
        //     // Act
        //     var match1 = await sut.SettingRead(Settings.awsAccessKeyId);
        //     var match2 = await sut.SettingRead(Settings.awsEndPoint);
        //     var match3 = await sut.SettingRead(Settings.awsSecretAccessKey);
        //     var match4 = await sut.SettingRead(Settings.comAddressApi);
        //     var match5 = await sut.SettingRead(Settings.comAddressBasic);
        //     var match6 = await sut.SettingRead(Settings.comAddressPdfUpload);
        //     var match7 = await sut.SettingRead(Settings.comOrganizationId);
        //     var match8 = await sut.SettingRead(Settings.fileLocationJasper);
        //     var match9 = await sut.SettingRead(Settings.fileLocationPdf);
        //     var match10 = await sut.SettingRead(Settings.fileLocationPicture);
        //     var match11 = await sut.SettingRead(Settings.firstRunDone);
        //     var match12 = await sut.SettingRead(Settings.httpServerAddress);
        //     var match13 = await sut.SettingRead(Settings.knownSitesDone);
        //     var match14 = await sut.SettingRead(Settings.logLevel);
        //     var match15 = await sut.SettingRead(Settings.logLimit);
        //     var match16 = await sut.SettingRead(Settings.token);
        //     var match17 = await sut.SettingRead(Settings.unitLicenseNumber);
        //
        //
        //     // Assert
        //     Assert.AreEqual(match1, "XXX");
        //     Assert.AreEqual(match2, "XXX");
        //     Assert.AreEqual(match3, "098u34098uergijt3098w");
        //     Assert.AreEqual(match4, "https://xxxxxx.xxxxxx.com");
        //     Assert.AreEqual(match5, "https://basic.microting.com");
        //     Assert.AreEqual(match6, "https://srv16.microting.com");
        //     Assert.AreEqual(match7, "64856189");
        //     Assert.AreEqual(match8, @"\output\dataFolder\reports\");
        //     Assert.AreEqual(match9, @"\output\dataFolder\pdf\");
        //     Assert.AreEqual(match10, @"\output\dataFolder\picture\");
        //     Assert.AreEqual(match11, "true");
        //     Assert.AreEqual(match12, "http://localhost:3000");
        //     Assert.AreEqual(match13, "true");
        //     Assert.AreEqual(match14, "4");
        //     Assert.AreEqual(match15, "25000");
        //     Assert.AreEqual(match16, "abc1234567890abc1234567890abcdef");
        //     Assert.AreEqual(match17, "55");
        //
        //
        // }

        [Test]
        public async Task SQL_Setting_SettingUpdate_UpdatesSetting()
        {
            // Arrance

            // Act
            await sut.SettingUpdate(Settings.token, "player");
            var match = DbContext.Settings.AsNoTracking().ToList();

            // Assert
            Assert.AreEqual(match[7].Value, "player");
        }

        // [Test]
        // public async Task SQL_Setting_SettingCheckAll_AllSettingsAreCreated()
        // {
        //     // Arrance
        //
        //     // Act
        //     List<Setting> setting = DbContext.Settings.AsNoTracking().ToList();
        //     await sut.SettingCheckAll();
        //     var match = DbContext.Settings.AsNoTracking().ToList();
        //
        //     // Assert
        //     Assert.NotNull(match);
        //     #region Name
        //
        //     Assert.AreEqual(match[0].Name, "firstRunDone");
        //     Assert.AreEqual(match[1].Name, "logLevel");
        //     Assert.AreEqual(match[2].Name, "logLimit");
        //     Assert.AreEqual(match[3].Name, "knownSitesDone");
        //     Assert.AreEqual(match[4].Name, "fileLocationPicture");
        //     Assert.AreEqual(match[5].Name, "fileLocationPdf");
        //     Assert.AreEqual(match[6].Name, "fileLocationJasper");
        //     Assert.AreEqual(match[7].Name, "token");
        //     Assert.AreEqual(match[8].Name, "comAddressBasic");
        //     Assert.AreEqual(match[9].Name, "comAddressApi");
        //     Assert.AreEqual(match[10].Name, "comAddressPdfUpload");
        //     Assert.AreEqual(match[11].Name, "comOrganizationId");
        //     Assert.AreEqual(match[12].Name, "awsAccessKeyId");
        //     Assert.AreEqual(match[13].Name, "awsSecretAccessKey");
        //     Assert.AreEqual(match[14].Name, "awsEndPoint");
        //     Assert.AreEqual(match[15].Name, "unitLicenseNumber");
        //     Assert.AreEqual(match[16].Name, "httpServerAddress");
        //     #endregion
        //
        //     #region Value
        //     Assert.AreEqual(match[0].Value, "true");
        //     Assert.AreEqual(match[1].Value, "4");
        //     Assert.AreEqual(match[2].Value, "25000");
        //     Assert.AreEqual(match[3].Value, "true");
        //     Assert.AreEqual(match[4].Value, @"\output\dataFolder\picture\");
        //     Assert.AreEqual(match[5].Value, @"\output\dataFolder\pdf\");
        //     Assert.AreEqual(match[6].Value, @"\output\dataFolder\reports\");
        //     Assert.AreEqual(match[7].Value, "abc1234567890abc1234567890abcdef");
        //     Assert.AreEqual(match[8].Value, "https://basic.microting.com");
        //     Assert.AreEqual(match[9].Value, "https://xxxxxx.xxxxxx.com");
        //     Assert.AreEqual(match[10].Value, "https://xxxxxx.xxxxxx.com");
        //     Assert.AreEqual(match[11].Value, "64856189");
        //     Assert.AreEqual(match[12].Value, "3T98EGIO4Y9H8W2");
        //     Assert.AreEqual(match[13].Value, "098u34098uergijt3098w");
        //     Assert.AreEqual(match[14].Value, "https://sqs.eu-central-1.amazonaws.com/564456879978/");
        //     Assert.AreEqual(match[15].Value, "55");
        //     Assert.AreEqual(match[16].Value, "http://localhost:3000");
        //     #endregion
        //
        //     #region ID's
        //     Assert.AreEqual(match[0].Id, 1);
        //     Assert.AreEqual(match[1].Id, 2);
        //     Assert.AreEqual(match[2].Id, 3);
        //     Assert.AreEqual(match[3].Id, 4);
        //     Assert.AreEqual(match[4].Id, 5);
        //     Assert.AreEqual(match[5].Id, 6);
        //     Assert.AreEqual(match[6].Id, 7);
        //     Assert.AreEqual(match[7].Id, 8);
        //     Assert.AreEqual(match[8].Id, 9);
        //     Assert.AreEqual(match[9].Id, 10);
        //     Assert.AreEqual(match[10].Id, 11);
        //     Assert.AreEqual(match[11].Id, 12);
        //     Assert.AreEqual(match[12].Id, 13);
        //     Assert.AreEqual(match[13].Id, 14);
        //     Assert.AreEqual(match[14].Id, 15);
        //     Assert.AreEqual(match[15].Id, 16);
        //
        //     #endregion
        //
        // }
        #endregion

        #region eventhandlers
#pragma warning disable 1998
        public async Task EventCaseCreated(object sender, EventArgs args)
        {
            // Does nothing for web implementation
        }

        public async Task EventCaseRetrived(object sender, EventArgs args)
        {
            // Does nothing for web implementation
        }

        public async Task EventCaseCompleted(object sender, EventArgs args)
        {
            // Does nothing for web implementation
        }

        public async Task EventCaseDeleted(object sender, EventArgs args)
        {
            // Does nothing for web implementation
        }

        public async Task EventFileDownloaded(object sender, EventArgs args)
        {
            // Does nothing for web implementation
        }

        public async Task EventSiteActivated(object sender, EventArgs args)
        {
            // Does nothing for web implementation
        }
#pragma warning restore 1998
        #endregion
    }

}


text:
package io.parsingdata.metal.data;

import java.io.IOException;

public abstract class Source {

    public Slice slice(final long offset, final int size) throws IOException {
        final byte[] data = getData(offset, size);
        return new Slice(this, offset, data);
    }

    protected abstract byte[] getData(long offset, int size) throws IOException;

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DatabaseUtilities_1 = require("./DatabaseUtilities");
after((done) => {
    DatabaseUtilities_1.DatabaseUtilities.shutdownPool();
    done();
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFsX2FmdGVyLnRlc3QuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJnbG9iYWxfYWZ0ZXIudGVzdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLDJEQUF3RDtBQUV4RCxLQUFLLENBQUMsQ0FBQyxJQUFJLEVBQUUsRUFBRTtJQUNYLHFDQUFpQixDQUFDLFlBQVksRUFBRSxDQUFDO0lBQ2pDLElBQUksRUFBRSxDQUFDO0FBQ1gsQ0FBQyxDQUFDLENBQUMifQ==


text:
<?php

namespace Cordova\UploaderBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Cordova\UploaderBundle\Entity\SignedDocument;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DefaultController extends Controller
{
    public function indexAction()
    {
	$form = $this->get('cordova_uploader.form_factory.signeddocument')->createForm();

        $request = $this->get('request');

        if ($request->getMethod() == 'POST') {

            $form->bindRequest($request);

            $dir = '../media/reception/';

            if($form->isValid()) {

                $signeddocument = $form->getData();

                $uploadedfile = $signeddocument->getAttachment();
                $uploadedfile->move($dir, 'signeddoc.doc');

                $em = $this->get('doctrine')->getEntityManager();
                $em->persist($signeddocument);
                $em->flush();

                //reset the form
                $form->setData(new SignedDocument());
            }
        }

        return $this->render(
            'CordovaUploaderBundle:Default:index.html.twig',
            array(
                'form' => $form->createView()
            )
        );
    }
}


text:
package org.yumix.quaoar;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

import javax.inject.Inject;
import javax.mail.Session;

import org.yumix.mail.sender.Mail;
import org.yumix.mail.session.UserSetting;
import org.yumix.mail.session.SessionProvider;
import org.yumix.mail.session.qualifier.ICloud;

public class MailWriterController implements Initializable {

	@Inject
	private QuaoarRunner quaoarRunner;

	@FXML
	private Button send;

	@FXML
	private Button cancel;

	@FXML
	private TextField fromAddr;

	@FXML
	private TextField ccAddr;

	@FXML
	private TextField bccAddr;

	@FXML
	private TextField toAddr;

	@FXML
	private TextField subject;

	@FXML
	private TextArea messageBody;

	@Inject
	private UserSetting userSetting;

	@Inject
	@ICloud
	private SessionProvider sessionProvider;

	@FXML
	public void onClickSend(ActionEvent event) {
		String[] toList = this.toAddr.getText().split("[,;]");
		String[] ccList = this.ccAddr.getText().split("[,;]");
		String[] bccList = this.bccAddr.getText().split("[,;]");
		String subject = this.subject.getText();
		String message = this.messageBody.getText();

//		Session session = SessionProviderFactory.getInstance().getSession(ICloudProvider.class, from, "yumix_h@icloud.com", "Dysnomi@0");
		Session session = sessionProvider.getSession();
		Mail.from(userSetting.getFromAddress()).to(toList).cc(ccList).bcc(bccList).subject(subject).message(message).send(session);

		quaoarRunner.select(WhichScene.MAILBOX);
	}

	@FXML
	public void onClickCancel(ActionEvent event) {
		quaoarRunner.select(WhichScene.MAILBOX);
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		fromAddr.setText(userSetting.getFromAddress());
	}
}


text:
package soundcheck.musicPlayer.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXTable;
import org.pushingpixels.substance.api.skin.SubstanceRavenLookAndFeel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import soundcheck.musicPlayer.ServiceCallback;
import soundcheck.shared.Const;
import soundcheck.shared.Peer;
import soundcheck.shared.Song;
import soundcheck.shared.Util;
import soundcheck.shared.Zone;
import soundcheck.shared.ZoneProperties;

/**
 * Creates the GUI by using methods to create each of the 5 quadrants in border layout.
 * Listeners are created inline for the individual elements.
 *
 */
public final class PlayerGUI {
	final static Logger logger = LoggerFactory.getLogger(PlayerGUI.class);

	List<Song> sl = new ArrayList<Song>();

	JFrame frame;
	private final OptionsPane optionsPane;
	private final PeerManagementPane peerPane;
	final SongPane songPane;
	private final PlaylistPane playPane;
	public final ControlPane controlPane;
	final InfoPane infoPane;

	JXCollapsiblePane collapsiblePane;

	// The zone that is being modified by user actions on the GUI
	private volatile Zone currentZone;

	private volatile Map<Zone, ZoneProperties> zoneMap;

	/**
	 * Create the application.
	 */
	public PlayerGUI(ServiceCallback callback) {
		// Create nice looking window
		JFrame.setDefaultLookAndFeelDecorated(true);
		try {
			UIManager.setLookAndFeel( new SubstanceRavenLookAndFeel());
		} catch (UnsupportedLookAndFeelException e) {
			logger.error("",e);
		}

		// Create GUI components
		optionsPane = new OptionsPane(this, callback);
		peerPane = new PeerManagementPane(this, callback);
		songPane = new SongPane(this, callback);
		playPane = new PlaylistPane(this, callback);
		controlPane = new ControlPane(this);
		infoPane = new InfoPane(this);

		initialize();
	}

	/**
	 * Change which zone is being modified by user actions
	 * @param zone
	 */
	void setCurrentZone(Zone zone) {
		// If zone is empty, don't allow switching to it.
		if( zoneMap.containsKey(zone) ) {

			currentZone = zone;

			/* The zone's name is set before it is added to
			 * the JTree, so we know this will be correct
			 * if the zone is added from the JTree */
			playPane.setZone(currentZone.toString());

			playPane.setPlayList(zoneMap.get(currentZone).getPlayList());
		}
	}

	/**
	 * Set the progress bar to the specified time
	 * @param timeStamp
	 */
	public void updateProgressBar(long timeStamp) {
		infoPane.setProgressPosition(timeStamp);
	}

	public void isStreaming(boolean isPlaying) {
		playPane.setIconPlay(isPlaying);
	}

	/**
	 * Get the zone that is being modified by user actions
	 * @return
	 */
	public Zone getCurrentZone() {
		return currentZone;
	}

	/**
	 * Get the queue currently displayed in the GUI. If no queue
	 * exists, return a list of size 0.
	 * @return
	 */
	List<Song> getCurrentQueue() {
		if( zoneMap != null && currentZone != null ) {
			return zoneMap.get(currentZone).getPlayList();
		} else {
			return new ArrayList<Song>();
		}
	}

	/**
	 * Sets the current zone to the given zone only if
	 * the current zone is not valid as is.
	 */
	void refreshCurrentZone(Zone zone, boolean force) {
		// Ensure argument zone is valid
		if( zone == null) {
			return;
		}

		// Check if current zone is valid
		if( (currentZone == null
				|| zoneMap.get(currentZone) == null)
				|| force == true ) {
			setCurrentZone(zone);
		}
	}

	/**
	 * Set the values of the config pane to the values in the hash map
	 * @param configs
	 */
	public void setInitConfig(HashMap<String,String> configs) {
		optionsPane.setInitialValues(configs);
	}

	/**
	 * Set the visibility of the GUI
	 * @param b True if the GUI should be visible
	 */
	public void setVisible(boolean b) {
		frame.setVisible(b);
	}

	/**
	 * Apply update to peer management pane.
	 * @param peerList
	 */
	public void updatePeerList(List<Peer> peerList) {
		logger.trace("Updating peerlist");
		peerPane.setPeers(peerList);
	}

	/**
	 * Apply peer song update to song pane.
	 * @param peerList
	 */
	public void updateSongList(List<Song> songList) {
		logger.trace("Updating songlist");
		songPane.loadSongList( songList );
	}

	/**
	 * Apply new zone filter to peer management pane
	 * @param zoneMap
	 */
	public void updateZoneMap(Map<Zone,ZoneProperties> zoneMap) {
		this.zoneMap = zoneMap;
		peerPane.refreshZones();
		playPane.setPlayList(zoneMap.get(currentZone).getPlayList());
	}

	public Map<Zone, ZoneProperties> getZoneMap() {
		return zoneMap;
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		// Create the overall frame
		frame = new JFrame();

		// Revert to system look and feel for specific components, since I don't have enough time to
		// learn how to modify my own look and feels and the L&F I'm using overrides custom settings.
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			logger.error("",e);
		} catch (InstantiationException e) {
			logger.error("",e);
		} catch (IllegalAccessException e) {
			logger.error("",e);
		} catch (UnsupportedLookAndFeelException e) {
			logger.error("",e);
		}

		frame.setBackground(Const.bgColor);

		frame.setTitle(Const.PROJECT_NAME);

		frame.setIconImage( new Util().createImageIcon("/images/soundCheckLogoSmall.png", "SoundCheck Icon").getImage());
		frame.setBounds(100, 100, 1280, 720);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new BorderLayout(5, 0));
		frame.setResizable(true);

		// Create the left pane. This pane contains zone information
		JPanel leftPanel = peerPane.createPeerManagementPane();

		// Create the middle pane. This is where song information is stored.
		JXTable songTable = songPane.createSongPane();

		// Create right pane. This controls the playlist
		JPanel rightPanel = playPane.createPlaylistPane();
		rightPanel.setPreferredSize(new Dimension(150, 0));

		// Revert back to nice looking L&F for the remainder of the options
		try {
			UIManager.setLookAndFeel(new SubstanceRavenLookAndFeel());
		} catch (UnsupportedLookAndFeelException e) {
			logger.error("",e);
		}

		// Create the collapsible left pane for the options menu.
		collapsiblePane = optionsPane.createOptionsPane();

		// Add scroll panes
		JScrollPane songScrollPane = new JScrollPane(songTable);

		JScrollPane rightScrollPane = new JScrollPane(rightPanel);
		rightScrollPane.setMinimumSize(new Dimension(210,130));
		rightScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

		// Create top pane. This pane contains the search bar
		JPanel topPanel = controlPane.createControlPane();

		// Create the bottom pane. This contains information on the currently playing song
		JPanel bottomPanel = infoPane.createInfoPane();

		// Build the splitpanes to allow resizing of panes
		JSplitPane leftSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, songScrollPane );
		JSplitPane rightSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSplit, rightScrollPane);

		leftSplit.setResizeWeight(.2);
		rightSplit.setResizeWeight(.9);

		leftSplit.setContinuousLayout(true);
		rightSplit.setContinuousLayout(true);

		leftSplit.setDividerSize(5);
		rightSplit.setDividerSize(5);

		// Add all elements to the frame
		frame.getContentPane().add(topPanel, BorderLayout.PAGE_START);
		frame.getContentPane().add(collapsiblePane, BorderLayout.LINE_START);
		frame.getContentPane().add(rightSplit, BorderLayout.CENTER);
		frame.getContentPane().add(bottomPanel, BorderLayout.PAGE_END);
	}

	/**
	 * The search box has changed. Update the filter
	 * for the song list.
	 */
	void newFilter(String filterText) {
		songPane.newFilter(filterText);
	}
}


text:
package in.arjsna.audiorecorder.recordingservice;

import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.processors.BehaviorProcessor;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.inject.Inject;

public class AudioRecorder implements IAudioRecorder {

  private static final int RECORDER_STATE_FAILURE = -1;
  private static final int RECORDER_STATE_IDLE = 0;
  private static final int RECORDER_STATE_STARTING = 1;
  private static final int RECORDER_STATE_STOPPING = 2;
  private static final int RECORDER_STATE_BUSY = 3;

  private volatile int recorderState;

  private int mRecorderSampleRate = 8000;

  private AudioSaveHelper audioSaveHelper = null;

  private final Object recorderStateMonitor = new Object();

  private byte[] recordBuffer;

  private final CompositeDisposable compositeDisposable = new CompositeDisposable();

  private final AtomicLong mRecordTimeCounter = new AtomicLong(0);
  private final AtomicBoolean mIsPaused = new AtomicBoolean(false);
  private RecordTime currentRecordTime;

  @Inject
  public AudioRecorder(AudioSaveHelper audioSaveHelper) {
    this.audioSaveHelper = audioSaveHelper;
  }

  @SuppressWarnings("ResultOfMethodCallIgnored") private void onRecordFailure() {
    recorderState = RECORDER_STATE_FAILURE;
    finishRecord();
  }

  @Override public void startRecord(int recorderSampleRate) {
    if (recorderState != RECORDER_STATE_IDLE) {
      return;
    }
    this.mRecorderSampleRate = recorderSampleRate;
    audioSaveHelper.setSampleRate(mRecorderSampleRate);
    startTimer();
    recorderState = RECORDER_STATE_STARTING;
    startRecordThread();
  }

  private final BehaviorProcessor<RecordTime> recordTimeProcessor = BehaviorProcessor.create();

  private void startTimer() {
    getTimerObservable().subscribeOn(Schedulers.newThread()).subscribe(recordTimeProcessor);
  }

  private Flowable<RecordTime> getTimerObservable() {
    return Flowable.interval(1000, TimeUnit.MILLISECONDS)
        .filter(timeElapsed -> !mIsPaused.get())
        .map(tick -> {
          long seconds = mRecordTimeCounter.incrementAndGet();
          RecordTime recordTime = new RecordTime();
          recordTime.millis = seconds * 1000;
          recordTime.hours = seconds / (60 * 60);
          seconds = seconds % (60 * 60);
          recordTime.minutes = seconds / 60;
          seconds = seconds % 60;
          recordTime.seconds = seconds;
          currentRecordTime = recordTime;
          return recordTime;
        });
  }

  private final Flowable<byte[]> audioDataFlowable = Flowable.create(emitter -> {
    int bufferSize = 4 * 1024;

    AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, mRecorderSampleRate,
        Constants.RECORDER_CHANNELS, Constants.RECORDER_AUDIO_ENCODING, bufferSize);
    audioSaveHelper.createNewFile();

    try {
      if (recorderState == RECORDER_STATE_STARTING) {
        recorderState = RECORDER_STATE_BUSY;
      }
      recorder.startRecording();

      recordBuffer = new byte[bufferSize];
      do {
        if (!mIsPaused.get()) {
          int bytesRead = recorder.read(recordBuffer, 0, bufferSize);
          emitter.onNext(recordBuffer);
          if (bytesRead == 0) {
            Log.e(AudioRecorder.class.getSimpleName(), "error: " + bytesRead);
            onRecordFailure();
          }
        }
      } while (recorderState == RECORDER_STATE_BUSY);
    } finally {
      recorder.release();
    }
    emitter.onComplete();
  }, BackpressureStrategy.DROP);

  private final PublishProcessor<byte[]> recordDataPublishProcessor = PublishProcessor.create();

  private void startRecordThread() {
    audioDataFlowable.subscribeOn(Schedulers.io()).subscribe(recordDataPublishProcessor);
    compositeDisposable.add(recordDataPublishProcessor.onBackpressureBuffer()
        .observeOn(Schedulers.io())
        .subscribeWith(new DisposableSubscriber<byte[]>() {
          @Override public void onNext(byte[] bytes) {
            audioSaveHelper.onDataReady(recordBuffer);
          }

          @Override public void onError(Throwable t) {

          }

          @Override public void onComplete() {
            audioSaveHelper.onRecordingStopped(currentRecordTime);
            synchronized (recorderStateMonitor) {
              recorderState = RECORDER_STATE_IDLE;
              recorderStateMonitor.notifyAll();
            }
          }
        }));
  }

  @Override public void finishRecord() {
    int recorderStateLocal = recorderState;
    if (recorderStateLocal != RECORDER_STATE_IDLE) {
      synchronized (recorderStateMonitor) {
        recorderStateLocal = recorderState;
        if (recorderStateLocal == RECORDER_STATE_STARTING
            || recorderStateLocal == RECORDER_STATE_BUSY) {

          recorderStateLocal = recorderState = RECORDER_STATE_STOPPING;
        }

        do {
          try {
            if (recorderStateLocal != RECORDER_STATE_IDLE) {
              recorderStateMonitor.wait();
            }
          } catch (InterruptedException ignore) {
                        /* Nothing to do */
          }
          recorderStateLocal = recorderState;
        } while (recorderStateLocal == RECORDER_STATE_STOPPING);
      }
    }
    compositeDisposable.dispose();
  }

  @Override public void pauseRecord() {
    mIsPaused.set(true);
  }

  @Override public void resumeRecord() {
    mIsPaused.set(false);
  }

  @Override public boolean isRecording() {
    return recorderState != RECORDER_STATE_IDLE;
  }

  public Flowable<byte[]> getAudioDataFlowable() {
    return recordDataPublishProcessor;
  }

  public Disposable subscribeTimer(Consumer<RecordTime> timerConsumer) {
    Disposable disposable =
        recordTimeProcessor.observeOn(AndroidSchedulers.mainThread()).subscribe(timerConsumer);
    compositeDisposable.add(disposable);
    return disposable;
  }

  boolean isPaused() {
    return mIsPaused.get();
  }

  public static class RecordTime {
    public long seconds = 0;
    public long minutes = 0;
    public long hours = 0;
    long millis = 0;
  }
}


text:
<?php

namespace Oro\Bundle\DashboardBundle\Tests\Unit\Provider\Converters;

use Doctrine\ORM\AbstractQuery;

use Oro\Bundle\DashboardBundle\Provider\Converters\WidgetEntitySelectConverter;
use Oro\Bundle\UserBundle\Entity\User;

class WidgetEntitySelectConverterTest extends \PHPUnit_Framework_TestCase
{
    /** @var AbstractQuery|\PHPUnit_Framework_MockObject_MockObject */
    protected $query;

    /** @var  WidgetEntitySelectConverter */
    protected $converter;

    public function setUp()
    {
        $entityNameResolver = $this->getMockBuilder('Oro\Bundle\EntityBundle\Provider\EntityNameResolver')
            ->disableOriginalConstructor()
            ->getMock();

        $entityNameResolver->expects($this->any())
            ->method('getName')
            ->willReturnCallback(
                function ($object) {
                    /** @var User $object */
                    return $object->getFirstName() . ' ' . $object->getLastName();
                }
            );

        $doctrineHelper = $this->getMockBuilder('Oro\Bundle\EntityBundle\ORM\DoctrineHelper')
            ->disableOriginalConstructor()
            ->getMock();

        $entityManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $this->query = $this->getMockBuilder('Doctrine\ORM\AbstractQuery')
            ->disableOriginalConstructor()
            ->setMethods(['getResult'])
            ->getMockForAbstractClass();

        $aclHelper = $this->getMockBuilder('Oro\Bundle\SecurityBundle\ORM\Walker\AclHelper')
            ->disableOriginalConstructor()
            ->getMock();

        $aclHelper->expects($this->any())
            ->method('apply')
            ->will($this->returnValue($this->query));

        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $expr = $this->getMockBuilder('Doctrine\ORM\Query\Expr')
            ->disableOriginalConstructor()
            ->getMock();
        $expr->expects($this->any())
            ->method('in')
            ->with()
            ->will($this->returnSelf());

        $queryBuilder->expects($this->any())
            ->method('expr')
            ->willReturn($expr);

        $repository = $this->getMockBuilder('Doctrine\ORM\EntityRepository')
            ->disableOriginalConstructor()
            ->getMock();

        $entityManager->expects($this->any())
            ->method('getRepository')
            ->willReturn($repository);

        $repository->expects($this->any())
            ->method('createQueryBuilder')
            ->with('e')
            ->will($this->returnValue($queryBuilder));

        $this->converter = new WidgetEntitySelectConverter(
            $aclHelper,
            $entityNameResolver,
            $doctrineHelper,
            $entityManager,
            'Oro\Bundle\UserBundle\Entity\User'
        );
    }

    public function testGetViewValueWithoutEntities()
    {
        $this->assertNull($this->converter->getViewValue([]));
    }

    public function testGetViewValueWithOneEntity()
    {
        $user1 = new User();
        $user1->setFirstName('Joe');
        $user1->setLastName('Doe');

        $this->query->expects($this->any())
            ->method('getResult')
            ->will(
                $this->returnValue(
                    [
                        $user1,
                    ]
                )
            );

        $this->assertEquals('Joe Doe', $this->converter->getViewValue([1, 2]));
    }

    public function testGetViewValueWithSeveralEntities()
    {
        $user1 = new User();
        $user1->setFirstName('Joe');
        $user1->setLastName('Doe');

        $user2 = new User();
        $user2->setFirstName('Joyce');
        $user2->setLastName('Palmer');

        $this->query->expects($this->any())
            ->method('getResult')
            ->will(
                $this->returnValue(
                    [
                        $user1,
                        $user2
                    ]
                )
            );

        $this->assertEquals('Joe Doe; Joyce Palmer', $this->converter->getViewValue([1, 2]));
    }
}


text:
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AppRating.svg)](https://img.shields.io/cocoapods/v/AppRating.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Platform](https://img.shields.io/cocoapods/p/AppRating.svg?style=flat)](http://cocoadocs.org/docsets/AppRating)
[![Swift 5.0](https://img.shields.io/badge/Swift-5.0-orange.svg?style=flat)](https://developer.apple.com/swift/)

AppRating is a simple yet powerful App Review Manager for iOS and OSX written in Swift. It is based on [Armchair](https://github.com/UrbanApps/Armchair) but mainly rewritten for Swift 5.0.

## Other Version

Flutter: https://pub.dev/packages/advanced_in_app_review

Android: https://github.com/grizzly/android-in-app-reviews/

## What's new?

- SKStoreReviewController - Now supporting the brand new iOS 10.3 API SKStoreReviewController which makes it really easy to get a huge number of ratings for your app. It opens the rating directly in an alert:

![AppRating supports the brand new SKStoreReviewController API](https://pbs.twimg.com/media/C3BFBGMWEAAL5Di.png)

## Why AppRating?

The average end-user will only write a review if something is wrong with your App. This leads to an unfairly negative skew in the ratings, when the majority of satisfied customers don't leave reviews and only the dissatisfied ones do. In order to counter-balance the negatives, AppRating prompts the user to write a review, but only after the developer knows they are satisfied. For example, you may only show the popup if the user has been using it for more than a week, and has done at least 5 significant events (the core functionality of your App). The rules are fully customizable for your App and easy to setup.

## Requirements

- Xcode 10.0+ (get the beta version at [Apple Developer](https://developer.apple.com/))
- iOS 10.3+

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:

```bash
$ gem install cocoapods
```

> CocoaPods 0.39.0+ is required to build AppRating.

To integrate AppRating into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.3'
use_frameworks!

pod 'AppRating', '>= 0.0.1'
```

Then, run the following command:

```bash
$ pod install
```
### Carthage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with [Homebrew](http://brew.sh/) using the following command:

```bash
$ brew update
$ brew install carthage
```

To integrate AppRating into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
github "grizzly/AppRating"
```

Run `carthage update` to build the framework and drag the built `AppRating.framework` into your Xcode project.

## Usage

### Simple 1-line Setup

AppRating includes sensible defaults as well as reads data from your localized, or unlocalized `info.plist` to set itself up. While everything is configurable, the only **required** item to configure is your App Store ID. This call should be made as part of your App Delegate's `initialize()` function

```swift
AppRating.appID("12345678")
```

That's it to get started. Setting AppRating up with this line uses some sensible default criterion (detailed below) and will present a rating prompt whenever they are met.

## What's Planned?

There are some ideas we have for future versions of AppRating. Feel free to fork/implement if you would like to expedite the process.

- Get 100% Unit Test coverage
- Add additional localizations: ongoing
- [Your idea](https://github.com/grizzly/AppRating/issues)

## Bugs / Pull Requests
Let us know if you see ways to improve AppRating or see something wrong with it. We are happy to pull in pull requests that have clean code, and have features that are useful for most people. While the Swift community is still deciding on proper code structure and style, please refrain from simple style complaints (space > tabs, etc...)

## License

AppRating is released under an MIT license. See [LICENSE](https://github.com/grizzly/AppRating/blob/master/LICENSE) for more information


text:
layout: post
title: Tweets
date: 2020-05-07
summary: These are the tweets for May 7, 2020.
categories:
---


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/gwt-dynamic-host">
	<Loader delegate="true"/>
</Context>


text:
<?php

namespace KpasteCore\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Session\Container as SessionContainer;

class RSSController extends AbstractActionController
{
    protected $authData;
    protected $settings;
    protected $rssHeader;
    protected $items;

    public function __construct()
    {
        $auth           = new AuthenticationService();
        $this->authData = @unserialize($auth->getStorage()->read());
        $settings       = new SessionContainer( 'settings' );
        $this->settings = $settings->settings;
        $lang = str_replace('_', '-', $this->settings['language']);
        $this->rssHeader = <<<RSSHEADER
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

    <channel>
        <title>%TITLE%</title>
        <link>%LINK%</link>
        <description>%DESCRIPTION%</description>
        <language>$lang</language>
RSSHEADER;

        $this->items = "";
    }

    private function initialize($title, $link, $description)
    {
        $this->rssHeader = str_replace('%TITLE%', $title, $this->rssHeader);
        $this->rssHeader = str_replace('%LINK%', $link, $this->rssHeader);
        $this->rssHeader = str_replace('%DESCRIPTION%', $description, $this->rssHeader);
    }

    private function addItem($title, $link, $description)
    {
        $newItem = <<<NEWITEM
        <item>
            <title>%TITLE%</title>
            <link>%LINK%</link>
            <description>%DESCRIPTION%</description>
        </item>

NEWITEM;
        $newItem = str_replace('%TITLE%', $title, $newItem);
        $newItem = str_replace('%LINK%', $link, $newItem);
        $newItem = str_replace('%DESCRIPTION%', $description, $newItem);

        $this->items .= "\n";
        $this->items .= $newItem;
    }

    private function finalize()
    {
        $tail = "</channel>\n</rss>";
        $response = $this->getResponse();

        $headers = new \Zend\Http\Headers();
        $headers->addHeaderLine('Content-Type', "application/rss+xml; charset=UTF-8");

        $response->setHeaders($headers);

        $response->setContent($this->rssHeader . $this->items . $tail);

        return $response;
    }

    public function AnnouncementsAction()
    {
        $link = $this->url()->fromRoute('kpastecore', array(
            'lang'      => $this->params()->fromRoute('lang', substr($this->settings['language'], 0, 2)),
            'controller'=> 'Home',
            'action'    => 'Announcement',
        ), array('force_canonical' => true));
        $translator = $this->getServiceLocator()->get('translator');

        $this->initialize($translator->translate("kPaste's Announcements"),
                $link, $translator->translate("kPaste's Announcements"));

        $news = $this->getNewsTable()->fetchNews(50);

        foreach($news as $_news)
        {
            $this->addItem($_news->title, $link, $_news->news);
        }

        return($this->finalize());
    }

    public function LatestPublicPastesAction()
    {
        $userid = (int)$this->params()->fromRoute('param1');

        if($userid)
        {
            $pastes = $this->getPastesTable()->fetchPastes(array(
                'exposure'      => 'public',
                'users.userid'  => $userid,
            ), false, 50);

            $user = $this->getUsersTable()->fetchUser('userid', $userid);

            $link = $this->url()->fromRoute('kpastecore', array(
                'lang'      => $this->params()->fromRoute('lang', substr($this->settings['language'], 0, 2)),
            ), array('force_canonical' => true));
            $translator = $this->getServiceLocator()->get('translator');

            $title = sprintf($translator->translate("%s's Latest Public Pastes"), $user->username);
            $this->initialize($title, $link, $title);
        }
        else
        {
            $pastes = $this->getPastesTable()->fetchPastes(array('exposure' => 'public'), false, 50);
            $link = $this->url()->fromRoute('kpastecore', array(
                'lang'      => $this->params()->fromRoute('lang', substr($this->settings['language'], 0, 2)),
            ), array('force_canonical' => true));
            $translator = $this->getServiceLocator()->get('translator');

            $this->initialize($translator->translate("Latest Public Pastes"),
                    $link, $translator->translate("Latest Public Pastes"));
        }

        foreach($pastes as $paste)
        {
            $link = $this->url()->fromRoute('kpastecore', array(
                'lang'      => $this->params()->fromRoute('lang', substr($this->settings['language'], 0, 2)),
                'controller'=> 'ViewPaste',
                'action'    => 'view',
                'param1'    => $paste->pasteid,
            ), array('force_canonical' => true));
            if($paste->password_test && strlen($paste->password_test))
            {
                $pasteDigest = '(((PASSWORD PROTECTED)))';
            }
            else
            {
                $pasteDigest = mb_substr($paste->paste, 0, 256);
                if(strlen($paste->paste) > 255) $pasteDigest .= '...';
            }
            $pasteDigest = str_replace('<', '<', $pasteDigest);
            $this->addItem($paste->title, $link, $pasteDigest);
        }

        return($this->finalize());
    }

    public function getPastesTable()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('Paster\Model\PastesTable');
    }
    public function getNewsTable()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('KpasteCore\Model\NewsTable');
    }
    public function getUsersTable()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('User\Model\UserTable');
    }
}


text:
namespace Simple.OData.ProductService.Models
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }
}


text:
package org.apache.coyote.ajp;

import org.apache.coyote.AbstractProtocol;
import org.apache.coyote.Processor;
import org.apache.coyote.UpgradeProtocol;
import org.apache.coyote.UpgradeToken;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.SSLHostConfig;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;

/**
 * The is the base implementation for the AJP protocol handlers. Implementations
 * typically extend this base class rather than implement {@link
 * org.apache.coyote.ProtocolHandler}. All of the implementations that ship with
 * Tomcat are implemented this way.
 *
 * @param <S> The type of socket used by the implementation
 */
public abstract class AbstractAjpProtocol<S> extends AbstractProtocol<S> {

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(AbstractAjpProtocol.class);

    public AbstractAjpProtocol(AbstractEndpoint<S,?> endpoint) {
        super(endpoint);
        setConnectionTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT);
        // AJP does not use Send File
        getEndpoint().setUseSendfile(false);
        ConnectionHandler<S> cHandler = new ConnectionHandler<>(this);
        setHandler(cHandler);
        getEndpoint().setHandler(cHandler);
    }

    @Override
    protected String getProtocolName() {
        return "Ajp";
    }

    /**
     * {@inheritDoc}
     *
     * Overridden to make getter accessible to other classes in this package.
     */
    @Override
    protected AbstractEndpoint<S,?> getEndpoint() {
        return super.getEndpoint();
    }

    /**
     * {@inheritDoc}
     *
     * AJP does not support protocol negotiation so this always returns null.
     */
    @Override
    protected UpgradeProtocol getNegotiatedProtocol(String name) {
        return null;
    }

    /**
     * {@inheritDoc}
     *
     * AJP does not support protocol upgrade so this always returns null.
     */
    @Override
    protected UpgradeProtocol getUpgradeProtocol(String name) {
        return null;
    }

    // ------------------------------------------------- AJP specific properties
    // ------------------------------------------ managed in the ProtocolHandler

    private boolean ajpFlush = true;
    public boolean getAjpFlush() { return ajpFlush; }
    /**
     * Configure whether to aend an AJP flush packet when flushing. A flush
     * packet is a zero byte AJP13 SEND_BODY_CHUNK packet. mod_jk and
     * mod_proxy_ajp interpret this as a request to flush data to the client.
     * AJP always does flush at the and of the response, so if it is not
     * important, that the packets get streamed up to the client, do not use
     * extra flush packets. For compatibility and to stay on the safe side,
     * flush packets are enabled by default.
     *
     * @param ajpFlush  The new flush setting
     */
    public void setAjpFlush(boolean ajpFlush) {
        this.ajpFlush = ajpFlush;
    }

    private boolean tomcatAuthentication = true;
    /**
     * Should authentication be done in the native web server layer,
     * or in the Servlet container ?
     *
     * @return {@code true} if authentication should be performed by Tomcat,
     *         otherwise {@code false}
     */
    public boolean getTomcatAuthentication() { return tomcatAuthentication; }
    public void setTomcatAuthentication(boolean tomcatAuthentication) {
        this.tomcatAuthentication = tomcatAuthentication;
    }

    private boolean tomcatAuthorization = false;
    /**
     * Should authentication be done in the native web server layer and
     * authorization in the Servlet container?
     *
     * @return {@code true} if authorization should be performed by Tomcat,
     *         otherwise {@code false}
     */
    public boolean getTomcatAuthorization() { return tomcatAuthorization; }
    public void setTomcatAuthorization(boolean tomcatAuthorization) {
        this.tomcatAuthorization = tomcatAuthorization;
    }

    private String requiredSecret = null;
    /**
     * Set the required secret that must be included with every request.
     *
     * @param requiredSecret The required secret
     */
    public void setRequiredSecret(String requiredSecret) {
        this.requiredSecret = requiredSecret;
    }
    protected String getRequiredSecret() {
        return requiredSecret;
    }

    /**
     * AJP packet size.
     */
    private int packetSize = Constants.MAX_PACKET_SIZE;
    public int getPacketSize() { return packetSize; }
    public void setPacketSize(int packetSize) {
        if(packetSize < Constants.MAX_PACKET_SIZE) {
            this.packetSize = Constants.MAX_PACKET_SIZE;
        } else {
            this.packetSize = packetSize;
        }
    }

    // --------------------------------------------- SSL is not supported in AJP

    @Override
    public void addSslHostConfig(SSLHostConfig sslHostConfig) {
        getLog().warn(sm.getString("ajpprotocol.noSSL", sslHostConfig.getHostName()));
    }

    @Override
    public SSLHostConfig[] findSslHostConfigs() {
        return new SSLHostConfig[0];
    }

    @Override
    public void addUpgradeProtocol(UpgradeProtocol upgradeProtocol) {
        getLog().warn(sm.getString("ajpprotocol.noUpgrade", upgradeProtocol.getClass().getName()));
    }

    @Override
    public UpgradeProtocol[] findUpgradeProtocols() {
        return new UpgradeProtocol[0];
    }

    @Override
    protected Processor createProcessor() {
        AjpProcessor processor = new AjpProcessor(this);
        processor.setAdapter(getAdapter());
        return processor;
    }

    @Override
    protected Processor createUpgradeProcessor(SocketWrapperBase<?> socket,
            UpgradeToken upgradeToken) {
        throw new IllegalStateException(sm.getString("ajpprotocol.noUpgradeHandler",
                upgradeToken.getHttpUpgradeHandler().getClass().getName()));
    }
}


text:
/**
 * The Creator's prototype points to the Citizen which we inherit.
 * Nasledqvame attributite na Citizen-a kakto i vsichko po prototipnata veriga
 *
 * Drawbacks:
 *	Not able to pass parameters to the parent
 *  Inherit data that is specific for the parent instance not only data from parent prototype
 */
function classicInheritance1(Creator, ParentCreator) {
	Creator.prototype = new ParentCreator(); //new ParentCreator() = createParent();
}

function classicInheritance1_1(Creator, Parent) {
	Creator.prototype = Parent;
}

/**
 * We create new Citizen bazed on passed Citizen.
 * Za celta si definirame Creator, kazvame che Model-a mu e podadeniq Citizen i vrushtame suzdaden nov Citizen s nego.
 *
 * Spored men tova ima sashtite nedostataci kato classicInheritance1.
 * Vtoriq moje lesno da se preodolee kato kato parameter na funkciqtada podadem Model, a ne Citizen.
 */
function prototypalInheritance(o){
	function Creator () {}
	Creator.prototype = o;
	return new Creator();	//new Creator() = createDataHolder();
}


text:
import React from 'react'
import { IndexRoute, Router, Route, hashHistory } from 'react-router'
import { render } from 'react-dom'

import App from './components/app'
import Home from './components/Home'
import Projects from './components/Projects'
import Contact from './components/Contact'
import Resume from './components/Resume'

render((
    <Router history={hashHistory}>
        <Route path='/' component={App}>
            <IndexRoute component={Home}/>
            <Route path='/projects' component={Projects}/>
            <Route path='/about' component={Contact}/>
            <Route path='/resume' component={Resume}/>
        </Route>
    </Router>
), document.getElementById('main'))


text:
package victor.training.mybatis.persistence;

import java.util.List;

import victor.training.mybatis.model.Employee;
import victor.training.mybatis.model.EmployeeSearchCriteria;
import victor.training.mybatis.model.Project;
import victor.training.mybatis.model.ProjectType;

public interface DynamicQueryMapper {
	List<Employee> searchEmployees(EmployeeSearchCriteria criteria);

	void updateEmployeeSelectively(Employee employee);

	List<Project> searchProjects(List<ProjectType> types);

}


text:
layout: post
title:  "Cajado Abençoado"
date:   2018-01-01
source: Módulo Básico 157, Módulo Básico Edição Revisada 167.
tags: [nenhum, bardo]
---

**divina 1 (transmutação)**

**Alcance**: toque

**Teste de Resistência**: nenhum.

**Duração**: 10 minutos

**Alvo**: 1 bordão ou clava mundanos

**Tempo de Execução**: ação padrão

A arma afetada fornece +1 nas jogadas de ataque e dano. Além disso, causa dano como se fosse de duas categorias de tamanho maior; por exemplo, um bordão Médio (dano normal 1d6) causará 2d6 pontos de dano.
Esses efeitos só ocorrem se a arma é empunhada por você. Nas mãos de qualquer outra criatura, é uma arma normal.


text:
package com.android.shelter.user.landlord;

import android.app.Activity;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.shelter.R;
import com.android.shelter.property.Property;

import java.util.List;

/**
 * Adapter for property images
 */
public class MyPostingAdapter extends RecyclerView.Adapter<MyPostingHolder> {

    private List<Property> mPropertyList;

    private Activity mActivity;

    private FragmentManager mFragmentManager;

    /**
     * Constructor for adapter
     * @param propertyList
     * @param activity
     * @param fragmentManager
     */
    public MyPostingAdapter(List<Property> propertyList, Activity activity, FragmentManager fragmentManager) {
        mPropertyList = propertyList;
        mActivity = activity;
        mFragmentManager = fragmentManager;
    }

    @Override
    public MyPostingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
        View view = layoutInflater.inflate(R.layout.my_postings_list, parent, false);

        return new MyPostingHolder(view, mActivity, mFragmentManager);
    }

    @Override
    public void onBindViewHolder(MyPostingHolder holder, int position) {
        Property property = mPropertyList.get(position);
        holder.bindView(property);
    }

    @Override
    public int getItemCount() {
        return mPropertyList.size();
    }
}


text:
using System;
using System.Data.SqlClient;
using System.Dynamic;
using System.IO;
using System.Windows.Forms;

namespace OsmMsSqlUpload
{
    public partial class OSM2MSSQL4ROADS : Form
    {
        public OSM2MSSQL4ROADS()
        {
            InitializeComponent();
        }

        string GetConnectionString(string catalog = null)
        {
            var cnxStringBuilder = new SqlConnectionStringBuilder();
            cnxStringBuilder.DataSource = txtServerName.Text;
            cnxStringBuilder.IntegratedSecurity = cbIntegratedSecurity.Checked;
            cnxStringBuilder.AsynchronousProcessing = true;

            if(!cnxStringBuilder.IntegratedSecurity)
            {
                cnxStringBuilder.UserID     = txtUserName.Text.Trim();
                cnxStringBuilder.Password   = txtPassword.Text.Trim();
            }
            if(!string.IsNullOrEmpty(catalog))
                cnxStringBuilder.InitialCatalog = catalog;
            return cnxStringBuilder.ConnectionString;
        }

        private void btnDbPopulate_Click(object sender, EventArgs e)
        {
            cbDatabases.Items.Clear();
            try
            {
                using (var cnx = new SqlConnection(GetConnectionString()))
                {
                    cnx.Open();
                    using(var cmd = cnx.CreateCommand())
                    {
                        cmd.CommandText = @"select name from master.sys.databases where database_id>4";
                        using(var rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read()) cbDatabases.Items.Add(rdr.GetString(0));
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(this, "Unable to get the list of database :\n" + ex.Message,
                                "OSM2MSSQL4ROADS - Database Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cbIntegratedSecurity_CheckedChanged(object sender, EventArgs e)
        {
            var txtEnabled = !cbIntegratedSecurity.Checked;
            txtUserName.Enabled =
            txtPassword.Enabled = txtEnabled;
        }

        static bool CheckIfDatabaseEmpty(SqlConnection cnx)
        {
            using (var cmd = cnx.CreateCommand())
            {
                cmd.CommandText =
                    @"
SELECT ISNULL( (
	SELECT 1
	WHERE
		OBJECT_ID ( 'dbo.PlnEdge',        'U' ) IS NOT NULL OR
		OBJECT_ID ( 'dbo.OsmWayEdge',     'U' ) IS NOT NULL OR
		OBJECT_ID ( 'dbo.PlnIntersection','U' ) IS NOT NULL OR
		OBJECT_ID ( 'dbo.OsmWays',        'U' ) IS NOT NULL OR
		OBJECT_ID ( 'dbo.OsmWayTypes',    'U' ) IS NOT NULL OR
		OBJECT_ID ( 'dbo.OsmPolygon',     'U' ) IS NOT NULL
	),0)";
                return Convert.ToBoolean(cmd.ExecuteScalar());
            }
        }

        private void btnProceed_Click(object sender, EventArgs e)
        {
            try
            {
                var dbName = cbDatabases.Text.Trim();
                var cnxString = GetConnectionString(dbName);
                using (var cnx = new SqlConnection(cnxString))
                {
                    cnx.Open();
                    if(string.IsNullOrEmpty(dbName))
                    {
                        cbDatabases.Text = cnx.Database;
                    }

                    if(CheckIfDatabaseEmpty(cnx) && !cbCleanData.Checked)
                    {
                        MessageBox.Show(this, "The database is not empty. Please check 'Clean Data'.",
                                        "OSM2MSSQL4ROADS - Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    dynamic parameters = new ExpandoObject();

                    parameters.Connection = cnx;
                    parameters.ConnectionString = cnxString;
                    parameters.SourceFile = txtSourceFile.Text;
                    parameters.UseDbAsTemp = cbUseTargetDb.Checked;
                    parameters.BulkInsert = cbBulkInsert.Checked;
                    parameters.TempFile =
                        Environment.ExpandEnvironmentVariables(
                                txtTempFile.Text.Trim()
                            );

                    if(!File.Exists(parameters.SourceFile))
                    {
                        MessageBox.Show(this, "Unable to access source file. Please check path.",
                                        "OSM2MSSQL4ROADS - Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    var dialog = new ProcessDlg(parameters);
                    dialog.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Unable to initialize upload process :\n" + ex.Message,
                                "OSM2MSSQL4ROADS - Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cbUseTargetDb_CheckedChanged(object sender, EventArgs e)
        {
            txtTempFile.Enabled = !cbUseTargetDb.Checked;
        }

        private void btnBrowseSource_Click(object sender, EventArgs e)
        {
            var open = new OpenFileDialog();

            open.AddExtension = true;
            open.CheckFileExists = true;
            open.Filter = @"BZip2 OSM XML (*.osm.bz2)|*.osm.bz2|Binary PBF OSM (*.osm.pbf)|*.osm.pbf";
            if(open.ShowDialog(this)!=DialogResult.OK) return;

            txtSourceFile.Text = open.FileName;

        }
    }
}