text:
from __future__ import absolute_import, unicode_literals

from collections import defaultdict
from hashlib import sha224

import posixpath
import unittest
import responses
import six
from docker.utils import parse_bytes

from dockermap import DEFAULT_COREIMAGE, DEFAULT_BASEIMAGE
from dockermap.map.config.client import ClientConfiguration
from dockermap.map.config.main import ContainerMap
from dockermap.map.config.utils import get_map_config_ids
from dockermap.map.input import ExecCommand, ExecPolicy, MapConfigId, ItemType, UsedVolume
from dockermap.map.policy import ConfigFlags
from dockermap.map.policy.base import BasePolicy
from dockermap.map.policy.utils import get_shared_volume_path
from dockermap.map.state import INITIAL_START_TIME, State, StateFlags
from dockermap.map.state.base import DependencyStateGenerator, DependentStateGenerator, SingleStateGenerator
from dockermap.map.state.update import UpdateStateGenerator
from dockermap.map.state.update.container import CONTAINER_UPDATE_VARS
from dockermap.map.state.utils import merge_dependency_paths
from dockermap.utils import format_image_tag

from tests import MAP_DATA_2, CLIENT_DATA_1, CLIENT_DATA_2, SKIP_LEGACY_TESTS

if SKIP_LEGACY_TESTS:
    client_versions = CLIENT_DATA_1['version'],
else:
    client_versions = CLIENT_DATA_1['version'], CLIENT_DATA_2['version']

URL_PREFIXES = ['http+docker://{1}/v{0}'.format(v, h)
                for h in ('localunixsocket',
                          'localhost')
                for v in client_versions]

P_STATE_INITIAL = 0
P_STATE_RUNNING = 1
P_STATE_RESTARTING = 2
P_STATE_EXITED_0 = 3
P_STATE_EXITED_127 = 4
STATE_RESULTS = {
    P_STATE_INITIAL: {
        'Running': False,
        'Restarting': False,
        'Pid': 0,
        'ExitCode': 0,
        'StartedAt': INITIAL_START_TIME,
    },
    P_STATE_RESTARTING: {
        'Running': False,
        'Restarting': True,
        'Pid': 0,
        'ExitCode': 255,
        'StartedAt': "2016-02-05T20:14:04.655843958Z",
    },
    P_STATE_RUNNING: {
        'Running': True,
        'Restarting': False,
        'Pid': 1,
        'ExitCode': 0,
        'StartedAt': "2016-02-05T20:14:04.655843958Z",
    },
    P_STATE_EXITED_0: {
        'Running': False,
        'Restarting': False,
        'Pid': 0,
        'ExitCode': 0,
        'StartedAt': "2016-02-05T20:14:04.655843958Z",
    },
    P_STATE_EXITED_127: {
        'Running': False,
        'Restarting': False,
        'Pid': 0,
        'ExitCode': -127,
        'StartedAt': "2016-02-05T20:14:04.655843958Z",
    },
}

def _get_hash(main, *args):
    h = sha224(main.encode('utf-8'))
    for a in args:
        h.update(a.encode('utf-8'))
    return h.hexdigest()

def get_image_id(image_name):
    return _get_hash('image_name', image_name)

def get_container_id(container_name):
    return _get_hash('container', container_name)

def get_network_id(network_name):
    return _get_hash('network', network_name)

def get_endpoint_id(network_name, container_id):
    return _get_hash('network-endpoint', network_name, container_id)

def get_invalid_endpoint_id(network_name, container_id):
    return 'invalid-{0}'.format(get_endpoint_id(network_name, container_id))

def _container(config_name, p_state=P_STATE_RUNNING, instances=None, attached_volumes_valid=True,
               instance_volumes_valid=True, **kwargs):
    return config_name, p_state, instances, attached_volumes_valid, instance_volumes_valid, kwargs

def _network(config_name, **kwargs):
    return config_name, kwargs

def _add_container_list(rsps, container_names):
    results = [
        {'Id': get_container_id(name), 'Names': ['/{0}'.format(name)]}
        for name in container_names
    ]
    for prefix in URL_PREFIXES:
        rsps.add('GET', '{0}/containers/json'.format(prefix), content_type='application/json', json=results)

def _add_network_list(rsps, network_names):
    results = [
        {'Id': get_network_id(name), 'Name': name}
        for name in network_names
    ]
    for prefix in URL_PREFIXES:
        rsps.add('GET', '{0}/networks'.format(prefix), content_type='application/json', json=results)

def _add_volume_list(rsps, volume_names):
    results = {
        'Volumes': [
            {'Name': name} for name in volume_names
        ] or None,
        'Warnings': None,
    }
    for prefix in URL_PREFIXES:
        rsps.add('GET', '{0}/volumes'.format(prefix), content_type='application/json', json=results)

def _add_image_list(rsps, image_names):
    image_list = [
        {
            'RepoTags': ['{0}:latest'.format(i_name), '{0}:1.0'.format(i_name)] if ':' not in i_name else [i_name],
            'Id': i_id,
        }
        for i_id, i_name in image_names
    ]
    for prefix in URL_PREFIXES:
        rsps.add('GET', '{0}/images/json'.format(prefix), content_type='application/json', json=image_list)
    for image in image_list:
        for r_tag in image['RepoTags']:
            for prefix in URL_PREFIXES:
                rsps.add('GET', '{0}/images/{1}/json'.format(prefix, r_tag), content_type='application/json',
                         json=image)
    for prefix in URL_PREFIXES:
        rsps.add('POST', '{0}/images/create'.format(prefix), content_type='application/json')

def _get_container_mounts(config_id, container_map, c_config, named_volumes, valid):
    if valid:
        path_prefix = '/valid'
    else:
        path_prefix = '/invalid_{0}'.format(config_id.config_name)
    for a in c_config.attaches:
        if isinstance(a, UsedVolume):
            c_path = a.path
        else:
            c_path = container_map.volumes[a.name].default_path
        yield {
            'Type': 'volume',
            'Source': posixpath.join(path_prefix, 'attached', a.name),
            'Destination': c_path,
            'Name': '{0}.{1}.{2}'.format(config_id.map_name, config_id.config_name, a.name)
                    if named_volumes else '',
            'RW': True
        }
    if config_id.config_type == ItemType.CONTAINER:
        for vol in c_config.binds:
            c_path, h_path = get_shared_volume_path(container_map, vol, config_id.instance_name)
            yield {
                'Type': 'bind',
                'Source': posixpath.join(path_prefix, h_path),
                'Destination': c_path,
                'RW': not vol.readonly,
            }
        for s in c_config.shares:
            yield {
                'Type': 'volume',
                'Source': posixpath.join(path_prefix, 'shared', s),
                'Destination': s,
                'Name': _get_hash('shared-volume', path_prefix, s) if named_volumes else '',
                'RW': True,
            }
        for vol in c_config.uses:
            c, __, i = vol.name.partition('.')
            c_ref = container_map.get_existing(c)
            if c_ref:
                attached_volumes = {a.name: a for a in c_ref.attaches}
                if i and i in attached_volumes:
                    instance_volume = attached_volumes[i]
                    if isinstance(instance_volume, UsedVolume):
                        c_path = instance_volume.path
                    else:
                        c_path = container_map.volumes[i].default_path
                    yield {
                        'Type': 'volume',
                        'Source': posixpath.join(path_prefix, 'attached', i) if not named_volumes else '',
                        'Destination': c_path,
                        'Name': '{0}.{1}'.format(config_id.map_name, vol.name) if named_volumes else '',
                        'RW': not vol.readonly,
                    }
                elif not i or i in c_ref.instances:
                    for r_mount in _get_container_mounts(MapConfigId(config_id.config_type, config_id.map_name, c, i),
                                                         container_map, c_ref, named_volumes, valid):
                        yield r_mount
                else:
                    raise ValueError("Invalid uses declaration in {0}: volume for {1} not found.".format(config_id.config_name, vol))
            else:
                raise ValueError("Invalid uses declaration in {0}: configuration for {1} not found.".format(config_id.config_name, vol))

