text:
import collections
import json
from itertools import chain
from threading import Thread
import subprocess
import os

import netaddr
import toml
import yaml

from lib.base import (
    community_str,
    wait_for_completion,
    BGPContainer,
    CmdBuffer,
    BGP_ATTR_TYPE_AS_PATH,
    BGP_ATTR_TYPE_NEXT_HOP,
    BGP_ATTR_TYPE_MULTI_EXIT_DISC,
    BGP_ATTR_TYPE_LOCAL_PREF,
    BGP_ATTR_TYPE_COMMUNITIES,
    BGP_ATTR_TYPE_MP_REACH_NLRI,
    GRACEFUL_RESTART_TIME,
    LONG_LIVED_GRACEFUL_RESTART_TIME,
    BGP_FSM_IDLE,
    BGP_FSM_ACTIVE,
    BGP_FSM_ESTABLISHED,
    yellow,
    indent,
    local,
)

def extract_path_attribute(path, typ):
    for a in path['attrs']:
        if a['type'] == typ:
            return a
    return None

class GoBGPContainer(BGPContainer):

    SHARED_VOLUME = '/root/shared_volume'
    QUAGGA_VOLUME = '/etc/quagga'

    def __init__(self, name, asn, router_id, ctn_image_name='osrg/gobgp',
                 log_level='debug', zebra=False, config_format='toml',
                 zapi_version=2, bgp_config=None, ospfd_config=None,
                 zebra_multipath_enabled=False):
        super(GoBGPContainer, self).__init__(name, asn, router_id,
                                             ctn_image_name)
        self.shared_volumes.append((self.config_dir, self.SHARED_VOLUME))
        self.quagga_config_dir = '{0}/quagga'.format(self.config_dir)
        self.shared_volumes.append((self.quagga_config_dir, self.QUAGGA_VOLUME))

        self.log_level = log_level
        self.prefix_set = None
        self.neighbor_set = None
        self.bgp_set = None
        self.statements = None
        self.default_policy = None
        self.zebra = zebra
        self.zapi_version = zapi_version
        self.zebra_multipath_enabled = zebra_multipath_enabled
        self.config_format = config_format

        # bgp_config is equivalent to config.BgpConfigSet structure
        # Example:
        # bgp_config = {
        #     'global': {
        #         'confederation': {
        #             'config': {
        #                 'identifier': 10,
        #                 'member-as-list': [65001],
        #             }
        #         },
        #     },
        # }
        self.bgp_config = bgp_config or {}

        # To start OSPFd in GoBGP container, specify 'ospfd_config' as a dict
        # type value.
        # Example:
        # ospfd_config = {
        #     'redistributes': [
        #         'connected',
        #     ],
        #     'networks': {
        #         '192.168.1.0/24': '0.0.0.0',  # <network>: <area>
        #     },
        # }
        self.ospfd_config = ospfd_config or {}

    def _start_gobgp(self, graceful_restart=False):
        c = CmdBuffer()
        c << '#!/bin/sh'
        c << '/go/bin/gobgpd -f {0}/gobgpd.conf -l {1} -p {2} -t {3} > ' \
             '{0}/gobgpd.log 2>&1'.format(self.SHARED_VOLUME, self.log_level, '-r' if graceful_restart else '', self.config_format)
        cmd = 'echo "{0:s}" > {1}/start.sh'.format(str(c), self.config_dir)
        local(cmd, capture=True)
        cmd = "chmod 755 {0}/start.sh".format(self.config_dir)
        local(cmd, capture=True)
        self.local("{0}/start.sh".format(self.SHARED_VOLUME), detach=True)

    def start_gobgp(self, graceful_restart=False):
        if self._is_running():
            raise RuntimeError('GoBGP is already running')
        self._start_gobgp(graceful_restart=graceful_restart)
        self._wait_for_boot()

    def stop_gobgp(self):
        self.local("pkill -INT gobgpd")

    def _start_zebra(self):
        if self.zapi_version == 2:
            daemon_bin = '/usr/lib/quagga/zebra'
        else:
            daemon_bin = 'zebra'
        cmd = '{0} -f {1}/zebra.conf'.format(daemon_bin, self.QUAGGA_VOLUME)
        self.local(cmd, detach=True)

    def _start_ospfd(self):
        if self.zapi_version == 2:
            daemon_bin = '/usr/lib/quagga/ospfd'
        else:
            daemon_bin = 'ospfd'
        cmd = '{0} -f {1}/ospfd.conf'.format(daemon_bin, self.QUAGGA_VOLUME)
        self.local(cmd, detach=True)

    def _get_enabled_quagga_daemons(self):
        daemons = []
        if self.zebra:
            daemons.append('zebra')
            if self.ospfd_config:
                daemons.append('ospfd')
        return daemons

    def _is_running(self):
        return self.local('gobgp global'
                          ' > /dev/null 2>&1; echo $?', capture=True) == '0'

    def _wait_for_boot(self):
        for daemon in self._get_enabled_quagga_daemons():
            def _f_quagga():
                ret = self.local("vtysh -d {0} -c 'show run' > /dev/null 2>&1; echo $?".format(daemon), capture=True)
                return ret == '0'

            wait_for_completion(_f_quagga)

        wait_for_completion(self._is_running)

    def run(self):
        super(GoBGPContainer, self).run()
        if self.zebra:
            self._start_zebra()
            if self.ospfd_config:
                self._start_ospfd()
        self._start_gobgp()
        self._wait_for_boot()
        return self.WAIT_FOR_BOOT

    @staticmethod
    def _get_as_path(path):
        asps = (p['as_paths'] for p in path['attrs']
                if p['type'] == BGP_ATTR_TYPE_AS_PATH and 'as_paths' in p and p['as_paths'] is not None)
        asps = chain.from_iterable(asps)
        asns = (asp['asns'] for asp in asps)
        return list(chain.from_iterable(asns))

    @staticmethod
    def _get_nexthop(path):
        for p in path['attrs']:
            if p['type'] == BGP_ATTR_TYPE_NEXT_HOP or p['type'] == BGP_ATTR_TYPE_MP_REACH_NLRI:
                return p['nexthop']

    @staticmethod
    def _get_local_pref(path):
        for p in path['attrs']:
            if p['type'] == BGP_ATTR_TYPE_LOCAL_PREF:
                return p['value']
        return None

    @staticmethod
    def _get_med(path):
        for p in path['attrs']:
            if p['type'] == BGP_ATTR_TYPE_MULTI_EXIT_DISC:
                return p['metric']
        return None

    @staticmethod
    def _get_community(path):
        for p in path['attrs']:
            if p['type'] == BGP_ATTR_TYPE_COMMUNITIES:
                return [community_str(c) for c in p['communities']]
        return None

    def _get_rib(self, dests_dict):
        dests = []
        for k, v in list(dests_dict.items()):
            for p in v:
                p["nexthop"] = self._get_nexthop(p)
                p["aspath"] = self._get_as_path(p)
                p["local-pref"] = self._get_local_pref(p)
                p["community"] = self._get_community(p)
                p["med"] = self._get_med(p)
                p["prefix"] = k
                path_id = p.get("id", None)
                if path_id:
                    p["identifier"] = p["id"]
            dests.append({'paths': v, 'prefix': k})
        return dests

    def _trigger_peer_cmd(self, cmd, peer):
        peer_addr = self.peer_name(peer)
        cmd = 'gobgp neighbor {0} {1}'.format(peer_addr, cmd)
        self.local(cmd)

    def disable_peer(self, peer):
        self._trigger_peer_cmd('disable', peer)

    def enable_peer(self, peer):
        self._trigger_peer_cmd('enable', peer)

    def reset(self, peer):
        self._trigger_peer_cmd('reset', peer)

    def softreset(self, peer, rf='ipv4', type='in'):
        self._trigger_peer_cmd('softreset{0} -a {1}'.format(type, rf), peer)

    def get_local_rib(self, peer, prefix='', rf='ipv4'):
        peer_addr = self.peer_name(peer)
        cmd = 'gobgp -j neighbor {0} local {1} -a {2}'.format(peer_addr, prefix, rf)
        output = self.local(cmd, capture=True)
        return self._get_rib(json.loads(output))

    def get_global_rib(self, prefix='', rf='ipv4'):
        cmd = 'gobgp -j global rib {0} -a {1}'.format(prefix, rf)
        output = self.local(cmd, capture=True)
        return self._get_rib(json.loads(output))

    def monitor_global_rib(self, queue, rf='ipv4'):
        host = self.ip_addrs[0][1].split('/')[0]

        if not os.path.exists('{0}/gobgp'.format(self.config_dir)):
            self.local('cp /go/bin/gobgp {0}/'.format(self.SHARED_VOLUME))

        args = '{0}/gobgp -u {1} -j monitor global rib -a {2}'.format(self.config_dir, host, rf).split(' ')

        def monitor():
            process = subprocess.Popen(args, stdout=subprocess.PIPE)
            for line in iter(process.stdout.readline, ''):
                p = json.loads(line)[0]
                p["nexthop"] = self._get_nexthop(p)
                p["aspath"] = self._get_as_path(p)
                p["local-pref"] = self._get_local_pref(p)
                p["med"] = self._get_med(p)
                queue.put(p)

        t = Thread(target=monitor)
        t.daemon = True
        t.start()

    def _get_adj_rib(self, adj_type, peer, prefix='', rf='ipv4', add_path_enabled=False):
        peer_addr = self.peer_name(peer)
        cmd = 'gobgp neighbor {0} adj-{1} {2} -a {3} -j'.format(peer_addr,
                                                                adj_type,
                                                                prefix, rf)
        output = self.local(cmd, capture=True)
        if add_path_enabled:
            return self._get_rib(json.loads(output))

        ret = [p[0] for p in json.loads(output).values()]
        for p in ret:
            p["nexthop"] = self._get_nexthop(p)
            p["aspath"] = self._get_as_path(p)
            p["prefix"] = p['nlri']['prefix']
            p["local-pref"] = self._get_local_pref(p)
            p["med"] = self._get_med(p)
        return ret

    def get_adj_rib_in(self, peer, prefix='', rf='ipv4', add_path_enabled=False):
        return self._get_adj_rib('in', peer, prefix, rf, add_path_enabled)

    def get_adj_rib_out(self, peer, prefix='', rf='ipv4', add_path_enabled=False):
        return self._get_adj_rib('out', peer, prefix, rf, add_path_enabled)

    def get_neighbor(self, peer):
        cmd = 'gobgp -j neighbor {0}'.format(self.peer_name(peer))
        return json.loads(self.local(cmd, capture=True))

    def get_neighbor_state(self, peer):
        s = self.get_neighbor(peer)['state']['session_state']
        if s == 1:
            return BGP_FSM_IDLE
        elif s == 3:
            return BGP_FSM_ACTIVE
        elif s == 6:
            return BGP_FSM_ESTABLISHED
        return "unknown"

    def clear_policy(self):
        self.policies = {}
        for info in self.peers.values():
            info['policies'] = {}
        self.prefix_set = []
        self.neighbor_set = []
        self.statements = []

    def set_prefix_set(self, ps):
        if not isinstance(ps, list):
            ps = [ps]
        self.prefix_set = ps

    def add_prefix_set(self, ps):
        if self.prefix_set is None:
            self.prefix_set = []
        self.prefix_set.append(ps)

    def set_neighbor_set(self, ns):
        if not isinstance(ns, list):
            ns = [ns]
        self.neighbor_set = ns

    def add_neighbor_set(self, ns):
        if self.neighbor_set is None:
            self.neighbor_set = []
        self.neighbor_set.append(ns)

    def set_bgp_defined_set(self, bs):
        self.bgp_set = bs

    def create_config(self):
        self._create_config_bgp()
        if self.zebra:
            local('mkdir -p {0}'.format(self.quagga_config_dir))
            local('chmod 777 {0}'.format(self.quagga_config_dir))
            self._create_config_zebra()
            if self.ospfd_config:
                self._create_config_ospfd()

    def _merge_dict(self, dct, merge_dct):
        for k, v in merge_dct.items():
            if (k in dct and isinstance(dct[k], dict)
                    and isinstance(merge_dct[k], collections.Mapping)):
                self._merge_dict(dct[k], merge_dct[k])
            else:
                dct[k] = merge_dct[k]

    def _create_config_bgp(self):
        config = {
            'global': {
                'config': {
                    'as': self.asn,
                    'router-id': self.router_id,
                },
                'route-selection-options': {
                    'config': {
                        'external-compare-router-id': True,
                    },
                },
            },
            'neighbors': [],
        }

        self._merge_dict(config, self.bgp_config)

        if self.zebra and self.zapi_version == 2:
            config['global']['use-multiple-paths'] = {'config': {'enabled': True}}
        else:
            config['global']['use-multiple-paths'] = {'config': {'enabled': self.zebra_multipath_enabled}}

        for peer, info in self.peers.items():
            afi_safi_list = []
            if info['interface'] != '':
                afi_safi_list.append({'config': {'afi-safi-name': 'ipv4-unicast'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'ipv6-unicast'}})
            else:
                version = netaddr.IPNetwork(info['neigh_addr']).version
                if version == 4:
                    afi_safi_list.append({'config': {'afi-safi-name': 'ipv4-unicast'}})
                elif version == 6:
                    afi_safi_list.append({'config': {'afi-safi-name': 'ipv6-unicast'}})
                else:
                    Exception('invalid ip address version. {0}'.format(version))

            if info['vpn']:
                afi_safi_list.append({'config': {'afi-safi-name': 'l3vpn-ipv4-unicast'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'l3vpn-ipv6-unicast'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'l2vpn-evpn'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'rtc'}, 'route-target-membership': {'config': {'deferral-time': 10}}})

            if info['flowspec']:
                afi_safi_list.append({'config': {'afi-safi-name': 'ipv4-flowspec'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'l3vpn-ipv4-flowspec'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'ipv6-flowspec'}})
                afi_safi_list.append({'config': {'afi-safi-name': 'l3vpn-ipv6-flowspec'}})

            neigh_addr = None
            interface = None
            peer_as = None
            if info['interface'] == '':
                neigh_addr = info['neigh_addr'].split('/')[0]
                peer_as = info['remote_as']
            else:
                interface = info['interface']
            n = {
                'config': {
                    'neighbor-address': neigh_addr,
                    'neighbor-interface': interface,
                    'peer-as': peer_as,
                    'auth-password': info['passwd'],
                    'vrf': info['vrf'],
                    'remove-private-as': info['remove_private_as'],
                },
                'afi-safis': afi_safi_list,
                'timers': {
                    'config': {
                        'connect-retry': 10,
                    },
                },
                'transport': {
                    'config': {},
                },
            }

            n['as-path-options'] = {'config': {}}
            if info['allow_as_in'] > 0:
                n['as-path-options']['config']['allow-own-as'] = info['allow_as_in']
            if info['replace_peer_as']:
                n['as-path-options']['config']['replace-peer-as'] = info['replace_peer_as']

            if ':' in info['local_addr']:
                n['transport']['config']['local-address'] = info['local_addr'].split('/')[0]

            if info['passive']:
                n['transport']['config']['passive-mode'] = True

            if info['is_rs_client']:
                n['route-server'] = {'config': {'route-server-client': True}}

            if info['local_as']:
                n['config']['local-as'] = info['local_as']

            if info['prefix_limit']:
                for v in afi_safi_list:
                    v['prefix-limit'] = {'config': {'max-prefixes': info['prefix_limit'], 'shutdown-threshold-pct': 80}}

            if info['graceful_restart'] is not None:
                n['graceful-restart'] = {'config': {'enabled': True, 'restart-time': GRACEFUL_RESTART_TIME}}
                for afi_safi in afi_safi_list:
                    afi_safi['mp-graceful-restart'] = {'config': {'enabled': True}}

                if info['llgr'] is not None:
                    n['graceful-restart']['config']['restart-time'] = 1
                    n['graceful-restart']['config']['long-lived-enabled'] = True
                    for afi_safi in afi_safi_list:
                        afi_safi['long-lived-graceful-restart'] = {'config': {'enabled': True, 'restart-time': LONG_LIVED_GRACEFUL_RESTART_TIME}}

            if info['is_rr_client']:
                cluster_id = self.router_id
                if 'cluster_id' in info and info['cluster_id'] is not None:
                    cluster_id = info['cluster_id']
                n['route-reflector'] = {'config': {'route-reflector-client': True,
                                                   'route-reflector-cluster-id': cluster_id}}

            if info['addpath']:
                n['add-paths'] = {'config': {'receive': True,
                                             'send-max': 16}}

            if len(info.get('default-policy', [])) + len(info.get('policies', [])) > 0:
                n['apply-policy'] = {'config': {}}

            for typ, p in info.get('policies', {}).items():
                n['apply-policy']['config']['{0}-policy-list'.format(typ)] = [p['name']]

            def _f(v):
                if v == 'reject':
                    return 'reject-route'
                elif v == 'accept':
                    return 'accept-route'
                raise Exception('invalid default policy type {0}'.format(v))

            for typ, d in info.get('default-policy', {}).items():
                n['apply-policy']['config']['default-{0}-policy'.format(typ)] = _f(d)

            if info['treat_as_withdraw']:
                n['error-handling'] = {'config': {'treat-as-withdraw': True}}

            config['neighbors'].append(n)

        config['defined-sets'] = {}
        if self.prefix_set:
            config['defined-sets']['prefix-sets'] = self.prefix_set

        if self.neighbor_set:
            config['defined-sets']['neighbor-sets'] = self.neighbor_set

        if self.bgp_set:
            config['defined-sets']['bgp-defined-sets'] = self.bgp_set

        policy_list = []
        for p in self.policies.values():
            policy = {'name': p['name']}
            if 'statements' in p:
                policy['statements'] = p['statements']
            policy_list.append(policy)

        if len(policy_list) > 0:
            config['policy-definitions'] = policy_list

        if self.zebra:
            config['zebra'] = {'config': {'enabled': True,
                                          'redistribute-route-type-list': ['connect'],
                                          'version': self.zapi_version}}

        with open('{0}/gobgpd.conf'.format(self.config_dir), 'w') as f:
            print(yellow('[{0}\'s new gobgpd.conf]'.format(self.name)))
            if self.config_format is 'toml':
                raw = toml.dumps(config)
            elif self.config_format is 'yaml':
                raw = yaml.dump(config)
            elif self.config_format is 'json':
                raw = json.dumps(config)
            else:
                raise Exception('invalid config_format {0}'.format(self.config_format))
            raw = raw.strip()
            print(yellow(indent(raw)))
            f.write(raw)

    def _create_config_zebra(self):
        c = CmdBuffer()
        c << 'hostname zebra'
        c << 'password zebra'
        c << 'log file {0}/zebra.log'.format(self.QUAGGA_VOLUME)
        c << 'debug zebra packet'
        c << 'debug zebra kernel'
        c << 'debug zebra rib'
        c << 'ipv6 forwarding'
        c << ''

        with open('{0}/zebra.conf'.format(self.quagga_config_dir), 'w') as f:
            print(yellow('[{0}\'s new zebra.conf]'.format(self.name)))
            c = str(c).strip()
            print(yellow(indent(c)))
            f.writelines(c)

    def _create_config_ospfd(self):
        c = CmdBuffer()
        c << 'hostname ospfd'
        c << 'password zebra'
        c << 'router ospf'
        for redistribute in self.ospfd_config.get('redistributes', []):
            c << ' redistribute {0}'.format(redistribute)
        for network, area in list(self.ospfd_config.get('networks', {}).items()):
            c << ' network {0} area {1}'.format(network, area)
        c << 'log file {0}/ospfd.log'.format(self.QUAGGA_VOLUME)
        c << ''

        with open('{0}/ospfd.conf'.format(self.quagga_config_dir), 'w') as f:
            print(yellow('[{0}\'s new ospfd.conf]'.format(self.name)))
            print(yellow(indent(str(c))))
            f.writelines(str(c))

    def reload_config(self):
        for daemon in self._get_enabled_quagga_daemons():
            self.local('pkill -SIGHUP {0}'.format(daemon), capture=True)
        self.local('pkill -SIGHUP gobgpd', capture=True)
        self._wait_for_boot()

    def add_route(self, route, rf='ipv4', attribute=None, aspath=None,
                  community=None, med=None, extendedcommunity=None,
                  nexthop=None, matchs=None, thens=None,
                  local_pref=None, identifier=None, reload_config=False):
        if not self._is_running():
            raise RuntimeError('GoBGP is not yet running')

        self.routes.setdefault(route, [])
        path = {
            'prefix': route,
            'rf': rf,
            'attr': attribute,
            'next-hop': nexthop,
            'as-path': aspath,
            'community': community,
            'med': med,
            'local-pref': local_pref,
            'extended-community': extendedcommunity,
            'identifier': identifier,
            'matchs': matchs,
            'thens': thens,
        }

        c = CmdBuffer(' ')
        c << 'gobgp global rib -a {0} add'.format(rf)
        if rf in ('ipv4', 'ipv6'):
            c << route
            if path['identifier']:
                c << 'identifier {0}'.format(path['identifier'])
            if path['next-hop']:
                c << 'nexthop {0}'.format(path['next-hop'])
            if path['local-pref']:
                c << 'local-pref {0}'.format(path['local-pref'])
            if path['med']:
                c << 'med {0}'.format(path['med'])
            if path['community']:
                comm = str(path['community'])
                if isinstance(path['community'], (list, tuple)):
                    comm = ','.join(path['community'])
                c << 'community {0}'.format(comm)
        elif rf.endswith('-flowspec'):
            c << 'match {0}'.format(' '.join(path['matchs']))
            c << 'then {0}'.format(' '.join(path['thens']))
        else:
            raise Exception('unsupported address family: {0}'.format(rf))
        self.local(str(c), capture=True)

        self.routes[route].append(path)

    def del_route(self, route, identifier=None, reload_config=True):
        if not self._is_running():
            raise RuntimeError('GoBGP is not yet running')

        if route not in self.routes:
            return

        new_paths = []
        for path in self.routes[route]:
            if path['identifier'] != identifier:
                new_paths.append(path)
            else:
                r = CmdBuffer(' ')
                r << 'gobgp global -a {0}'.format(path['rf'])
                prefix = path['prefix']
                if path['rf'].endswith('-flowspec'):
                    prefix = 'match {0}'.format(' '.join(path['matchs']))
                r << 'rib del {0}'.format(prefix)
                if identifier:
                    r << 'identifier {0}'.format(identifier)
                cmd = str(r)
                self.local(cmd, capture=True)
        self.routes[route] = new_paths
        # no need to reload config

