text:
import collections
import copy
import datetime
import itertools
import os
import six
import traceback

from oslo.serialization import jsonutils
from sqlalchemy import or_

from nailgun import consts
from nailgun import notifier
from nailgun import objects
from nailgun.rpc import utils
from nailgun.settings import settings

from nailgun.consts import TASK_STATUSES
from nailgun.db import db
from nailgun.db.sqlalchemy.models import IPAddr
from nailgun.db.sqlalchemy.models import Node
from nailgun.db.sqlalchemy.models import Release
from nailgun.logger import logger
from nailgun.network import connectivity_check
from nailgun.network import utils as net_utils
from nailgun.task.helpers import TaskHelper
from nailgun.utils import logs as logs_utils
from nailgun.utils import reverse

class NailgunReceiver(object):

    @classmethod
    def remove_nodes_resp(cls, **kwargs):
        logger.info(
            "RPC method remove_nodes_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes') or []
        error_nodes = kwargs.get('error_nodes') or []
        inaccessible_nodes = kwargs.get('inaccessible_nodes') or []
        error_msg = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')
        if status in [consts.TASK_STATUSES.ready, consts.TASK_STATUSES.error]:
            progress = 100

        # locking tasks on cluster
        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)
        objects.TaskCollection.lock_cluster_tasks(task.cluster_id)
        task = objects.Task.get_by_uuid(
            task_uuid,
            fail_if_not_found=True,
            lock_for_update=True
        )

        # locking cluster
        if task.cluster_id is not None:
            objects.Cluster.get_by_uid(
                task.cluster_id,
                fail_if_not_found=True,
                lock_for_update=True
            )

        # locking nodes
        all_nodes = itertools.chain(nodes, error_nodes, inaccessible_nodes)
        all_nodes_ids = [
            node['id'] if 'id' in node else node['uid']
            for node in all_nodes
        ]
        locked_nodes = objects.NodeCollection.filter_by_list(
            None,
            'id',
            all_nodes_ids,
            order_by='id'
        )
        objects.NodeCollection.lock_for_update(locked_nodes).all()

        def get_node_id(n):
            return n.get('id', int(n.get('uid')))

        nodes_to_delete_ids = [get_node_id(n) for n in nodes]

        if(len(inaccessible_nodes) > 0):
            inaccessible_node_ids = [
                get_node_id(n) for n in inaccessible_nodes]

            logger.warn(u'Nodes %s not answered by RPC, removing from db',
                        inaccessible_nodes)

            nodes_to_delete_ids.extend(inaccessible_node_ids)

        for node in objects.NodeCollection.filter_by_id_list(
                None, nodes_to_delete_ids):
            logs_utils.delete_node_logs(node)

        Node.delete_by_ids(nodes_to_delete_ids)

        for node in error_nodes:
            node_db = objects.Node.get_by_uid(node['uid'])
            if not node_db:
                logger.error(
                    u"Failed to delete node '%s' marked as error from Astute:"
                    " node doesn't exist", str(node)
                )
            else:
                node_db.pending_deletion = False
                node_db.status = 'error'
                db().add(node_db)
                node['name'] = node_db.name
        db().flush()

        success_msg = u"No nodes were removed"
        err_msg = u"No errors occurred"
        if nodes:
            success_msg = u"Successfully removed {0} node(s)".format(
                len(nodes)
            )
            notifier.notify("done", success_msg)
        if error_nodes:
            err_msg = u"Failed to remove {0} node(s): {1}".format(
                len(error_nodes),
                ', '.join(
                    [n.get('name') or "ID: {0}".format(n['uid'])
                        for n in error_nodes])
            )
            notifier.notify("error", err_msg)
        if not error_msg:
            error_msg = ". ".join([success_msg, err_msg])
        data = {
            'status': status,
            'progress': progress,
            'message': error_msg,
        }
        objects.Task.update(task, data)

        cls._update_action_log_entry(status, task.name, task_uuid, nodes)

    @classmethod
    def remove_cluster_resp(cls, **kwargs):
        logger.info(
            "RPC method remove_cluster_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')

        # in remove_nodes_resp method all objects are already locked
        cls.remove_nodes_resp(**kwargs)

        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)
        cluster = task.cluster

        if task.status in ('ready',):
            logger.debug("Removing environment itself")
            cluster_name = cluster.name

            ips = db().query(IPAddr).filter(
                IPAddr.network.in_([n.id for n in cluster.network_groups])
            )
            map(db().delete, ips)
            db().flush()

            db().delete(cluster)
            db().flush()

            notifier.notify(
                "done",
                u"Environment '%s' and all its nodes are deleted" % (
                    cluster_name
                )
            )

        elif task.status in ('error',):
            cluster.status = 'error'
            db().add(cluster)
            db().flush()
            if not task.message:
                task.message = "Failed to delete nodes:\n{0}".format(
                    cls._generate_error_message(
                        task,
                        error_types=('deletion',)
                    )
                )
            notifier.notify(
                "error",
                task.message,
                cluster.id
            )

    @classmethod
    def deploy_resp(cls, **kwargs):
        logger.info(
            "RPC method deploy_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes') or []
        message = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')

        task = objects.Task.get_by_uuid(
            task_uuid,
            fail_if_not_found=True,
        )

        # locking all cluster tasks
        objects.TaskCollection.lock_cluster_tasks(task.cluster_id)

        # lock cluster
        objects.Cluster.get_by_uid(
            task.cluster_id,
            fail_if_not_found=True,
            lock_for_update=True
        )

        if not status:
            status = task.status

        # for deployment we need just to pop
        master = next((
            n for n in nodes if n['uid'] == consts.MASTER_ROLE), {})

        # we should remove master node from the nodes since it requires
        # special handling and won't work with old code
        if master:
            nodes.remove(master)

        # if there no node except master - then just skip updating
        # nodes status, for the task itself astute will send
        # message with descriptive error
        if nodes:

            # lock nodes for updating so they can't be deleted
            q_nodes = objects.NodeCollection.filter_by_id_list(
                None,
                [n['uid'] for n in nodes],
            )
            q_nodes = objects.NodeCollection.order_by(q_nodes, 'id')
            objects.NodeCollection.lock_for_update(q_nodes).all()

        # First of all, let's update nodes in database
        for node in nodes:
            node_db = objects.Node.get_by_uid(node['uid'])
            if not node_db:
                logger.warning(
                    u"No node found with uid '{0}' - nothing changed".format(
                        node['uid']
                    )
                )
                continue

            update_fields = (
                'error_msg',
                'error_type',
                'status',
                'progress',
                'online'
            )
            for param in update_fields:
                if param in node:
                    logger.debug(
                        u"Updating node {0} - set {1} to {2}".format(
                            node['uid'],
                            param,
                            node[param]
                        )
                    )
                    setattr(node_db, param, node[param])

                    if param == 'progress' and node.get('status') == 'error' \
                            or node.get('online') is False:
                        # If failure occurred with node
                        # it's progress should be 100
                        node_db.progress = 100
                        # Setting node error_msg for offline nodes
                        if node.get('online') is False \
                                and not node_db.error_msg:
                            node_db.error_msg = u"Node is offline"
                        # Notification on particular node failure
                        notifier.notify(
                            "error",
                            u"Failed to deploy node '{0}': {1}".format(
                                node_db.name,
                                node_db.error_msg or "Unknown error"
                            ),
                            cluster_id=task.cluster_id,
                            node_id=node['uid'],
                            task_uuid=task_uuid
                        )
        db().flush()
        if nodes and not progress:
            progress = TaskHelper.recalculate_deployment_task_progress(task)

        # full error will be provided in next astute message
        if master.get('status') == consts.TASK_STATUSES.error:
            status = consts.TASK_STATUSES.error

        # Let's check the whole task status
        if status == consts.TASK_STATUSES.error:
            cls._error_action(task, status, progress, message)
        elif status == consts.TASK_STATUSES.ready:
            cls._success_action(task, status, progress)
        else:
            data = {'status': status, 'progress': progress, 'message': message}
            objects.Task.update(task, data)

        cls._update_action_log_entry(status, task.name, task_uuid, nodes)

    @classmethod
    def provision_resp(cls, **kwargs):
        logger.info(
            "RPC method provision_resp received: %s" %
            jsonutils.dumps(kwargs))

        task_uuid = kwargs.get('task_uuid')
        message = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')
        nodes = kwargs.get('nodes', [])

        task = objects.Task.get_by_uuid(
            task_uuid,
            fail_if_not_found=True,
            lock_for_update=True
        )

        # if task was failed on master node then we should
        # mark all cluster's nodes in error state
        master = next((
            n for n in nodes if n['uid'] == consts.MASTER_ROLE), {})

        # we should remove master node from the nodes since it requires
        # special handling and won't work with old code
        if master:
            nodes.remove(master)

        if master.get('status') == consts.TASK_STATUSES.error:
            status = consts.TASK_STATUSES.error
            progress = 100

        # lock nodes for updating
        q_nodes = objects.NodeCollection.filter_by_id_list(
            None,
            [n['uid'] for n in nodes])
        q_nodes = objects.NodeCollection.order_by(q_nodes, 'id')
        objects.NodeCollection.lock_for_update(q_nodes).all()

        for node in nodes:
            uid = node.get('uid')
            node_db = objects.Node.get_by_uid(node['uid'])

            if not node_db:
                logger.warn('Node with uid "{0}" not found'.format(uid))
                continue

            if node.get('status') == consts.TASK_STATUSES.error:
                node_db.status = consts.TASK_STATUSES.error
                node_db.progress = 100
                node_db.error_type = 'provision'
                node_db.error_msg = node.get('error_msg', 'Unknown error')
            else:
                node_db.status = node.get('status')
                node_db.progress = node.get('progress')

        db().flush()
        if nodes and not progress:
            progress = TaskHelper.recalculate_provisioning_task_progress(task)

        data = {'status': status, 'progress': progress, 'message': message}
        objects.Task.update(task, data)

        cls._update_action_log_entry(status, task.name, task_uuid, nodes)

    @classmethod
    def _update_action_log_entry(cls, task_status, task_name, task_uuid,
                                 nodes_from_resp):
        try:
            if task_status in (consts.TASK_STATUSES.ready,
                               consts.TASK_STATUSES.error):
                al = objects.ActionLog.get_by_kwargs(task_uuid=task_uuid,
                                                     action_name=task_name)

                if al:
                    data = {
                        'end_timestamp': datetime.datetime.utcnow(),
                        'additional_info': {
                            'nodes_from_resp': cls.sanitize_nodes_from_resp(
                                nodes_from_resp),
                            'ended_with_status': task_status
                        }
                    }
                    objects.ActionLog.update(al, data)
        except Exception as e:
            logger.error("_update_action_log_entry failed: %s",
                         six.text_type(e))

    @classmethod
    def sanitize_nodes_from_resp(cls, nodes):
        resp = []
        if isinstance(nodes, list):
            for n in nodes:
                if isinstance(n, dict) and 'uid' in n:
                    resp.append(n['uid'])
        return resp

    @classmethod
    def _generate_error_message(cls, task, error_types, names_only=False):
        nodes_info = []
        error_nodes = db().query(Node).filter_by(
            cluster_id=task.cluster_id
        ).filter(
            or_(
                Node.status == 'error',
                Node.online == (False)
            )
        ).filter(
            Node.error_type.in_(error_types)
        ).all()
        for n in error_nodes:
            if names_only:
                nodes_info.append(u"'{0}'".format(n.name))
            else:
                nodes_info.append(u"'{0}': {1}".format(n.name, n.error_msg))
        if nodes_info:
            if names_only:
                message = u", ".join(nodes_info)
            else:
                message = u"\n".join(nodes_info)
        else:
            message = u"Unknown error"
        return message

    @classmethod
    def _error_action(cls, task, status, progress, message=None):
        task_name = task.name.title()
        if message:
            message = u"{0} has failed. {1}".format(task_name, message)
            # in case we are sending faild task message from astute
            # we should not create a notification with it, because its add
            # a lot of clutter for user
            notify_message = message.split('\n\n')[0]
        else:
            message = u"{0} has failed. Check these nodes:\n{1}".format(
                task_name,
                cls._generate_error_message(
                    task,
                    error_types=('deploy', 'provision'),
                    names_only=True
                )
            )
            notify_message = message

        notifier.notify(
            "error",
            notify_message,
            task.cluster_id
        )
        data = {'status': status, 'progress': progress, 'message': message}
        objects.Task.update(task, data)

    @classmethod
    def _success_action(cls, task, status, progress):
        # check if all nodes are ready
        if any(map(lambda n: n.status == 'error',
                   task.cluster.nodes)):
            cls._error_action(task, 'error', 100)
            return

        task_name = task.name.title()
        if task.cluster.mode in ('singlenode', 'multinode'):
            # determining horizon url - it's an IP
            # of a first cluster controller
            controller = db().query(Node).filter_by(
                cluster_id=task.cluster_id
            ).filter(
                Node.roles.any('controller')
            ).first()

            if controller:
                logger.debug(
                    u"Controller is found, node_id=%s, "
                    "getting it's IP addresses",
                    controller.id
                )
                public_net = filter(
                    lambda n: n['name'] == 'public' and 'ip' in n,
                    objects.Cluster.get_network_manager(
                        controller.cluster
                    ).get_node_networks(controller)
                )
                if public_net:
                    horizon_ip = public_net[0]['ip'].split('/')[0]
                    protocol = utils.get_protocol_for_horizon(task.cluster)
                    message = (
                        u"{task} of environment '{name}' is done. "
                        "Access the OpenStack dashboard (Horizon) at "
                        "{proto}://{horizon_address}/ or via internal "
                        "network at http://{controller_address}/"
                    ).format(
                        task=task_name,
                        name=task.cluster.name,
                        proto=protocol,
                        horizon_address=horizon_ip,
                        controller_address=controller.ip
                    )
                else:
                    message = u"{0} of environment '{1}' is done".format(
                        task_name,
                        task.cluster.name
                    )
                    logger.warning(
                        u"Public ip for controller node "
                        "not found in '{0}'".format(task.cluster.name)
                    )
            else:
                message = u"{0} of environment '{1}' is done".format(
                    task_name,
                    task.cluster.name
                )
                logger.warning(u"Controller node not found in '{0}'".format(
                    task.cluster.name
                ))
        elif task.cluster.is_ha_mode:
            # determining horizon url in HA mode - it's vip
            # from a public network saved in task cache
            try:
                message = (
                    u"{0} of environment '{1}' is done. "
                    "Access the OpenStack dashboard (Horizon) at {2}"
                ).format(
                    task_name,
                    task.cluster.name,
                    objects.Cluster.get_network_manager(
                        task.cluster
                    ).get_horizon_url(task.cluster.id)
                )
            except Exception as exc:
                logger.error(": ".join([
                    str(exc),
                    traceback.format_exc()
                ]))
                message = u"{0} of environment '{1}' is done".format(
                    task_name,
                    task.cluster.name
                )
                logger.warning(
                    u"Cannot find virtual IP for '{0}'".format(
                        task.cluster.name
                    )
                )

        zabbix_url = objects.Cluster.get_network_manager(
            task.cluster
        ).get_zabbix_url(task.cluster)

        if zabbix_url:
            message = "{0} Access Zabbix dashboard at {1}".format(
                message, zabbix_url)

        plugins_msg = cls._make_plugins_success_message(task.cluster.plugins)
        if plugins_msg:
            message = '{0}\n\n{1}'.format(message, plugins_msg)

        notifier.notify("done", message, task.cluster_id)
        data = {'status': status, 'progress': progress, 'message': message}
        objects.Task.update(task, data)

    @classmethod
    def _make_plugins_success_message(cls, plugins):
        """Makes plugins installation message
        """
        msg = 'Plugin {0} is deployed. {1}'
        return '\n'.join(
            map(lambda p: msg.format(p.name, p.description), plugins))

    @classmethod
    def stop_deployment_resp(cls, **kwargs):
        logger.info(
            "RPC method stop_deployment_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes', [])
        ia_nodes = kwargs.get('inaccessible_nodes', [])
        message = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')

        task = objects.Task.get_by_uuid(
            task_uuid,
            fail_if_not_found=True,
        )

        # locking all cluster tasks
        objects.TaskCollection.lock_cluster_tasks(task.cluster_id)

        stopping_task_names = [
            consts.TASK_NAMES.deploy,
            consts.TASK_NAMES.deployment,
            consts.TASK_NAMES.provision
        ]

        # Locking other tasks for stopping
        q_stop_tasks = objects.TaskCollection.filter_by_list(
            None,
            'name',
            stopping_task_names
        )
        q_stop_tasks = objects.TaskCollection.filter_by(
            q_stop_tasks,
            cluster_id=task.cluster_id
        )
        q_stop_tasks = objects.TaskCollection.order_by(
            q_stop_tasks,
            'id'
        )
        stop_tasks = objects.TaskCollection.lock_for_update(q_stop_tasks).all()

        # Locking cluster
        objects.Cluster.get_by_uid(
            task.cluster_id,
            fail_if_not_found=True,
            lock_for_update=True
        )

        if not stop_tasks:
            logger.warning("stop_deployment_resp: deployment tasks \
                            not found for environment '%s'!", task.cluster_id)

        if status == "ready":
            task.cluster.status = "stopped"

            if stop_tasks:
                map(db().delete, stop_tasks)

            node_uids = [n['uid'] for n in itertools.chain(nodes, ia_nodes)]
            q_nodes = objects.NodeCollection.filter_by_id_list(None, node_uids)
            q_nodes = objects.NodeCollection.filter_by(
                q_nodes,
                cluster_id=task.cluster_id
            )
            q_nodes = objects.NodeCollection.order_by(q_nodes, 'id')
            q_nodes = objects.NodeCollection.lock_for_update(q_nodes)

            # locking Nodes for update
            update_nodes = objects.NodeCollection.lock_for_update(
                q_nodes
            ).all()

            for node in update_nodes:
                objects.Node.reset_to_discover(node)

            if ia_nodes:
                cls._notify_inaccessible(
                    task.cluster_id,
                    [n["uid"] for n in ia_nodes],
                    u"deployment stopping"
                )

            message = (
                u"Deployment of environment '{0}' was successfully stopped. "
                u"Please reset the environment if you want to redeploy it."
                .format(task.cluster.name or task.cluster_id)
            )

            notifier.notify(
                "done",
                message,
                task.cluster_id
            )

        data = {'status': status, 'progress': progress, 'message': message}
        objects.Task.update(task, data)

        cls._update_action_log_entry(status, task.name, task_uuid, nodes)

    @classmethod
    def reset_environment_resp(cls, **kwargs):
        logger.info(
            "RPC method reset_environment_resp received: %s",
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes', [])
        ia_nodes = kwargs.get('inaccessible_nodes', [])
        message = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')

        task = objects.Task.get_by_uuid(
            task_uuid,
            fail_if_not_found=True,
            lock_for_update=True
        )

        # Locking cluster
        objects.Cluster.get_by_uid(
            task.cluster_id,
            fail_if_not_found=True,
            lock_for_update=True
        )

        if status == consts.TASK_STATUSES.ready:
            # restoring pending changes
            task.cluster.status = consts.CLUSTER_STATUSES.new
            objects.Cluster.add_pending_changes(
                task.cluster,
                consts.CLUSTER_CHANGES.attributes
            )
            objects.Cluster.add_pending_changes(
                task.cluster,
                consts.CLUSTER_CHANGES.networks
            )

            node_uids = [n["uid"] for n in itertools.chain(nodes, ia_nodes)]
            q_nodes = objects.NodeCollection.filter_by_id_list(None, node_uids)
            q_nodes = objects.NodeCollection.filter_by(
                q_nodes,
                cluster_id=task.cluster_id
            )
            q_nodes = objects.NodeCollection.order_by(q_nodes, 'id')

            # locking Nodes for update
            update_nodes = objects.NodeCollection.lock_for_update(
                q_nodes
            ).all()

            for node in update_nodes:
                logs_utils.delete_node_logs(node)
                objects.Node.reset_to_discover(node)

            if ia_nodes:
                cls._notify_inaccessible(
                    task.cluster_id,
                    [n["uid"] for n in ia_nodes],
                    u"environment resetting"
                )

            message = (
                u"Environment '{0}' "
                u"was successfully reset".format(
                    task.cluster.name or task.cluster_id
                )
            )

            notifier.notify(
                "done",
                message,
                task.cluster_id
            )

        data = {'status': status, 'progress': progress, 'message': message}
        objects.Task.update(task, data)

        cls._update_action_log_entry(status, task.name, task_uuid, nodes)

    @classmethod
    def _notify_inaccessible(cls, cluster_id, nodes_uids, action):
        ia_nodes_db = db().query(Node.name).filter(
            Node.id.in_(nodes_uids),
            Node.cluster_id == cluster_id
        ).order_by(Node.id).yield_per(100)
        ia_message = (
            u"Fuel couldn't reach these nodes during "
            u"{0}: {1}. Manual check may be needed.".format(
                action,
                u", ".join([
                    u"'{0}'".format(n.name)
                    for n in ia_nodes_db
                ])
            )
        )
        notifier.notify(
            "warning",
            ia_message,
            cluster_id
        )

    @classmethod
    def verify_networks_resp(cls, **kwargs):
        logger.info(
            "RPC method verify_networks_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes')
        error_msg = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')

        # We simply check that each node received all vlans for cluster
        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)

        result = []
        #  We expect that 'nodes' contains all nodes which we test.
        #  Situation when some nodes not answered must be processed
        #  in orchestrator early.
        if nodes is None:
            # If no nodes in kwargs then we update progress or status only.
            pass
        elif isinstance(nodes, list):
            cached_nodes = task.cache['args']['nodes']
            node_uids = [str(n['uid']) for n in nodes]
            cached_node_uids = [str(n['uid']) for n in cached_nodes]
            forgotten_uids = set(cached_node_uids) - set(node_uids)

            if forgotten_uids:
                absent_nodes = db().query(Node).filter(
                    Node.id.in_(forgotten_uids)
                ).all()
                absent_node_names = []
                for n in absent_nodes:
                    if n.name:
                        absent_node_names.append(n.name)
                    else:
                        absent_node_names.append('id: %s' % n.id)
                if not error_msg:
                    error_msg = 'Node(s) {0} didn\'t return data.'.format(
                        ', '.join(absent_node_names)
                    )
                status = 'error'
            else:
                error_nodes = []
                node_excluded_networks = []

                for node in nodes:
                    cached_nodes_filtered = filter(
                        lambda n: str(n['uid']) == str(node['uid']),
                        cached_nodes
                    )

                    if not cached_nodes_filtered:
                        logger.warning(
                            "verify_networks_resp: arguments contain node "
                            "data which is not in the task cache: %r",
                            node
                        )
                        continue

                    cached_node = cached_nodes_filtered[0]

                    # Check if we have excluded interfaces for LACP bonds
                    excluded_networks = cached_node.get(
                        'excluded_networks', [])
                    if excluded_networks:
                        interfaces = ', '.join(
                            [net.get('iface') for net in excluded_networks])

                        node_excluded_networks.append({
                            'node_name': cached_node['name'],
                            'interfaces': interfaces
                        })

                    errors = connectivity_check.check_received_data(
                        cached_node, node)

                    error_nodes.extend(errors)

                if error_nodes:
                    result = error_nodes
                    status = 'error'
                else:
                    # notices must not rewrite error messages
                    if node_excluded_networks:
                        interfaces_list = ', '.join(
                            ['node {0} [{1}]'.format(
                                item['node_name'], item['interfaces'])
                             for item in node_excluded_networks])
                        error_msg = connectivity_check.append_message(
                            error_msg,
                            'Notice: some interfaces were skipped from '
                            'connectivity checking because this version of '
                            'Fuel cannot establish LACP on Bootstrap nodes. '
                            'Only interfaces of successfully deployed nodes '
                            'may be checked with LACP enabled. The list of '
                            'skipped interfaces: {0}.'.format(interfaces_list)
                        )
                    if task.cache['args']['offline'] > 0:
                        error_msg = connectivity_check.append_message(
                            error_msg,
                            'Notice: {0} node(s) were offline during '
                            'connectivity check so they were skipped from the '
                            'check.'.format(task.cache['args']['offline'])
                        )

        else:
            error_msg = (error_msg or
                         'verify_networks_resp: argument "nodes"'
                         ' have incorrect type')
            status = 'error'
            logger.error(error_msg)

        if status not in ('ready', 'error'):
            data = {
                'status': status,
                'progress': progress,
                'message': error_msg,
                'result': result
            }
            objects.Task.update(task, data)
        else:
            objects.Task.update_verify_networks(
                task, status, progress, error_msg, result)

        cls._update_action_log_entry(status, task.name, task_uuid, nodes)

    @classmethod
    def multicast_verification_resp(cls, **kwargs):
        """Receiver for verification of multicast packages
        data - {1: response, 2: response}
        """
        logger.info(
            u"RPC method multicast_resp received: {0}".format(
                jsonutils.dumps(kwargs))
        )
        task_uuid = kwargs.get('task_uuid')
        task = objects.task.Task.get_by_uuid(uuid=task_uuid)
        if kwargs.get('status'):
            task.status = kwargs['status']
        task.progress = kwargs.get('progress', 0)

        response = kwargs.get('nodes', {})
        error_msg = kwargs.get('error')

        if task.status == TASK_STATUSES.error:
            task.message = error_msg
        elif task.status == TASK_STATUSES.ready:
            errors = []
            results = []
            node_ids = set(config['uid'] for config
                           in task.cache['args']['nodes'])
            not_received_nodes = node_ids - set(response.keys())
            if not_received_nodes:
                msg = (u'No answer from nodes: {0}').format(
                    list(not_received_nodes))
                errors.append(msg)
            for node_id, received_ids in response.iteritems():
                result = {}
                not_received_ids = node_ids - set(received_ids or [])
                result = {'node_id': node_id,
                          'not_received': list(not_received_ids)}
                results.append(result)
                if not_received_ids:
                    msg = (u'Not received ids {0}'
                           u' for node {1}.').format(not_received_ids, node_id)
                    errors.append(msg)

            task.message = '\n'.join(errors)
            if errors:
                task.status = TASK_STATUSES.error
            task.result = results
        if task.status == TASK_STATUSES.ready:
            editable = copy.deepcopy(task.cluster.attributes.editable)
            editable['corosync']['verified']['value'] = True
            task.cluster.attributes.editable = editable
        logger.debug(u'Multicast verification message %s', task.message)
        objects.Task.update_verify_networks(
            task, task.status,
            task.progress, task.message, task.result)

    @classmethod
    def check_dhcp_resp(cls, **kwargs):
        """Receiver method for check_dhcp task
        For example of kwargs check FakeCheckingDhcpThread
        """
        logger.info(
            "RPC method check_dhcp_resp received: %s",
            jsonutils.dumps(kwargs)
        )
        messages = []

        result = collections.defaultdict(list)
        message_template = (
            u"Node {node_name} discovered DHCP server "
            u"via {iface} with following parameters: IP: {server_id}, "
            u"MAC: {mac}. This server will conflict with the installation.")
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes', [])
        error_msg = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')

        nodes_uids = [node['uid'] for node in nodes]
        nodes_db = db().query(Node).filter(Node.id.in_(nodes_uids)).all()
        nodes_map = dict((str(node.id), node) for node in nodes_db)

        master_network_mac = settings.ADMIN_NETWORK['mac']
        logger.debug('Mac addr on master node %s', master_network_mac)

        for node in nodes:
            if node['status'] == 'ready':
                for row in node.get('data', []):
                    if not net_utils.is_same_mac(row['mac'],
                                                 master_network_mac):
                        node_db = nodes_map.get(node['uid'])
                        if node_db:
                            row['node_name'] = node_db.name
                            message = message_template.format(**row)
                            messages.append(message)
                            result[node['uid']].append(row)
                        else:
                            logger.warning(
                                'Received message from nonexistent node. '
                                'Message %s', row)
        status = status if not messages else "error"
        error_msg = '\n'.join(messages) if messages else error_msg
        logger.debug('Check dhcp message %s', error_msg)

        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)
        objects.Task.update_verify_networks(task, status, progress,
                                            error_msg, result)

    @classmethod
    def download_release_resp(cls, **kwargs):
        logger.info(
            "RPC method download_release_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        error_msg = kwargs.get('error')
        status = kwargs.get('status')
        progress = kwargs.get('progress')

        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)

        release_info = task.cache['args']['release_info']
        release_id = release_info['release_id']
        release = db().query(Release).get(release_id)
        if not release:
            logger.error("download_release_resp: Release"
                         " with ID %s not found", release_id)
            return

        if error_msg:
            status = 'error'
            error_msg = "{0} download and preparation " \
                        "has failed.".format(release.name)
            cls._download_release_error(
                release_id,
                error_msg
            )
        elif progress == 100 and status == 'ready':
            cls._download_release_completed(release_id)

        result = {
            "release_info": {
                "release_id": release_id
            }
        }

        data = {'status': status, 'progress': progress, 'message': error_msg,
                'result': result}
        objects.Task.update(task, data)

    @classmethod
    def dump_environment_resp(cls, **kwargs):
        logger.info(
            "RPC method dump_environment_resp received: %s" %
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        status = kwargs.get('status')
        progress = kwargs.get('progress')
        error = kwargs.get('error')
        msg = kwargs.get('msg')

        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)

        if status == 'error':
            notifier.notify('error', error)

            data = {'status': status, 'progress': 100, 'message': error}
            objects.Task.update(task, data)

        elif status == 'ready':
            dumpfile = os.path.basename(msg)
            notifier.notify('done', 'Snapshot is ready. '
                            'Visit Support page to download')
            dumpfile_url = reverse('SnapshotDownloadHandler',
                                   kwargs={'snapshot_name': dumpfile})
            data = {'status': status, 'progress': progress,
                    'message': dumpfile_url}
            objects.Task.update(task, data)

    @classmethod
    def stats_user_resp(cls, **kwargs):
        logger.info("RPC method stats_user_resp received: %s",
                    jsonutils.dumps(kwargs))

        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes', [])
        status = kwargs.get('status')
        error = kwargs.get('error')
        message = kwargs.get('msg')

        task = objects.Task.get_by_uuid(
            task_uuid, fail_if_not_found=True, lock_for_update=True)

        if status not in (consts.TASK_STATUSES.ready,
                          consts.TASK_STATUSES.error):
            logger.debug("Task %s, id: %s in status: %s",
                         task.name, task.id, task.status)
            return

        data = {'status': status, 'progress': 100, 'message': message}
        if status == consts.TASK_STATUSES.error:
            logger.error("Task %s, id: %s failed: %s",
                         task.name, task.id, error)
            data['message'] = error

        objects.Task.update(task, data)
        cls._update_action_log_entry(status, task.name, task_uuid, nodes)
        logger.info("RPC method stats_user_resp processed")

    @classmethod
    def check_repositories_resp(cls, **kwargs):
        logger.info(
            "RPC method check_repositories_resp received: %s",
            jsonutils.dumps(kwargs)
        )
        task_uuid = kwargs.get('task_uuid')
        nodes = kwargs.get('nodes')

        task = objects.Task.get_by_uuid(task_uuid, fail_if_not_found=True)
        failed_nodes = [node for node in nodes if node['status'] != 0]
        failed_nodes_ids = [node['uid'] for node in failed_nodes]

        progress = 100
        message = ''

        if not failed_nodes_ids:
            status = consts.TASK_STATUSES.ready
        else:
            failed_urls = set()
            for n in failed_nodes:
                failed_urls.update(n['out'].get('failed_urls', []))

            message = ('These nodes: "{0}" failed to connect to '
                       'some of these repositories: "{1}"').format(
                           '", "'.join([str(id) for id in failed_nodes_ids]),
                           '", "'.join(failed_urls))

            status = consts.TASK_STATUSES.error

        objects.Task.update_verify_networks(
            task, status, progress, message, [])

    @classmethod
    def check_repositories_with_setup_resp(cls, **kwargs):
        logger.info(
            "RPC method check_repositories_with_setup received: %s" %
            jsonutils.dumps(kwargs)
        )

        task_uuid = kwargs.get('task_uuid')
        response = kwargs.get('nodes', [])
        status = consts.TASK_STATUSES.ready
        progress = 100

        task = objects.Task.get_by_uuid(
            task_uuid, fail_if_not_found=True)

        response_nodes = dict([(n['uid'], n) for n in response])
        nodes = objects.NodeCollection.filter_by_list(
            None, 'id', response_nodes.keys(), order_by='id')

        failed_nodes = []
        failed_repos = set()
        for node in nodes:
            node_response = response_nodes[node.uid]
            if node_response['status'] != 0:
                if isinstance(node_response['out'], dict):
                    failed_repos.update(
                        node_response['out'].get('failed_urls', []))
                failed_nodes.append(node.name)
        msg = ''

        if failed_nodes:
            msg = ('Repo availability verification using public network'
                   ' failed on following nodes {0}.\n '.format(
                       ', '.join(failed_nodes)))
        if failed_repos:
            msg += ('Following repos are not available - {0}\n. '.format(
                    ', '.join(failed_repos)))
        if msg:
            msg += ('Check your public network settings and '
                    'availability of the repositories from public network. '
                    'Please examine nailgun and astute'
                    ' logs for additional details.')
            status = consts.TASK_STATUSES.error

        objects.Task.update_verify_networks(
            task, status, progress, msg, {})


text:
<?php

namespace RC\TokenMatcher\Assertion\Expr\Cast;

use RC\TokenMatcher\Assertion\Expr\CastAssertion;

class ObjectAssertion extends Expr\CastAssertion
{
}

redpajama_set_name: RedPajamaGithub


text:
local runner = require('user_modules/script_runner')
local commonRC = require('test_scripts/RC/commonRC')

--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false

--[[ Local Functions ]]
local function rpcInvalidHMIResponse(pModuleType, pAppId, pRPC)
  local consentRPC = "GetInteriorVehicleDataConsent"
  local mobSession = commonRC.getMobileSession(pAppId)
  local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), commonRC.getAppRequestParams(pRPC, pModuleType))
  EXPECT_HMICALL(commonRC.getHMIEventName(consentRPC), commonRC.getHMIRequestParams(consentRPC, pModuleType, pAppId))
  :Do(function(_, data)
      commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {
        allowed = "aaa" -- invalid type of parameter
      })
      EXPECT_HMICALL(commonRC.getHMIEventName(pRPC)):Times(0)
    end)
  mobSession:ExpectResponse(cid, { success = false, resultCode = "GENERIC_ERROR" })
  commonRC.wait(commonRC.timeout)