def _add_container_inspect(rsps, config_id, container_name, container_map, c_config, state, image_id, named_volumes,
                           volumes_valid, links_valid=True, network_ep_valid=True, network_link_valid=True,
                           skip_network=None, extra_network=False, **kwargs):
    config_type = config_id.config_type
    container_id = get_container_id(container_name)
    ports = defaultdict(list)
    host_config = {}
    network_settings = {}
    config_dict = {
        'Env': None,
        'Cmd': [],
        'Entrypoint': [],
    }
    host_config['NetworkMode'] = 'default'  # TODO: Vary.
    if config_type == ItemType.CONTAINER:
        for ex in c_config.exposes:
            ex_port = '{0}/tcp'.format(ex.exposed_port)
            if ex.host_port:
                if ex.interface:
                    ip = CLIENT_DATA_1['interfaces'][ex.interface]
                else:
                    ip = '0.0.0.0'
                ports[ex_port].append({
                    'HostIp': ip,
                    'HostPort': '{0}'.format(ex.host_port)
                })
            else:
                ports[ex_port].extend(())
        if links_valid:
            links_format = '/{0}.{1}:/{2}/{3}'
        else:
            links_format = '/{0}.{1}:/{2}/invalid-{3}'
        host_config['Links'] = [
            links_format.format(config_id.map_name, link.container, container_name,
                                link.alias or BasePolicy.get_hostname(link.container))
            for link in c_config.links
        ]
        networks = {}
        network_ep_func = get_endpoint_id if network_ep_valid else get_invalid_endpoint_id
        default_aliases = ['{0}_alias'.format(config_id.config_name)]
        if c_config.network_mode != 'none':  # TODO: Vary.
            for n in c_config.networks:
                if n.network_name == skip_network:
                    continue
                network_name = '{0}.{1}'.format(config_id.map_name, n.network_name)
                if n.links and network_link_valid:
                    link_list = ['{0}.{1}'.format(config_id.map_name, nl) for nl in n.links]
                else:
                    link_list = None
                networks[network_name] = {
                    'Links': link_list,
                    'Aliases': n.aliases or default_aliases,
                    'NetworkID': get_network_id(network_name),
                    'EndpointID': network_ep_func(network_name, container_id),
                }
            if not c_config.networks:
                networks['bridge'] = {
                    'Links': None,
                    'Aliases': default_aliases,
                    'NetworkID': get_network_id('bridge'),
                    'EndpointID': network_ep_func('bridge', container_id),
                }
            if extra_network:
                networks['extra'] = {
                    'Links':  None,
                    'Aliases': default_aliases,
                    'NetworkID': get_network_id('extra'),
                    'EndpointID': network_ep_func('extra', container_id),
                }
        else:
            config_dict['NetworkDisabled'] = True
        network_settings = {
            'Ports': ports,
            'Networks': networks,
        }
        for i_hc_key, c_hc_kwarg, c_cc_opt, i_hc_func in CONTAINER_UPDATE_VARS:
            if c_hc_kwarg in kwargs:
                c_val = kwargs.pop(c_hc_kwarg)
            elif c_hc_kwarg in c_config.host_config:
                c_val = c_config.host_config[c_hc_kwarg]
            elif c_cc_opt and c_hc_kwarg in c_config.create_options:
                c_val = c_config.create_options[c_hc_kwarg]
            elif c_hc_kwarg == 'memswap_limit':
                # Has a dependent default value.
                if 'mem_limit' in c_config.host_config:
                    c_val = parse_bytes(c_config.host_config['mem_limit']) * 2
                elif 'mem_limit' in c_config.create_options:
                    c_val = parse_bytes(c_config.create_options['mem_limit']) * 2
                else:
                    continue
            else:
                continue
            if c_val and i_hc_func:
                c_val = i_hc_func(c_val)
            if c_val is not None:
                host_config[i_hc_key] = c_val
        if 'restart_policy' in kwargs:
            c_rp_val = kwargs.pop('restart_policy')
        else:
            c_rp_val = c_config.host_config.get('restart_policy')
        if c_rp_val:
            host_config['RestartPolicy'] = c_rp_val
    else:
        config_dict['NetworkDisabled'] = True
    name_list = [container_name]
    results = {
        'Id': container_id,
        'Names': name_list,
        'State': STATE_RESULTS[state],
        'Image': image_id,
        'Mounts': list(_get_container_mounts(config_id, container_map, c_config, named_volumes, volumes_valid)),
        'HostConfig': host_config,
        'Config': config_dict,
        'NetworkSettings': network_settings,
    }
    exec_results = {
        'Processes': [
            [cmd_i, cmd.user, cmd.cmd]
            for cmd_i, cmd in enumerate(c_config.exec_commands)
        ],
    }
    results.update(kwargs)
    for i_id in (container_name, container_id):
        for prefix in URL_PREFIXES:
            rsps.add('GET', '{0}/containers/{1}/json'.format(prefix, i_id),
                     content_type='application/json',
                     json=results)
            rsps.add('GET', '{0}/containers/{1}/top'.format(prefix, i_id),
                     content_type='application/json',
                     json=exec_results)
    return container_name

def _add_network_inspect(rsps, network_name, n_config, containers, **kwargs):
    network_id = get_network_id(network_name)
    container_ids = [(get_container_id(c_name), c_name) for c_name in containers]
    if n_config:
        driver = n_config.driver
        internal = n_config.internal
    else:
        driver = network_name if network_name != 'none' else 'null'
        internal = False
    results = {
        'Id': network_id,
        'Name': network_name,
        'Driver': driver,
        'Internal': internal,
        'Options': {},
        'Containers': {
            c_id: {
                'Name': c_name,
                'EndpointID': get_endpoint_id(network_name, c_id),
            }
            for c_id, c_name in container_ids
        },
    }
    results.update(kwargs)
    for i_id in (network_name, network_id):
        for prefix in URL_PREFIXES:
            rsps.add('GET', '{0}/networks/{1}'.format(prefix, i_id),
                     content_type='application/json',
                     json=results)

def _add_volume_inspect(rsps, volume_name, **kwargs):
    results = {
        'Driver': 'local',
        'Mountpoint': '/docker/volumes/{0}/_data'.format(volume_name),
        'Name': volume_name,
        'Options': {},
    }
    results.update(kwargs)
    for prefix in URL_PREFIXES:
        rsps.add('GET', '{0}/volumes/{1}'.format(prefix, volume_name),
                 content_type='application/json',
                 json=results)

def _get_single_state(sg, config_ids):
    states = [s
              for s in sg.get_states(config_ids)
              if s.config_id.config_type == ItemType.CONTAINER]
    return states[-1]

def _get_states_dict(sl):
    cd = {}
    nd = {}
    vd = {}
    imd = {}
    for s in sl:
        config_id = s.config_id
        if config_id.config_type == ItemType.CONTAINER:
            cd[(config_id.config_name, config_id.instance_name)] = s
        elif config_id.config_type == ItemType.VOLUME:
            vd[(config_id.config_name, config_id.instance_name)] = s
        elif config_id.config_type == ItemType.NETWORK:
            nd[config_id.config_name] = s
        elif config_id.config_type == ItemType.IMAGE:
            imd[(config_id.config_name, config_id.instance_name)] = s
        else:
            raise ValueError("Invalid configuration type.", config_id.config_type)
    return {
        'containers': cd,
        'volumes': vd,
        'networks': nd,
        'images': imd,
    }