class RawGoBGPContainer(GoBGPContainer):
    def __init__(self, name, config, ctn_image_name='osrg/gobgp',
                 log_level='debug', zebra=False, config_format='yaml'):
        if config_format is 'toml':
            d = toml.loads(config)
        elif config_format is 'yaml':
            d = yaml.load(config)
        elif config_format is 'json':
            d = json.loads(config)
        else:
            raise Exception('invalid config format {0}'.format(config_format))
        asn = d['global']['config']['as']
        router_id = d['global']['config']['router-id']
        self.config = config
        super(RawGoBGPContainer, self).__init__(name, asn, router_id,
                                                ctn_image_name, log_level,
                                                zebra, config_format)

    def create_config(self):
        with open('{0}/gobgpd.conf'.format(self.config_dir), 'w') as f:
            print(yellow('[{0}\'s new gobgpd.conf]'.format(self.name)))
            print(yellow(indent(self.config)))
            f.write(self.config)


text:
package weixin.popular.bean.message.message;

/**
 * 视频
 *
 * @author LiYi
 */
public class VideoMessage extends Message {

    public VideoMessage() {
    }

    public VideoMessage(String touser, Video video) {
        super(touser, "video");
        this.video = video;
    }

    public Video video;

    public Video getVideo() {
        return video;
    }