end

--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", commonRC.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start)
runner.Step("RAI1", commonRC.registerAppWOPTU)
runner.Step("Activate App1", commonRC.activateApp)
runner.Step("RAI2", commonRC.registerAppWOPTU, { 2 })
runner.Step("Activate App2", commonRC.activateApp, { 2 })

runner.Title("Test")
runner.Step("Set RA mode: ASK_DRIVER", commonRC.defineRAMode, { true, "ASK_DRIVER" })

for _, mod in pairs(commonRC.modules) do
  runner.Title("Module: " .. mod)
  -- set control for App1
  runner.Step("App1 SetInteriorVehicleData", commonRC.rpcAllowed, { mod, 1, "SetInteriorVehicleData" })
  -- set control for App2 --> Ask driver --> HMI: response with invalid data
  runner.Step("App2 ButtonPress 1st GENERIC_ERROR", rpcInvalidHMIResponse, { mod, 2, "ButtonPress" })
  runner.Step("App2 ButtonPress 2nd SUCCESS", commonRC.rpcAllowedWithConsent, { mod, 2, "ButtonPress" })
end

runner.Title("Postconditions")
runner.Step("Stop SDL", commonRC.postconditions)


text:
> Note: The following usages use the demo database. You have to custumize your own setting table before practical use!