class TestPolicyStateGenerators(unittest.TestCase):
    def setUp(self):
        self.map_name = map_name = 'main'
        self.sample_map = sample_map = ContainerMap('main', MAP_DATA_2,
                                                    use_attached_parent_name=True).get_extended_map()
        self.sample_map.repository = None
        self.sample_client_config1 = client_config1 = ClientConfiguration(**CLIENT_DATA_1)
        self.sample_client_config2 = client_config2 = ClientConfiguration(**CLIENT_DATA_2)
        self.policy = BasePolicy({map_name: sample_map}, {'__default__': client_config1})
        self.policy_legacy = BasePolicy({map_name: sample_map}, {'__default__': client_config2})
        self.server_config_id = self._config_id('server')
        all_images = set(format_image_tag(sample_map.get_image(c_config.image or c_name))
                         for c_name, c_config in sample_map)
        all_images.add(DEFAULT_COREIMAGE)
        all_images.add(DEFAULT_BASEIMAGE)
        self.images = [(get_image_id(image_name), image_name)
                       for image_name in all_images]

    def _config_id(self, config_name, instance=None):
        return [MapConfigId(ItemType.CONTAINER, self.map_name, config_name, instance)]

    def _setup_containers(self, rsps, containers_states, networks=(), use_named_volumes=True):
        container_names = []
        volume_names = []
        network_names = []
        _add_image_list(rsps, self.images)
        image_dict = {name: _id for _id, name in self.images}
        base_image_id = image_dict[DEFAULT_BASEIMAGE]
        network_containers = defaultdict(list)
        for name, state, instances, attached_valid, instances_valid, kwargs in containers_states:
            c_config = self.sample_map.get_existing(name)
            for a in c_config.attaches:
                config_id = MapConfigId(ItemType.VOLUME, self.map_name, name, a.name)
                volume_name = '{0.map_name}.{0.config_name}.{0.instance_name}'.format(config_id)
                if use_named_volumes:
                    _add_volume_inspect(rsps, volume_name)
                    volume_names.append(volume_name)
                else:
                    _add_container_inspect(rsps, config_id, volume_name, self.sample_map, c_config,
                                           P_STATE_EXITED_0, base_image_id, False, attached_valid)
                    container_names.append(volume_name)
            image_name = format_image_tag(self.sample_map.get_image(c_config.image or name))
            image_id = image_dict[image_name]
            for i in instances or c_config.instances or [None]:
                config_id = MapConfigId(ItemType.CONTAINER, self.map_name, name, i)
                if config_id.instance_name:
                    container_name = '{0.map_name}.{0.config_name}.{0.instance_name}'.format(config_id)
                else:
                    container_name = '{0.map_name}.{0.config_name}'.format(config_id)
                _add_container_inspect(rsps, config_id, container_name, self.sample_map, c_config,
                                       state, image_id, use_named_volumes, instances_valid, **kwargs)
                container_names.append(container_name)
                if c_config.networks:
                    for cn in c_config.networks:
                        network_containers[cn.network_name].append(container_name)
                elif c_config.network_mode != 'disabled':
                    network_containers['bridge'].append(container_name)
                    if kwargs.get('extra_network'):
                        network_containers['extra'].append(container_name)
        for n_name, kwargs in networks:
            n_config = self.sample_map.get_existing_network(n_name)
            config_id = MapConfigId(ItemType.NETWORK, self.map_name, n_name)
            network_name = '{0.map_name}.{0.config_name}'.format(config_id)
            _add_network_inspect(rsps, network_name, n_config, network_containers.get(n_name, []), **kwargs)
            network_names.append(network_name)
        for dn_name in ('bridge', 'none', 'host'):
            _add_network_inspect(rsps, dn_name, None, network_containers.get(dn_name, []))
            network_names.append(dn_name)
        _add_container_list(rsps, container_names)
        _add_network_list(rsps, network_names)
        _add_volume_list(rsps, volume_names)

    def _setup_default_containers(self, rsps):
        self._setup_containers(rsps, [
            _container('sub_sub_svc'),
            _container('sub_svc'),
            _container('redis'),
            _container('svc'),
            _container('server'),
        ])

    def test_dependency_states_running(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            states = list(DependencyStateGenerator(self.policy, {}).get_states(self.server_config_id))
            instance_base_states = [s.base_state
                                    for s in states
                                    if s.config_id.config_type == ItemType.CONTAINER]
            attached_base_states = [s.base_state
                                    for s in states
                                    if s.config_id.config_type == ItemType.VOLUME]
            self.assertTrue(all(si == State.RUNNING
                                for si in instance_base_states))
            self.assertTrue(all(si == State.PRESENT
                                for si in attached_base_states))
            self.assertTrue(all(s.config_flags == ConfigFlags.DEPENDENT
                                for s in states
                                if s.config_id.config_type == ItemType.CONTAINER and s.config_id.config_name != 'server'))

    def test_single_states_mixed(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('redis', P_STATE_EXITED_0, instances=['cache']),
                _container('redis', instances=['queue']),
                _container('svc', P_STATE_EXITED_127),
                _container('worker', P_STATE_RESTARTING),
                _container('worker_q2', P_STATE_INITIAL),
            ])
            sg = SingleStateGenerator(self.policy, {})
            cache_state = _get_single_state(sg, self._config_id('redis', 'cache'))
            self.assertEqual(cache_state.base_state, State.PRESENT)
            queue_state = _get_single_state(sg, self._config_id('redis', 'queue'))
            self.assertEqual(queue_state.base_state, State.RUNNING)
            svc_state = _get_single_state(sg, self._config_id('svc'))
            self.assertEqual(svc_state.base_state, State.PRESENT)
            self.assertEqual(svc_state.state_flags & StateFlags.NONRECOVERABLE, StateFlags.NONRECOVERABLE)
            worker_state = _get_single_state(sg, self._config_id('worker'))
            self.assertEqual(worker_state.state_flags & StateFlags.RESTARTING, StateFlags.RESTARTING)
            worker2_state = _get_single_state(sg, self._config_id('worker_q2'))
            self.assertEqual(worker2_state.base_state, State.PRESENT)
            self.assertEqual(worker2_state.state_flags & StateFlags.INITIAL, StateFlags.INITIAL)
            server_states = _get_single_state(sg, self.server_config_id)
            self.assertEqual(server_states.base_state, State.ABSENT)

    def test_single_states_forced_config(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('redis', instances=['cache', 'queue']),
            ])
            force_update = set(get_map_config_ids('redis', {self.map_name: self.sample_map}, self.map_name))
            sg = SingleStateGenerator(self.policy, {'force_update': force_update})
            cache_state = _get_single_state(sg, self._config_id('redis', 'cache'))
            self.assertEqual(cache_state.state_flags & StateFlags.FORCED_RESET, StateFlags.FORCED_RESET)
            queue_state = _get_single_state(sg, self._config_id('redis', 'queue'))
            self.assertEqual(queue_state.state_flags & StateFlags.FORCED_RESET, StateFlags.FORCED_RESET)

    def test_single_states_forced_instance(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('redis', instances=['cache', 'queue']),
            ])
            force_update = set(get_map_config_ids('redis', {self.map_name: self.sample_map}, self.map_name, 'cache'))
            sg = SingleStateGenerator(self.policy, {'force_update': force_update})
            cache_state = _get_single_state(sg, self._config_id('redis', 'cache'))
            self.assertEqual(cache_state.state_flags & StateFlags.FORCED_RESET, StateFlags.FORCED_RESET)
            queue_state = _get_single_state(sg, self._config_id('redis', 'queue'))
            self.assertEqual(queue_state.state_flags & StateFlags.NEEDS_RESET, 0)

    def test_dependent_states(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis'),
                _container('svc'),
                _container('server'),
                _container('server2'),
                _container('worker'),
                _container('worker_q2'),
            ])
            states = list(DependentStateGenerator(self.policy, {}).get_states(self._config_id('redis', 'cache')))
            instance_base_states = [s.base_state
                                    for s in states
                                    if s.config_id.config_type == ItemType.CONTAINER]
            volume_base_states = [s.base_state
                                  for s in states
                                  if s.config_id.config_type == ItemType.VOLUME]
            self.assertTrue(all(si == State.RUNNING
                                for si in instance_base_states))
            self.assertTrue(all(si == State.PRESENT
                                for si in volume_base_states))
            self.assertTrue(all(s.config_flags == ConfigFlags.DEPENDENT
                                for s in states
                                if not (s.config_id.config_type == ItemType.CONTAINER and s.config_id.config_name == 'redis')))

    def test_update_states_clean(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            states = list(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            valid_order = ['sub_sub_svc', 'sub_svc', 'redis', 'server']
            for c_state in states:
                config_id = c_state.config_id
                if config_id.config_type == ItemType.CONTAINER:
                    config_name = config_id.config_name
                    if config_name in valid_order:
                        self.assertEqual(valid_order[0], config_name)
                        valid_order.pop(0)
                        self.assertEqual(c_state.base_state, State.RUNNING)
                        self.assertEqual(c_state.state_flags, StateFlags.NONE)

    def test_update_states_invalid_attached(self):
        if SKIP_LEGACY_TESTS:
            return
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis', attached_volumes_valid=False),
                _container('svc'),
                _container('server'),
            ])
            states = _get_states_dict(UpdateStateGenerator(self.policy_legacy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.VOLUME_MISMATCH, StateFlags.VOLUME_MISMATCH)
            for ri in ('cache', 'queue'):
                redis_state = states['containers'][('redis', ri)]
                self.assertEqual(redis_state.base_state, State.RUNNING)
                self.assertEqual(redis_state.state_flags & StateFlags.VOLUME_MISMATCH, StateFlags.VOLUME_MISMATCH)

    def test_update_states_invalid_dependent_instance(self):
        if SKIP_LEGACY_TESTS:
            return
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis', instance_volumes_valid=False),
                _container('svc'),
                _container('server'),
            ], use_named_volumes=False)
            states = _get_states_dict(UpdateStateGenerator(self.policy_legacy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.NEEDS_RESET, 0)
            for ri in ('cache', 'queue'):
                redis_state = states['containers'][('redis', ri)]
                self.assertEqual(redis_state.base_state, State.RUNNING)
                self.assertEqual(redis_state.state_flags & StateFlags.VOLUME_MISMATCH, StateFlags.VOLUME_MISMATCH)

    def test_update_states_invalid_dependent_instance_attached(self):
        if SKIP_LEGACY_TESTS:
            return
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis'),
                _container('svc'),
                _container('server', attached_volumes_valid=False),
            ], use_named_volumes=False)
            states = _get_states_dict(UpdateStateGenerator(self.policy_legacy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.VOLUME_MISMATCH, StateFlags.VOLUME_MISMATCH)
            for ri in ('cache', 'queue'):
                redis_state = states['containers'][('redis', ri)]
                self.assertEqual(redis_state.base_state, State.RUNNING)
                self.assertEqual(redis_state.state_flags & StateFlags.NEEDS_RESET, 0)

    def test_update_states_invalid_image(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis'),
                _container('svc'),
                _container('server', Image='invalid'),
            ])
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.IMAGE_MISMATCH, StateFlags.IMAGE_MISMATCH)

    def test_update_states_invalid_links(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis'),
                _container('svc'),
                _container('server', links_valid=False),
            ])
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.MISSING_LINK, StateFlags.MISSING_LINK)

    def test_update_states_invalid_network_ports(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('sub_sub_svc'),
                _container('sub_svc'),
                _container('redis'),
                _container('svc'),
                _container('server', NetworkSettings=dict(Ports={})),
            ])
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.MISC_MISMATCH, StateFlags.MISC_MISMATCH)

    def test_update_states_network_clean(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('net_svc'),
                _container('server3'),
            ], [
                _network('app_net1'),
                _network('app_net2'),
            ])
            svc_id = self._config_id('server3')
            states = list(UpdateStateGenerator(self.policy, {}).get_states(svc_id))
            self.assertTrue(all(((cs.config_id.config_type in (ItemType.NETWORK, ItemType.VOLUME, ItemType.IMAGE) and
                                  cs.base_state == State.PRESENT) or
                                 (cs.config_id.config_type == ItemType.CONTAINER and
                                  cs.base_state == State.RUNNING)) and
                                cs.state_flags == 0
                                for cs in states))

    def test_update_states_updated_or_missing_network(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('net_svc', skip_network='app_net1'),
                _container('server3', skip_network='app_net1'),
            ], [
                _network('app_net2', Driver='new'),
            ])
            svc_ids = [
                MapConfigId(ItemType.CONTAINER, self.map_name, 'server3'),
                MapConfigId(ItemType.CONTAINER, self.map_name, 'net_svc')
            ]
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(svc_ids))
            self.assertEqual(states['containers'][('net_svc', None)].state_flags & StateFlags.NETWORK_DISCONNECTED, StateFlags.NETWORK_DISCONNECTED)
            self.assertEqual(states['containers'][('server3', None)].state_flags & StateFlags.NETWORK_DISCONNECTED, StateFlags.NETWORK_DISCONNECTED)
            self.assertEqual(states['networks']['app_net1'].base_state, State.ABSENT)
            self.assertEqual(states['networks']['app_net2'].state_flags & StateFlags.MISC_MISMATCH, StateFlags.MISC_MISMATCH)

    def test_update_states_network_mismatch(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('net_svc', network_link_valid=False),
                _container('server3', network_ep_valid=False),
            ], [
                _network('app_net1'),
                _network('app_net2'),
            ])
            svc_ids = [
                MapConfigId(ItemType.CONTAINER, self.map_name, 'server3'),
                MapConfigId(ItemType.CONTAINER, self.map_name, 'net_svc')
            ]
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(svc_ids))
            self.assertEqual(states['containers'][('net_svc', None)].state_flags & StateFlags.NETWORK_MISMATCH, StateFlags.NETWORK_MISMATCH)
            self.assertEqual(states['containers'][('server3', None)].state_flags & StateFlags.NETWORK_MISMATCH, StateFlags.NETWORK_MISMATCH)

    def test_update_states_left_network(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_containers(rsps, [
                _container('server3', extra_network=True),
            ], [
                _network('app_net1'),
                _network('app_net2'),
            ])
            svc_ids = [
                MapConfigId(ItemType.CONTAINER, self.map_name, 'server3'),
            ]
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(svc_ids))
            self.assertEqual(states['containers'][('server3', None)].state_flags & StateFlags.NETWORK_LEFT, StateFlags.NETWORK_LEFT)

    def test_update_states_updated_environment(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            self.sample_map.containers['server'].create_options.update(environment=dict(Test='x'))
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.MISC_MISMATCH, StateFlags.MISC_MISMATCH)

    def test_update_states_updated_command(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            self.sample_map.containers['server'].create_options.update(command='/bin/true')
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.MISC_MISMATCH, StateFlags.MISC_MISMATCH)

    def test_update_states_updated_exec(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            cmd1 = ExecCommand(2, '/bin/true', ExecPolicy.INITIAL)
            cmd2 = ExecCommand(3, '/bin/true', ExecPolicy.INITIAL)
            cmd3 = ExecCommand(4, '/bin/true', ExecPolicy.RESTART)
            self.sample_map.containers['server'].exec_commands = [cmd1]
            self._setup_default_containers(rsps)
            self.sample_map.containers['server'].exec_commands = [cmd1, cmd2, cmd3]
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
            server_state = states['containers'][('server', None)]
            self.assertEqual(server_state.base_state, State.RUNNING)
            self.assertEqual(server_state.state_flags & StateFlags.NEEDS_RESET, 0)
            self.assertEqual(server_state.state_flags & StateFlags.EXEC_COMMANDS, StateFlags.EXEC_COMMANDS)
            self.assertDictEqual(server_state.extra_data, {
                'exec_commands': [cmd3],
                'id': get_container_id('{0}.server'.format(self.map_name, 'server')),
                'pid': 1,
            })

    def test_update_memlimit(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            self.sample_map.containers['server'].host_config['mem_limit'] = '3g'
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
        server_state = states['containers'][('server', None)]
        self.assertEqual(server_state.base_state, State.RUNNING)
        self.assertEqual(server_state.state_flags & StateFlags.HOST_CONFIG_UPDATE, StateFlags.HOST_CONFIG_UPDATE)
        self.assertEqual(server_state.extra_data['update_container'], {'mem_limit': 3221225472,
                                                                       'memswap_limit': 6442450944})

    def test_reset_memlimit(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            del self.sample_map.containers['server'].create_options['mem_limit']
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
        server_state = states['containers'][('server', None)]
        self.assertEqual(server_state.base_state, State.RUNNING)
        self.assertEqual(server_state.state_flags & StateFlags.MISC_MISMATCH, StateFlags.MISC_MISMATCH)

    def test_skip_reset_memlimit(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            del self.sample_map.containers['server'].create_options['mem_limit']
            states = _get_states_dict(UpdateStateGenerator(self.policy, {'skip_limit_reset': True})
                                      .get_states(self.server_config_id))
        server_state = states['containers'][('server', None)]
        self.assertEqual(server_state.base_state, State.RUNNING)
        self.assertEqual(server_state.state_flags & StateFlags.MISC_MISMATCH, 0)

    def test_update_restart_policy(self):
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            self._setup_default_containers(rsps)
            self.sample_map.containers['server'].host_config['restart_policy']['Name'] = 'on-failure'
            states = _get_states_dict(UpdateStateGenerator(self.policy, {}).get_states(self.server_config_id))
        server_state = states['containers'][('server', None)]
        self.assertEqual(server_state.base_state, State.RUNNING)
        self.assertEqual(server_state.state_flags & StateFlags.HOST_CONFIG_UPDATE, StateFlags.HOST_CONFIG_UPDATE)
        self.assertEqual(server_state.extra_data['update_container'],
                         {'restart_policy': {'Name': 'on-failure', 'MaximumRetryCount': 3}})

class TestPolicyStateUtils(unittest.TestCase):
    def setUp(self):
        self.map_name = map_name = 'main'
        self.sample_map = sample_map = ContainerMap('main', MAP_DATA_2,
                                                    use_attached_parent_name=True).get_extended_map()
        self.sample_client_config = client_config = ClientConfiguration(**CLIENT_DATA_1)
        self.policy = policy = BasePolicy({map_name: sample_map}, {'__default__': client_config})
        self.state_gen = DependencyStateGenerator(policy, {})
        self.server_dependencies = [
            (ItemType.IMAGE, map_name, 'registry.example.com/sub_sub_svc', 'latest'),
            (ItemType.CONTAINER, map_name, 'sub_sub_svc', None),
            (ItemType.IMAGE, map_name, 'registry.example.com/sub_svc', 'latest'),
            (ItemType.CONTAINER, map_name, 'sub_svc', None),
            (ItemType.VOLUME, map_name, 'redis', 'redis_socket'),
            (ItemType.VOLUME, map_name, 'redis', 'redis_log'),
            (ItemType.IMAGE, map_name, 'registry.example.com/redis', 'latest'),
            (ItemType.IMAGE, map_name, 'registry.example.com/svc', 'latest'),
            (ItemType.CONTAINER, map_name, 'redis', 'queue'),
            (ItemType.CONTAINER, map_name, 'redis', 'cache'),
            (ItemType.CONTAINER, map_name, 'svc', None),
            (ItemType.VOLUME, map_name, 'server', 'app_log'),
            (ItemType.VOLUME, map_name, 'server', 'server_log'),
            (ItemType.IMAGE, map_name, 'registry.example.com/server', 'latest'),
        ]
        self.redis_dependencies = [
            (ItemType.IMAGE, map_name, 'registry.example.com/sub_sub_svc', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'sub_sub_svc', None),
            (ItemType.IMAGE, map_name, 'registry.example.com/sub_svc', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'sub_svc', None),
            (ItemType.VOLUME, map_name, 'redis', 'redis_socket'),
            (ItemType.VOLUME, map_name, 'redis', 'redis_log'),
            (ItemType.IMAGE, map_name, 'registry.example.com/redis', 'latest'),
        ]

    def test_merge_single(self):
        redis_config = self._config_id('redis', 'queue')
        merged_paths = merge_dependency_paths([
            (redis_config, self.state_gen.get_dependency_path(redis_config))
        ])
        six.assertCountEqual(self, [
            (redis_config, self.redis_dependencies)
        ], merged_paths)

    def test_merge_empty(self):
        svc_config = self._config_id('sub_sub_svc')
        merged_paths = merge_dependency_paths([
            (svc_config, [])
        ])
        six.assertCountEqual(self, [(svc_config, [])], merged_paths)

    def _config_id(self, config_name, instance=None):
        return MapConfigId(ItemType.CONTAINER, self.map_name, config_name, instance)

    def test_merge_two_common(self):
        server_config = self._config_id('server')
        worker_config = self._config_id('worker')
        merged_paths = merge_dependency_paths([
            (c, self.state_gen.get_dependency_path(c))
            for c in [server_config, worker_config]
        ])
        self.assertEqual(len(merged_paths), 2)
        self.assertEqual(merged_paths[0][0], server_config)
        self.assertListEqual(self.server_dependencies, merged_paths[0][1])
        self.assertEqual(merged_paths[1][0], worker_config)
        self.assertListEqual([
            (ItemType.VOLUME, self.map_name, 'worker', 'app_log'),
        ], merged_paths[1][1])

    def test_merge_three_common(self):
        server_config = self._config_id('server')
        worker_config = self._config_id('worker')
        worker_q2_config = self._config_id('worker_q2')
        merged_paths = merge_dependency_paths([
            (c, self.state_gen.get_dependency_path(c))
            for c in [server_config, worker_config, worker_q2_config]
        ])
        self.assertEqual(len(merged_paths), 3)
        self.assertEqual(merged_paths[0][0], server_config)
        self.assertEqual(merged_paths[1][0], worker_config)
        self.assertEqual(merged_paths[2][0], worker_q2_config)
        self.assertListEqual(self.server_dependencies, merged_paths[0][1])
        self.assertListEqual([
            (ItemType.VOLUME, self.map_name, 'worker', 'app_log'),
        ], merged_paths[1][1])
        self.assertListEqual([
            (ItemType.VOLUME, self.map_name, 'worker_q2', 'app_log'),
        ], merged_paths[2][1])

    def test_merge_three_common_with_extension(self):
        worker_config = self._config_id('worker')
        server2_config = self._config_id('server2')
        worker_q2_config = self._config_id('worker_q2')
        merged_paths = merge_dependency_paths([
            (c, self.state_gen.get_dependency_path(c))
            for c in [worker_config, server2_config, worker_q2_config]
        ])
        self.assertEqual(len(merged_paths), 3)
        self.assertEqual(merged_paths[0][0], worker_config)
        self.assertEqual(merged_paths[1][0], server2_config)
        self.assertEqual(merged_paths[2][0], worker_q2_config)
        self.assertListEqual([
            (ItemType.IMAGE, self.map_name, 'registry.example.com/sub_sub_svc', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'sub_sub_svc', None),
            (ItemType.IMAGE, self.map_name, 'registry.example.com/sub_svc', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'sub_svc', None),
            (ItemType.VOLUME, self.map_name, 'redis', 'redis_socket'),
            (ItemType.VOLUME, self.map_name, 'redis', 'redis_log'),
            (ItemType.IMAGE, self.map_name, 'registry.example.com/redis', 'latest'),
            (ItemType.IMAGE, self.map_name, 'registry.example.com/svc', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'redis', 'queue'),
            (ItemType.CONTAINER, self.map_name, 'redis', 'cache'),
            (ItemType.CONTAINER, self.map_name, 'svc', None),
            (ItemType.VOLUME, self.map_name, 'worker', 'app_log'),
            (ItemType.IMAGE, self.map_name, 'registry.example.com/server', 'latest'),
        ], merged_paths[0][1])
        self.assertListEqual([
            (ItemType.IMAGE, self.map_name, 'registry.example.com/svc2', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'svc2', None),
            (ItemType.VOLUME, self.map_name, 'server2', 'app_log'),
            (ItemType.VOLUME, self.map_name, 'server2', 'server_log'),
        ], merged_paths[1][1])
        self.assertListEqual([
            (ItemType.VOLUME, self.map_name, 'worker_q2', 'app_log'),
        ], merged_paths[2][1])

    def test_merge_included_first(self):
        redis_config = self._config_id('redis', 'cache')
        server_config = self._config_id('server')
        merged_paths = merge_dependency_paths([
            (c, self.state_gen.get_dependency_path(c))
            for c in [redis_config, server_config]
        ])
        self.assertEqual(len(merged_paths), 1)
        self.assertEqual(merged_paths[0][0], server_config)
        self.assertListEqual(self.server_dependencies, merged_paths[0][1])

    def test_merge_included_second(self):
        server_config = self._config_id('server')
        redis_config = self._config_id('redis', 'cache')
        merged_paths = merge_dependency_paths([
            (c, self.state_gen.get_dependency_path(c))
            for c in [server_config, redis_config]
        ])
        self.assertEqual(len(merged_paths), 1)
        self.assertEqual(merged_paths[0][0], server_config)
        self.assertListEqual(self.server_dependencies, merged_paths[0][1])

    def test_merge_included_multiple(self):
        sub_svc_config = self._config_id('sub_svc')
        sub_sub_svc_config = self._config_id('sub_sub_svc')
        svc_config = self._config_id('svc')
        server_config = self._config_id('server')
        redis_config = self._config_id('redis', 'queue')
        server2_config = self._config_id('server2')
        merged_paths = merge_dependency_paths([
            (c, self.state_gen.get_dependency_path(c))
            for c in [sub_sub_svc_config, sub_svc_config, svc_config, server_config, redis_config, server2_config]
        ])
        self.assertEqual(len(merged_paths), 2)
        self.assertEqual(merged_paths[0][0], server_config)
        self.assertEqual(merged_paths[1][0], server2_config)
        self.assertListEqual(self.server_dependencies, merged_paths[0][1])
        self.assertListEqual([
            (ItemType.IMAGE, self.map_name, 'registry.example.com/svc2', 'latest'),
            (ItemType.CONTAINER, self.map_name, 'svc2', None),
            (ItemType.VOLUME, self.map_name, 'server2', 'app_log'),
            (ItemType.VOLUME, self.map_name, 'server2', 'server_log'),
        ], merged_paths[1][1])


text:
package com.zimbra.cs.taglib.bean;

import com.zimbra.client.*;
import com.zimbra.client.ZSearchResult.ZConversationSummary;

import java.util.ArrayList;
import java.util.List;

public class ZSearchResultBean {

    private ZSearchResult mResult;
    private ArrayList<ZSearchHitBean> mHits;
    private int mLimit;
    private int mOffset;
    private int mPrevOffset;
    private int mNextOffset;

    public ZSearchResultBean(ZSearchResult result, ZSearchParams params) {
        mResult = result;
        mLimit = params.getLimit();
        mOffset = params.getOffset();
        mPrevOffset = mLimit > mOffset ? 0 : mOffset - mLimit;
        mNextOffset = mOffset + mLimit;
    }

    public int getSize() { return mResult.getHits().size(); }

    public ZConversationSummary getConversationSummary() { return mResult.getConversationSummary(); }

    public synchronized ZMessageBean getFetchedMessage() {
        for (ZSearchHitBean hit : getHits()) {
            if (hit.getIsMessage()) {
                ZMessageBean msg = hit.getMessageHit().getMessage();
                if (msg != null) return msg;
            }
        }
        return null;
    }

    /**
     *
     * @return index of first message in result that matched, or -1.
     *
     */
    public synchronized int getFetchedMessageIndex() {
        int i = 0;
        for (ZSearchHitBean hit : getHits()) {
            if (hit.getIsMessage()) {
                ZMessageBean msg = hit.getMessageHit().getMessage();
                if (msg != null) return i;
            }
            i++;
        }
        return -1;
    }

    /**
     * @return ZSearchHit objects from search
     */
    public synchronized List<ZSearchHitBean> getHits() {
        if (mHits == null) {
            mHits = new ArrayList<ZSearchHitBean>();
            for (ZSearchHit hit : mResult.getHits()) {
                if (hit instanceof ZConversationHit) {
                    mHits.add(new ZConversationHitBean((ZConversationHit)hit));
                } else if (hit instanceof ZMessageHit) {
                    mHits.add(new ZMessageHitBean((ZMessageHit)hit));
                } else if (hit instanceof ZContactHit) {
                    mHits.add(new ZContactHitBean((ZContactHit)hit));
                } else if (hit instanceof ZVoiceMailItemHit) {
                    mHits.add(new ZVoiceMailItemHitBean((ZVoiceMailItemHit)hit));
                } else if (hit instanceof ZCallHit) {
                    mHits.add(new ZCallHitBean((ZCallHit)hit));
                } else if (hit instanceof ZTaskHit) {
                    mHits.add(new ZTaskHitBean((ZTaskHit)hit));
                } else if (hit instanceof ZDocumentHit) {
                    mHits.add(new ZDocumentHitBean((ZDocumentHit)hit));
                } else if (hit instanceof ZAppointmentHit) {
                    mHits.add(new ZAppointmentHitBean((ZAppointmentHit)hit));
                }else if (hit instanceof ZWikiHit) {
                    mHits.add(new ZWikiHitBean((ZWikiHit)hit));
                }
            }
        }
        return mHits;
    }

    /**
     * @return true if there are more search results on the server
     */
    public boolean getHasMore() { return mResult.hasMore(); }

    public boolean getHasNextPage() { return mResult.hasMore(); }
    public boolean getHasPrevPage() { return mOffset > 0; }

    /**
     * @return the sort by value
     */
    public String getSortBy() { return mResult.getSortBy(); }

    /**
     * @return offset used for the search.
     */
    public int getOffset() { return mOffset; }

    public int getPrevOffset() { return mPrevOffset; }

    public int getNextOffset() { return mNextOffset; }

    /** @return limit used with search */
    public int getLimit() { return mLimit; }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Creating cache services instead of providers
---

The *Provider Model* is common in .NET Framework as we might know some like RoleProvider, ProfileProvider,
MembershipProvider and so on. I want have something similar for *cache*, my application can switch
to a different cache system just by changing some configuration element. So Provider Model seems a good approach to follow.

Reading more on some articles from active guys [Provider is not a pattern][1], [PROVIDER MODEL IS A SOLID PATTERN][2],
[The Provider Model Pattern, Really][3]... I have my own choosen

## 1. A simple Cache Service interface

        T Get<T>(string key) where T : class;

        bool Set<T>(string key, T value) where T : class;
        bool Set<T>(string key, T value, TimeSpan expiry) where T : class;

        bool Remove(string key);

## 2. An InMemoryCache implementation

This implementor uses the system MemoryCache, it is an Adapter to MemoryCache

## 3. A RedisCache implementation

This service uses [Redis Client][5] to perform connection to Redis server and the serialization methods
from [SerializationMaster][4] to serialize/deserialize string to object of any type.

![_config.yml]({{ site.baseurl }}/images/posts/redis/redis-cache.jpg)

[1]: http://blog.ploeh.dk/2011/04/27/Providerisnotapattern/
[2]: http://candordeveloper.com/2012/06/26/provider-model-is-a-solid-pattern/
[3]: http://www.codethinked.com/the-provider-model-pattern-really
[4]: https://www.nuget.org/packages/Rabbit.SerializationMaster
[5]: https://www.nuget.org/packages/StackExchange.Redis


text:
import idl_parser
from type_model import ComplexType, ComplexTypeLocate
from type_classgen import TypeClassGenerator, TypeImplGenerator
from type_parser import TypeParserGenerator

class TypeGenerator(object):
    """ Type generator
        Step 1. Build a list of data structures to be generated.
        Step 2. Generate C++ classes.
        Step 3. Generate C++ decoder
        Step 4. Generate xsd corresponding to data structures.
    """
    def __init__(self, parser):
        self._Parser = parser
        self._idl_parser = None
        self._cTypesDict = {}

    def _BuildDataModel(self, children):
        for child in children:
            xtypename = child.getType()
            self._complexType = ComplexTypeLocate(self._Parser.ElementDict, self._cTypesDict, xtypename)

    def _GenerateClassDefinitions(self):
        hfilename = self._Parser.outFilename + '_types.h'
        hfile = self._Parser.makeFile(hfilename)
        classgen = TypeClassGenerator(self._cTypesDict)
        classgen.Generate(hfile, self._complexType)

    def _GenerateClassImpl(self):
        hfilename = self._Parser.outFilename + '_types.h'
        cfilename = self._Parser.outFilename + '_types.cc'
        cfile = self._Parser.makeFile(cfilename)
        classimpl = TypeImplGenerator(self._cTypesDict)
        classimpl.Generate(hfilename, cfile)

    def _GenerateParsers(self):
        hfilename = self._Parser.outFilename + '_types.h'
        cfilename = self._Parser.outFilename + '_parser.cc'
        cfile = self._Parser.makeFile(cfilename)
        parsergen = TypeParserGenerator(self._cTypesDict)
        parsergen.Generate(cfile, hfilename)

    def setLanguage(self, lang):
        pass

    def generate(self, root, infile, outFilename):
        children = root.getChildren()
        self._BuildDataModel(children)
        self._GenerateClassDefinitions()
        self._GenerateClassImpl()
        self._GenerateParsers()


text:
let fs = new Map()

export function setFs(newFs?: Map) {
  fs = newFs
}

export function readFileSync(file: string, options: ?string | ?Object): ?string | ?Buffer {
  if (fs instanceof Map) {
    const data = fs.get(file)
    if (data) {
      const buffer = new Buffer(data, 'base64')

      if (options) {
        let encoding

        switch (typeof options) {
          case 'string':
            encoding = options
            break
          case 'object':
            encoding = options.encoding
            break
          default:
        }

        if (encoding) {
          return buffer.toString(encoding)
        }
      }

      return buffer
    }
  }
}

export default {
  setFs,
  readFileSync
}


text:
layout: default
title : NFS
header : Using OSiRIS NFS
group: documentation
subnavgroup: documentation
---
{% include JB/setup %}

OSiRIS can provide access to your CephFS space via our NFS servers if you are on campus at MSU, UM, or WSU.  Please email osiris-help@umich.edu if interested in using OSiRIS via NFS so we can setup the necessary 'user mapping' from your local user to your OSiRIS identity.  Once configured, files owned by your OSiRIS identity will show as owned by your local (non-osiris) identity when listed in the NFS mount.  Groups will still show as 'nobody' but actual group permissions will be respected as determined by your OSiRIS group memberships.  We can also map selected OSiRIS groups to local groups if there is an appropriate correlation.

HPCC at MSU

HPCC users at MSU can access OSiRIS storage already mounted on globus-01.hpcc.msu.edu at /mnt/cephfs.  After login you will need to run 'kinit' and enter your password to manually obtain Kerberos credentials.

Client Configuration

Mounting NFS requires Kerberos credentials.  Your client will require a keytab and users of the space require credentials to verify their identity.

If interested in mounting NFS on your client OSiRIS admins can obtain a keytab for your client as well as assist with configuration.  We also have to configure a 'user mapping' to map your local system user to your OSiRIS identity.  It is not strictly required but if not setup then your files will all show as owned by the NFS 'nobody' user.

For reference, the NFS servers are:

um-nfs01.osris.org

msu-nfs01.osris.org

Your client must have rpc.gssd and gssproxyd running.  These should startup automatically if /etc/krb5.keytab exists.  If you have just installed a keytab and need to start them on RHEL7 (or CentOS 7):

systemctl start rpc-gssd.service
systemctl start gssproxy.service

You should also set a default_realm in /etc/krb5.conf under libdefaults.  For example:

/etc/krb5.conf:

[libdefaults]
    default_realm = UMICH.EDU

On your client system the /etc/idmapd.conf file should have a domain that matches your institution.  At UM that domain is 'umich.edu'.  At MSU that domain is 'hpcc.msu.edu'.  For example:

/etc/idmapd.conf:

[General]

  # The default is the host's DNS domain name.
  Domain = umich.edu

A typical mount command might look like this:

mount -t nfs4 -o sec=krb5,nfsvers=4.1,noacl um-nfs01.osris.org:/cephfs /mnt/cephfs/

Or in fstab:

um-nfs01.osris.org:/cephfs /mnt/cephfs nfs sec=krb5,nfsvers=4.1,noacl,_netdev,rw 0 0


text:
var climbingRoute = prompt('Which Mountain are you planning to climb? Mt.StHellens, Mt.Hood or Mt.Rainier?');
console.log('Sweet! You are going to climbing' + climbingRoute + '! Good choice.');

// add variables that differentiate between StHellens, Hood and Rainer

//02 Who with ?
// confirm experience

var climbingPartner = prompt('Who are You climbing with?');
console.log('Great, so You are climbing with ' + climbingPartner + '.');

//03 Conditions
// add resource links... or iframes ?

//04 Research

//05 Gear

//06 Register

alert('So, ' + userName + ', I heard you like ' + userGame);

var loveHate = confirm(userName + ' do you love interweb?');
alert('Does, ' + userName + ' love interweb? ' + loveHate);


text:
@interface FLEXProperty (Compare)
- (NSComparisonResult)compare:(FLEXProperty *)other;
@end

@interface FLEXIvar (Compare)
- (NSComparisonResult)compare:(FLEXIvar *)other;
@end

@interface FLEXMethodBase (Compare)
- (NSComparisonResult)compare:(FLEXMethodBase *)other;
@end

@interface FLEXProtocol (Compare)
- (NSComparisonResult)compare:(FLEXProtocol *)other;
@end


text:
Shop
====

This folder collects files of the newest **[PrestaShop](http://www.prestashop.com/)** software for the "Jack's Dogs Family" shop.


text:
package com.dushyant.flume.sink.aws.sqs;

import org.apache.flume.Channel;
import org.apache.flume.EventDeliveryException;

/**
 * An internal message sender interface for sending messages to Amazon Simple
 * Queue Service (Amazon SQS).. The sender takes event(s) from the specified channel and sends them to SQS.
 *
 * @author dpandya
 */
public interface SQSMsgSender {
    /**
     * Takes events from the specified channel and sends them to Amazon SQS until the Channel is empty or until
     * configured batchSize is reached (whichever occurs first). The method returns the number of events successfully
     * taken from the channel and sent to the SQS by this method call.
     *

     * The concrete implementations are NOT expected to manage transaction. It is assumed that the transaction
     * management is taken care of by the calling Sink class.
     *
     * @param channel The flume channel to pick events from
     *
     * @return int - Number of events sent to SQS by this method call.
     * @throws EventDeliveryException If a message delivery to SQS fails.
     */
    public int send(Channel channel) throws EventDeliveryException;
}


text:
function toggleChat() {
	// If your window is too small to use the Chatroom in the same page.. open in new window
	if ($(window).width() < 500) {
		window.open("http://chat.seriousbears.net/");
	}
	else {
		if (document.getElementById("chat").style.display == "none" || document.getElementById("chat").style.display === "") {
			document.getElementById("homepage").style.display = "none";
			document.getElementById("chat").style.display = "block";
		}
		else {
			document.getElementById("homepage").style.display = "block";
			document.getElementById("chat").style.display = "none";
		}
	}
}
// This function will return you back to the main page
function returnHome() {
	if (document.getElementById("homepage").style.display == "none" || document.getElementById("homepage").style.display === "") {
		document.getElementById("homepage").style.display = "block";
		document.getElementById("chat").style.display = "none";
	}
}


text:
[![Build Status](https://travis-ci.org/bjorand/ansible.docker.debian.svg)](https://travis-ci.org/bjorand/ansible.docker.debian)

Ansible role to bootstrap a raw Debian Jessie into a Docker host.

## Requirements

- Debian Stretch

## Dependencies

None.

## Testing

To test the role in a Vagrant environment just run `vagrant up`.  This will
create a Debian Jessie VMs and it will provision the VM by applying this role with Ansible.

Requires `ansible-playbook` to be in your local path.

## License

MIT


text:
package com.example.customviewdemo.MyPopupwindow;

import java.util.ArrayList;

import com.example.customviewdemo.R;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
 * 实现下拉选择框的视图
 * @author ASUS-H61M
 *
 */
public class MyPopupwindowActivity extends Activity implements OnClickListener, OnItemClickListener{
	private EditText et_input;
	private ImageView ib_dropdown;
	private ListView listView;
	private ArrayList<String> data;
	private PopupWindow popupWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_mypopupwindow);

		et_input = (EditText) findViewById(R.id.et_input);
		ib_dropdown = (ImageView) findViewById(R.id.ib_dropdown);
		ib_dropdown.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.ib_dropdown){
			showPopupWindow();
		}
	}

	private void showPopupWindow() {

		initListView();
		// 显示下拉选择框
		popupWindow = new PopupWindow(listView, et_input.getWidth(), 300);
		// 设置点击外部区域, 自动隐藏
		popupWindow.setOutsideTouchable(true);// 外部可触摸
		popupWindow.setBackgroundDrawable(new BitmapDrawable());// 设置空的背景, 响应点击事件
		popupWindow.setFocusable(true); //设置可获取焦点
		popupWindow.showAsDropDown(et_input, 0, 0);
	}
	// 初始化要显示的内容
	private void initListView() {
		listView = new ListView(getApplicationContext());
		listView.setDividerHeight(0);  // 设置分割线边距
		listView.setBackgroundResource(R.drawable.listview_background);

		listView.setOnItemClickListener(this);

		data = new ArrayList<String>();
		for (int i = 0; i < 30; i ++){
			// 添加数据
			String str = "1000" + i;
			data.add(str);
		}

		listView.setAdapter(new MyAdapter());
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// listview条目点击事件
		String string = data.get(position);
		et_input.setText(string);
		popupWindow.dismiss();
	}

	private class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View view;
			ViewHolder viewHolder;
			if (convertView == null) {
				view = View.inflate(getApplicationContext(), R.layout.item_number, null);
				viewHolder = new ViewHolder();
				viewHolder.iv_number = (ImageView) view.findViewById(R.id.iv_number);
				viewHolder.tv_number = (TextView) view.findViewById(R.id.tv_number);
				viewHolder.ib_delete = (ImageView) view.findViewById(R.id.ib_delete);
				view.setTag(viewHolder);
			} else {
				view = convertView;
				viewHolder = (ViewHolder) view.getTag();
			}
			viewHolder.tv_number.setText(data.get(position));

			viewHolder.ib_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 在条目中点击删除
					data.remove(position);
					notifyDataSetChanged();
					if (data.size() == 0) {
						// 当数据为0的时候隐藏popuwindow
						popupWindow.dismiss();
					}
				}
			});

			return view;
		}

		class ViewHolder{
			ImageView iv_number;
			TextView tv_number;
			ImageView ib_delete;
		}

	}

}