    public void setVideo(Video video) {
        this.video = video;
    }

    public static class Video {
        private String media_id;
        private String title;
        private String description;
        private String thumb_media_id;

        public Video() {

        }

        public Video(String media_id, String title, String description, String thumb_media_id) {
            super();
            this.media_id = media_id;
            this.thumb_media_id = thumb_media_id;
            this.title = title;
            this.description = description;
        }

        public Video(String media_id, String title, String description) {
            super();
            this.media_id = media_id;
            this.title = title;
            this.description = description;
        }

        public String getMedia_id() {
            return media_id;
        }

        public void setMedia_id(String mediaId) {
            media_id = mediaId;
        }

        public String getThumb_media_id() {
            return thumb_media_id;
        }

        public void setThumb_media_id(String thumb_media_id) {
            this.thumb_media_id = thumb_media_id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Elcodi\Component\Geo\Factory;

use Elcodi\Component\Core\Factory\Abstracts\AbstractFactory;
use Elcodi\Component\Geo\Entity\Address;

/**
 * Class AddressFactory.
 */
class AddressFactory extends AbstractFactory
{
    /**
     * Creates an instance of an entity.
     *
     * This method must return always an empty instance
     *
     * @return Address Empty entity
     */
    public function create()
    {
        /**
         * @var Address $address
         */
        $classNamespace = $this->getEntityNamespace();
        $address = new $classNamespace();
        $address
            ->setAddressMore('')
            ->setEnabled(true)
            ->setCreatedAt($this->now());

        return $address;
    }
}


text:
gitproject-roadmap(7) -- Roadmap for git-project
================================================

## INTRODUCTION

This page contains information about the unofficial road-map for git-project.
Stuff yet not implemented.

## HIGH PRIO

  1.

## COMMANDS TO IMPLEMENT

  1. git-project-help
  1. git-project-config -l|--list
  1. git-project-init --no-checkout
  1. git-project-clone --no-checkout
  1. git-project-component --list --add --delete
  1. git-project-component COMPONENT follow BRANCH alias to --branch/--follow
  1. git-project-component COMPONENT is REPO alias to --repo/--is

## GENERAL IMPROVEMENTS

  1. Improve the documentation about the commands to run to install ronn
  1. Create make target to generate complete site with links to all pages
     and assisted navigation such as headers/footers with links to TOC/index
     next/previous topic, etc.

## NOTES

### Components


text:
using System;
using System.Windows.Forms;

namespace PersonalRobotics.Kinect2Server
{
    static class Kinect2ServerLauncher
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            if (Environment.UserInteractive)
            {
                Application.Run(new Kinect2ServerTray());
            }
            else
            {
                System.ServiceProcess.ServiceBase.Run(new Kinect2ServerService());
            }
        }
    }
}


text:
using System;
using Shouldly.Tests.Strings;
using Xunit;

namespace Shouldly.Tests.ShouldThrow
{
    public class ActionDelegateScenario
    {

        [Fact]
        public void ActionDelegateScenarioShouldFail()
        {
            Action action = () => { };
            Verify.ShouldFail(() =>
action.ShouldThrow<NotImplementedException>("Some additional context"),

errorWithSource:
@"`action()`
    should throw
System.NotImplementedException
    but did not

Additional Info:
    Some additional context",

    errorWithoutSource:
@"delegate
    should throw
System.NotImplementedException
    but did not

Additional Info:
    Some additional context");
        }

        [Fact]
        public void ShouldPass()
        {
            var action = new Action(() => { throw new NotImplementedException(); });

            var ex = action.ShouldThrow<NotImplementedException>();
            ex.ShouldBeOfType<NotImplementedException>();
            ex.ShouldNotBe(null);
        }
    }
}


text:
import r from 'rethinkdb';
import config from 'config';

const rethinkdb = config.get('rethinkdb');
const DATABASE = rethinkdb.db;

r.connect(rethinkdb)
.then(conn => {
	console.log(' [-] Database Drop');
	return dropTables(conn)
    .then(() => closeConnection(conn));
});

function dropTables(conn) {
	return r.dbDrop(DATABASE).run(conn);
}

function closeConnection(conn) {
	console.log(' [x] Close connection!');
	return conn.close();
}


text:
package voldemort.performance;

import java.io.StringReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import voldemort.client.ClientConfig;
import voldemort.client.SocketStoreClientFactory;
import voldemort.store.metadata.MetadataStore;
import voldemort.xml.ClusterMapper;
import voldemort.xml.MappingException;
import voldemort.xml.StoreDefinitionsMapper;

public class MetadataStressTest {

    private final static Logger logger = Logger.getLogger(MetadataStressTest.class);

    public static void main(String[] args) throws Exception {

        if(args.length < 3) {
            System.err.println("java voldemort.performance.MetadataStressTest url iterations threads selectors");
            System.exit(-1);
        }

        String url = args[0];
        final int count = Integer.parseInt(args[1]);
        int numThreads = Integer.parseInt(args[2]);
        int numSelectors = args.length > 3 ? Integer.parseInt(args[3]) : 8;
        int timeoutSecs = args.length > 4 ? Integer.parseInt(args[4]) : 10;

        ExecutorService executor = Executors.newFixedThreadPool(numThreads, new ThreadFactory() {

            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("stress-test");
                return thread;
            }
        });
        try {
            final SocketStoreClientFactory factory = new SocketStoreClientFactory(new ClientConfig().setBootstrapUrls(url)
                                                                                .setEnableLazy(false)
                                                                                .setConnectionTimeout(timeoutSecs,
                                                                                TimeUnit.SECONDS)
                                                                                .setSocketTimeout(timeoutSecs,
                                                                                TimeUnit.SECONDS)
                                                                                .setMaxThreads(numThreads)
                                                                                .setSelectors(numSelectors));
            for(int i = 0; i < numThreads; i++) {
                executor.submit(new Runnable() {

                    public void run() {
                        for(int j = 0; j < count; j++) {
                            try {
                                String clusterXml = factory.bootstrapMetadataWithRetries(MetadataStore.CLUSTER_KEY);
                                new ClusterMapper().readCluster(new StringReader(clusterXml));
                                String storesXml = factory.bootstrapMetadataWithRetries(MetadataStore.STORES_KEY);
                                new StoreDefinitionsMapper().readStoreList(new StringReader(storesXml));
                                if(logger.isTraceEnabled())
                                    logger.trace("ok " + j);
                            } catch(MappingException me) {
                                logger.fatal(me, me);
                                System.exit(-1);
                            } catch(Exception e) {
                                logger.error(e, e);
                            }
                        }
                    }
                });
            }
        } finally {
            executor.shutdown();
        }
    }
}


text:
package org.lwjgl.opengles;

import org.lwjgl.util.generator.*;
import org.lwjgl.util.generator.opengl.GLenum;
import org.lwjgl.util.generator.opengl.GLreturn;
import org.lwjgl.util.generator.opengl.GLsizei;
import org.lwjgl.util.generator.opengl.GLuint;

import java.nio.IntBuffer;

public interface NV_fence {

	/** Accepted by the <condition> parameter of SetFenceNV: */
	int GL_ALL_COMPLETED_NV = 0x84F2;

	/** Accepted by the <pname> parameter of GetFenceivNV: */
	int GL_FENCE_STATUS_NV    = 0x84F3,
		GL_FENCE_CONDITION_NV = 0x84F4;