You can setup the `items` ONLY for `radioList`, `checkboxList`, `listBox`, `dropDownList`, and setup the `options` for all `input field types`.

The `array keys` are option values, and the `array values` are the corresponding option labels.

Please refer to:

- [`yii\widgets\ActiveField#radioList()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#radioList()-detail)

- [`yii\widgets\ActiveField#checkboxList()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#checkboxList()-detail)

- [`yii\widgets\ActiveField#listBox()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#listBox()-detail)

- [`yii\widgets\ActiveField#dropDownList()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#dropDownList()-detail)

(TBD)

#### Multiselect

- [`yii\widgets\ActiveField#checkboxList()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#checkboxList()-detail)

- [`yii\widgets\ActiveField#listBox()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#listBox()-detail)

- [`yii\widgets\ActiveField#dropDownList()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#dropDownList()-detail)

(TBD)

#### Sub-array Nested

- [`yii\widgets\ActiveField#listBox()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#listBox()-detail)

- [`yii\widgets\ActiveField#dropDownList()`](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#dropDownList()-detail)

(TBD)


text:
'use strict';
angular.module('starter').
controller('ProfileController', ['$scope', 'WakandaManager', '$state', 'userID', function($scope, WakandaManager, $state, userID) {
    $scope.notEditable = true;
    WakandaManager.ready().then(function() {
        var $wakanda = WakandaManager.$wakanda;
        var ds = $wakanda.getDatastore();
            ds.Users.$find(userID).$promise.then(function(event) {
                $scope.info = event.result;

            });
    });

    $scope.save = function() {
        $scope.notEditable = true;

        WakandaManager.ready().then(function() {
            var $wakanda = WakandaManager.$wakanda;
            var ds = $wakanda.getDatastore();
            ds.Users.edit(userID, $scope.info.firstname, $scope.info.lastname, $scope.info.country).$promise.then(function(event) {
				$scope.uploadFile();
            });
        });

    };

    $scope.logout = function() {
        WakandaManager.ready().then(function() {
            var $wakanda = WakandaManager.$wakanda;
            $wakanda.$logout().$promise.then(function() {
                $state.go("login");
            });
        });
    };

    $scope.uploadFile = function() {
        WakandaManager.ready().then(function() {
            var $wakanda = WakandaManager.$wakanda;
            var ds = $wakanda.getDatastore();
            ds.Users.$find(userID).$promise.then(function(user) {
                var file = document.getElementById('fileInput').files[0];
                user.result.photo.$upload(file).$promise.then(function() {
                    user.result.$save().$promise.then(function() {
                        $state.reload();
                    });
                });
            });
        });
    };
}]);


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Tigra.Models
{
    public class EmailModel
    {

        public string Email { get; set; }

    }
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WizardsChess.VoiceControl.Commands;
using System.Collections.Generic;

namespace WizardsChessTest.VoiceControl.Commands
{
	[TestClass]
	public class CommandTest
	{
		public CommandTest()
		{
			var cmdParams = new Dictionary<string, IReadOnlyList<string>>();
			cmdParams.Add("action", new List<string>{ "move" });
			commandParams = cmdParams;
			commandType = CommandType.Move;
		}

		private IReadOnlyDictionary<string, IReadOnlyList<string>> commandParams;
		private CommandType commandType;

		[TestMethod]
		public void TestTypeConstruction()
		{
			var cmd = new Command(CommandType.Yes);
			Assert.AreEqual(CommandType.Yes, cmd.Type);
		}

		[TestMethod]
		public void TestStringConstruction()
		{
			var cmd2 = new Command(commandParams);
			Assert.AreEqual(commandType, cmd2.Type);
		}
	}
}


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.DataMigration.Models
{
    /// <summary> The MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutputError. </summary>
    public partial class MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutputError : MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutput
    {
        /// <summary> Initializes a new instance of MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutputError. </summary>
        internal MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutputError()
        {
            Events = new ChangeTrackingList<SyncMigrationDatabaseErrorEvent>();
            ResultType = "ErrorOutput";
        }

        /// <summary> Initializes a new instance of MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutputError. </summary>
        /// <param name="id"> Result identifier. </param>
        /// <param name="resultType"> Result type. </param>
        /// <param name="error"> Migration error. </param>
        /// <param name="events"> List of error events. </param>
        internal MigratePostgreSqlAzureDBForPostgreSqlSyncTaskOutputError(string id, string resultType, ReportableException error, IReadOnlyList<SyncMigrationDatabaseErrorEvent> events) : base(id, resultType)
        {
            Error = error;
            Events = events;
            ResultType = resultType ?? "ErrorOutput";
        }

        /// <summary> Migration error. </summary>
        public ReportableException Error { get; }
        /// <summary> List of error events. </summary>
        public IReadOnlyList<SyncMigrationDatabaseErrorEvent> Events { get; }
    }
}


text:
DIR=${PWD}

LIB_GO_PATH=github.com/lian/gdax-bookmap
LIB_FILE_PATH=${GOPATH}/src/${LIB_GO_PATH}

VERSION=0.0.2
GITHASH=$(git rev-parse HEAD)
FILENAME=gedw99-trader-${GOOS}-${GOARCH}

check:

	@echo "## Checking paths ##"
	@echo

	@echo "DIR \t \t ${DIR}"
	@echo

	@echo "LIB_GO_PATH: \t ${LIB_GO_PATH}"
	@echo "LIB_FILE_PATH: \t ${LIB_FILE_PATH}"
	@echo

dep:

	# Get program
	go get -u ${LIB_GO_PATH}/...

	# Get GO cross compiler
	docker pull karalabe/xgo-latest
	go get -u github.com/karalabe/xgo/...

dep-clean:

	# delete lib code
	rm -rf ${LIB_FILE_PATH}

open-bash:

	# open bash terminal
	open -a Terminal.app ${LIB_FILE_PATH}

open-fs:

	# Opens Finder.
	open ${LIB_FILE_PATH}

open-vsc:

	# Opens Visual Studio Code
	code ${LIB_FILE_PATH}

open-vs:

	# Opens Visual Studio for Mac
	open ${LIB_FILE_PATH}

######

build:

	cd ${LIB_FILE_PATH} && go build -o ${FILENAME}-osx -v -ldflags -s -ldflags "-X main.AppVersion=${VERSION} -X main.AppGitHash=${GITHASH}" main.go

run:

	cd ${LIB_FILE_PATH} && ./${FILENAME}-osx

###

buildx:

	cd ${LIB_FILE_PATH} && xgo -go latest -out ${FILENAME}

runx:

run-web:

	cd ${LIB_FILE_PATH}/web && npm install
	cd ${LIB_FILE_PATH}/web && bower install
	cd ${LIB_FILE_PATH}/web && npm start


text:
package com.jiangjg.lib.ThingkingInJava.Th17;

import java.util.Queue;

import com.jiangjg.lib.ThingkingInJava.Th15.Generator;

public class QueueBeHavior {

	private static int count = 10;
	static <T> void test (Queue<T> queue, Generator<T> gen){
		for(int i=0; i<count ; i++){
			queue.offer(gen.next());
		}
		while(queue.peek() != null){
			System.out.println(queue.remove() + " ");
		}
		System.out.println();
	}
	static class Gen implements Generator<String>{
		String[] s = ("o t t f f s s e n t").split(" ");
		int i;
		public String next(){
			return s[i++];
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


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

{% block active_examples %}class="active"{% endblock %}

{% block content %}

Examples

These are some highlights of changes that have been
curated by hand. Do you see a good
one? Let us know.

 In
 Yvonne Brill, a Pioneering Rocket Scientist, Dies at 88

By DOUGLAS MARTIN on March 30, 2013

 In an obituary, the start of the lede changed from
 "She made a mean beef stroganoff" to "She
 was a brilliant rocket scientist".

 In
    Gunman Massacres 20 Children at School in Connecticut; 28 Dead, Including Killer

By JOSEPH GOLDSTEIN, WILLIAM K. RASHBAUM, and JAMES BARRON on December 14-17, 2012

 The story evolved as the reporters got a clearer picture of
 events, mostly over the course of the first day.  We display 19
 different versions of the article, giving a clear view of the story's
 evolution.

 In
 U.S. Officials Say Iran Has Agreed To Nuclear Talks

By HELENE COOPER and MARK LANDLER on October 20, 2012

 The original lede was "The United States and Iran have agreed
 for the first time to one-on-one negotiations over Iran's nuclear
 program".  Two hours later, it was changed to "... have agreed in
 principle for the first time..."; a paragraph was added to say
 that "The White House publicly denied the report on Saturday
 evening".

 In
    Behind Romney's Decision to Attack Obama on Libya ==> A Challenger's Criticism Is Furiously Returned

By DAVID E. SANGER and ASHLEY PARKER ==> PETER BAKER and ASHLEY PARKER on September 12, 2012

 An article discussing Romney's response to the Benghazi attacks
 was completely rewritten in a very different tone.  The first version
 was quite critical of Romney, while the second was more neutral
 he-said she-said coverage.  Compare

   For a country looking to understand how Mr. Romney, a Republican
   candidate with no foreign policy experience, would respond to a major
   crisis, this was a first glimpse. And as an adviser to the campaign
   who worked in the George W. Bush administration said on Wednesday,
   Mr. Romney's accusation that Mr. Obama had invited the attacks because
   he had weakened America looked like "he had forgotten the first rule
   in a crisis: don't start talking before you understand what's
   happening."

 to

   Mr. Romney's criticism fed into his larger theme of painting Mr. Obama
   as apologizing for the United States, and his team stuck by it. "While
   there may be differences of opinion regarding issues of timing," said
   one senior strategist, who asked not to be named, "I think everyone
   stands behind the critique of the administration, which we believe has
   conducted its foreign policy in a feckless manner."

These are sampled from the first week we were in operation:

In Mubarak Rushed To Military Care After a Stroke

By DAVID D. KIRKPATRICK and KAREEM FAHIM on June 19, 2012

The story was updated and rewritten after former President Hosni Mubarak's condition was changed from being
"clinically dead" to ""critical condition and still alive."

In As Singapore Loosens Its Grip, Residents Lose Fear to Challenge Authority

By ANDREW JACOBS on June 16, 2012

"Singapore's single-party rule" ==> "Singapore's single-party dominance."

In
Egyptians Return to Polls for a Second Day

By DAVID D. KIRKPATRICK and KAREEM FAHIM on June 17, 2012

"the democratically elected, Islamist-led Parliament" ==> "the competitively elected, Islamist-led Parliament."

In
China Closes Window on Economic Debate, Protecting Dominance of State

By IAN JOHNSON on June 16, 2012

A "Propaganda Ministry directive" ==> "A propaganda department directive".

With the correction: "An earlier version of this article incorrectly referred to the Propaganda Ministry of the Communist Party. While there is a propaganda department under the Communist Party Central Committee, there is no government ministry by that name."

In
Rodney King, Whose Beating Led to L.A. Riots, Dies at 47

By JENNIFER MEDINA on June 17, 2012

The breaking news story of Rodney King's death evolved over time. Changes ranged from adding his middle initial (G.) to attributing the suspected cause of death (drowning).

In Supporters of Bailout Claim Victory in Greece

By RACHEL DONADIO on June 17, 2012

The following paragraph was removed: "The fact that Syriza did not place first may make European
leaders
more
likely to grant some concessions to Greece, but they also have to consider the larger economies of Spain and Italy, which are also under intense pressure."

In Obama
and Putin Meet at Last, but Deadlock on Syria Strategy

By HELENE COOPER on June 18, 2012

Increased detail in phrasing."White House officials in the past few days have been sounding increasingly impatient." ==> "it has put Mr. Obama in a difficult
position as he tries
to
persuade
Mr.
Putin of
America's good
intentions — or, at least, its lack of ill intentions — toward Russia."

In Questions on Women's Rights and Ethnic Strife Stir Worries Over Afghanistan's Path

By GRAHAM BOWLEY on June 19, 2012

Headline changed from "Insurgents Strike Checkpoint in Southern Afghanistan" to "Questions on Women's Rights and Ethnic Strife Stir Worries Over Afghanistan's Path"

In Road Trip Helps Romney Brush Up on Banter

By ASHLEY PARKER on June 18, 2012

The following paragraph was removed: "Al Gore was so stilted in 2000 that his campaign, trying to warm him up, paid the feminist writer Naomi Wolf for sartorial advice: earth tones for the man who wrote "Earth in the Balance."" And this correction added: "An earlier version of this article referred incorrectly to the role of Naomi Wolf in Al Gore's 2000 presidential campaign. She was a consultant on women's issues and outreach to young voters; she was not Mr. Gore's image consultant and did not give him sartorial advice."

{% endblock %}


text:
package com.book3.t01;

import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;

public class Topology {
	public static void main(String[] args) {
		TopologyBuilder builder = new TopologyBuilder();
		builder.setSpout("log-reader", new LogReader(),1);

		builder.setBolt("log-stat", new LogStat(),1)
		.fieldsGrouping("log-reader",new Fields("user"));

		builder.setBolt("log-writer", new LogWriter(),1)
		.shuffleGrouping("log-stat");

		Config conf = new Config();
//		conf.setNumAckers(5);
		if (args.length == 0) {
			LocalCluster cluster = new LocalCluster();
			cluster.submitTopology("t01", conf, builder.createTopology());
		} else {
			conf.setNumAckers(3);
			try {
				StormSubmitter.submitTopology(args[0], conf, builder.createTopology());
			} catch (AlreadyAliveException | InvalidTopologyException e) {
				e.printStackTrace();
			}
		}
		Utils.sleep(200000);
	}

}


text:
package be.bittich.workshop.quote.service;

import be.bittich.workshop.quote.conf.QuoteProps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import yahoofinance.Stock;
import yahoofinance.YahooFinance;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Nordine on 03-03-16.
 */
@Service
@Cacheable(cacheNames = "stock")
public class StockService {

    static final Logger log = LoggerFactory.getLogger(StockService.class);

    @Autowired
    private QuoteProps quoteProps;

    public Map<String, Stock> getStocks() throws IOException {

        log.info("goes there for the first time before caching");

        return YahooFinance.get(quoteProps.getQuotes().toArray(new String[]{}));
    }

    @CacheEvict(value = "stock", allEntries = true)
    public void evictCache() {
        log.info("cache will be evicted...");
    }

}


text:
  CREATE TABLE SUBAWARD_STATUS
   (	SUBAWARD_STATUS_CODE NUMBER(3,0) NOT NULL,
	DESCRIPTION VARCHAR2(200 BYTE) NOT NULL,
	UPDATE_TIMESTAMP DATE NOT NULL,
	UPDATE_USER VARCHAR2(60 BYTE) NOT NULL,
	VER_NBR NUMBER(8,0) DEFAULT 1 NOT NULL,
	OBJ_ID VARCHAR2(36 BYTE) NOT NULL
  )
/
ALTER TABLE SUBAWARD_STATUS
  ADD CONSTRAINT PK_SUBAWARD_STATUS_TYPE PRIMARY KEY (SUBAWARD_STATUS_CODE)
/


text:
export default [];
//# sourceMappingURL=os-RU.js.map


text: exports.Node = require('./node')


text:
/*globals define, module */

// This module contains functions for converting milliseconds
// to and from CSS time strings.

(function (globals) {
    'use strict';

    var regex = /^([\-\+]?[0-9]+(\.[0-9]+)?)(m?s)$/,

    functions = {
        from: from,
        to: to
    };

    exportFunctions();

    // Public function `from`.
    //
    // Returns the number of milliseconds represented by a
    // CSS time string.
    function from (cssTime) {
        var matches = regex.exec(cssTime);

        if (matches === null) {
            throw new Error('Invalid CSS time');
        }

        return parseFloat(matches[1]) * (matches[3] === 's' ? 1000 : 1);
    }

    // Public function `to`.
    //
    // Returns a CSS time string representing the number
    // of milliseconds passed in the arguments.
    function to (milliseconds) {
        if (typeof milliseconds !== 'number' || isNaN(milliseconds)) {
            throw new Error('Invalid milliseconds');
        }

        return milliseconds + 'ms';
    }

    function exportFunctions () {
        if (typeof define === 'function' && define.amd) {
            define(function () {
                return functions;
            });
        } else if (typeof module !== 'undefined' && module !== null && module.exports) {
            module.exports = functions;
        } else {
            globals.cssTime = functions;
        }
    }
}(this));


text:
package org.example.calculator.helpers;

import org.opendolphin.core.comm.Codec;
import org.opendolphin.core.server.ServerConnector;
import org.opendolphin.core.server.ServerDolphin;
import org.opendolphin.core.server.ServerModelStore;

import javax.inject.Inject;
import javax.inject.Provider;

public class ServerDolphinProvider implements Provider<ServerDolphin> {
    @Inject
    private ServerModelStore serverModelStore;

    @Inject
    private ServerConnector serverConnector;

    @Inject
    private Codec codec;

    @Override
    public ServerDolphin get() {
        serverConnector.setCodec(codec);
        serverConnector.setServerModelStore(serverModelStore);
        ServerDolphin serverDolphin = new ServerDolphin(serverModelStore, serverConnector);
        serverDolphin.registerDefaultActions();
        return serverDolphin;
    }
}


text:
//>>built
define("dojo/data/api/Request",["../../_base/declare"],function(_1){return _1("dojo.data.api.Request",null,{abort:function(){throw new Error("Unimplemented API: dojo.data.api.Request.abort");}});});


text:
ntrees_opt = [5,10,15]
max_depth_opt = [2,3,4]
learn_rate_opt = [0.1,0.2]
hyper_parameters = {"ntrees": ntrees_opt, "max_depth":max_depth_opt,
    "learn_rate":learn_rate_opt}

from h2o.grid.grid_search import H2OGridSearch
gs = H2OGridSearch(H2OGradientBoostingEstimator,
    hyper_params=hyper_parameters)
gs.train(x=myX, y="IsDepDelayed", training_frame=air_train_hex,
    validation_frame=air_valid_hex)


text:
#ifndef PSTDBOOL_H
#define PSTDBOOL_H

#if !defined(__cplusplus) && !__bool_true_false_are_defined && !defined(bool) && !defined(__STDBOOL_H)

#ifdef HAVE_STDBOOL_H

#include <stdbool.h>

#elif (defined(__STDC__) && __STDC__ && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L)
/* C99 or newer */

#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1

#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)

#define bool bool
#define true true
#define false false
#define __bool_true_false_are_defined 1

#else

typedef unsigned char _Portable_bool;
#define bool _Portable_bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1

#endif

#endif

#endif /* PSTDBOOL_H */


text:
using System.Net.Http;
using System.Web.Http;

using MvcRouteTester.Test.Assertions;

using NUnit.Framework;

namespace MvcRouteTester.Test.ApiRoute
{
	[TestFixture]
	public class RouteParamsTests
	{
		private HttpConfiguration config;

		[SetUp]
		public void MakeRouteTable()
		{
			RouteAssert.UseAssertEngine(new NunitAssertEngine());

			config = new HttpConfiguration();

			config.Routes.MapHttpRoute(
				name: "DefaultApi",
				routeTemplate: "api/{controller}/{id}",
				defaults: new { id = RouteParameter.Optional });
		}

		[Test]
		public void HasRouteWithParams()
		{
			RouteAssert.HasApiRoute(config, "/api/customer/1?foo=1&bar=2", HttpMethod.Get);
		}

		[Test]
		public void HasRouteWithParamsCapturesValues()
		{
			var expectedRoute = new { controller = "customer", action = "get", id = "1", foo = "1", bar = "2" };
			RouteAssert.HasApiRoute(config, "/api/customer/1?foo=1&bar=2", HttpMethod.Get, expectedRoute);
		}
	}
}


text:
"""
Django settings for school_manager project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from os.path import join
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'schools',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'analytics',
    'rest_framework',
    'api',
    'students',
    'school_calendar',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'school_manager.urls'

WSGI_APPLICATION = 'school_manager.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    #'default': {
    #    'ENGINE': 'django.db.backends.sqlite3',
    #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #},
    'default': {
        'ENGINE':'django.db.backends.postgresql_psycopg2',
        'NAME': 'school_manager',
        'USER': os.environ.get('PSQL_USER'),
        'PASSWORD': os.environ.get('PSQL_PASS'),
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

#DEFAULT_INDEX_TABLESPACE = 'school_manager'
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = (
    BASE_DIR + '/static/'
)

STATICFILES_DIRS = (os.path.join(BASE_DIR,'staticfiles'), )

TEMPLATE_DIRS = (
    join(BASE_DIR,  'templates'),
)

#AUTH_PROFILE_MODULE = 'schools.Person' #actually this is deprecated as of Django 1.5
LOGIN_REDIRECT_URL = '/'
#SOUTH_TESTS_MIGRATE = False

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}


text:
package org.apache.ignite.internal.processors.cache.extras;

import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.cache.version.*;
import org.apache.ignite.internal.util.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.jetbrains.annotations.*;

import java.util.*;

/**
 * Extras where attributes and obsolete version are set.
 */
public class GridCacheAttributesObsoleteEntryExtras extends GridCacheEntryExtrasAdapter {
    /** Attributes data. */
    private GridLeanMap<UUID, Object> attrData;

    /** Obsolete version. */
    private GridCacheVersion obsoleteVer;

    /**
     * Constructor.
     *
     * @param attrData Attributes data.
     * @param obsoleteVer Obsolete version.
     */
    public GridCacheAttributesObsoleteEntryExtras(GridLeanMap<UUID, Object> attrData, GridCacheVersion obsoleteVer) {
        assert attrData != null;
        assert obsoleteVer != null;

        this.attrData = attrData;
        this.obsoleteVer = obsoleteVer;
    }

    /** {@inheritDoc} */
    @Override public GridLeanMap<UUID, Object> attributesData() {
        return attrData;
    }

    /** {@inheritDoc} */
    @Override public GridCacheEntryExtras attributesData(@Nullable GridLeanMap<UUID, Object> attrData) {
        if (attrData != null) {
            this.attrData = attrData;

            return this;
        }
        else
            return new GridCacheObsoleteEntryExtras(obsoleteVer);
    }

    /** {@inheritDoc} */
    @Override public GridCacheEntryExtras mvcc(GridCacheMvcc mvcc) {
        return mvcc != null ? new GridCacheAttributesMvccObsoleteEntryExtras(attrData, mvcc, obsoleteVer) : this;
    }

    /** {@inheritDoc} */
    @Override public GridCacheVersion obsoleteVersion() {
        return obsoleteVer;
    }

    /** {@inheritDoc} */
    @Override public GridCacheEntryExtras obsoleteVersion(GridCacheVersion obsoleteVer) {
        if (obsoleteVer != null) {
            this.obsoleteVer = obsoleteVer;

            return this;
        }
        else
            return new GridCacheAttributesEntryExtras(attrData);
    }

    /** {@inheritDoc} */
    @Override public GridCacheEntryExtras ttlAndExpireTime(long ttl, long expireTime) {
        return ttl != 0 ? new GridCacheAttributesObsoleteTtlEntryExtras(attrData, obsoleteVer, ttl, expireTime) :
            this;
    }

    /** {@inheritDoc} */
    @Override public int size() {
        return 16;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridCacheAttributesObsoleteEntryExtras.class, this);
    }
}


text:
package com.javarush.test.level21.lesson02.task03;

/* Все гениальное - просто!
Упростить. Переменные не переименовывать, комментарии не оставлять.
*/
public class Solution {
    public static boolean calculate(boolean a, boolean b, boolean c, boolean d) {
        return c;
    }

}


text:
package com.wayneleo.quickstart.framework.extensions.configuration;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.wayneleo.quickstart.publish.test.BaseTest;

public class Tester extends BaseTest {
    @Autowired
    private ConfigObject conf;

    @Override
    public void beforeTest() {}

    @Override
    public void afterTest() {}

    @Test
    public void read() {
        Assert.assertNotNull( conf );
        Assert.assertTrue( StringUtils.isNotEmpty( conf.getName() ) );
        System.out.println( "======> " + conf.getName() );
    }
}


text:
namespace Dune {
namespace Stuff {
namespace Grid {

template< int dd >
class FakeEntity
{
public:
  GeometryType type() const;

  class Geometry
  {
  public:
    template< class T >
    T global(const T& t) const
    {
      return t;
    }
  }; // class Geometry

  Geometry geometry() const
  {
    return Geometry();
  }

  static constexpr int dimension = dd;
}; // class FakeEntity

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_GRID_FAKEENTITY_HH


text: PRAGMA encoding=UTF16le


text:
namespace AudioSwitch.Controls
{
    partial class Devices
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label4 = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.checkEnableAsCommunicationsOnStartup = new System.Windows.Forms.CheckBox();
            this.checkEnableAsMultimediaOnStartup = new System.Windows.Forms.CheckBox();
            this.checkCustomName = new System.Windows.Forms.CheckBox();
            this.pictureModded = new System.Windows.Forms.PictureBox();
            this.textCustomName = new System.Windows.Forms.TextBox();
            this.label12 = new System.Windows.Forms.Label();
            this.checkHideDevice = new System.Windows.Forms.CheckBox();
            this.label13 = new System.Windows.Forms.Label();
            this.label14 = new System.Windows.Forms.Label();
            this.label15 = new System.Windows.Forms.Label();
            this.buttonRemove = new System.Windows.Forms.Button();
            this.buttonSave = new System.Windows.Forms.Button();
            this.trackBrightness = new System.Windows.Forms.TrackBar();
            this.trackSaturation = new System.Windows.Forms.TrackBar();
            this.trackHue = new System.Windows.Forms.TrackBar();
            this.listDevices = new AudioSwitch.Controls.CustomListView();
            this.groupBox1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureModded)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackBrightness)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackSaturation)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackHue)).BeginInit();
            this.SuspendLayout();
            //
            // label4
            //
            this.label4.Location = new System.Drawing.Point(2, 2);
            this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(133, 20);
            this.label4.TabIndex = 13;
            this.label4.Text = "Connected Devices";
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.checkEnableAsCommunicationsOnStartup);
            this.groupBox1.Controls.Add(this.checkEnableAsMultimediaOnStartup);
            this.groupBox1.Controls.Add(this.checkCustomName);
            this.groupBox1.Controls.Add(this.pictureModded);
            this.groupBox1.Controls.Add(this.textCustomName);
            this.groupBox1.Controls.Add(this.label12);
            this.groupBox1.Controls.Add(this.checkHideDevice);
            this.groupBox1.Controls.Add(this.label13);
            this.groupBox1.Controls.Add(this.label14);
            this.groupBox1.Controls.Add(this.label15);
            this.groupBox1.Controls.Add(this.buttonRemove);
            this.groupBox1.Controls.Add(this.buttonSave);
            this.groupBox1.Controls.Add(this.trackBrightness);
            this.groupBox1.Controls.Add(this.trackSaturation);
            this.groupBox1.Controls.Add(this.trackHue);
            this.groupBox1.Location = new System.Drawing.Point(200, 2);
            this.groupBox1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.groupBox1.Size = new System.Drawing.Size(321, 279);
            this.groupBox1.TabIndex = 14;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Selected Device Settings";
            //
            // checkEnableAsCommunicationsOnStartup
            //
            this.checkEnableAsCommunicationsOnStartup.Location = new System.Drawing.Point(14, 184);
            this.checkEnableAsCommunicationsOnStartup.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.checkEnableAsCommunicationsOnStartup.Name = "checkEnableAsCommunicationsOnStartup";
            this.checkEnableAsCommunicationsOnStartup.Size = new System.Drawing.Size(285, 16);
            this.checkEnableAsCommunicationsOnStartup.TabIndex = 28;
            this.checkEnableAsCommunicationsOnStartup.Text = "Enable as communications device on startup";
            this.checkEnableAsCommunicationsOnStartup.UseVisualStyleBackColor = true;
            //
            // checkEnableAsMultimediaOnStartup
            //
            this.checkEnableAsMultimediaOnStartup.Location = new System.Drawing.Point(14, 164);
            this.checkEnableAsMultimediaOnStartup.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.checkEnableAsMultimediaOnStartup.Name = "checkEnableAsMultimediaOnStartup";
            this.checkEnableAsMultimediaOnStartup.Size = new System.Drawing.Size(263, 16);
            this.checkEnableAsMultimediaOnStartup.TabIndex = 27;
            this.checkEnableAsMultimediaOnStartup.Text = "Enable as multimedia device on startup";
            this.checkEnableAsMultimediaOnStartup.UseVisualStyleBackColor = true;
            //
            // checkCustomName
            //
            this.checkCustomName.Location = new System.Drawing.Point(14, 109);
            this.checkCustomName.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.checkCustomName.Name = "checkCustomName";
            this.checkCustomName.Size = new System.Drawing.Size(149, 18);
            this.checkCustomName.TabIndex = 3;
            this.checkCustomName.Text = "Customize display name";
            this.checkCustomName.UseVisualStyleBackColor = true;
            this.checkCustomName.CheckedChanged += new System.EventHandler(this.checkCustomName_CheckedChanged_1);
            //
            // pictureModded
            //
            this.pictureModded.Location = new System.Drawing.Point(288, 15);
            this.pictureModded.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.pictureModded.Name = "pictureModded";
            this.pictureModded.Size = new System.Drawing.Size(24, 24);
            this.pictureModded.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureModded.TabIndex = 20;
            this.pictureModded.TabStop = false;
            //
            // textCustomName
            //
            this.textCustomName.Enabled = false;
            this.textCustomName.Location = new System.Drawing.Point(14, 131);
            this.textCustomName.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.textCustomName.Name = "textCustomName";
            this.textCustomName.Size = new System.Drawing.Size(190, 20);
            this.textCustomName.TabIndex = 4;
            //
            // label12
            //
            this.label12.Location = new System.Drawing.Point(233, 19);
            this.label12.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label12.Name = "label12";
            this.label12.Size = new System.Drawing.Size(66, 17);
            this.label12.TabIndex = 26;
            this.label12.Text = "Tray Icon Color";
            //
            // checkHideDevice
            //
            this.checkHideDevice.Location = new System.Drawing.Point(4, 255);
            this.checkHideDevice.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.checkHideDevice.Name = "checkHideDevice";
            this.checkHideDevice.Size = new System.Drawing.Size(177, 16);
            this.checkHideDevice.TabIndex = 5;
            this.checkHideDevice.Text = "Hide device from switch list";
            this.checkHideDevice.UseVisualStyleBackColor = true;
            //
            // label13
            //
            this.label13.Location = new System.Drawing.Point(50, 30);
            this.label13.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label13.Name = "label13";
            this.label13.Size = new System.Drawing.Size(27, 20);
            this.label13.TabIndex = 16;
            this.label13.Text = "Hue";
            //
            // label14
            //
            this.label14.Location = new System.Drawing.Point(21, 50);
            this.label14.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label14.Name = "label14";
            this.label14.Size = new System.Drawing.Size(56, 18);
            this.label14.TabIndex = 19;
            this.label14.Text = "Saturation";
            //
            // label15
            //
            this.label15.Location = new System.Drawing.Point(20, 71);
            this.label15.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label15.Name = "label15";
            this.label15.Size = new System.Drawing.Size(57, 14);
            this.label15.TabIndex = 21;
            this.label15.Text = "Brightness";
            //
            // buttonRemove
            //
            this.buttonRemove.Location = new System.Drawing.Point(108, 207);
            this.buttonRemove.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.buttonRemove.Name = "buttonRemove";
            this.buttonRemove.Size = new System.Drawing.Size(100, 33);
            this.buttonRemove.TabIndex = 6;
            this.buttonRemove.Text = "Remove Settings";
            this.buttonRemove.UseVisualStyleBackColor = true;
            this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click);
            //
            // buttonSave
            //
            this.buttonSave.Location = new System.Drawing.Point(212, 207);
            this.buttonSave.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.buttonSave.Name = "buttonSave";
            this.buttonSave.Size = new System.Drawing.Size(100, 33);
            this.buttonSave.TabIndex = 7;
            this.buttonSave.Text = "Save Settings";
            this.buttonSave.UseVisualStyleBackColor = true;
            this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
            //
            // trackBrightness
            //
            this.trackBrightness.BackColor = System.Drawing.SystemColors.Control;
            this.trackBrightness.Location = new System.Drawing.Point(70, 70);
            this.trackBrightness.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.trackBrightness.Maximum = 60;
            this.trackBrightness.Name = "trackBrightness";
            this.trackBrightness.Size = new System.Drawing.Size(131, 45);
            this.trackBrightness.TabIndex = 2;
            this.trackBrightness.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trackBrightness.Scroll += new System.EventHandler(this.trackBrightness_Scroll);
            //
            // trackSaturation
            //
            this.trackSaturation.BackColor = System.Drawing.SystemColors.Control;
            this.trackSaturation.Location = new System.Drawing.Point(70, 49);
            this.trackSaturation.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.trackSaturation.Maximum = 100;
            this.trackSaturation.Name = "trackSaturation";
            this.trackSaturation.Size = new System.Drawing.Size(131, 45);
            this.trackSaturation.TabIndex = 1;
            this.trackSaturation.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trackSaturation.Scroll += new System.EventHandler(this.trackSaturation_Scroll);
            //
            // trackHue
            //
            this.trackHue.BackColor = System.Drawing.SystemColors.Control;
            this.trackHue.Location = new System.Drawing.Point(70, 29);
            this.trackHue.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
            this.trackHue.Maximum = 360;
            this.trackHue.Name = "trackHue";
            this.trackHue.Size = new System.Drawing.Size(131, 45);
            this.trackHue.TabIndex = 22;
            this.trackHue.TickStyle = System.Windows.Forms.TickStyle.None;
            this.trackHue.Scroll += new System.EventHandler(this.trackHue_Scroll);
            //
            // listDevices
            //
            this.listDevices.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.listDevices.BackColor = System.Drawing.SystemColors.Control;
            this.listDevices.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.listDevices.FullRowSelect = true;
            this.listDevices.HideSelection = false;
            this.listDevices.Location = new System.Drawing.Point(2, 17);
            this.listDevices.Margin = new System.Windows.Forms.Padding(2);
            this.listDevices.MultiSelect = false;
            this.listDevices.Name = "listDevices";
            this.listDevices.Size = new System.Drawing.Size(194, 300);
            this.listDevices.Sorting = System.Windows.Forms.SortOrder.Ascending;
            this.listDevices.TabIndex = 12;
            this.listDevices.TileSize = new System.Drawing.Size(238, 40);
            this.listDevices.UseCompatibleStateImageBehavior = false;
            this.listDevices.View = System.Windows.Forms.View.Tile;
            this.listDevices.SelectedIndexChanged += new System.EventHandler(this.listDevices_SelectedIndexChanged_1);
            //
            // Devices
            //
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            this.Controls.Add(this.listDevices);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.groupBox1);
            this.Name = "Devices";
            this.Size = new System.Drawing.Size(528, 319);
            this.Load += new System.EventHandler(this.Devices_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureModded)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackBrightness)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackSaturation)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackHue)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private Controls.CustomListView listDevices;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.CheckBox checkEnableAsCommunicationsOnStartup;
        private System.Windows.Forms.CheckBox checkEnableAsMultimediaOnStartup;
        private System.Windows.Forms.CheckBox checkCustomName;
        private System.Windows.Forms.PictureBox pictureModded;
        private System.Windows.Forms.TextBox textCustomName;
        private System.Windows.Forms.Label label12;
        private System.Windows.Forms.CheckBox checkHideDevice;
        private System.Windows.Forms.Label label13;
        private System.Windows.Forms.Label label14;
        private System.Windows.Forms.Label label15;
        private System.Windows.Forms.Button buttonRemove;
        private System.Windows.Forms.Button buttonSave;
        private System.Windows.Forms.TrackBar trackBrightness;
        private System.Windows.Forms.TrackBar trackSaturation;
        private System.Windows.Forms.TrackBar trackHue;
    }
}


text:
<?php

namespace eig\APIAuth\Tests;

use eig\APIAuth\Facades\ClientRegistrar;
use eig\Configurator\Configurator;
use eig\Configurator\Options as ConfigOptions;
use Lcobucci\JWT\Parser;
use PasswordLib\PasswordLib;
use eig\APIAuth\Facades\JWT;
use Mockery;

class ClientRegistrarFacadeTest extends TestAbstract
{
    protected $clientPersistence;

    protected $sessionPersistence;

    protected $tokenGenerator;

    protected $library;

    protected $fingerprint;

    protected $jwtPersistence;

    /**
     * @var
     */
    protected $type;

    protected $configFiles = [
        [
            'source' => 'APIAuth.php',
            'path' => 'src/config/',
            'pathType' => 'relative',
            'type' => 'array',
            'alias' => 'APIAuth'
        ]
    ];

    protected $configOptions;

    protected $config;

    public function setUp ()
    {
        $this->configOptions = new ConfigOptions();
        $this->configOptions->basePath = realpath('src/config');
        $this->config = new Configurator($this->configFiles, $this->configOptions);
        $this->fingerprint = md5('this is the clients guid');
        $this->type = 'Android';
        $this->library = new PasswordLib();
        $this->clientPersistence = Mockery::mock('eig\APIAuth\Contracts\ClientPersistenceInterface');
        $this->sessionPersistence = Mockery::mock('eig\APIAuth\Contracts\SessionPersistenceInterface');
        $this->jwtPersistence = Mockery::mock('eig\APIAuth\Abstracts\AbstractJWTPersistence');
        $this->jwtPersistence->shouldReceive('issued');
        $this->jwtPersistence->shouldReceive('expiration');
        $this->jwtPersistence->shouldReceive('notBefore');
        $this->jwtPersistence->shouldReceive('token');
        $this->jwtPersistence->shouldReceive('save');
        JWT::initialize($this->config, $this->jwtPersistence);

        parent::setUp();
    }

    public function tearDown ()
    {
        \Mockery::close();
        parent::tearDown();
    }

    public function testRegister() {
        $ctoken = $this->library->createPasswordHash($this->fingerprint . $this->type, '$2a$', array('cost' => 10));
        $this->jwtPersistence->shouldReceive('create');
        $this->jwtPersistence->shouldReceive('id')->andReturn('123456543');
        $this->clientPersistence->shouldReceive('fingerprint')->andReturn(true);
        $this->clientPersistence->shouldReceive('exists')->andReturn(false);
        $this->clientPersistence->shouldReceive('type');
        $this->clientPersistence->shouldReceive('create');
        $this->clientPersistence->shouldReceive('token')->andReturn($ctoken);
        $this->clientPersistence->shouldReceive('save')->andReturn(true);
        $this->sessionPersistence->shouldReceive('client')->andReturn(true);
        $this->sessionPersistence->shouldReceive('setRevoked');
        $this->sessionPersistence->shouldReceive('create');
        $this->sessionPersistence->shouldReceive('timeout');
        $this->sessionPersistence->shouldReceive('exists')->andReturn(false);
        $this->sessionPersistence->shouldReceive('token')->andReturn(
            $this->library->createPasswordHash($ctoken . $this->fingerprint, '$2a$', array('cost' => 10))
        );
        $this->sessionPersistence->shouldReceive('save')->andReturn(true);

        ClientRegistrar::initialize($this->clientPersistence, $this->sessionPersistence, null, $this->jwtPersistence);
        $data = ClientRegistrar::register($this->fingerprint, $this->type);
        $data = (new Parser())->parse((string) $data);
        //$data->getHeaders();
        //$data->getClaims();
        $registrarData = (array)json_decode($data->getClaim('data'));
        //print_r($registrarData);
        $clientToken = $registrarData['ClientToken'];
        $sessionToken = $registrarData['SessionToken'];
        $this->assertTrue($this->library->verifyPasswordHash($this->fingerprint . $this->type, $clientToken));
        $this->assertTrue($this->library->verifyPasswordHash($ctoken . $this->fingerprint, $sessionToken));
    }
}