text:
using System;
using VkNet.Utils;

namespace VkNet.Model.RequestParams
{
	/// <summary>
	/// Список параметров для метода photos.edit
	/// </summary>
	[Serializable]
	public class PhotoEditParams
	{
		/// <summary>
		/// Идентификатор пользователя или сообщества, которому принадлежит фотография.
		/// </summary>
		public long OwnerId { get; set; }

		/// <summary>
		/// Идентификатор фотографии.
		/// </summary>
		public ulong PhotoId { get; set; }

		/// <summary>
		/// Новый текст описания к фотографии. Если параметр не задан, то считается, что он
		/// равен пустой строке.
		/// </summary>
		public string Caption { get; set; }

		/// <summary>
		/// Широта.
		/// </summary>
		public decimal? Latitude { get; set; }

		/// <summary>
		/// Долгота.
		/// </summary>
		public decimal? Longitude { get; set; }

		/// <summary>
		/// Место.
		/// </summary>
		public string PlaceStr { get; set; }

		/// <summary>
		/// Идентификатор квадрата.
		/// </summary>
		public string FoursquareId { get; set; }

		/// <summary>
		/// Место удалено.
		/// </summary>
		public bool? DeletePlace { get; set; }

		/// <summary>
		/// Идентификатор капчи
		/// </summary>
		public string CaptchaSid { get; set; }