	void glGenFencesNV(@AutoSize("fences") @GLsizei int n, @OutParameter @GLuint IntBuffer fences);

	@Alternate("glGenFencesNV")
	@GLreturn("fences")
	void glGenFencesNV2(@Constant("1") @GLsizei int n, @OutParameter @GLuint IntBuffer fences);

	void glDeleteFencesNV(@AutoSize("fences") @GLsizei int n, @Const @GLuint IntBuffer fences);

	@Alternate("glDeleteFencesNV")
	void glDeleteFencesNV(@Constant("1") @GLsizei int n, @Const @GLuint @Constant(value = "APIUtil.getInt(fence)", keepParam = true) int fence);

	void glSetFenceNV(@GLuint int fence, @GLenum int condition);

	boolean glTestFenceNV(@GLuint int fence);

	void glFinishFenceNV(@GLuint int fence);

	boolean glIsFenceNV(@GLuint int fence);

	void glGetFenceivNV(@GLuint int fence, @GLenum int pname, @OutParameter @Check("1") IntBuffer params);

}


text:
'use strict';

// For some reason thinks it's a strict violation.
/* jshint ignore:start */
if (exports !== this) {
  throw new Error('Invalid module context');
}
/* jshint ignore:end */

var moduleStateValue = 'default';

function setModuleStateValue(value) {
  moduleStateValue = value;
}

function getModuleStateValue() {
  return moduleStateValue;
}

exports.getModuleStateValue = getModuleStateValue;
exports.isRealModule = true;
exports.setModuleStateValue = setModuleStateValue;


text:
/* ------------------------------------------------------------------
 * Copyright (C) 1998-2009 PacketVideo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 * -------------------------------------------------------------------
 */
/*

 Pathname: PVMP4AudioDecoderConfig

------------------------------------------------------------------------------
 REVISION HISTORY

 Description: (1) Modified to decode AudioSpecificConfig for any frame number
                  pVars->bno
              (2) Update the input and output descriptions

 Description: Eliminated search for ADIF header

 Description: Added support for AAC+

 Who:                                         Date:
 Description:

------------------------------------------------------------------------------
 INPUT AND OUTPUT DEFINITIONS

 Inputs:
    pExt = pointer to the external interface structure. See the file
           PVMP4AudioDecoder_API.h for a description of each field.
           Data type of pointer to a tPVMP4AudioDecoderExternal
           structure.

           pExt->pInputBuffer: pointer to input buffer containing input
                               bitstream

           pExt->inputBufferCurrentLength: number of bytes in the input buffer

           pExt->inputBufferUsedLength: number of bytes already consumed in
                                        input buffer

           pExt->remainderBits: number of bits consumed in addition to
                                pExt->inputBufferUsedLength

    pMem = void pointer to hide the internal implementation of the library
           It is cast back to a tDec_Int_File structure. This structure
           contains information that needs to persist between calls to
           this function, or is too big to be placed on the stack, even
           though the data is only needed during execution of this function
           Data type void pointer, internally pointer to a tDec_Int_File
           structure.

 Local Stores/Buffers/Pointers Needed: None
           (The memory set aside in pMem performs this task)

 Global Stores/Buffers/Pointers Needed: None

 Outputs:
     status = 0                       if no error occurred
              MP4AUDEC_NONRECOVERABLE if a non-recoverable error occurred
              MP4AUDEC_RECOVERABLE    if a recoverable error occurred.
              Presently a recoverable error does not exist, but this
              was a requirement.

 Pointers and Buffers Modified:
    pMem contents are modified.
    pExt: (more detail in the file PVMP4AudioDecoder_API.h)
    inputBufferUsedLength - number of array elements used up by the stream.
    remainderBits - remaining bits in the next UInt32 buffer
    samplingRate - sampling rate in samples per sec
    encodedChannels - channels found on the file (informative)
    frameLength - length of the frame

 Local Stores Modified: None.

 Global Stores Modified: None.

------------------------------------------------------------------------------
 FUNCTION DESCRIPTION

------------------------------------------------------------------------------
 REQUIREMENTS

 PacketVideo Document # CCC-AUD-AAC-ERS-0003

------------------------------------------------------------------------------
 REFERENCES

 (1) ISO/IEC 14496-3: 1999(E)
      subclause 1.6

------------------------------------------------------------------------------
 RESOURCES USED
   When the code is written for a specific target processor the
     the resources used should be documented below.

 STACK USAGE: [stack count for this module] + [variable to represent
          stack usage for each subroutine called]

     where: [stack usage variable] = stack usage for [subroutine
         name] (see [filename].ext)

 DATA MEMORY USED: x words

 PROGRAM MEMORY USED: x words

 CLOCK CYCLES: [cycle count equation for this module] + [variable
           used to represent cycle count for each subroutine
           called]

     where: [cycle count variable] = cycle count for [subroutine
        name] (see [filename].ext)

------------------------------------------------------------------------------
*/

/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "pv_audio_type_defs.h"
#include "s_tdec_int_file.h"
#include "ibstream.h"           /* where #define INBUF_ARRAY_INDEX_SHIFT */
#include "sfb.h"                   /* Where samp_rate_info[] is declared */

#include "get_audio_specific_config.h"
#include "pvmp4audiodecoder_api.h"   /* Where this function is declared */

/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/

OSCL_EXPORT_REF Int PVMP4AudioDecoderConfig(
    tPVMP4AudioDecoderExternal  *pExt,
    void                        *pMem)
{

    UInt           initialUsedBits;  /* Unsigned for C55x */
    tDec_Int_File *pVars;           /* Helper pointer */

    Int            status = MP4AUDEC_INCOMPLETE_FRAME;

    /*
     * Initialize "helper" pointers to existing memory.
     */
    pVars = (tDec_Int_File *)pMem;
    /*
     * Translate input buffer variables.
     */
    pVars->inputStream.pBuffer = pExt->pInputBuffer;

    pVars->inputStream.inputBufferCurrentLength =
        (UInt)pExt->inputBufferCurrentLength;

    pVars->inputStream.availableBits =
        (UInt)(pExt->inputBufferCurrentLength << INBUF_ARRAY_INDEX_SHIFT);

    initialUsedBits =
        (UInt)((pExt->inputBufferUsedLength << INBUF_ARRAY_INDEX_SHIFT) +
               pExt->remainderBits);

    pVars->inputStream.usedBits = initialUsedBits;

    if (initialUsedBits <= pVars->inputStream.availableBits)
    {

        /*
         * Buffer is not overrun, then
         * decode the AudioSpecificConfig() structure
         */

        pVars->aacConfigUtilityEnabled = false;  /* set aac dec mode */

        status = get_audio_specific_config(pVars);

    }

    byte_align(&pVars->inputStream);

    if (status == SUCCESS)
    {

        pVars->bno++;

        /*
         * A possible improvement would be to set these values only
         * when they change.
         */
        pExt->samplingRate =
            samp_rate_info[pVars->prog_config.sampling_rate_idx].samp_rate;

        /*
         *  we default to 2 channel, even for mono files, (where channels have same content)
         *  this is done to ensure support for enhanced aac+ with implicit signalling
         */
        pExt->aacPlusEnabled = pVars->aacPlusEnabled;

//        pExt->encodedChannels = pVars->mc_info.nch;

        pExt->encodedChannels = 2;

        pExt->frameLength = pVars->frameLength;
#ifdef AAC_PLUS
        pExt->aacPlusUpsamplingFactor = pVars->mc_info.upsamplingFactor;
#endif

    }
    else
    {
        /*
         *  Default to nonrecoverable error status unless there is a Buffer overrun
         */
        status = MP4AUDEC_INVALID_FRAME;

        if (pVars->inputStream.usedBits > pVars->inputStream.availableBits)
        {
            /* all bits were used but were not enough to complete parsing */
            pVars->inputStream.usedBits = pVars->inputStream.availableBits;

            status = MP4AUDEC_INCOMPLETE_FRAME; /* audio config too small */
        }

    }

    /*
     * Translate from units of bits back into units of words.
     */

    pExt->inputBufferUsedLength =
        pVars->inputStream.usedBits >> INBUF_ARRAY_INDEX_SHIFT;

    pExt->remainderBits = pVars->inputStream.usedBits & INBUF_BIT_MODULO_MASK;

    pVars->status = status;

    return (status);

} /* PVMP4AudioDecoderDecodeFrame */


text:
<?php

//start session (see get.php for details)
	error_reporting(E_ALL ^ E_NOTICE);

session_start();
if(!isset($_SESSION["id"]))
	$_SESSION["id"] = microtime();

//include db connection settings
require_once("../../common/config.php");

$link = mysql_pconnect($mysql_host, $mysql_user, $mysql_pasw);
$db = mysql_select_db ($mysql_db);

//FUNCTION TO USE IN THE CODE LATER

//deletes single node in db
function deleteSingleNode($id){
		$d_sql = "Delete from samples_tree where item_id=".$id." and GUID='".$_SESSION["id"]."'";
		$resDel = mysql_query($d_sql);
	}
//deletes all child nodes of the item
function deleteBranch($pid){
	$s_sql = "Select item_id,item_order from samples_tree where item_parent_id=$pid  and GUID='".$_SESSION["id"]."'";
	$res = mysql_query($s_sql);
	if($res){
		while($row=mysql_fetch_array($res)){
			deleteBranch($row['item_id']);
			deleteSingleNode($row['item_id']);
		}
	}
}

//XML HEADER

//include XML Header (as response will be in xml format)
if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
 		header("Content-type: application/xhtml+xml"); } else {
 		header("Content-type: text/xml");
}
echo("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");