		/// <summary>
		/// текст, который ввел пользователь
		/// </summary>
		public string CaptchaKey { get; set; }

		/// <summary>
		/// Привести к типу VkParameters.
		/// </summary>
		/// <param name="p"> Параметры. </param>
		/// <returns> </returns>
		public static VkParameters ToVkParameters(PhotoEditParams p)
		{
			var parameters = new VkParameters
			{
					{ "owner_id", p.OwnerId }
					, { "photo_id", p.PhotoId }
					, { "caption", p.Caption }
					, { "latitude", p.Latitude }
					, { "longitude", p.Longitude }
					, { "place_str", p.PlaceStr }
					, { "foursquare_id", p.FoursquareId }
					, { "delete_place", p.DeletePlace }
					, { "captcha_sid", p.CaptchaSid }
					, { "captcha_key", p.CaptchaKey }
			};

			return parameters;
		}
	}
}


text:
class FdoFilterException : public FdoException
{
/// \cond DOXYGEN-IGNORE
protected:
    /// Constructs a default instance of an FdoFilterException.
    FdoFilterException();

    /// Constructs an instance of an FdoFilterException using the specified
    /// arguments.
    FdoFilterException(FdoString* message);

    /// Constructs an instance of an FdoFilterException using the specified
    /// arguments.
    FdoFilterException(FdoString* message, FdoException* cause);

    virtual ~FdoFilterException();

    virtual void Dispose();
/// \endcond

public:
    /// \brief
    /// Constructs a default instance of an FdoFilterException.
    ///
    /// \return
    /// Returns FdoFilterException
    ///
    FDO_API static FdoFilterException* Create();

    /// \brief
    /// Constructs an instance of an FdoFilterException using the specified arguments.
    ///
    /// \param message
    /// Input message text
    ///
    /// \return
    /// Returns FdoFilterException
    ///
    FDO_API static FdoFilterException* Create(FdoString* message);

    /// \brief
    /// Constructs an instance of an FdoFilterException using the specified arguments.
    ///
    /// \param message
    /// Input message text
    /// \param cause
    /// Input cause of exception
    ///
    /// \return
    /// Returns FdoFilterException
    ///
    FDO_API static FdoFilterException* Create(FdoString* message, FdoException* cause);
};
#endif


text:
var eio = require( 'engine.io-client' ),
    readline = require('readline'),
    url = 'ws://localhost:' + ( process.argv[ 2 ] || 6020 ),
    connection = eio( url ),
    rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

console.log( 'Connecting to ' + url + ' ...' );

var send = function( msg ) {
    console.log( 'OUTGOING', msg );
    connection.send( msg.replace( /\|/g, String.fromCharCode( 31 ) ) );
};