if(isset($_GET["!nativeeditor_status"]) && $_GET["!nativeeditor_status"]=="inserted"){

	//INSERT

	//insert new row
	$sql = 	"Insert into samples_tree(item_nm,item_parent_id,item_desc,item_order,GUID) ";
	$sql.= 	"Values('".addslashes($_GET["tr_text"])."',".$_GET["tr_pid"].",'',".$_GET["tr_order"].",'".$_SESSION["id"]."')";

		$res = mysql_query($sql);
		$newId = mysql_insert_id();
	//update items orders on the level where node was added
	$sql_uorders = "UPDATE samples_tree SET item_order=item_order+1 WHERE item_parent_id=".$_GET["tr_pid"]." AND item_order>=".$_GET["tr_order"]." and item_id!=".$newId." and GUID='".$_SESSION["id"]."'";
		$res = mysql_query($sql_uorders);

	//set value to use in response
	$action = "insert";

}else if(isset($_GET["!nativeeditor_status"]) && $_GET["!nativeeditor_status"]=="deleted"){

	//DELETE

	//updateitems order on the level where node was deleted
	$sql_uorders = "UPDATE samples_tree SET item_order=item_order-1 WHERE item_parent_id=".$_GET["tr_pid"]." AND item_order>".($_GET["tr_order"])." and GUID='".$_SESSION["id"]."'";

		//delete all nested nodes and current node
		deleteBranch($_GET["tr_id"]);
		deleteSingleNode($_GET["tr_id"]);
		$res = mysql_query($sql_uorders);
	//set values to use in response
	$newId = $_GET["tr_id"];
	$action = "delete";

}else{

	//UPDATE and Drag-n-Drop

	//get information about node parent and order before update
	$sql_getoldparent = "Select item_parent_id,item_order from samples_tree where item_id=".$_GET["tr_id"]." and GUID='".$_SESSION["id"]."'";
	$res = mysql_query($sql_getoldparent);
	$old_values = mysql_fetch_array($res);
	//update node info
	$sql = 	"Update samples_tree set item_nm = '".addslashes($_GET["tr_text"])."',item_parent_id = ".$_GET["tr_pid"].",item_desc = '".addslashes($_GET["ud_description"])."',item_order = ".$_GET["tr_order"]." where item_id=".$_GET["tr_id"]." and GUID='".$_SESSION["id"]."'";
	//update nodes order on old node level (after drag-n-drop node level can be changed)
	$sql_uorders_old = "UPDATE samples_tree SET item_order=item_order-1 WHERE item_parent_id=".$old_values[0]." AND item_order>".$old_values[1]." and item_id<>".$_GET["tr_id"]." and GUID='".$_SESSION["id"]."'";
	//update nodes order on current node level
	$sql_uorders_new = "UPDATE samples_tree SET item_order=item_order+1 WHERE item_parent_id=".$_GET["tr_pid"]." AND item_order>=".$_GET["tr_order"]." and item_id<>".$_GET["tr_id"]." and GUID='".$_SESSION["id"]."'";
		$res = mysql_query($sql);
		$res = mysql_query($sql_uorders_old);
		$res = mysql_query($sql_uorders_new);

	//set values to include in response
	$newId = $_GET["tr_id"];
	$action = "update";
}
?>
<!-- response xml -->
<data>
	<action type='<?php echo $action; ?>' sid='<?php echo $_GET["tr_id"]; ?>' tid='<?php echo $newId; ?>'/>
</data>


text:
package lombok.installer.eclipse;

import static lombok.installer.IdeLocation.canonical;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import lombok.installer.IdeLocation;
import lombok.installer.IdeLocationProvider;
import lombok.installer.CorruptedIdeLocationException;
import lombok.installer.IdeFinder.OS;

import org.mangosdk.spi.ProviderFor;

@ProviderFor(IdeLocationProvider.class)
public class EclipseLocationProvider implements IdeLocationProvider {
	@Override public IdeLocation create(String path) throws CorruptedIdeLocationException {
		return create0(path);
	}

	protected List<String> getEclipseExecutableNames() {
		return Arrays.asList("eclipse.app", "eclipse.exe", "eclipse");
	}

	protected String getIniName() {
		return "eclipse.ini";
	}

	protected IdeLocation makeLocation(String name, File ini) throws CorruptedIdeLocationException {
		return new EclipseLocation(name, ini);
	}

	protected String getMacAppName() {
		return "Eclipse.app";
	}

	protected String getUnixAppName() {
		return "eclipse";
	}

	/**
	 * Create a new EclipseLocation by pointing at either the directory contains the Eclipse executable, or the executable itself,
	 * or an eclipse.ini file.
	 *
	 * @throws NotAnIdeLocationException
	 *             If this isn't an Eclipse executable or a directory with an
	 *             Eclipse executable.
	 */
	protected IdeLocation create0(String path) throws CorruptedIdeLocationException {
		if (path == null) throw new NullPointerException("path");
		File p = new File(path);

		if (!p.exists()) return null;
		if (p.isDirectory()) {
			for (String possibleExeName : getEclipseExecutableNames()) {
				File f = new File(p, possibleExeName);
				if (f.exists()) return findEclipseIniFromExe(f, 0);
			}

			File f = new File(p, getIniName());
			if (f.exists()) return new EclipseLocation(canonical(p), f);
		}

		if (p.isFile()) {
			if (p.getName().equalsIgnoreCase(getIniName())) {
				return new EclipseLocation(canonical(p.getParentFile()), p);
			}
		}

		if (getEclipseExecutableNames().contains(p.getName().toLowerCase())) {
			return findEclipseIniFromExe(p, 0);
		}

		return null;
	}

	private IdeLocation findEclipseIniFromExe(File exePath, int loopCounter) throws CorruptedIdeLocationException {
		/* Try looking for eclipse.ini as sibling to the executable */ {
			File ini = new File(exePath.getParentFile(), getIniName());
			if (ini.isFile()) return makeLocation(canonical(exePath), ini);
		}

		/* Try looking for Eclipse/app/Contents/MacOS/eclipse.ini as sibling to executable; this works on Mac OS X. */ {
			File ini = new File(exePath.getParentFile(), getMacAppName() + "/Contents/MacOS/" + getIniName());
			if (ini.isFile()) return makeLocation(canonical(exePath), ini);
		}

		/* If executable is a soft link, follow it and retry. */ {
			if (loopCounter < 50) {
				try {
					String oPath = exePath.getAbsolutePath();
					String nPath = exePath.getCanonicalPath();
					if (!oPath.equals(nPath)) try {
						IdeLocation loc = findEclipseIniFromExe(new File(nPath), loopCounter + 1);
						if (loc != null) return loc;
					} catch (CorruptedIdeLocationException ignore) {
						// Unlinking didn't help find an eclipse, so continue.
					}
				} catch (IOException ignore) { /* okay, that didn't work, assume it isn't a soft link then. */ }
			}
		}

		/* If executable is a linux LSB-style path, then look in the usual places that package managers like apt-get use.*/ {
			String path = exePath.getAbsolutePath();
			try {
				path = exePath.getCanonicalPath();
			} catch (IOException ignore) { /* We'll stick with getAbsolutePath()'s result then. */ }

			if (path.equals("/usr/bin/" + getUnixAppName()) || path.equals("/bin/" + getUnixAppName()) || path.equals("/usr/local/bin/" + getUnixAppName())) {
				File ini = new File("/usr/lib/" + getUnixAppName() + "/" + getIniName());
				if (ini.isFile()) return makeLocation(path, ini);
				ini = new File("/usr/local/lib/" + getUnixAppName() + "/" + getIniName());
				if (ini.isFile()) return makeLocation(path, ini);
				ini = new File("/usr/local/etc/" + getUnixAppName() + "/" + getIniName());
				if (ini.isFile()) return makeLocation(path, ini);
				ini = new File("/etc/" + getIniName());
				if (ini.isFile()) return makeLocation(path, ini);
			}
		}

		/* If we get this far, we lose. */
		return null;
	}

	@Override public Pattern getLocationSelectors(OS os) {
		switch (os) {
		case MAC_OS_X:
			return Pattern.compile("^(eclipse|eclipse\\.ini|eclipse\\.app)$", Pattern.CASE_INSENSITIVE);
		case WINDOWS:
			return Pattern.compile("^(eclipse\\.exe|eclipse\\.ini)$", Pattern.CASE_INSENSITIVE);
		default:
		case UNIX:
			return Pattern.compile("^(eclipse|eclipse\\.ini)$", Pattern.CASE_INSENSITIVE);
		}
	}
}


text:
package com.eagle.programmar.Java.Statements;

import com.eagle.programmar.Java.Java_Expression;
import com.eagle.programmar.Java.Terminals.Java_Keyword;
import com.eagle.tokens.TokenSequence;
import com.eagle.tokens.punctuation.PunctuationSemicolon;

public class Java_ReturnStatement extends TokenSequence
{
	public @NEWLINE @DOC("statements.html#14.17") Java_Keyword RETURN = new Java_Keyword("return");
	public @OPT Java_Expression expression;
	public @NOSPACE PunctuationSemicolon semicolon;
}


text:
@interface MPConnector ()

@property (nonatomic) NSURLSession *urlSession;

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error;
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error;

@end

@interface MPConnectorTests  : MPBaseTestCase

@end

@implementation MPConnectorTests

- (void)setUp {
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
}

- (void)testSessionIsInvalidatedWithError {
    MPConnector *connector = [[MPConnector alloc] init];
    NSURLSession *mockSession = OCMClassMock([NSURLSession class]);
    connector.urlSession = mockSession;
    NSURLSessionTask *mockTask = OCMClassMock([NSURLSessionTask class]);
    NSError *error = [NSError new];

    [connector URLSession:mockSession task:mockTask didCompleteWithError:error];
    OCMVerify([mockSession finishTasksAndInvalidate]);
}

- (void)testSessionIsInvalidatedNoError {
    MPConnector *connector = [[MPConnector alloc] init];
    NSURLSession *mockSession = OCMClassMock([NSURLSession class]);
    connector.urlSession = mockSession;
    NSURLSessionTask *mockTask = OCMClassMock([NSURLSessionTask class]);

    [connector URLSession:mockSession task:mockTask didCompleteWithError:nil];
    OCMVerify([mockSession finishTasksAndInvalidate]);
}

- (void)testSessionIsNotInvalidatedUnnecessarily {
    MPConnector *connector = [[MPConnector alloc] init];
    NSURLSession *mockSession = OCMClassMock([NSURLSession class]);
    OCMReject([mockSession finishTasksAndInvalidate]);

    connector.urlSession = mockSession;
    NSError *error = [NSError new];

    [connector URLSession:mockSession didBecomeInvalidWithError:error];

    OCMVerifyAll((id)mockSession);
}

- (void)testSemaphoreWaitTimeout {
    XCTAssertLessThan(NETWORK_REQUEST_MAX_WAIT_SECONDS+1, DISPATCH_TIME_FOREVER);
}

- (void)testURLSession {
    MPConnector *connector = [[MPConnector alloc] init];
    NSURLSession *mockSession = OCMClassMock([NSURLSession class]);
    OCMReject(ClassMethod([(id)mockSession sessionWithConfiguration:[OCMArg any] delegate:[OCMArg any] delegateQueue:[OCMArg  isNotNil]])).andReturn(@"Test string");
    NSURLSession *resultSession = connector.urlSession;
    XCTAssertNotNil(resultSession);
    OCMVerifyAll((id)mockSession);
}

- (void)testResponseFromGetRequestToURL {
    MPConnector *connector = [[MPConnector alloc] init];
    NSURL *customURL = [NSURL URLWithString:@"https://192.168.1"];
    NSURL *defaultURL = [NSURL URLWithString:@"https://nativesdks.mparticle.com"];
    MPURL *mpURL = [[MPURL alloc] initWithURL:customURL defaultURL:defaultURL];

    MPURLRequestBuilder *mockRequestBuilder = OCMClassMock([MPURLRequestBuilder class]);
    OCMVerify([[mockRequestBuilder class] newBuilderWithURL:mpURL message:nil httpMethod:kMPHTTPMethodGet]);

    NSObject<MPConnectorResponseProtocol> *connectorResponse = [connector responseFromGetRequestToURL:mpURL];
    XCTAssertNotNil(connectorResponse);
    OCMVerifyAll((id)mockRequestBuilder);
}

- (void)testResponseFromPostRequestToURL {
    MPConnector *connector = [[MPConnector alloc] init];
    NSURL *customURL = [NSURL URLWithString:@"https://192.168.1"];
    NSURL *defaultURL = [NSURL URLWithString:@"https://nativesdks.mparticle.com"];
    MPURL *mpURL = [[MPURL alloc] initWithURL:customURL defaultURL:defaultURL];

    MPURLRequestBuilder *mockRequestBuilder = OCMClassMock([MPURLRequestBuilder class]);
    OCMVerify([[mockRequestBuilder class] newBuilderWithURL:mpURL message:nil httpMethod:kMPHTTPMethodGet]);

    NSObject<MPConnectorResponseProtocol> *connectorResponse = [connector responseFromPostRequestToURL:mpURL message:nil serializedParams:nil];
    XCTAssertNotNil(connectorResponse);
    OCMVerifyAll((id)mockRequestBuilder);
}

@end

#endif


text:
/*
 * ProductionPatternAlternative.cs
 */

using System;
using System.Collections;
using System.Text;

namespace Core.Library {

    /**
     * A production pattern alternative. This class represents a list of
     * production pattern elements. In order to provide productions that
     * cannot be represented with the element occurance counters, multiple
     * alternatives must be created and added to the same production
     * pattern. A production pattern alternative is always contained
     * within a production pattern.
     *

     *
     */
    public class ProductionPatternAlternative {

        /**
         * The production pattern.
         */
        private ProductionPattern pattern;

        /**
         * The element list.
         */
        private ArrayList elements = new ArrayList();

        /**
         * The look-ahead set associated with this alternative.
         */
        private LookAheadSet lookAhead = null;

        /**
         * Creates a new production pattern alternative.
         */
        public ProductionPatternAlternative() {
        }

        /**
         * The production pattern property (read-only). This property
         * contains the pattern having this alternative.
         *
         *
         */
        public ProductionPattern Pattern {
            get {
                return pattern;
            }
        }

        /**
         * Returns the production pattern containing this alternative.
         *
         * @return the production pattern for this alternative
         *
         * @see #Pattern
         *
         * @deprecated Use the Pattern property instead.
         */
        public ProductionPattern GetPattern() {
            return Pattern;
        }

        /**
         * The look-ahead set property. This property contains the
         * look-ahead set associated with this alternative.
         */
        internal LookAheadSet LookAhead {
            get {
                return lookAhead;
            }
            set {
                lookAhead = value;
            }
        }

        /**
         * The production pattern element count property (read-only).
         *
         *
         */
        public int Count {
            get {
                return elements.Count;
            }
        }

        /**
         * Returns the number of elements in this alternative.
         *
         * @return the number of elements in this alternative
         *
         * @see #Count
         *
         * @deprecated Use the Count property instead.
         */
        public int GetElementCount() {
            return Count;
        }

        /**
         * The production pattern element index (read-only).
         *
         * @param index          the element index, 0 <= pos < Count
         *
         * @return the element found
         *
         *
         */
        public ProductionPatternElement this[int index] {
            get {
                return (ProductionPatternElement) elements[index];
            }
        }

        /**
         * Returns an element in this alternative.
         *
         * @param pos            the element position, 0 <= pos < count
         *
         * @return the element found
         *
         * @deprecated Use the class indexer instead.
         */
        public ProductionPatternElement GetElement(int pos) {
            return this[pos];
        }

        /**
         * Checks if this alternative is recursive on the left-hand
         * side. This method checks all the possible left side
         * elements and returns true if the pattern itself is among
         * them.
         *
         * @return true if the alternative is left side recursive, or
         *         false otherwise
         */
        public bool IsLeftRecursive() {
            ProductionPatternElement  elem;

            for (int i = 0; i < elements.Count; i++) {
                elem = (ProductionPatternElement) elements[i];
                if (elem.Id == pattern.Id) {
                    return true;
                } else if (elem.MinCount > 0) {
                    break;
                }
            }
            return false;
        }

        /**
         * Checks if this alternative is recursive on the right-hand side.
         * This method checks all the possible right side elements and
         * returns true if the pattern itself is among them.
         *
         * @return true if the alternative is right side recursive, or
         *         false otherwise
         */
        public bool IsRightRecursive() {
            ProductionPatternElement  elem;

            for (int i = elements.Count - 1; i >= 0; i--) {
                elem = (ProductionPatternElement) elements[i];
                if (elem.Id == pattern.Id) {
                    return true;
                } else if (elem.MinCount > 0) {
                    break;
                }
            }
            return false;
        }

        /**
         * Checks if this alternative would match an empty stream of
         * tokens. This check is equivalent of getMinElementCount()
         * returning zero (0).
         *
         * @return true if the rule can match an empty token stream, or
         *         false otherwise
         */
        public bool IsMatchingEmpty() {
            return GetMinElementCount() == 0;
        }

        /**
         * Changes the production pattern containing this alternative.
         * This method should only be called by the production pattern
         * class.
         *
         * @param pattern        the new production pattern
         */
        internal void SetPattern(ProductionPattern pattern) {
            this.pattern = pattern;
        }

        /**
         * Returns the minimum number of elements needed to satisfy
         * this alternative. The value returned is the sum of all the
         * elements minimum count.
         *
         * @return the minimum number of elements
         */
        public int GetMinElementCount() {
            ProductionPatternElement  elem;
            int                       min = 0;

            for (int i = 0; i < elements.Count; i++) {
                elem = (ProductionPatternElement) elements[i];
                min += elem.MinCount;
            }
            return min;
        }

        /**
         * Returns the maximum number of elements needed to satisfy
         * this alternative. The value returned is the sum of all the
         * elements maximum count.
         *
         * @return the maximum number of elements
         */
        public int GetMaxElementCount() {
            ProductionPatternElement  elem;
            int                       max = 0;

            for (int i = 0; i < elements.Count; i++) {
                elem = (ProductionPatternElement) elements[i];
                if (elem.MaxCount >= Int32.MaxValue) {
                    return Int32.MaxValue;
                } else {
                    max += elem.MaxCount;
                }
            }
            return max;
        }

        /**
         * Adds a token to this alternative. The token is appended to
         * the end of the element list. The multiplicity values
         * specified define if the token is optional or required, and
         * if it can be repeated.
         *
         * @param id             the token (pattern) id
         * @param min            the minimum number of occurancies
         * @param max            the maximum number of occurancies, or
         *                       -1 for infinite
         */
        public void AddToken(int id, int min, int max) {
            AddElement(new ProductionPatternElement(true, id, min, max));
        }

        /**
         * Adds a production to this alternative. The production is
         * appended to the end of the element list. The multiplicity
         * values specified define if the production is optional or
         * required, and if it can be repeated.
         *
         * @param id             the production (pattern) id
         * @param min            the minimum number of occurancies
         * @param max            the maximum number of occurancies, or
         *                       -1 for infinite
         */
        public void AddProduction(int id, int min, int max) {
            AddElement(new ProductionPatternElement(false, id, min, max));
        }

        /**
         * Adds a production pattern element to this alternative. The
         * element is appended to the end of the element list.
         *
         * @param elem           the production pattern element
         */
        public void AddElement(ProductionPatternElement elem) {
            elements.Add(elem);
        }

        /**
         * Adds a production pattern element to this alternative. The
         * multiplicity values in the element will be overridden with
         * the specified values. The element is appended to the end of
         * the element list.
         *
         * @param elem           the production pattern element
         * @param min            the minimum number of occurancies
         * @param max            the maximum number of occurancies, or
         *                       -1 for infinite
         */
        public void AddElement(ProductionPatternElement elem,
                               int min,
                               int max) {

            if (elem.IsToken()) {
                AddToken(elem.Id, min, max);
            } else {
                AddProduction(elem.Id, min, max);
            }
        }

        /**
         * Checks if this object is equal to another. This method only
         * returns true for another production pattern alternative
         * with identical elements in the same order.
         *
         * @param obj            the object to compare with
         *
         * @return true if the object is identical to this one, or
         *         false otherwise
         */
        public override bool Equals(object obj) {
            if (obj is ProductionPatternAlternative) {
                return Equals((ProductionPatternAlternative) obj);
            } else {
                return false;
            }
        }

        /**
         * Checks if this alternative is equal to another. This method
         * returns true if the other production pattern alternative
         * has identical elements in the same order.
         *
         * @param alt            the alternative to compare with
         *
         * @return true if the object is identical to this one, or
         *         false otherwise
         */
        public bool Equals(ProductionPatternAlternative alt) {
            if (elements.Count != alt.elements.Count) {
                return false;
            }
            for (int i = 0; i < elements.Count; i++) {
                if (!elements[i].Equals(alt.elements[i])) {
                    return false;
                }
            }
            return true;
        }

        /**
         * Returns a hash code for this object.
         *
         * @return a hash code for this object
         */
        public override int GetHashCode() {
            return elements.Count.GetHashCode();
        }

        /**
         * Returns a string representation of this object.
         *
         * @return a token string representation
         */
        public override string ToString() {
            StringBuilder  buffer = new StringBuilder();

            for (int i = 0; i < elements.Count; i++) {
                if (i > 0) {
                    buffer.Append(" ");
                }
                buffer.Append(elements[i]);
            }
            return buffer.ToString();
        }
    }
}