connection.on( 'open', function( socket ){
	console.log( 'connection opened' );
	send( 'AUTH|REQ|{"user":"wolfram"}' );
});

connection.on( 'message', function( msg ){
    var regExp = new RegExp( String.fromCharCode(31), 'g');
    if( msg ) {
        msg = msg.replace( regExp, '|' );
    }

    console.log( 'INCOMING', msg );
});

connection.on( 'error', function( err ){
	console.log( 'ERROR', err );
});

connection.on( 'connect_error', function( err ){
	console.log( 'CONNECT_ERROR', err );
});

connection.on( 'close', function(){
	console.log( 'CLOSE' );
});

rl.on( 'line', function ( cmd ) {
    if( cmd.toUpperCase() === 'OPEN' ) {
        connection.open();
        return;
    }

    send( cmd );

});


text:
package fr.univ.nantes.roomanager.bean

import scala.beans.BeanProperty

/**
 * @author Pierre Gaultier
 * @author Alexis Giraudet
 */
class AdresseBean(@BeanProperty var adresse: String,
                  @BeanProperty var code: String,
                  @BeanProperty var ville: String) extends BaseBean {}


text:
/*
 * SamplingFiltering.java
 *
 *
 * @author Deepayan Bhowmik
 */

package DSPnMath;

import DSPnMath.Convolution;

public class SamplingFiltering {
    public void SamplingFiltering() {
     /* This class and function organisaes all the filtering and up / down sampling parameters.
        This particular function is just to check all the values. No operation so far ... Deepayan says so :-)
      */

    }

    public double[] Lshift(double[] image){
        double[] imshift = new double[image.length];
        for(int i=1; i<image.length; i++){
            imshift[i-1] = image[i];
        }
        imshift[image.length-1] = image[0];
        return imshift;
    }

     public double[] Rshift(double[] image){
        double[] imshift = new double[image.length];
        for(int i=1; i<image.length; i++){
            imshift[i] = image[i-1];
        }
        imshift[0] = image[image.length-1];
        return imshift;
    }

    public double[] Highpass(double[] filter_coeff, double[] image){
        double[] pixel_coeff = Downsample(ConvHL(filter_coeff,Lshift(image)));
        return pixel_coeff;
    }

     public double[] Lowpass(double[] filter_coeff, double[] image){
        double[] pixel_coeff = Downsample(ConvLH(filter_coeff,image));
        return pixel_coeff;
    }

    public double[] InvHighpass(double[] filter_coeff, double[] image){
        double[] pixel = ConvLH(filter_coeff, Rshift(Upsample(image)));
        return pixel;
    }

    public double[] InvLowpass(double[] filter_coeff, double[] image){
        double[] pixel = ConvHL(filter_coeff,Upsample(image));
        return pixel;
    }

    public double[] ConvLH(double[] filter_coeff, double[] image){
        double[] padded_image = new double[image.length+filter_coeff.length];
        for(int i=0; i<image.length; i++){
            padded_image[i] = image[i];
        }

        for(int j=image.length; j<(image.length+filter_coeff.length); j++){
            padded_image[j] = image[j-image.length];
        }

        Convolution func = new Convolution();
        double[] padout_coeff = func.Convolution(filter_coeff,padded_image);

        double[] pixel_coeff_dw = new double[image.length];
        for(int i=0;i<image.length;i++){
            pixel_coeff_dw[i] = padout_coeff[filter_coeff.length-1+i];
        }
        return pixel_coeff_dw;
    }

    public double[] ConvHL(double[] filter_coeff, double[] image){
        double[] padded_image = new double[image.length+filter_coeff.length];
        for(int i=0; i<(filter_coeff.length);i++){
            padded_image[i] = image[(image.length-filter_coeff.length) + i];
        }

        for(int j=(filter_coeff.length); j<(image.length+filter_coeff.length);j++){
            padded_image[j] = image[j-(filter_coeff.length)];
        }

        Convolution func = new Convolution();
        double[] padout_coeff = func.Convolution(filter_coeff,padded_image);

        double[] pixel_coeff_dw = new double[image.length];
        for(int i=0;i<image.length;i++){
            pixel_coeff_dw[i] = padout_coeff[filter_coeff.length+i];
        }
        return pixel_coeff_dw;
    }

    public double[] Downsample(double[] image_coeff){
        double[] image_ds = new double[image_coeff.length/2];
        for(int i=0; i<image_coeff.length/2; i++){
            image_ds[i] = image_coeff[i*2];
        }
        return image_ds;
    }

     public double[] Upsample(double[] image_coeff){
        double[] image_us = new double[image_coeff.length*2];
        for(int i=0; i<image_coeff.length*2; i++){
            if((i%2)==0){
                image_us[i] = image_coeff[i/2];
            } else{
                image_us[i] = 0;
            }
        }
        return image_us;
    }

}


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.internal.xml;

import java.util.List;
import java.util.Map;

import static org.hibernate.validator.internal.util.CollectionHelper.newHashMap;

/**
 * Builder for group conversions.
 *
 * @author Hardy Ferentschik
 */
class GroupConversionBuilder {

	private final ClassLoadingHelper classLoadingHelper;

	GroupConversionBuilder(ClassLoadingHelper classLoadingHelper) {
		this.classLoadingHelper = classLoadingHelper;
	}

	Map<Class<?>, Class<?>> buildGroupConversionMap(List<GroupConversionType> groupConversionTypes,
																  String defaultPackage) {
		Map<Class<?>, Class<?>> groupConversionMap = newHashMap();
		for ( GroupConversionType groupConversionType : groupConversionTypes ) {
			Class<?> fromClass = classLoadingHelper.loadClass( groupConversionType.getFrom(), defaultPackage );
			Class<?> toClass = classLoadingHelper.loadClass( groupConversionType.getTo(), defaultPackage );
			groupConversionMap.put( fromClass, toClass );
		}

		return groupConversionMap;
	}
}


text:
{% extends "base.html" %}
{% load static from staticfiles %}
{% block add_css %}
    <link rel="stylesheet" href="{% static "chosen-bootstrap/chosen.bootstrap.min.css" %}">
{% endblock %}
{% block add_styles %}
.chosen-container {
    width: 70% !important;
}
{% endblock %}
{% block content %}

 {{ name }} {{ template }}

    <form class="form-horizontal" method="post">{% csrf_token %}
        {% include "dojo/form_fields.html" with form=form %}

                <input class="btn btn-primary" type="submit" name="add_template" value="Save Template"/>

    </form>
    {% if template %}
        <form class="form-horizontal" method="post" action="{% url 'delete_template' template.id %}">{% csrf_token %}

                    <input class="btn btn-danger" type="submit" name="delete_template" value="Delete Template"/>

                    <input type="hidden" name="id" value="{{ template.id }}"/>

        </form>
    {% endif %}
{% endblock %}
{% block postscript %}

{% endblock %}


text:
layout: post
title: Errata in Essential Astrophysics
---

I've adopted Kenneth Lang's [_Essential Astrophysics_](http://link.springer.com/book/10.1007%2F978-3-642-35963-7) for my ASTRO 320 class at U. Alberta this year.  It has the wonderful feature of being relatively low cost owing to the University Library subscribing to the Springer eBooks.  Thanks, Library.  Unfortunately, the book is a First Edition.  As such there are typos.  Here is a list of the ones we've found so far.

#### Section 2.4, Page 45
The Planck function (Eq. 2.17) is given as

$$
B_\nu(\nu,T) = \frac{2h\nu^3}{c^2}\frac{1}{\exp\left[h\nu/(kT)-1\right]}
$$

where it should be

$$
B_\nu(\nu,T) = \frac{2h\nu^3}{c^2}\frac{1}{\exp [h\nu/(kT)]-1}.
$$

#### Section 2.4, Page 45
The value of $$\pi$$ is given as 3.13159 and should be 3.14159.

#### Section 2.4, Page 46

The Planck function (Eq. 2.18) is given as

$$
B_\lambda(\lambda,T) = \frac{2h c^2 }{\lambda^5}\frac{1}{\exp\left[hc/(\lambda kT)-1\right]}
$$

where it should be

$$
B_\lambda(\lambda,T) = \frac{2hc^2}{\lambda^5}\frac{1}{\exp [hc/(\lambda kT)]-1}.
$$

#### Section 2.4, Page 48
The radiation energy (Eq. 2.23) density

$$
u_\nu(T) = \frac{8\pi \nu^2}{c^3}\frac{1}{\exp\left[\left(\frac{h\nu}{kT}\right)-1\right]}
$$

should read

$$
u_\nu(\nu, T) = \frac{8\pi\nu^2}{c^3}\frac{1} {\exp\left(\frac{h\nu}{kT}\right)-1}
$$

#### Section 2.4, Page 49
Above Equation 2.29, the text says "energy flowing out of the blackbody over $$\pi$$ sr, or over the hemisphere facing an observer."

A hemisphere is $$2\pi$$ sr, but the equation is correct.  The "missing" factor of $$1/2$$ comes from the shrinking projected size of the differential area at larger angles.

#### Section 2.4, Page 50
The Stefan-Boltzmann Constant is given as $$5.6704\times 10^{-8}\mathrm{~W~m^{-2}~K^{4}}$$ and it should be $$5.6704\times 10^{-8}\mathrm{~W~m^{-2}~K^{-4}}$$.  (Thank you Tanner S.)

#### Focus 2.5, Page 59
Dr. Hans Seuss died in 1993 not 1920, which makes his story a lot less about tragic death at an early age.  (Thanks to Paul).

#### Section 5.4.1, Page 141
The book gives the solar wind pressure as a "startling $$10^{18}$$ Pa," which would be truly startling and would also deliver enough energy to destroy the planet in a year.  The actual numbers that NOAA bandies about are closer to $$2\times 10^{-9}$$ Pa.

#### Section 6.3, Page 174
Boltzmann was born in 1844 not 1894, which Michelle S. noted the date in the text would be hard to reconcile with Boltzmann deriving his eponymous distribution in 1872.

#### Section 8.3.3, Page 232
An MeV is $$1.602\times 10^{-13}\mbox{ J}$$ not 1.692 as given at the bottom of the page.

#### Section 10.1.2, Page 296
The magnitude system is defined so that an interval of five magnitudes correspond to exactly a factor of 100 in brightness.  Thus, Equation 10.4 should read

$$
m_1 - m_2 = -2.5 \log_{10}\left(\frac{f_1}{f_2}\right) = 2.5 \log_{10}\left(\frac{f_2}{f_1}\right)
$$

#### Section 10.5.6, Page 354
The first generation of stars is broadly described as _Population III_ and theoretically had $$Z=0$$.  The second, slightly enriched generation was called _Population II_, which are relatively metal-poor compared to most stars ($$Z\sim 10^{-3}$$).  Finally, most stars seen today have roughly solar metallicity ($$Z\sim 0.02$$) and are called _Population I_.


text:
<?php
declare(strict_types=1);

namespace StingerSoft\EntitySearchBundle\Model\Result;

interface FacetSet extends \IteratorAggregate, \Countable {

	const FACET_AUTHOR = 'facet_author';

	const FACET_ENTITY_TYPE = 'facet_entity_type';

	const FACET_MIME_TYPE = 'facet_mime_type';

	const FACET_EDITOR = 'facet_editor';

	/**
	 * Get a facet by key.
	 *
	 * @param string $key
	 *            The key of the facet
	 *
	 * @return string[string][int] The amount of results with facet
	 */
	public function getFacet(string $key): ?array;

	/**
	 * Get all facets.
	 *
	 * @return string[string][int]
	 */
	public function getFacets(): array;

	public function addFacetValue(string $key, string $label, $value = null, int $increaseCounterBy = 1) : void;
}


text:
template <class C, class Iterator, class A>
void
test(Iterator first, Iterator last, const A& a)
{
    C c(first, last, a);
    assert(c.__invariants());
    assert(c.size() == std::distance(first, last));
    assert(is_contiguous_container_asan_correct(c));
    for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e; ++i, ++first)
        assert(*i == *first);
}