text:
package com.marcelherd.uebung4.quicksort;
import static gdi.MakeItSimple.*;
import java.util.Random;

public class Application {
public static void main(String[] args) {

	QuickSort test = new QuickSort();
	Integer[] testArray;
	testArray = QuickSort.getIntegerArray("resources/randoms.txt");
	int threadsBeforeSort = Thread.activeCount();
	long startTime = System.currentTimeMillis();
	test.sort(testArray);
	while(Thread.activeCount() > threadsBeforeSort){
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	startTime = System.currentTimeMillis() - startTime;
	println(test);
	println("Array Sorted: " + QuickSort.checkSorted(testArray));
	println("Time: " + startTime + "ms");
	test.write("resources/randoms_sorted.txt");
	println("written!");
}

public static void createEnormFile(int numbers){
	StringBuilder safer = new StringBuilder();
	Random r = new Random();
	for(int i = 0; i<numbers; i++){
		safer.append((i + r.nextInt(numbers) - (numbers/2)) + " ");
	}
	Object file = openOutputFile("resources/randoms_" + numbers + ".txt");
	print(file, safer.toString());
	closeOutputFile(file);
}
}


text:
from supybot.test import *

class HacklabSignTestCase(PluginTestCase):
    plugins = ('HacklabSign',)

# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:


text:
/**
 * parse block-structured languages that use braces and semicolons
 */
package com.jme3.util.blockparser;


text:
![LogoHeadMasterCES](https://sites.google.com/site/manuparra/home/logo_master_ciber.png)

[UGR](http://www.ugr.es) | [DICITS](http://dicits.ugr.es) | [SCI2S](http://sci2s.ugr.es) | [DECSAI](http://decsai.ugr.es)

Manuel J. Parra Royón (manuelparra@decsai.ugr.es) & José. M. Benítez Sánchez (j.m.benitez@decsai.ugr.es)

Table of Contents
=================

   * [What is docker?](#what-is-docker)
      * [What is the difference between Docker and Virtual Machines?](#what-is-the-difference-between-docker-and-virtual-machines)
         * [VIRTUAL MACHINES](#virtual-machines)
         * [CONTAINERS](#containers)
      * [Advantages of Docker](#advantages-of-docker)
   * [Starting](#starting)
   * [First container](#first-container)
      * [A simple web server with NGINX](#a-simple-web-server-with-nginx)
         * [Enter in the nginx container:](#enter-in-the-nginx-container)
         * [Docker ports redirection](#docker-ports-redirection)
   * [ Review of docker commands](#review-of-docker-commands)
      * [Show docker Images](#show-docker-images)
      * [List of launched/running docker containers:](#list-of-launchedrunning-docker-containers)
      * [Download a image of docker container:](#download-a-image-of-docker-container)
      * [Run a container](#run-a-container)
      * [Stop a container](#stop-a-container)
      * [Restarting a container](#restarting-a-container)
      * [Deleting a container or shutdown a container](#deleting-a-container-or-shutdown-a-container)
      * [Execute commands inside running container:](#execute-commands-inside-running-container)
      * [Upload image to docker::hub](#upload-image-to-dockerhub)
      * [Statistics of a container](#statistics-of-a-container)
      * [Logs of a container](#logs-of-a-container)
   * [Basic exercise with containers:](#basic-exercise-with-containers)
   * [References and more information](#references-and-more-information)

# What is docker?

Docker containers wrap a piece of software in a complete filesystem that contains everything needed to run: code, runtime, system tools, system libraries, anything that can be installed on a server. This guarantees that the software will always run the same, regardless of its environment.

## What is the difference between Docker and Virtual Machines?

Containers and virtual machines have similar resource isolation and allocation benefits, but a different architectural approach allows containers to be more portable and efficient.

### VIRTUAL MACHINES

Virtual machines include the application, the necessary binaries and libraries, and an **entire guest operating system**,  all of which can amount to tens of GBs.

![VMsDiff](https://www.docker.com/sites/default/files/WhatIsDocker_2_VMs_0-2_2.png)

### CONTAINERS

Containers include the application and all of its dependencies, but **share the kernel with other containers, running as isolated processes in user space on the host operating system**. Docker containers are not tied to any specific infrastructure: they run on any computer, on any infrastructure, and in any cloud.

![DockersDiff](https://www.docker.com/sites/default/files/WhatIsDocker_3_Containers_2_0.png)

## Advantages of Docker

**Rapid development**

- Stop wasting hours setting up developer environments, spinning up new instances, and making copies of production code to run locally. With Docker, you simply take copies of your live environment and run them on any new endpoint running a Docker engine.

**Work comfortably**

- The isolation capabilities of Docker containers free developers from constraints: they can use the best language and tools for their application services without worrying about causing internal tooling conflicts.

**Forget inconsistences**

- Packaging an application in a container with its configs and dependencies guarantees that the application will always work as designed in any environment: locally, on another machine, in test or production. No more worries about having to install the same configurations into different environments.

**Share your containers**

- Store, distribute, and manage Docker images in Docker Hub with your team. Image updates, changes, and history are automatically shared across your organization.

**Scale**

- Docker allows you to dynamically change your application from adding new capabilities and scaling services, to quickly changing problem areas.

- Docker containers spin up and down in seconds, making it easy to scale application services to satisfy peak customer demand, and then reduce running containers.

- Docker makes it easy to identify issues, isolate the problem container, quickly roll back to make the necessary changes, and then push the updated container into production. Isolation between containers makes these changes less disruptive than in traditional software models.

**Multiplataform**

- Docker runs on Windows, Mac and Linux.

# Starting

Log and connect to our system with:

```
ssh manuparra@.........es
```

First of all, check that you have access to the docker system, try this command:

```
docker run hello-world
```

And it will return a message where it shows that your installation appears to be working correctly and you are allow use it.

# First container

To create a new container in docker, it can be done in two ways:

- on the one hand by doing it by creating a docker file (link) or

- by downloading / using a container that is already created by other users.

Containers already created available to be used are stored in a kind of container market at https://hub.docker.com/. *Virtually anything you think will already be dockerized*.

But you can also build your own container with everything you need. For example a container having your complete application with all its dependencies, mixing i.e. php, mysql, nginx, etc. on the same container or on different containers.

## A simple web server with NGINX

The first thing we need is to download the docker image from nginx, for them we check whether or not the image is in the list of available images:

```
docker images
```

If the image is not found locally, Docker will pull it from Docker Hub and you will use it:

```
docker pull nginx
```

It will download the image of nginx container.

And now you can see if image is on images repository using:

```
docker images
```

```
REPOSITORY                        TAG                 IMAGE ID            CREATED             SIZE
docker.io/nginx                   latest              abf312888d13        12 days ago         181.5 MB
...
```

Run the container, using the next syntax:

```
docker run -d -p <yourport>:<containerport> --name <mynameofcontainer> <container>
```

Options:

``-d Run container in background and print container ID``

``-p Publish a container's port(s) to the host``

``--name Name of your contaniner i.e. 'containerofmanuparra'``

``<container> This is the container that will be executed``

So, we execute:

```
docker run -d -p <yourport>:80 --name testnginx nginx
```

In ``<yourport>`` write your individually assigned port.

To check if your container is runnig and see the status of all your container:

```
docker ps
```

And it returns:

```
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                            NAMES
52ad2efb9fff        nginx               "nginx -g 'daemon off"   12 minutes ago      Up 12 minutes       443/tcp, 0.0.0.0:14000->80/tcp   testnginx
...
```

Where ``container ID`` is the unique ID of your Container. You can use Container ID or NAMES to refer to your container. ``IMAGE`` is the name of the container image. ``PORTS`` show what is the correspondence of the ports between server and docker container.

And now, go to your browser and write:

```
http://docker.ugr.es:<yourport>/
```

![nginxDocker](https://sites.google.com/site/manuparra/home/docker_nginx.png)

### Enter in the nginx container:

```
docker exec -i -t testnginx /bin/bash
```

With this command your are inside of the container and you can modify things, for instance change the main website exposed by NGINX:

``
vim /usr/share/nginx/html/index.html
``

ERROR: command ´´vi´´ is not in container.

***Why***? -> Container has been built with minimal software! ... , so you need to install it:

```
apt-get install vim
```

and try again:

``
vim /usr/share/nginx/html/index.html
``

Edit the file and change something ``
Hello Manuel Parra
``. Save and close and try again in your browser:

```
http://docker.ugr.es:<yourport>/
```

![dockerchanged](https://sites.google.com/site/manuparra/home/docker_changed_nginx.png)

### Docker ports redirection

This diagram shows the port equivalence between the docker containers and the server ports. As you can see, the containers can run on the same ports, as they are independent of each other.

![DockerPorts](https://sites.google.com/site/manuparra/home/portasig.jpg)

In addition each container can export several ports:

```
docker run -d -p 12000:80 -p 12001:81   --name <name> <container>
```

# Review of docker commands

## Show docker Images

With:

```
docker images
```

The default docker images will show all top level images, their repository and tags, and their size, and it will return:

```
REPOSITORY                        TAG                 IMAGE ID            CREATED             SIZE
docker.io/tomcat                  latest              c6cfe59eb987        3 weeks ago         356.9 MB
docker.io/osixia/openldap         1.1.7               7043188ce9b7        4 weeks ago         223 MB
...
```

## List of launched/running docker containers:

``docker ps``

Show all docker containers running and details about execution, ports and status.

```
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                            NAMES
52ad2efb9fff        nginx               "nginx -g 'daemon off"   About an hour ago   Up About an hour    443/tcp, 0.0.0.0:14000->80/tcp   testnginx
```

## Download a image of docker container:

``docker pull``

Download the image container selected. You can go to https://hub.docker.com/ and search for 'dockerized' images from other users.

```
docker pull <nameofcontainer>
```

```
docker pull jetbrainshost/telegram-bot
```

It will download a telegram bot named: jetbrainshost/telegram-bot

## Run a container

``docker run``

Run a docker image. It allows to assign port in/out, name, external folders, etc.

```
docker run -d -p <yourport>:80 --name <name> <container>
```

```
docker run -d -p 8080:80 --name testnginx nginx
```

It will run nginx at 8080 external port ant connect it with internal container port 80. The name of container will be testnginx.

Run a container allows multiple options to improve docker performance:

```
      --add-host value              Add a custom host-to-IP mapping (host:ip) (default [])
  -a, --attach value                Attach to STDIN, STDOUT or STDERR (default [])
      --blkio-weight value          Block IO (relative weight), between 10 and 1000
      --blkio-weight-device value   Block IO weight (relative device weight) (default [])
      --cap-add value               Add Linux capabilities (default [])
      --cap-drop value              Drop Linux capabilities (default [])
      --cgroup-parent string        Optional parent cgroup for the container
      --cidfile string              Write the container ID to the file
      --cpu-percent int             CPU percent (Windows only)
      --cpu-period int              Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int               Limit CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int              CPU shares (relative weight)
      --cpuset-cpus string          CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string          MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                      Run container in background and print container ID
      --detach-keys string          Override the key sequence for detaching a container
      --device value                Add a host device to the container (default [])
      --device-read-bps value       Limit read rate (bytes per second) from a device (default [])
      --device-read-iops value      Limit read rate (IO per second) from a device (default [])
      --device-write-bps value      Limit write rate (bytes per second) to a device (default [])
      --device-write-iops value     Limit write rate (IO per second) to a device (default [])
      --disable-content-trust       Skip image verification (default true)
      --dns value                   Set custom DNS servers (default [])
      --dns-opt value               Set DNS options (default [])
      --dns-search value            Set custom DNS search domains (default [])
      --entrypoint string           Overwrite the default ENTRYPOINT of the image
  -e, --env value                   Set environment variables (default [])
      --env-file value              Read in a file of environment variables (default [])
      --expose value                Expose a port or a range of ports (default [])
      --group-add value             Add additional groups to join (default [])
      --health-cmd string           Command to run to check health
      --health-interval duration    Time between running the check
      --health-retries int          Consecutive failures needed to report unhealthy
      --health-timeout duration     Maximum time to allow one check to run
      --help                        Print usage
  -h, --hostname string             Container host name
  -i, --interactive                 Keep STDIN open even if not attached
      --io-maxbandwidth string      Maximum IO bandwidth limit for the system drive (Windows only)
                                    (Windows only). The format is `<number><unit>`.
                                    Unit is optional and can be `b` (bytes per second),
                                    `k` (kilobytes per second), `m` (megabytes per second),
                                    or `g` (gigabytes per second). If you omit the unit,
                                    the system uses bytes per second.
                                    --io-maxbandwidth and --io-maxiops are mutually exclusive options.
      --io-maxiops uint             Maximum IOps limit for the system drive (Windows only)
      --ip string                   Container IPv4 address (e.g. 172.30.100.104)
      --ip6 string                  Container IPv6 address (e.g. 2001:db8::33)
      --ipc string                  IPC namespace to use
      --isolation string            Container isolation technology
      --kernel-memory string        Kernel memory limit
  -l, --label value                 Set meta data on a container (default [])
      --label-file value            Read in a line delimited file of labels (default [])
      --link value                  Add link to another container (default [])
      --link-local-ip value         Container IPv4/IPv6 link-local addresses (default [])
      --log-driver string           Logging driver for the container
      --log-opt value               Log driver options (default [])
      --mac-address string          Container MAC address (e.g. 92:d0:c6:0a:29:33)
  -m, --memory string               Memory limit
      --memory-reservation string   Memory soft limit
      --memory-swap string          Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int       Tune container memory swappiness (0 to 100) (default -1).
      --name string                 Assign a name to the container
      --network-alias value         Add network-scoped alias for the container (default [])
      --network string              Connect a container to a network
                                    'bridge': create a network stack on the default Docker bridge
                                    'none': no networking
                                    'container:<name|id>': reuse another container's network stack
                                    'host': use the Docker host network stack
                                    '<network-name>|<network-id>': connect to a user-defined network
      --no-healthcheck              Disable any container-specified HEALTHCHECK
      --oom-kill-disable            Disable OOM Killer
      --oom-score-adj int           Tune host's OOM preferences (-1000 to 1000)
      --pid string                  PID namespace to use
      --pids-limit int              Tune container pids limit (set -1 for unlimited)
      --privileged                  Give extended privileges to this container
  -p, --publish value               Publish a container's port(s) to the host (default [])
  -P, --publish-all                 Publish all exposed ports to random ports
      --read-only                   Mount the container's root filesystem as read only
      --restart string              Restart policy to apply when a container exits (default "no")
                                    Possible values are : no, on-failure[:max-retry], always, unless-stopped
      --rm                          Automatically remove the container when it exits
      --runtime string              Runtime to use for this container
      --security-opt value          Security Options (default [])
      --shm-size string             Size of /dev/shm, default value is 64MB.
                                    The format is `<number><unit>`. `number` must be greater than `0`.
                                    Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes),
                                    or `g` (gigabytes). If you omit the unit, the system uses bytes.
      --sig-proxy                   Proxy received signals to the process (default true)
      --stop-signal string          Signal to stop a container, SIGTERM by default (default "SIGTERM")
      --storage-opt value           Storage driver options for the container (default [])
      --sysctl value                Sysctl options (default map[])
      --tmpfs value                 Mount a tmpfs directory (default [])
  -t, --tty                         Allocate a pseudo-TTY
      --ulimit value                Ulimit options (default [])
  -u, --user string                 Username or UID (format: <name|uid>[:<group|gid>])
      --userns string               User namespace to use
                                    'host': Use the Docker host user namespace
                                    '': Use the Docker daemon user namespace specified by `--userns-remap` option.
      --uts string                  UTS namespace to use
  -v, --volume value                Bind mount a volume (default []). The format
                                    is `[host-src:]container-dest[:<options>]`.
                                    The comma-delimited `options` are [rw|ro],
                                    [z|Z], [[r]shared|[r]slave|[r]private], and
                                    [nocopy]. The 'host-src' is an absolute path
                                    or a name value.
      --volume-driver string        Optional volume driver for the container
      --volumes-from value          Mount volumes from the specified container(s) (default [])
  -w, --workdir string              Working directory inside the container
```

We comment on several of the most relevant options to optimize the operation of the container: cpu-limit, memory-limit, external storage, ...

## Stop a container

You can stop a container using

```
docker stop <nameofcontainer or container ID>
```

```
docker stop testnginx
```

## Restarting a container

You can restart a container using:

```
docker restart <nameofcontainer or container ID>
```

```
docker restart testnginx
```

## Deleting a container or shutdown a container

If the lifecycle of your container has finished and you want remove it:

```
docker rm <nameofcontainer or container ID>
```

```
docker rm testnginx
```

If the container is running, first try ``stop `` and then ``rm``, but if you cant stop it, force remove:

```
docker rm --force <nameofcontainer or container ID>
```

```
docker rm --force testnginx
```

## Execute commands inside running container:

If you need modify files or add something inside container:

```
docker exec -i -t <nameofcontainer or ID> /bin/bash
```

```
docker exec -i -t testnginx /bin/bash
```

It will open a shell (bash) into the container to manage internal container.

## Upload image to docker::hub

If you have created a container with an application or service already prepared you can upload it to the application repository of DockerHub.

```
docker push manuparra/myapp_dockerized
```

Previously you must have registered on the dockerhub platform .

## Statistics of a container

Display a live stream of container resource usage statistics. It is very useful to know what is the performance of you services or application deployed with docker.

```
docker stats testnginx
```

```
CONTAINER           CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O
testnginx           0.00%               75.51 MB / 67.32 GB   0.11%               16.53 MB / 393 kB   94.21 kB / 0 B
```

## Logs of a container

To view the logs for a container it's as simple as running just one command:

```
docker logs testnginx
```

```
90.170.152.124 - - [11/Dec/2016:12:03:08 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36" "-"
```

Nginx logs

# Basic exercise with containers:

1. Create a docker container (A) with APACHE, SSL and PHP5
	- What is the SSL port?
	- How to redirect SSL port to your assigned port?

2. Create a docker container (B) with MySQL
3. Create a webpage in web server A that connect to MySQL in container B

Remember:

* Use your assigned port

# References and more information

- Definition of docker: https://www.docker.com/what-docker
- Docker Hub: https://hub.docker.com/
- First steps with Docker: https://docs.docker.com/engine/getstarted/
- Running `Hello World`: https://docs.docker.com/engine/tutorials/dockerizing/
- Free EBook about Docker:  https://goto.docker.com/docker-for-the-virtualization-admin.html


text:
package org.sagebionetworks.search;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.simpleHttpClient.SimpleHttpClient;
import org.sagebionetworks.simpleHttpClient.SimpleHttpRequest;
import org.sagebionetworks.simpleHttpClient.SimpleHttpResponse;
import org.springframework.test.util.ReflectionTestUtils;

public class CloudSearchClientTest {

	@Mock
	SimpleHttpClient mockHttpClient;
	@Mock
	SimpleHttpResponse mockResponse;
	CloudSearchClient cloudSearchClient;

	@Before
	public void before() {
		MockitoAnnotations.initMocks(this);
		cloudSearchClient = new CloudSearchClient("https://svc.endpoint.com", "https://doc.endpoint.com");
		ReflectionTestUtils.setField(cloudSearchClient, "httpClient", mockHttpClient);
	}

	@Test
	public void testPLFM2968NoError() throws Exception {
		when(mockResponse.getStatusCode()).thenReturn(200);
		when(mockResponse.getContent()).thenReturn("s");
		when(mockHttpClient.get(any(SimpleHttpRequest.class))).thenReturn(mockResponse);
		assertEquals(mockResponse.getContent(), cloudSearchClient.performSearch("aQuery"));
		verify(mockHttpClient).get(any(SimpleHttpRequest.class));
	}

	@Test
	public void testPLFM2968NoRecover() throws Exception {
		when(mockResponse.getStatusCode()).thenReturn(507);
		when(mockHttpClient.get(any(SimpleHttpRequest.class))).thenReturn(mockResponse);
		try {
			cloudSearchClient.performSearch("aQuery");
		} catch (CloudSearchClientException e) {
			assertEquals(507, e.getStatusCode());
		} finally {
			verify(mockHttpClient, times(6)).get(any(SimpleHttpRequest.class));
		}
	}

	@Test
	public void testPLFM3777() throws Exception {
		when(mockResponse.getStatusCode()).thenReturn(504);
		when(mockHttpClient.get(any(SimpleHttpRequest.class))).thenReturn(mockResponse);
		try {
			cloudSearchClient.performSearch("aQuery");
		} catch (CloudSearchClientException e) {
			assertEquals(504, e.getStatusCode());
		} finally {
			verify(mockHttpClient).get(any(SimpleHttpRequest.class));
		}
	}

}