#if __cplusplus >= 201103L

template <class T>
struct implicit_conv_allocator : min_allocator<T>
{
    implicit_conv_allocator(void* p) {}
    implicit_conv_allocator(const implicit_conv_allocator&) = default;
};

#endif

int main()
{
    {
    int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 1, 0};
    int* an = a + sizeof(a)/sizeof(a[0]);
    std::allocator<int> alloc;
    test<std::vector<int> >(input_iterator<const int*>(a), input_iterator<const int*>(an), alloc);
    test<std::vector<int> >(forward_iterator<const int*>(a), forward_iterator<const int*>(an), alloc);
    test<std::vector<int> >(bidirectional_iterator<const int*>(a), bidirectional_iterator<const int*>(an), alloc);
    test<std::vector<int> >(random_access_iterator<const int*>(a), random_access_iterator<const int*>(an), alloc);
    test<std::vector<int> >(a, an, alloc);
    }
#if __cplusplus >= 201103L
    {
    int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 1, 0};
    int* an = a + sizeof(a)/sizeof(a[0]);
    min_allocator<int> alloc;
    test<std::vector<int, min_allocator<int>> >(input_iterator<const int*>(a), input_iterator<const int*>(an), alloc);
    test<std::vector<int, min_allocator<int>> >(forward_iterator<const int*>(a), forward_iterator<const int*>(an), alloc);
    test<std::vector<int, min_allocator<int>> >(bidirectional_iterator<const int*>(a), bidirectional_iterator<const int*>(an), alloc);
    test<std::vector<int, min_allocator<int>> >(random_access_iterator<const int*>(a), random_access_iterator<const int*>(an), alloc);
    test<std::vector<int, min_allocator<int>> >(a, an, alloc);
    test<std::vector<int, implicit_conv_allocator<int>> >(a, an, nullptr);
    }
#endif
}


text:
using OpenInvoicePeru.Entidades;

namespace OpenInvoicePeru.Datos.Configurations
{
    public class CabeceraDocumentoConfiguration : BaseConfigurationEntity<CabeceraDocumento>
    {
        public CabeceraDocumentoConfiguration()
        {
            Property(e => e.IdReceptor).HasIndex(Prefix + "IdReceptor");

            Property(e => e.IdEmisor).HasIndex(Prefix + "IdEmisor");

            Property(e => e.IdTipoDocumento).HasIndex(Prefix + "IdTipoDocumento");

            Property(e => e.IdMoneda).HasIndex(Prefix + "IdMoneda");

            Property(e => e.IdTipoOperacion).HasIndex(Prefix + "IdTipoOperacion");

            Property(e => e.IdDocumentoAnticipo).HasIndex(Prefix + "IdDocumentoAnticipo");

            Property(e => e.IdGuiaTransportista).HasIndex(Prefix + "IdGuiaTransportista");

            Property(e => e.IdAnexo).HasIndex(Prefix + "IdAnexo");

            HasRequired(e => e.Emisor)
                .WithMany()
                .HasForeignKey(e => e.IdEmisor)
                .WillCascadeOnDelete(false);

            HasRequired(e => e.Receptor)
                .WithMany()
                .HasForeignKey(e => e.IdReceptor)
                .WillCascadeOnDelete(false);

            HasRequired(e => e.TipoDocumento)
                .WithMany()
                .HasForeignKey(e => e.IdTipoDocumento)
                .WillCascadeOnDelete(false);

            HasRequired(e => e.Moneda)
                .WithMany()
                .HasForeignKey(e => e.IdMoneda)
                .WillCascadeOnDelete(false);

            HasRequired(e => e.TipoOperacion)
                .WithMany()
                .HasForeignKey(e => e.IdTipoOperacion)
                .WillCascadeOnDelete(false);

            HasOptional(p => p.GuiaTransportista)
                .WithMany()
                .HasForeignKey(p => p.IdGuiaTransportista)
                .WillCascadeOnDelete(false);

            HasOptional(e => e.DocumentoAnticipo)
                .WithMany()
                .HasForeignKey(e => e.IdDocumentoAnticipo)
                .WillCascadeOnDelete(false);

            HasOptional(e => e.Anexo)
                .WithMany()
                .HasForeignKey(e => e.IdAnexo)
                .WillCascadeOnDelete(false);

            HasMany(e => e.Detalles)
                .WithRequired(e => e.Cabecera)
                .HasForeignKey(e => e.IdCabeceraDocumento)
                .WillCascadeOnDelete(false);

            Property(e => e.TotalIsc)
                .HasPrecision(11, 2);

            Property(e => e.TotalIgv)
                .HasPrecision(11, 2);

            Property(e => e.TotalOtrosTributos)
                .HasPrecision(11, 2);

            Property(e => e.TotalVenta)
                .HasPrecision(11, 2);

            Property(e => e.Gravadas)
                .HasPrecision(11, 2);

            Property(e => e.Gratuitas)
                .HasPrecision(11, 2);

            Property(e => e.Exoneradas)
                .HasPrecision(11, 2);

            Property(e => e.Inafectas)
                .HasPrecision(11, 2);

            Property(e => e.MontoDetraccion)
                .HasPrecision(11, 2);

            Property(e => e.MontoPercepcion)
                .HasPrecision(11, 2);

            Property(e => e.DescuentoGlobal)
                .HasPrecision(11, 2);

            Property(p => p.IdDocumento)
                .HasMaxLength(13)
                .IsRequired();

            Property(p => p.MontoEnLetras)
                .HasMaxLength(250)
                .IsRequired();

            Property(p => p.PlacaVehiculo)
                .HasMaxLength(15)
                .IsOptional();

            Property(p => p.EstadoDocumento)
                .HasMaxLength(2)
                .IsOptional();
        }
    }
}


text:
(function () {
'use strict';
var module = angular.module('fim.base');
module.factory('StatisticsProvider', function (nxt, $timeout) {

  function StatisticsProvider(api, $scope) {
    this.api                    = api;
    this.$scope                 = $scope;
    this.isLoading              = true;
    this.lastBlockDate          = null;
    this.lastBlockHeight        = null;
    this.lastBlockID            = null;
    this.average                = null;
    this.transactionCountToday  = null;
    this.transactionCountWeek   = null;
    this.transactionCountMonth  = null;
    this.rewardsToday           = null;
    this.rewardsWeek            = null;
    this.rewardsMonth           = null;
  }
  StatisticsProvider.prototype = {
    load: function () {
      var self = this;
      this.$scope.$evalAsync(function () {
        self.isLoading = true;
        $timeout(function () { self.getNetworkData(); }, 1, false);
      });
    },

    getNetworkData: function () {
      var self = this;
      this.api.engine.socket().getActivityStatistics().then(
        function (data) {
          self.$scope.$evalAsync(function () {
            self.processMofoGetActivityStatistics(data);
            self.isLoading = false;
          });
        },
        function (data) {
          self.$scope.$evalAsync(function () {
            self.isLoading = false;
          });
        }
      );
    },

    processMofoGetActivityStatistics: function (data) {
      this.lastBlockDate      = nxt.util.formatTimestamp(data.lastBlock.timestamp);
      this.lastBlockHeight    = data.lastBlock.height;
      this.lastBlockID        = data.lastBlock.block;
      this.average            = data.averageBlockTime24H,
      this.transactionCountToday  = data.transactionCountToday;
      this.transactionCountWeek   = data.transactionCountWeek;
      this.transactionCountMonth  = data.transactionCountMonth;
      this.rewardsToday       = nxt.util.convertToNXT(data.rewardsToday);
      this.rewardsWeek        = nxt.util.convertToNXT(data.rewardsWeek);
      this.rewardsMonth       = nxt.util.convertToNXT(data.rewardsMonth);
    }
  }
  return StatisticsProvider;
});
})();