text:
import abc
import collections
import os
import re
import shutil
import socket
import sys
import uuid

import netaddr
from oslo.config import cfg
import six

from neutron.agent.linux import ip_lib
from neutron.agent.linux import utils
from neutron.common import constants
from neutron.common import exceptions
from neutron.openstack.common import importutils
from neutron.openstack.common import jsonutils
from neutron.openstack.common import log as logging
from neutron.openstack.common import uuidutils

LOG = logging.getLogger(__name__)

OPTS = [
    cfg.StrOpt('dhcp_confs',
               default='$state_path/dhcp',
               help=_('Location to store DHCP server config files')),
    cfg.StrOpt('dhcp_domain',
               default='openstacklocal',
               help=_('Domain to use for building the hostnames')),
    cfg.StrOpt('dnsmasq_config_file',
               default='',
               help=_('Override the default dnsmasq settings with this file')),
    cfg.ListOpt('dnsmasq_dns_servers',
                help=_('Comma-separated list of the DNS servers which will be '
                       'used as forwarders.'),
                deprecated_name='dnsmasq_dns_server'),
    cfg.BoolOpt('dhcp_delete_namespaces', default=False,
                help=_("Delete namespace after removing a dhcp server.")),
    cfg.IntOpt(
        'dnsmasq_lease_max',
        default=(2 ** 24),
        help=_('Limit number of leases to prevent a denial-of-service.')),
]

IPV4 = 4
IPV6 = 6
UDP = 'udp'
TCP = 'tcp'
DNS_PORT = 53
DHCPV4_PORT = 67
DHCPV6_PORT = 547
METADATA_DEFAULT_PREFIX = 16
METADATA_DEFAULT_IP = '169.254.169.254'
METADATA_DEFAULT_CIDR = '%s/%d' % (METADATA_DEFAULT_IP,
                                   METADATA_DEFAULT_PREFIX)
METADATA_PORT = 80
WIN2k3_STATIC_DNS = 249
NS_PREFIX = 'qdhcp-'

class DictModel(object):
    """Convert dict into an object that provides attribute access to values."""
    def __init__(self, d):
        for key, value in d.iteritems():
            if isinstance(value, list):
                value = [DictModel(item) if isinstance(item, dict) else item
                         for item in value]
            elif isinstance(value, dict):
                value = DictModel(value)

            setattr(self, key, value)

class NetModel(DictModel):

    def __init__(self, use_namespaces, d):
        super(NetModel, self).__init__(d)

        self._ns_name = (use_namespaces and
                         "%s%s" % (NS_PREFIX, self.id) or None)

    @property
    def namespace(self):
        return self._ns_name

@six.add_metaclass(abc.ABCMeta)
class DhcpBase(object):

    def __init__(self, conf, network, root_helper='sudo',
                 version=None, plugin=None):
        self.conf = conf
        self.network = network
        self.root_helper = root_helper
        self.device_manager = DeviceManager(self.conf,
                                            self.root_helper, plugin)
        self.version = version

    @abc.abstractmethod
    def enable(self):
        """Enables DHCP for this network."""

    @abc.abstractmethod
    def disable(self, retain_port=False):
        """Disable dhcp for this network."""

    def restart(self):
        """Restart the dhcp service for the network."""
        self.disable(retain_port=True)
        self.enable()
        self.device_manager.update(self.network)

    @abc.abstractproperty
    def active(self):
        """Boolean representing the running state of the DHCP server."""

    @abc.abstractmethod
    def reload_allocations(self):
        """Force the DHCP server to reload the assignment database."""

    @classmethod
    def existing_dhcp_networks(cls, conf, root_helper):
        """Return a list of existing networks ids that we have configs for."""

        raise NotImplementedError

    @classmethod
    def check_version(cls):
        """Execute version checks on DHCP server."""

        raise NotImplementedError

class DhcpLocalProcess(DhcpBase):
    PORTS = []

    def _enable_dhcp(self):
        """check if there is a subnet within the network with dhcp enabled."""
        for subnet in self.network.subnets:
            if subnet.enable_dhcp:
                return True
        return False

    def enable(self):
        """Enables DHCP for this network by spawning a local process."""
        interface_name = self.device_manager.setup(self.network,
                                                   reuse_existing=True)
        if self.active:
            self.restart()
        elif self._enable_dhcp():
            self.interface_name = interface_name
            self.spawn_process()

    def disable(self, retain_port=False):
        """Disable DHCP for this network by killing the local process."""
        pid = self.pid

        if self.active:
            cmd = ['kill', '-9', pid]
            utils.execute(cmd, self.root_helper)
            if not retain_port:
                self.device_manager.destroy(self.network, self.interface_name)

        elif pid:
            LOG.debug(_('DHCP for %(net_id)s pid %(pid)d is stale, ignoring '
                        'command'), {'net_id': self.network.id, 'pid': pid})
        else:
            LOG.debug(_('No DHCP started for %s'), self.network.id)

        self._remove_config_files()

        if not retain_port:
            if self.conf.dhcp_delete_namespaces and self.network.namespace:
                ns_ip = ip_lib.IPWrapper(self.root_helper,
                                         self.network.namespace)
                try:
                    ns_ip.netns.delete(self.network.namespace)
                except RuntimeError:
                    msg = _('Failed trying to delete namespace: %s')
                    LOG.exception(msg, self.network.namespace)

    def _remove_config_files(self):
        confs_dir = os.path.abspath(os.path.normpath(self.conf.dhcp_confs))
        conf_dir = os.path.join(confs_dir, self.network.id)
        shutil.rmtree(conf_dir, ignore_errors=True)

    def get_conf_file_name(self, kind, ensure_conf_dir=False):
        """Returns the file name for a given kind of config file."""
        confs_dir = os.path.abspath(os.path.normpath(self.conf.dhcp_confs))
        conf_dir = os.path.join(confs_dir, self.network.id)
        if ensure_conf_dir:
            if not os.path.isdir(conf_dir):
                os.makedirs(conf_dir, 0o755)

        return os.path.join(conf_dir, kind)

    def _get_value_from_conf_file(self, kind, converter=None):
        """A helper function to read a value from one of the state files."""
        file_name = self.get_conf_file_name(kind)
        msg = _('Error while reading %s')

        try:
            with open(file_name, 'r') as f:
                try:
                    return converter and converter(f.read()) or f.read()
                except ValueError:
                    msg = _('Unable to convert value in %s')
        except IOError:
            msg = _('Unable to access %s')

        LOG.debug(msg % file_name)
        return None

    @property
    def pid(self):
        """Last known pid for the DHCP process spawned for this network."""
        return self._get_value_from_conf_file('pid', int)

    @property
    def active(self):
        pid = self.pid
        if pid is None:
            return False

        cmdline = '/proc/%s/cmdline' % pid
        try:
            with open(cmdline, "r") as f:
                return self.network.id in f.readline()
        except IOError:
            return False

    @property
    def interface_name(self):
        return self._get_value_from_conf_file('interface')

    @interface_name.setter
    def interface_name(self, value):
        interface_file_path = self.get_conf_file_name('interface',
                                                      ensure_conf_dir=True)
        utils.replace_file(interface_file_path, value)

    @abc.abstractmethod
    def spawn_process(self):
        pass

class Dnsmasq(DhcpLocalProcess):
    # The ports that need to be opened when security policies are active
    # on the Neutron port used for DHCP.  These are provided as a convenience
    # for users of this class.
    PORTS = {IPV4: [(UDP, DNS_PORT), (TCP, DNS_PORT), (UDP, DHCPV4_PORT)],
             IPV6: [(UDP, DNS_PORT), (TCP, DNS_PORT), (UDP, DHCPV6_PORT)],
             }

    _TAG_PREFIX = 'tag%d'

    NEUTRON_NETWORK_ID_KEY = 'NEUTRON_NETWORK_ID'
    NEUTRON_RELAY_SOCKET_PATH_KEY = 'NEUTRON_RELAY_SOCKET_PATH'
    MINIMUM_VERSION = 2.59

    @classmethod
    def check_version(cls):
        ver = 0
        try:
            cmd = ['dnsmasq', '--version']
            out = utils.execute(cmd)
            ver = re.findall("\d+.\d+", out)[0]
            is_valid_version = float(ver) >= cls.MINIMUM_VERSION
            if not is_valid_version:
                LOG.warning(_('FAILED VERSION REQUIREMENT FOR DNSMASQ. '
                              'DHCP AGENT MAY NOT RUN CORRECTLY! '
                              'Please ensure that its version is %s '
                              'or above!'), cls.MINIMUM_VERSION)
        except (OSError, RuntimeError, IndexError, ValueError):
            LOG.warning(_('Unable to determine dnsmasq version. '
                          'Please ensure that its version is %s '
                          'or above!'), cls.MINIMUM_VERSION)
        return float(ver)

    @classmethod
    def existing_dhcp_networks(cls, conf, root_helper):
        """Return a list of existing networks ids that we have configs for."""

        confs_dir = os.path.abspath(os.path.normpath(conf.dhcp_confs))

        return [
            c for c in os.listdir(confs_dir)
            if uuidutils.is_uuid_like(c)
        ]

    def spawn_process(self):
        """Spawns a Dnsmasq process for the network."""
        env = {
            self.NEUTRON_NETWORK_ID_KEY: self.network.id,
        }

        cmd = [
            'dnsmasq',
            '--no-hosts',
            '--no-resolv',
            '--strict-order',
            '--bind-interfaces',
            '--interface=%s' % self.interface_name,
            '--except-interface=lo',
            '--pid-file=%s' % self.get_conf_file_name(
                'pid', ensure_conf_dir=True),
            '--dhcp-hostsfile=%s' % self._output_hosts_file(),
            '--dhcp-optsfile=%s' % self._output_opts_file(),
            '--leasefile-ro',
        ]

        possible_leases = 0
        for i, subnet in enumerate(self.network.subnets):
            # if a subnet is specified to have dhcp disabled
            if not subnet.enable_dhcp:
                continue
            if subnet.ip_version == 4:
                mode = 'static'
            else:
                # TODO(mark): how do we indicate other options
                # ra-only, slaac, ra-nameservers, and ra-stateless.
                mode = 'static'
            if self.version >= self.MINIMUM_VERSION:
                set_tag = 'set:'
            else:
                set_tag = ''

            cidr = netaddr.IPNetwork(subnet.cidr)

            cmd.append('--dhcp-range=%s%s,%s,%s,%ss' %
                       (set_tag, self._TAG_PREFIX % i,
                        cidr.network,
                        mode,
                        self.conf.dhcp_lease_duration))
            possible_leases += cidr.size

        # Cap the limit because creating lots of subnets can inflate
        # this possible lease cap.
        cmd.append('--dhcp-lease-max=%d' %
                   min(possible_leases, self.conf.dnsmasq_lease_max))

        cmd.append('--conf-file=%s' % self.conf.dnsmasq_config_file)
        if self.conf.dnsmasq_dns_servers:
            cmd.extend(
                '--server=%s' % server
                for server in self.conf.dnsmasq_dns_servers)

        if self.conf.dhcp_domain:
            cmd.append('--domain=%s' % self.conf.dhcp_domain)

        ip_wrapper = ip_lib.IPWrapper(self.root_helper,
                                      self.network.namespace)
        ip_wrapper.netns.execute(cmd, addl_env=env)

    def _release_lease(self, mac_address, ip):
        """Release a DHCP lease."""
        cmd = ['dhcp_release', self.interface_name, ip, mac_address]
        ip_wrapper = ip_lib.IPWrapper(self.root_helper,
                                      self.network.namespace)
        ip_wrapper.netns.execute(cmd)

    def reload_allocations(self):
        """Rebuild the dnsmasq config and signal the dnsmasq to reload."""

        # If all subnets turn off dhcp, kill the process.
        if not self._enable_dhcp():
            self.disable()
            LOG.debug(_('Killing dhcpmasq for network since all subnets have '
                        'turned off DHCP: %s'), self.network.id)
            return

        self._release_unused_leases()
        self._output_hosts_file()
        self._output_opts_file()
        if self.active:
            cmd = ['kill', '-HUP', self.pid]
            utils.execute(cmd, self.root_helper)
        else:
            LOG.debug(_('Pid %d is stale, relaunching dnsmasq'), self.pid)
        LOG.debug(_('Reloading allocations for network: %s'), self.network.id)
        self.device_manager.update(self.network)

    def _output_hosts_file(self):
        """Writes a dnsmasq compatible hosts file."""
        r = re.compile('[:.]')
        buf = six.StringIO()
        filename = self.get_conf_file_name('host')

        LOG.debug(_('Building host file: %s'), filename)

        for port in self.network.ports:
            for alloc in port.fixed_ips:
                name = 'host-%s.%s' % (r.sub('-', alloc.ip_address),
                                       self.conf.dhcp_domain)
                set_tag = ''
                # (dzyu) Check if it is legal ipv6 address, if so, need wrap
                # it with '[]' to let dnsmasq to distinguish MAC address from
                # IPv6 address.
                ip_address = alloc.ip_address
                if netaddr.valid_ipv6(ip_address):
                    ip_address = '[%s]' % ip_address

                LOG.debug(_('Adding %(mac)s : %(name)s : %(ip)s'),
                          {"mac": port.mac_address, "name": name,
                           "ip": ip_address})

                if getattr(port, 'extra_dhcp_opts', False):
                    if self.version >= self.MINIMUM_VERSION:
                        set_tag = 'set:'

                    buf.write('%s,%s,%s,%s%s\n' %
                              (port.mac_address, name, ip_address,
                               set_tag, port.id))
                else:
                    buf.write('%s,%s,%s\n' %
                              (port.mac_address, name, ip_address))

        utils.replace_file(filename, buf.getvalue())
        LOG.debug(_('Done building host file %s'), filename)
        return filename

    def _read_hosts_file_leases(self, filename):
        leases = set()
        if os.path.exists(filename):
            with open(filename) as f:
                for l in f.readlines():
                    host = l.strip().split(',')
                    leases.add((host[2], host[0]))
        return leases

    def _release_unused_leases(self):
        filename = self.get_conf_file_name('host')
        old_leases = self._read_hosts_file_leases(filename)

        new_leases = set()
        for port in self.network.ports:
            for alloc in port.fixed_ips:
                new_leases.add((alloc.ip_address, port.mac_address))

        for ip, mac in old_leases - new_leases:
            self._release_lease(mac, ip)

    def _output_opts_file(self):
        """Write a dnsmasq compatible options file."""

        if self.conf.enable_isolated_metadata:
            subnet_to_interface_ip = self._make_subnet_interface_ip_map()

        options = []

        dhcp_ips = collections.defaultdict(list)
        subnet_idx_map = {}
        for i, subnet in enumerate(self.network.subnets):
            if not subnet.enable_dhcp:
                continue
            if subnet.dns_nameservers:
                options.append(
                    self._format_option(i, 'dns-server',
                                        ','.join(subnet.dns_nameservers)))
            else:
                # use the dnsmasq ip as nameservers only if there is no
                # dns-server submitted by the server
                subnet_idx_map[subnet.id] = i

            gateway = subnet.gateway_ip
            host_routes = []
            for hr in subnet.host_routes:
                if hr.destination == "0.0.0.0/0":
                    gateway = hr.nexthop
                else:
                    host_routes.append("%s,%s" % (hr.destination, hr.nexthop))

            # Add host routes for isolated network segments

            if self._enable_metadata(subnet):
                subnet_dhcp_ip = subnet_to_interface_ip[subnet.id]
                host_routes.append(
                    '%s/32,%s' % (METADATA_DEFAULT_IP, subnet_dhcp_ip)
                )

            if host_routes:
                options.append(
                    self._format_option(i, 'classless-static-route',
                                        ','.join(host_routes)))
                options.append(
                    self._format_option(i, WIN2k3_STATIC_DNS,
                                        ','.join(host_routes)))

            if subnet.ip_version == 4:
                if gateway:
                    options.append(self._format_option(i, 'router', gateway))
                else:
                    options.append(self._format_option(i, 'router'))

        for port in self.network.ports:
            if getattr(port, 'extra_dhcp_opts', False):
                options.extend(
                    self._format_option(port.id, opt.opt_name, opt.opt_value)
                    for opt in port.extra_dhcp_opts)

            # provides all dnsmasq ip as dns-server if there is more than
            # one dnsmasq for a subnet and there is no dns-server submitted
            # by the server
            if port.device_owner == constants.DEVICE_OWNER_DHCP:
                for ip in port.fixed_ips:
                    i = subnet_idx_map.get(ip.subnet_id)
                    if i is None:
                        continue
                    dhcp_ips[i].append(ip.ip_address)

        for i, ips in dhcp_ips.items():
            if len(ips) > 1:
                options.append(self._format_option(i,
                                                   'dns-server',
                                                   ','.join(ips)))

        name = self.get_conf_file_name('opts')
        utils.replace_file(name, '\n'.join(options))
        return name

    def _make_subnet_interface_ip_map(self):
        ip_dev = ip_lib.IPDevice(
            self.interface_name,
            self.root_helper,
            self.network.namespace
        )

        subnet_lookup = dict(
            (netaddr.IPNetwork(subnet.cidr), subnet.id)
            for subnet in self.network.subnets
        )

        retval = {}

        for addr in ip_dev.addr.list():
            ip_net = netaddr.IPNetwork(addr['cidr'])

            if ip_net in subnet_lookup:
                retval[subnet_lookup[ip_net]] = addr['cidr'].split('/')[0]

        return retval

    def _format_option(self, tag, option, *args):
        """Format DHCP option by option name or code."""
        if self.version >= self.MINIMUM_VERSION:
            set_tag = 'tag:'
        else:
            set_tag = ''

        option = str(option)

        if isinstance(tag, int):
            tag = self._TAG_PREFIX % tag

        if not option.isdigit():
            option = 'option:%s' % option

        return ','.join((set_tag + tag, '%s' % option) + args)

    def _enable_metadata(self, subnet):
        '''Determine if the metadata route will be pushed to hosts on subnet.

        If subnet has a Neutron router attached, we want the hosts to get
        metadata from the router's proxy via their default route instead.
        '''
        if self.conf.enable_isolated_metadata and subnet.ip_version == 4:
            if subnet.gateway_ip is None:
                return True
            else:
                for port in self.network.ports:
                    if port.device_owner == constants.DEVICE_OWNER_ROUTER_INTF:
                        for alloc in port.fixed_ips:
                            if alloc.subnet_id == subnet.id:
                                return False
                return True
        else:
            return False

    @classmethod
    def lease_update(cls):
        network_id = os.environ.get(cls.NEUTRON_NETWORK_ID_KEY)
        dhcp_relay_socket = os.environ.get(cls.NEUTRON_RELAY_SOCKET_PATH_KEY)

        action = sys.argv[1]
        if action not in ('add', 'del', 'old'):
            sys.exit()

        mac_address = sys.argv[2]
        ip_address = sys.argv[3]

        if action == 'del':
            lease_remaining = 0
        else:
            lease_remaining = int(os.environ.get('DNSMASQ_TIME_REMAINING', 0))

        data = dict(network_id=network_id, mac_address=mac_address,
                    ip_address=ip_address, lease_remaining=lease_remaining)

        if os.path.exists(dhcp_relay_socket):
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.connect(dhcp_relay_socket)
            sock.send(jsonutils.dumps(data))
            sock.close()

class DeviceManager(object):

    def __init__(self, conf, root_helper, plugin):
        self.conf = conf
        self.root_helper = root_helper
        self.plugin = plugin
        if not conf.interface_driver:
            msg = _('An interface driver must be specified')
            LOG.error(msg)
            raise SystemExit(msg)
        try:
            self.driver = importutils.import_object(
                conf.interface_driver, conf)
        except Exception as e:
            msg = (_("Error importing interface driver '%(driver)s': "
                   "%(inner)s") % {'driver': conf.interface_driver,
                                   'inner': e})
            LOG.error(msg)
            raise SystemExit(msg)

    def get_interface_name(self, network, port):
        """Return interface(device) name for use by the DHCP process."""
        return self.driver.get_device_name(port)

    def get_device_id(self, network):
        """Return a unique DHCP device ID for this host on the network."""
        # There could be more than one dhcp server per network, so create
        # a device id that combines host and network ids

        host_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, socket.gethostname())
        return 'dhcp%s-%s' % (host_uuid, network.id)

    def _get_device(self, network, port):
        """Return DHCP ip_lib device for this host on the network."""
        interface_name = self.get_interface_name(network, port)
        return ip_lib.IPDevice(interface_name,
                               self.root_helper,
                               network.namespace)

    def _set_default_route(self, network, port):
        """Sets the default gateway for this dhcp namespace.

        This method is idempotent and will only adjust the route if adjusting
        it would change it from what it already is.  This makes it safe to call
        and avoids unnecessary perturbation of the system.
        """
        device = self._get_device(network, port)
        gateway = device.route.get_gateway()
        if gateway:
            gateway = gateway['gateway']

        for subnet in network.subnets:
            skip_subnet = (
                subnet.ip_version != 4
                or not subnet.enable_dhcp
                or subnet.gateway_ip is None)

            if skip_subnet:
                continue

            if gateway != subnet.gateway_ip:
                m = _('Setting gateway for dhcp netns on net %(n)s to %(ip)s')
                LOG.debug(m, {'n': network.id, 'ip': subnet.gateway_ip})

                device.route.add_gateway(subnet.gateway_ip)

            return

        # No subnets on the network have a valid gateway.  Clean it up to avoid
        # confusion from seeing an invalid gateway here.
        if gateway is not None:
            msg = _('Removing gateway for dhcp netns on net %s')
            LOG.debug(msg, network.id)

            device.route.delete_gateway(gateway)

    def setup_dhcp_port(self, network):
        """Create/update DHCP port for the host if needed and return port."""

        device_id = self.get_device_id(network)
        subnets = {}
        dhcp_enabled_subnet_ids = []
        for subnet in network.subnets:
            if subnet.enable_dhcp:
                dhcp_enabled_subnet_ids.append(subnet.id)
                subnets[subnet.id] = subnet

        dhcp_port = None
        for port in network.ports:
            port_device_id = getattr(port, 'device_id', None)
            if port_device_id == device_id:
                port_fixed_ips = []
                for fixed_ip in port.fixed_ips:
                    port_fixed_ips.append({'subnet_id': fixed_ip.subnet_id,
                                           'ip_address': fixed_ip.ip_address})
                    if fixed_ip.subnet_id in dhcp_enabled_subnet_ids:
                        dhcp_enabled_subnet_ids.remove(fixed_ip.subnet_id)

                # If there are dhcp_enabled_subnet_ids here that means that
                # we need to add those to the port and call update.
                if dhcp_enabled_subnet_ids:
                    port_fixed_ips.extend(
                        [dict(subnet_id=s) for s in dhcp_enabled_subnet_ids])
                    dhcp_port = self.plugin.update_dhcp_port(
                        port.id, {'port': {'fixed_ips': port_fixed_ips}})
                    if not dhcp_port:
                        raise exceptions.Conflict()
                else:
                    dhcp_port = port
                # break since we found port that matches device_id
                break

        # DHCP port has not yet been created.
        if dhcp_port is None:
            LOG.debug(_('DHCP port %(device_id)s on network %(network_id)s'
                        ' does not yet exist.'), {'device_id': device_id,
                                                  'network_id': network.id})
            port_dict = dict(
                name='',
                admin_state_up=True,
                device_id=device_id,
                network_id=network.id,
                tenant_id=network.tenant_id,
                fixed_ips=[dict(subnet_id=s) for s in dhcp_enabled_subnet_ids])
            dhcp_port = self.plugin.create_dhcp_port({'port': port_dict})

        if not dhcp_port:
            raise exceptions.Conflict()

        # Convert subnet_id to subnet dict
        fixed_ips = [dict(subnet_id=fixed_ip.subnet_id,
                          ip_address=fixed_ip.ip_address,
                          subnet=subnets[fixed_ip.subnet_id])
                     for fixed_ip in dhcp_port.fixed_ips]

        ips = [DictModel(item) if isinstance(item, dict) else item
               for item in fixed_ips]
        dhcp_port.fixed_ips = ips

        return dhcp_port

    def setup(self, network, reuse_existing=False):
        """Create and initialize a device for network's DHCP on this host."""
        port = self.setup_dhcp_port(network)
        interface_name = self.get_interface_name(network, port)

        if ip_lib.device_exists(interface_name,
                                self.root_helper,
                                network.namespace):
            if not reuse_existing:
                raise exceptions.PreexistingDeviceFailure(
                    dev_name=interface_name)

            LOG.debug(_('Reusing existing device: %s.'), interface_name)
        else:
            self.driver.plug(network.id,
                             port.id,
                             interface_name,
                             port.mac_address,
                             namespace=network.namespace)
        ip_cidrs = []
        for fixed_ip in port.fixed_ips:
            subnet = fixed_ip.subnet
            net = netaddr.IPNetwork(subnet.cidr)
            ip_cidr = '%s/%s' % (fixed_ip.ip_address, net.prefixlen)
            ip_cidrs.append(ip_cidr)

        if (self.conf.enable_isolated_metadata and
            self.conf.use_namespaces):
            ip_cidrs.append(METADATA_DEFAULT_CIDR)

        self.driver.init_l3(interface_name, ip_cidrs,
                            namespace=network.namespace)

        # ensure that the dhcp interface is first in the list
        if network.namespace is None:
            device = ip_lib.IPDevice(interface_name,
                                     self.root_helper)
            device.route.pullup_route(interface_name)

        if self.conf.use_namespaces:
            self._set_default_route(network, port)

        return interface_name

    def update(self, network):
        """Update device settings for the network's DHCP on this host."""
        if self.conf.use_namespaces:
            device_id = self.get_device_id(network)
            port = self.plugin.get_dhcp_port(network.id, device_id)
            if not port:
                raise exceptions.NetworkNotFound(net_id=network.id)
            self._set_default_route(network, port)

    def destroy(self, network, device_name):
        """Destroy the device used for the network's DHCP on this host."""
        self.driver.unplug(device_name, namespace=network.namespace)

        self.plugin.release_dhcp_port(network.id,
                                      self.get_device_id(network))


text:
package org.pac4j.ldap.profile;

import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.ProfileHelper;

/**
 * This class tests the {@link ProfileHelper} class for the {@link LdapProfile}.
 *
 * @author Jerome Leleu
 * @since 1.8.0
 */
public final class TestLdapProfileHelper extends org.pac4j.core.profile.TestProfileHelper {

    @Override
    protected Class<? extends CommonProfile> getProfileClass() {
        return LdapProfile.class;
    }

    @Override
    protected String getProfileType() {
        return "LdapProfile";
    }

    @Override
    protected String getAttributeName() {
        return "whatever";
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
CamemBERT: a Tasty French Language Model
"""

from fairseq.models import register_model

from .hub_interface import RobertaHubInterface
from .model import RobertaModel

@register_model("camembert")
class CamembertModel(RobertaModel):
    @classmethod
    def hub_models(cls):
        return {
            "camembert": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz",
            "camembert.v0": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz",
            "camembert-base": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz",
            "camembert-large": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-large.tar.gz",
            "camembert-base-ccnet": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-ccnet.tar.gz",
            "camembert-base-ccnet-4gb": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-ccnet-4gb.tar.gz",
            "camembert-base-wikipedia-4gb": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-wikipedia-4gb.tar.gz",
            "camembert-base-oscar-4gb": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-oscar-4gb.tar.gz",
        }

    @classmethod
    def from_pretrained(
        cls,
        model_name_or_path,
        checkpoint_file="model.pt",
        data_name_or_path=".",
        bpe="sentencepiece",
        **kwargs
    ):
        from fairseq import hub_utils

        x = hub_utils.from_pretrained(
            model_name_or_path,
            checkpoint_file,
            data_name_or_path,
            archive_map=cls.hub_models(),
            bpe=bpe,
            load_checkpoint_heads=True,
            **kwargs,
        )
        return RobertaHubInterface(x["args"], x["task"], x["models"][0])


text:
"""Annotates the resource types with extra information."""
import collections
import httplib

from apitools.base.protorpclite import messages

from googlecloudsdk.api_lib.compute import instance_utils
from googlecloudsdk.api_lib.compute import path_simplifier
from googlecloudsdk.api_lib.compute import property_selector

def _FirewallRulesToCell(firewall):
  """Returns a compact string describing the firewall rules."""
  rules = []
  for allowed in firewall.get('allowed', []):
    protocol = allowed.get('IPProtocol')
    if not protocol:
      continue

    port_ranges = allowed.get('ports')
    if port_ranges:
      for port_range in port_ranges:
        rules.append('{0}:{1}'.format(protocol, port_range))
    else:
      rules.append(protocol)

  return ','.join(rules)

def _TargetPoolHealthChecksToCell(target_pool):
  """Comma-joins the names of health checks of the given target pool."""
  return ','.join(path_simplifier.Name(check) for check in
                  target_pool.get('healthChecks', []))

def _FirewallSourceRangesToCell(firewall):
  """Comma-joins the source ranges of the given firewall rule."""
  return ','.join(firewall.get('sourceRanges', []))

def _FirewallSourceTagsToCell(firewall):
  """Comma-joins the source tags of the given firewall rule."""
  return ','.join(firewall.get('sourceTags', []))

def _FirewallTargetTagsToCell(firewall):
  """Comma-joins the target tags of the given firewall rule."""
  return ','.join(firewall.get('targetTags', []))

def _ForwardingRuleTarget(forwarding_rule):
  """Gets the API-level target or backend-service of the given rule."""
  backend_service = forwarding_rule.get('backendService', None)
  if backend_service is not None:
    return backend_service
  else:
    return forwarding_rule.get('target', None)

def _StatusToCell(zone_or_region):
  """Returns status of a machine with deprecation information if applicable."""
  deprecated = zone_or_region.get('deprecated', '')
  if deprecated:
    return '{0} ({1})'.format(zone_or_region.get('status'),
                              deprecated.get('state'))
  else:
    return zone_or_region.get('status')

def _DeprecatedDateTimeToCell(zone_or_region):
  """Returns the turndown timestamp of a deprecated machine or ''."""
  deprecated = zone_or_region.get('deprecated', '')
  if deprecated:
    return deprecated.get('deleted')
  else:
    return ''

def _QuotaToCell(metric, is_integer=True):
  """Returns a function that can format the given quota as usage/limit."""

  def QuotaToCell(region):
    """Formats the metric from the parent function."""
    for quota in region.get('quotas', []):
      if quota.get('metric') != metric:
        continue

      if is_integer:
        return '{0:6}/{1}'.format(
            int(quota.get('usage')),
            int(quota.get('limit')))
      else:
        return '{0:7.2f}/{1:.2f}'.format(
            quota.get('usage'),
            quota.get('limit'))

    return ''

  return QuotaToCell

def _LocationName(instance_group):
  """Returns a location name, could be region name or zone name."""
  if 'zone' in instance_group:
    return path_simplifier.Name(instance_group['zone'])
  elif 'region' in instance_group:
    return path_simplifier.Name(instance_group['region'])
  else:
    return None

def _LocationScopeType(instance_group):
  """Returns a location scope type, could be region or zone."""
  if 'zone' in instance_group:
    return 'zone'
  elif 'region' in instance_group:
    return 'region'
  else:
    return None

def _MachineTypeMemoryToCell(machine_type):
  """Returns the memory of the given machine type in GB."""
  memory = machine_type.get('memoryMb')
  if memory:
    return '{0:5.2f}'.format(memory / 2.0 ** 10)
  else:
    return ''

def _FormatCustomMachineTypeName(mt):
  """Checks for custom machine type and modifies output.

  Args:
    mt: machine type to be formatted

  Returns:
    If mt was a custom type, then it will be formatted into the desired custom
      machine type output. Otherwise, it is returned unchanged.

  Helper function for _MachineTypeNameToCell
  """
  custom_cpu, custom_ram = instance_utils.GetCpuRamFromCustomName(mt)
  if custom_cpu and custom_ram:
    # Restricting output to 2 decimal places
    custom_ram_gb = '{0:.2f}'.format(float(custom_ram) / (2 ** 10))
    mt = 'custom ({0} vCPU, {1} GiB)'.format(custom_cpu, custom_ram_gb)
  return mt

def _MachineTypeNameToCell(machine_type):
  """Returns the formatted name of the given machine type.

  Most machine types will be untouched, with the exception of the custom machine
  type. This modifies the 'custom-N-M' custom machine types with
  'custom (N vCPU, M GiB)'.

  For example, given the following custom machine_type:

    custom-2-3500

  This function will return:

    custom (2 vCPU, 3.41 GiB)

  in the MACHINE_TYPE field when listing out the current instances.

  Args:
    machine_type: The machine type of the given instance

  Returns:
    A formatted version of the given custom machine type (as shown in example
    in docstring above).
  """
  mt = machine_type.get('properties', machine_type).get('machineType')
  if mt:
    return _FormatCustomMachineTypeName(mt)
  return mt

def FormatDescribeMachineTypeName(resources, com_path):
  """Formats a custom machine type when 'instances describe' is called.

  Args:
    resources: dict of resources available for the instance in question
    com_path: command path of the calling command

  Returns:
    If input is a custom type, returns the formatted custom machine type.
      Otherwise, returns None.
  """
  if ('instances' in com_path) and ('describe' in com_path):
    if not resources:
      return None
    if 'machineType' not in resources:
      return None
    mt_splitlist = resources['machineType'].split('/')
    mt = mt_splitlist[-1]
    if 'custom' not in mt:
      return None
    formatted_mt = _FormatCustomMachineTypeName(mt)
    mt_splitlist[-1] = formatted_mt
    return '/'.join(mt_splitlist)
  else:
    return None

def _OperationHttpStatusToCell(operation):
  """Returns the HTTP response code of the given operation."""
  if operation.get('status') == 'DONE':
    return operation.get('httpErrorStatusCode') or httplib.OK
  else:
    return ''

def _ProjectToCell(resource):
  """Returns the project name of the given resource."""
  self_link = resource.get('selfLink')
  if self_link:
    return path_simplifier.ProjectSuffix(self_link).split('/')[0]
  else:
    return ''

def _MembersToCell(group):
  members = group.get('members')
  if members:
    return len(members)
  # Must be '0' instead of 0 to pass comparison 0 or ''.
  return '0'

def _BackendsToCell(backend_service):
  """Comma-joins the names of the backend services."""
  return ','.join(backend.get('group')
                  for backend in backend_service.get('backends', []))

def _RoutesNextHopToCell(route):
  """Returns the next hop value in a compact form."""
  if route.get('nextHopInstance'):
    return path_simplifier.ScopedSuffix(route.get('nextHopInstance'))
  elif route.get('nextHopGateway'):
    return path_simplifier.ScopedSuffix(route.get('nextHopGateway'))
  elif route.get('nextHopIp'):
    return route.get('nextHopIp')
  elif route.get('nextHopVpnTunnel'):
    return path_simplifier.ScopedSuffix(route.get('nextHopVpnTunnel'))
  elif route.get('nextHopPeering'):
    return route.get('nextHopPeering')
  else:
    return ''

def _TargetProxySslCertificatesToCell(target_proxy):
  """Joins the names of ssl certificates of the given HTTPS or SSL proxy."""
  return ','.join(path_simplifier.Name(cert) for cert in
                  target_proxy.get('sslCertificates', []))

def _ProtobufDefinitionToFields(message_class):
  """Flattens the fields in a protocol buffer definition.

  For example, given the following definition:

    message Point {
      required int32 x = 1;
      required int32 y = 2;
      optional string label = 3;
    }

    message Polyline {
      repeated Point point = 1;
      optional string label = 2;
    }

  a call to this function with the Polyline class would produce:

    ['label',
     'point[].label',
     'point[].x',
     'point[].y']

  Args:
    message_class: A class that inherits from protorpc.self.messages.Message
        and defines a protocol buffer.

  Yields:
    The flattened fields, in non-decreasing order.
  """
  for field in sorted(message_class.all_fields(), key=lambda field: field.name):
    if isinstance(field, messages.MessageField):
      for remainder in _ProtobufDefinitionToFields(field.type):
        if field.repeated:
          yield field.name + '[].' + remainder
        else:
          yield field.name + '.' + remainder
    else:
      if field.repeated:
        yield field.name + '[]'
      else:
        yield field.name

_InternalSpec = collections.namedtuple(
    'Spec',
    ['message_class_name', 'table_cols', 'transformations', 'editables'])

_SPECS_V1 = {
    'addresses': _InternalSpec(
        message_class_name='Address',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('ADDRESS', 'address'),
            ('STATUS', 'status'),
        ],
        transformations=[
            ('region', path_simplifier.Name),
            ('users[]', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'autoscalers': _InternalSpec(
        message_class_name='Autoscaler',
        table_cols=[
            ('NAME', 'name'),
            ('TARGET', 'target'),
            ('POLICY', 'autoscalingPolicy'),
        ],
        transformations=[
            ('zone', path_simplifier.Name),
            ('target', path_simplifier.Name),
        ],
        editables=None,
    ),

    'backendServices': _InternalSpec(
        message_class_name='BackendService',
        table_cols=[
            ('NAME', 'name'),
            ('BACKENDS', _BackendsToCell),
            ('PROTOCOL', 'protocol'),
        ],
        transformations=[
            ('backends[].group', path_simplifier.ScopedSuffix),
        ],
        editables=[
            'backends',
            'description',
            'enableCDN',
            'healthChecks',
            'port',
            'portName',
            'protocol',
            'timeoutSec',
        ],
    ),

    'backendServiceGroupHealth': _InternalSpec(
        message_class_name='BackendServiceGroupHealth',
        table_cols=[
            ],
        transformations=[
            ('healthStatus[].instance', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'disks': _InternalSpec(
        message_class_name='Disk',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('SIZE_GB', 'sizeGb'),
            ('TYPE', 'type'),
            ('STATUS', 'status'),
        ],
        transformations=[
            ('sourceSnapshot', path_simplifier.Name),
            ('type', path_simplifier.Name),
            ('zone', path_simplifier.Name),
        ],
        editables=None,
    ),

    'diskTypes': _InternalSpec(
        message_class_name='DiskType',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('VALID_DISK_SIZES', 'validDiskSize'),
        ],
        transformations=[
            ('zone', path_simplifier.Name),
        ],
        editables=None,
    ),

    'firewalls': _InternalSpec(
        message_class_name='Firewall',
        table_cols=[
            ('NAME', 'name'),
            ('NETWORK', 'network'),
            ('SRC_RANGES', _FirewallSourceRangesToCell),
            ('RULES', _FirewallRulesToCell),
            ('SRC_TAGS', _FirewallSourceTagsToCell),
            ('TARGET_TAGS', _FirewallTargetTagsToCell),
        ],
        transformations=[
            ('network', path_simplifier.Name),
        ],
        editables=None,
    ),

    'forwardingRules': _InternalSpec(
        message_class_name='ForwardingRule',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('IP_ADDRESS', 'IPAddress'),
            ('IP_PROTOCOL', 'IPProtocol'),
            ('TARGET', _ForwardingRuleTarget),
        ],
        transformations=[
            ('region', path_simplifier.Name),
            ('target', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'groups': _InternalSpec(
        message_class_name='Group',
        table_cols=[
            ('NAME', 'name'),
            ('NUM_MEMBERS', _MembersToCell),
            ('DESCRIPTION', 'description'),
        ],
        transformations=[],
        editables=[],
    ),

    'healthChecks': _InternalSpec(
        message_class_name='HealthCheck',
        table_cols=[
            ('NAME', 'name'),
            ('PROTOCOL', 'type'),
        ],
        transformations=[],
        editables=None,
    ),

    'httpHealthChecks': _InternalSpec(
        message_class_name='HttpHealthCheck',
        table_cols=[
            ('NAME', 'name'),
            ('HOST', 'host'),
            ('PORT', 'port'),
            ('REQUEST_PATH', 'requestPath'),
        ],
        transformations=[
            ],
        editables=None,
    ),

    'httpsHealthChecks': _InternalSpec(
        message_class_name='HttpsHealthCheck',
        table_cols=[
            ('NAME', 'name'),
            ('HOST', 'host'),
            ('PORT', 'port'),
            ('REQUEST_PATH', 'requestPath'),
        ],
        transformations=[
            ],
        editables=None,
    ),

    'iap': _InternalSpec(
        message_class_name='BackendServiceIAP',
        table_cols=[
            ('NAME', 'name'),
            ('ENABLED', 'enabled'),
            ('OAUTH2_CLIENT_ID', 'oauth2ClientId'),
            ('OAUTH2_CLIENT_SECRET', 'oauth2ClientSecret'),
            ('OAUTH2_CLIENT_SECRET_SHA256', 'oauth2ClientSecretSha256'),
        ],
        transformations=[],
        editables=None,
    ),

    'images': _InternalSpec(
        message_class_name='Image',
        table_cols=[
            ('NAME', 'name'),
            ('PROJECT', _ProjectToCell),
            ('FAMILY', 'family'),
            ('DEPRECATED', 'deprecated.state'),
            ('STATUS', 'status'),
        ],
        transformations=[],
        editables=None,
    ),

    'instanceGroups': _InternalSpec(
        message_class_name='InstanceGroup',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('NETWORK', 'network'),
            ('MANAGED', 'isManaged'),
            ('INSTANCES', 'size'),
        ],
        transformations=[
            ('zone', path_simplifier.Name),
            ('size', str),
        ],
        editables=None,
    ),

    'instanceGroupManagers': _InternalSpec(
        message_class_name='InstanceGroupManager',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('BASE_INSTANCE_NAME', 'baseInstanceName'),
            ('SIZE', 'size'),
            ('TARGET_SIZE', 'targetSize'),
            ('INSTANCE_TEMPLATE', 'instanceTemplate'),
            ('AUTOSCALED', 'autoscaled'),
        ],
        transformations=[
            ('zone', path_simplifier.Name),
            ('instanceGroup', path_simplifier.Name),
            ('instanceTemplate', path_simplifier.Name),
        ],
        editables=None,
    ),

    'instances': _InternalSpec(
        message_class_name='Instance',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('MACHINE_TYPE', _MachineTypeNameToCell),
            ('PREEMPTIBLE', 'scheduling.preemptible'),
            ('INTERNAL_IP', 'networkInterfaces[].networkIP.notnull().list()'),
            ('EXTERNAL_IP',
             'networkInterfaces[].accessConfigs[0].natIP.notnull().list()'),
            ('STATUS', 'status'),
        ],
        transformations=[
            ('disks[].source', path_simplifier.Name),
            ('machineType', path_simplifier.Name),
            ('networkInterfaces[].network', path_simplifier.Name),
            ('zone', path_simplifier.Name),
        ],
        editables=None,
    ),

    'instanceTemplates': _InternalSpec(
        message_class_name='InstanceTemplate',
        table_cols=[
            ('NAME', 'name'),
            ('MACHINE_TYPE', _MachineTypeNameToCell),
            ('PREEMPTIBLE', 'properties.scheduling.preemptible'),
            ('CREATION_TIMESTAMP', 'creationTimestamp'),
        ],
        transformations=[],
        editables=None,
    ),

    'machineTypes': _InternalSpec(
        message_class_name='MachineType',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('CPUS', 'guestCpus'),
            ('MEMORY_GB', _MachineTypeMemoryToCell),
            ('DEPRECATED', 'deprecated.state'),
        ],
        transformations=[
            ('zone', path_simplifier.Name),
        ],
        editables=None,
    ),

    'networks': _InternalSpec(
        message_class_name='Network',
        table_cols=[
            ('NAME', 'name'),
            ('MODE', 'x_gcloud_mode'),
            ('IPV4_RANGE', 'IPv4Range'),
            ('GATEWAY_IPV4', 'gatewayIPv4'),
        ],
        transformations=[],
        editables=None,
    ),

    'projects': _InternalSpec(
        message_class_name='Project',
        table_cols=[],  # We do not support listing projects since
        # there is only one project (and there is no
        # API support).
        transformations=[
            ],
        editables=None,
    ),

    'operations': _InternalSpec(
        message_class_name='Operation',
        table_cols=[
            ('NAME', 'name'),
            ('TYPE', 'operationType'),
            ('TARGET', 'targetLink'),
            ('HTTP_STATUS', _OperationHttpStatusToCell),
            ('STATUS', 'status'),
            ('TIMESTAMP', 'insertTime'),
        ],
        transformations=[
            ('targetLink', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'invalidations': _InternalSpec(
        message_class_name='Operation',
        table_cols=[
            ('DESCRIPTION', 'description'),
            ('HTTP_STATUS', _OperationHttpStatusToCell),
            ('STATUS', 'status'),
            ('TIMESTAMP', 'insertTime'),
        ],
        transformations=[
            ('targetLink', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'regionBackendServices': _InternalSpec(
        message_class_name='BackendService',
        table_cols=[
            ('NAME', 'name'),
            ('BACKENDS', _BackendsToCell),
            ('PROTOCOL', 'protocol'),
        ],
        transformations=[
            ('backends[].group', path_simplifier.ScopedSuffix),
        ],
        editables=[
            'backends',
            'description',
            'enableCDN',
            'healthChecks',
            'port',
            'portName',
            'protocol',
            'timeoutSec',
        ],
    ),

    'regions': _InternalSpec(
        message_class_name='Region',
        table_cols=[
            ('NAME', 'name'),
            ('CPUS', _QuotaToCell('CPUS', is_integer=False)),
            ('DISKS_GB', _QuotaToCell('DISKS_TOTAL_GB', is_integer=True)),
            ('ADDRESSES', _QuotaToCell('IN_USE_ADDRESSES', is_integer=True)),
            ('RESERVED_ADDRESSES',
             _QuotaToCell('STATIC_ADDRESSES', is_integer=True)),
            ('STATUS', _StatusToCell),
            ('TURNDOWN_DATE', _DeprecatedDateTimeToCell),
        ],
        transformations=[
            ('zones[]', path_simplifier.Name),
        ],
        editables=None,
    ),

    'routes': _InternalSpec(
        message_class_name='Route',
        table_cols=[
            ('NAME', 'name'),
            ('NETWORK', 'network'),
            ('DEST_RANGE', 'destRange'),
            ('NEXT_HOP', _RoutesNextHopToCell),
            ('PRIORITY', 'priority'),
        ],
        transformations=[
            ('network', path_simplifier.Name),
        ],
        editables=None,
    ),

    'snapshots': _InternalSpec(
        message_class_name='Snapshot',
        table_cols=[
            ('NAME', 'name'),
            ('DISK_SIZE_GB', 'diskSizeGb'),
            ('SRC_DISK', 'sourceDisk'),
            ('STATUS', 'status'),
        ],
        transformations=[
            ('sourceDisk', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'sslCertificates': _InternalSpec(
        message_class_name='Network',
        table_cols=[
            ('NAME', 'name'),
            ('CREATION_TIMESTAMP', 'creationTimestamp'),
        ],
        transformations=[],
        editables=None,
    ),

    'subnetworks': _InternalSpec(
        message_class_name='Subnetwork',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('NETWORK', 'network'),
            ('RANGE', 'ipCidrRange')
        ],
        transformations=[
            ('network', path_simplifier.Name),
            ('region', path_simplifier.Name),
        ],
        editables=None,
    ),

    'targetHttpProxies': _InternalSpec(
        message_class_name='TargetHttpProxy',
        table_cols=[
            ('NAME', 'name'),
            ('URL_MAP', 'urlMap'),
        ],
        transformations=[
            ('urlMap', path_simplifier.Name),
        ],
        editables=None,
    ),

    'targetHttpsProxies': _InternalSpec(
        message_class_name='TargetHttpsProxy',
        table_cols=[
            ('NAME', 'name'),
            ('SSL_CERTIFICATES', _TargetProxySslCertificatesToCell),
            ('URL_MAP', 'urlMap'),
        ],
        transformations=[
            ('sslCertificates[]', path_simplifier.Name),
            ('urlMap', path_simplifier.Name),
        ],
        editables=None,
    ),

    'targetSslProxies': _InternalSpec(
        message_class_name='TargetSslProxy',
        table_cols=[
            ('NAME', 'name'),
            ('PROXY_HEADER', 'proxyHeader'),
            ('SERVICE', 'service'),
            ('SSL_CERTIFICATES', _TargetProxySslCertificatesToCell)
        ],
        transformations=[
            ('sslCertificates[]', path_simplifier.Name),
            ('service', path_simplifier.Name),
        ],
        editables=None,
    ),

    'targetInstances': _InternalSpec(
        message_class_name='TargetInstance',
        table_cols=[
            ('NAME', 'name'),
            ('ZONE', 'zone'),
            ('INSTANCE', 'instance'),
            ('NAT_POLICY', 'natPolicy'),
        ],
        transformations=[
            ('instance', path_simplifier.Name),
            ('zone', path_simplifier.Name),
        ],
        editables=None,
    ),

    'targetPoolInstanceHealth': _InternalSpec(
        message_class_name='TargetPoolInstanceHealth',
        table_cols=[
            ],
        transformations=[
            ('healthStatus[].instance', path_simplifier.ScopedSuffix),
        ],
        editables=None,
    ),

    'targetPools': _InternalSpec(
        message_class_name='TargetPool',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('SESSION_AFFINITY', 'sessionAffinity'),
            ('BACKUP', 'backupPool'),
            ('HEALTH_CHECKS', _TargetPoolHealthChecksToCell),
        ],
        transformations=[
            ('backupPool', path_simplifier.Name),
            ('healthChecks[]', path_simplifier.Name),
            ('instances[]', path_simplifier.ScopedSuffix),
            ('region', path_simplifier.Name),
        ],
        editables=None,
    ),

    'targetVpnGateways': _InternalSpec(
        message_class_name='TargetVpnGateway',
        table_cols=[
            ('NAME', 'name'),
            ('NETWORK', 'network'),
            ('REGION', 'region')
        ],
        transformations=[
            ('network', path_simplifier.Name),
            ('region', path_simplifier.Name)],
        editables=None
    ),

    'urlMaps': _InternalSpec(
        message_class_name='UrlMap',
        table_cols=[
            ('NAME', 'name'),
            ('DEFAULT_SERVICE', 'defaultService'),
        ],
        transformations=[
            ('defaultService', path_simplifier.Name),
            ('pathMatchers[].defaultService', path_simplifier.Name),
            ('pathMatchers[].pathRules[].service', path_simplifier.Name),
            ('tests[].service', path_simplifier.Name),
        ],
        editables=[
            'defaultService',
            'description',
            'hostRules',
            'pathMatchers',
            'tests',
        ],
    ),

    'users': _InternalSpec(
        message_class_name='User',
        table_cols=[
            ('NAME', 'name'),
            ('OWNER', 'owner'),
            ('DESCRIPTION', 'description'),
        ],
        transformations=[],
        editables=[],
    ),

    'zones': _InternalSpec(
        message_class_name='Zone',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('STATUS', _StatusToCell),
            ('TURNDOWN_DATE', _DeprecatedDateTimeToCell),
        ],
        transformations=[
            ('region', path_simplifier.Name),
        ],
        editables=None,
    ),

    'vpnTunnels': _InternalSpec(
        message_class_name='VpnTunnel',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('GATEWAY', 'targetVpnGateway'),
            ('PEER_ADDRESS', 'peerIp')
        ],
        transformations=[
            ('region', path_simplifier.Name),
            ('targetVpnGateway', path_simplifier.Name)],
        editables=None
    ),

    'routers': _InternalSpec(
        message_class_name='Router',
        table_cols=[
            ('NAME', 'name'),
            ('REGION', 'region'),
            ('NETWORK', 'network'),
        ],
        transformations=[
            ('network', path_simplifier.Name),
            ('region', path_simplifier.Name),
        ],
        editables=None,
    ),
}

_SPECS_BETA = _SPECS_V1.copy()
_SPECS_BETA['backendBuckets'] = _InternalSpec(
    message_class_name='BackendBucket',
    table_cols=[
        ('NAME', 'name'),
        ('GCS_BUCKET_NAME', 'bucketName'),
        ('ENABLE_CDN', 'enableCdn')
    ],
    transformations=[
        ('enableCdn', lambda x: str(x).lower()),
    ],
    editables=[
        'bucketName'
        'description',
        'enableCdn',
    ])
_SPECS_BETA['backendServices'] = _InternalSpec(
    message_class_name='BackendService',
    table_cols=[
        ('NAME', 'name'),
        ('BACKENDS', _BackendsToCell),
        ('PROTOCOL', 'protocol'),
    ],
    transformations=[
        ('backends[].group', path_simplifier.ScopedSuffix),
    ],
    editables=[
        'backends',
        'description',
        'enableCDN',
        'sessionAffinity',
        'affinityCookieTTL',
        'healthChecks',
        'iap.enabled',
        'iap.oauth2ClientId',
        'iap.oauth2ClientSecret',
        'port',
        'portName',
        'protocol',
        'timeoutSec',
    ],)
_SPECS_BETA['urlMaps'] = _InternalSpec(
    message_class_name='UrlMap',
    table_cols=[
        ('NAME', 'name'),
        ('DEFAULT_SERVICE', 'defaultService'),
    ],
    transformations=[
        ('defaultService', path_simplifier.TypeSuffix),
        ('pathMatchers[].defaultService', path_simplifier.TypeSuffix),
        ('pathMatchers[].pathRules[].service', path_simplifier.TypeSuffix),
        ('tests[].service', path_simplifier.TypeSuffix),
    ],
    editables=[
        'defaultService',
        'description',
        'hostRules',
        'pathMatchers',
        'tests',
    ])

_SPECS_ALPHA = _SPECS_BETA.copy()
_SPECS_ALPHA['hosts'] = _InternalSpec(
    message_class_name='Host',
    table_cols=[
        ('NAME', 'name'),
        ('REQUEST_PATH', 'requestPath'),
    ],
    transformations=[],
    editables=None)
_SPECS_ALPHA['hostTypes'] = _InternalSpec(
    message_class_name='HostType',
    table_cols=[
        ('NAME', 'name'),
        ('ZONE', 'zone'),
        ('DEPRECATED', 'deprecated'),
        ('CPUs', 'guestCpus'),
        ('MEMORY(MB)', 'memoryMb'),
        ('LOCAL SSD(GB)', 'localSsdGb'),
    ],
    transformations=[],
    editables=None)

_SPECS_ALPHA['instanceGroups'] = _InternalSpec(
    message_class_name='InstanceGroup',
    table_cols=[
        ('NAME', 'name'),
        ('LOCATION', _LocationName),
        ('SCOPE', _LocationScopeType),
        ('NETWORK', 'network'),
        ('MANAGED', 'isManaged'),
        ('INSTANCES', 'size'),
    ],
    transformations=[
        ('size', str),
    ],
    editables=None,
)
_SPECS_ALPHA['instanceGroupManagers'] = _InternalSpec(
    message_class_name='InstanceGroupManager',
    table_cols=[
        ('NAME', 'name'),
        ('LOCATION', _LocationName),
        ('SCOPE', _LocationScopeType),
        ('BASE_INSTANCE_NAME', 'baseInstanceName'),
        ('SIZE', 'size'),
        ('TARGET_SIZE', 'targetSize'),
        ('INSTANCE_TEMPLATE', 'instanceTemplate'),
        ('AUTOSCALED', 'autoscaled'),
    ],
    transformations=[
        ('instanceGroup', path_simplifier.Name),
        ('instanceTemplate', path_simplifier.Name),
    ],
    editables=None,
    )
_SPECS_ALPHA['urlMaps'] = _InternalSpec(
    message_class_name='UrlMap',
    table_cols=[
        ('NAME', 'name'),
        ('DEFAULT_SERVICE', 'defaultService'),
    ],
    transformations=[
        ('defaultService', path_simplifier.TypeSuffix),
        ('pathMatchers[].defaultService', path_simplifier.TypeSuffix),
        ('pathMatchers[].pathRules[].service', path_simplifier.TypeSuffix),
        ('tests[].service', path_simplifier.TypeSuffix),
    ],
    editables=[
        'defaultService',
        'description',
        'hostRules',
        'pathMatchers',
        'tests',
    ])
_SPECS_ALPHA['peerings'] = _InternalSpec(
    message_class_name='NetworkPeering',
    table_cols=[
        ('NAME', 'name'),
        ('network', 'network'),
        ('autoCreateRoutes', 'autoCreateRoutes'),
        ('state', 'state'),
        ],
    transformations=None,
    editables=None,
    )

def _GetSpecsForVersion(api_version):
  """Get Specs for the given API version.

  This currently always returns _SPECS_V1, but is left here for the future,
  as a pattern for providing different specs for different versions.

  Args:
    api_version: A string identifying the API version, e.g. 'v1'.

  Returns:
    A map associating each message class name with an _InternalSpec object.
  """
  if api_version == 'v1' or api_version == 'v2beta1':
    return _SPECS_V1
  if 'alpha' in api_version:
    return _SPECS_ALPHA
  return _SPECS_BETA

Spec = collections.namedtuple(
    'Spec',
    ['message_class', 'fields', 'table_cols', 'transformations', 'editables'])

def GetSpec(resource_type, message_classes, api_version):
  """Returns a Spec for the given resource type."""
  spec = _GetSpecsForVersion(api_version)

  if resource_type not in spec:
    raise KeyError('"%s" not found in Specs for version "%s"' %
                   (resource_type, api_version))

  spec = spec[resource_type]

  table_cols = []
  for name, action in spec.table_cols:
    if isinstance(action, basestring):
      table_cols.append((name, property_selector.PropertyGetter(action)))
    elif callable(action):
      table_cols.append((name, action))
    else:
      raise ValueError('expected function or property in table_cols list: {0}'
                       .format(spec))

  message_class = getattr(message_classes, spec.message_class_name)
  fields = list(_ProtobufDefinitionToFields(message_class))
  return Spec(message_class=message_class,
              fields=fields,
              table_cols=table_cols,
              transformations=spec.transformations,
              editables=spec.editables)


text:
var express = require('express');
passport = require('passport');
GitHubStrategy = require('passport-github').Strategy;
$ = require('jquery');
email = require('nodemailer');
var routes = require('./routes');
var poll = require('./routes/poll');
var login = require('./routes/login');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var pollDB = require('./public/javascript/pollDAO');
var userDB = require('./public/javascript/userDAO');
var count = require('./public/javascript/countDown');
var sendEmail = require('./public/javascript/mail');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon('./public/images/hackfavicon.ico'));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// Start database connection
var db = mongoose.connection;

db.on('error', console.error);
db.once('open', function() {
    console.log('Conectado ao MongoDB.')
});

mongoose.connect('mongodb://localhost/test'); // <--- Database name here

// Init DAOs
pollDAO = new pollDB.pollDAO(mongoose);
userDAO = new userDB.userDAO(mongoose);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// Polls
app.get('/', routes.index);
app.post('/poll/add', ensureAuthenticated, poll.add);
app.get('/poll/comment/:id/', ensureAuthenticated, poll.comment);
app.get('/poll/remove/:id', ensureAuthenticated, poll.remove);
app.get('/poll/vote/:id/:vote', ensureAuthenticated, poll.vote);
app.get('/polls', ensureAuthenticated, poll.list);

// login github
app.get('/auth/github',
        passport.authenticate('github', { failureRedirect: '/'}));
app.get('/auth/github/callback',
        passport.authenticate('github', { failureRedirect: '/'}),
        login.logged);

app.get('/logout', login.logout);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

// always connected
function ensureAuthenticated(req, res, next) {
   if (req.isAuthenticated()) { return next(); }
   res.redirect('/');
}

count.doEveryMidNight(function() {
    pollDAO.list(10, function(polls) {
        var maxTime = 7*24*3600; //one week in seconds
        actualDate = new Date().getTime() / 1000;
        for (var i = 0; i < polls.length; i++){
            pollDate = polls[i].date.getTime() / 1000;
            totalTime = actualDate - pollDate;
            if (totalTime > maxTime){
               console.log('Sending to all');
               sendEmail.sendToUsers(polls[i]);
                pollDAO.situation(polls[i], 1);
            }
        }
    });
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.wicket.markup.html.form (Wicket Parent 1.5.7 API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.wicket.markup.html.form package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.wicket.markup.html.form

Interfaces

AbstractTextComponent.ITextFormatProvider

IChoiceRenderer

IFormModelUpdateListener

IFormSubmitListener

IFormSubmitter

IFormSubmittingComponent

IFormVisitorParticipant

ILabelProvider

IOnChangeListener

Classes

AbstractCheckSelector

AbstractChoice

AbstractSingleSelectChoice

AbstractSubmitLink

AbstractTextComponent

AutoLabelResolver

AutoLabelResolver.AutoLabel

AutoLabelTagHandler

AutoLabelTextResolver

Button

Check

CheckBox

CheckBoxMultipleChoice

CheckboxMultipleChoiceSelector

CheckBoxSelector

CheckGroup

CheckGroupSelector

ChoiceRenderer

DropDownChoice

EmailTextField

EnumChoiceRenderer

Form

Form.ValidationVisitor

FormComponent

FormComponentLabel

FormComponentPanel

HiddenField

ImageButton

LabeledWebMarkupContainer

ListChoice

ListMultipleChoice

NumberTextField

PasswordTextField

Radio

RadioChoice

RadioGroup

RangeTextField

RequiredTextField

SimpleFormComponentLabel

StatelessForm

SubmitLink

TextArea

TextField

UrlTextField

ValidationErrorFeedback

Enums

Form.MethodMismatchResponse


text:
namespace mojo {
class ServiceProviderImpl;
namespace internal {
class ServiceConnectorBase;

// Implements a weak pointer to a ServiceProvider. Necessary as the lifetime of
// the ServiceProviderImpl is bound to that of its pipe, but code may continue
// to reference a remote service provider beyond the lifetime of said pipe.
// Calls to ConnectToService() are silently dropped when the pipe is closed.
class WeakServiceProvider : public ServiceProvider {
 public:
  WeakServiceProvider(ServiceProviderImpl* creator,
                      ServiceProvider* service_provider);
  ~WeakServiceProvider() override;

  void Clear();

 private:
  // Overridden from ServiceProvider:
  void ConnectToService(const String& service_name,
                        ScopedMessagePipeHandle client_handle) override;

  ServiceProviderImpl* creator_;
  ServiceProvider* service_provider_;

  MOJO_DISALLOW_COPY_AND_ASSIGN(WeakServiceProvider);
};

}  // namespace internal
}  // namespace mojo

#endif  // MOJO_PUBLIC_APPLICATION_LIB_WEAK_SERVICE_PROVIDER_H_


text:
import Resolver from 'ember/resolver';

var resolver = Resolver.create();

resolver.namespace = {
  modulePrefix: 'gaffer'
};

export default resolver;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class com.restfb.types.Location (RestFB)</title>
<meta name="date" content="2014-01-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.restfb.types.Location

Packages that use Location

Package
Description

com.restfb.types

Default implementations of Facebook Graph API Objects.

Uses of Location in com.restfb.types

Methods in com.restfb.types that return Location

Modifier and Type
Method and Description

Location
Place.getLocation()

Location containing geographic information such as latitude, longitude, country, and other fields (fields will vary
 based on geography and availability of information).

Location
Page.getLocation()

The location of the place this page represents.

Location
Checkin.Place.getLocation()

Deprecated.

The latitude/longitude of the check-in.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

RestFB 1.6.14. Copyright © 2010-2013 Mark Allen. All Rights Reserved.


text:
/***************************************************************************//**
 * @file em_timer.c
 * @brief Timer/counter (TIMER) Peripheral API
 * @version 5.1.2
 *******************************************************************************
 * @section License
 * <b>Copyright 2016 Silicon Laboratories, Inc. http://www.silabs.com</b>
 *******************************************************************************
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 *
 * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Labs has no
 * obligation to support this Software. Silicon Labs is providing the
 * Software "AS IS", with no express or implied warranties of any kind,
 * including, but not limited to, any implied warranties of merchantability
 * or fitness for any particular purpose or warranties against infringement
 * of any proprietary rights of a third party.
 *
 * Silicon Labs will not be liable for any consequential, incidental, or
 * special damages, or any other relief, or for any claim by any third party,
 * arising from your use of this Software.
 *
 ******************************************************************************/

#include "em_timer.h"
#if defined(TIMER_COUNT) && (TIMER_COUNT > 0)

#include "em_assert.h"

/***************************************************************************//**
 * @addtogroup emlib
 * @{
 ******************************************************************************/

/***************************************************************************//**
 * @addtogroup TIMER
 * @brief Timer/Counter (TIMER) Peripheral API
 * @details
 *   The timer module consists of three main parts:
 *   @li General timer config and enable control.
 *   @li Compare/capture control.
 *   @li Dead time insertion control (may not be available for all timers).
 * @{
 ******************************************************************************/

/*******************************************************************************
 **************************   GLOBAL FUNCTIONS   *******************************
 ******************************************************************************/

/***************************************************************************//**
 * @brief
 *   Initialize TIMER.
 *
 * @details
 *   Notice that counter top must be configured separately with for instance
 *   TIMER_TopSet(). In addition, compare/capture and dead-time insertion
 *   init must be initialized separately if used. That should probably
 *   be done prior to the use of this function if configuring the TIMER to
 *   start when initialization is completed.
 *
 * @param[in] timer
 *   Pointer to TIMER peripheral register block.
 *
 * @param[in] init
 *   Pointer to TIMER initialization structure.
 ******************************************************************************/
void TIMER_Init(TIMER_TypeDef *timer, const TIMER_Init_TypeDef *init)
{
  EFM_ASSERT(TIMER_REF_VALID(timer));

  /* Stop timer if specified to be disabled (dosn't hurt if already stopped) */
  if (!(init->enable))
  {
    timer->CMD = TIMER_CMD_STOP;
  }

  /* Reset counter */
  timer->CNT = _TIMER_CNT_RESETVALUE;

  timer->CTRL = ((uint32_t)(init->prescale)     << _TIMER_CTRL_PRESC_SHIFT)
                | ((uint32_t)(init->clkSel)     << _TIMER_CTRL_CLKSEL_SHIFT)
                | ((uint32_t)(init->fallAction) << _TIMER_CTRL_FALLA_SHIFT)
                | ((uint32_t)(init->riseAction) << _TIMER_CTRL_RISEA_SHIFT)
                | ((uint32_t)(init->mode)       << _TIMER_CTRL_MODE_SHIFT)
                | (init->debugRun               ?   TIMER_CTRL_DEBUGRUN  : 0)
                | (init->dmaClrAct              ?   TIMER_CTRL_DMACLRACT : 0)
                | (init->quadModeX4             ?   TIMER_CTRL_QDM_X4    : 0)
                | (init->oneShot                ?   TIMER_CTRL_OSMEN     : 0)

#if defined(TIMER_CTRL_X2CNT) && defined(TIMER_CTRL_ATI)
                | (init->count2x                ?   TIMER_CTRL_X2CNT     : 0)
                | (init->ati                    ?   TIMER_CTRL_ATI       : 0)
#endif
                | (init->sync                   ?   TIMER_CTRL_SYNC      : 0);

  /* Start timer if specified to be enabled (dosn't hurt if already started) */
  if (init->enable)
  {
    timer->CMD = TIMER_CMD_START;
  }
}

/***************************************************************************//**
 * @brief
 *   Initialize TIMER compare/capture channel.
 *
 * @details
 *   Notice that if operating channel in compare mode, the CCV and CCVB register
 *   must be set separately as required.
 *
 * @param[in] timer
 *   Pointer to TIMER peripheral register block.
 *
 * @param[in] ch
 *   Compare/capture channel to init for.
 *
 * @param[in] init
 *   Pointer to TIMER initialization structure.
 ******************************************************************************/
void TIMER_InitCC(TIMER_TypeDef *timer,
                  unsigned int ch,
                  const TIMER_InitCC_TypeDef *init)
{
  EFM_ASSERT(TIMER_REF_VALID(timer));
  EFM_ASSERT(TIMER_CH_VALID(ch));

  timer->CC[ch].CTRL =
    ((uint32_t)(init->eventCtrl) << _TIMER_CC_CTRL_ICEVCTRL_SHIFT)
    | ((uint32_t)(init->edge)    << _TIMER_CC_CTRL_ICEDGE_SHIFT)
    | ((uint32_t)(init->prsSel)  << _TIMER_CC_CTRL_PRSSEL_SHIFT)
    | ((uint32_t)(init->cufoa)   << _TIMER_CC_CTRL_CUFOA_SHIFT)
    | ((uint32_t)(init->cofoa)   << _TIMER_CC_CTRL_COFOA_SHIFT)
    | ((uint32_t)(init->cmoa)    << _TIMER_CC_CTRL_CMOA_SHIFT)
    | ((uint32_t)(init->mode)    << _TIMER_CC_CTRL_MODE_SHIFT)
    | (init->filter              ?   TIMER_CC_CTRL_FILT_ENABLE : 0)
    | (init->prsInput            ?   TIMER_CC_CTRL_INSEL_PRS   : 0)
    | (init->coist               ?   TIMER_CC_CTRL_COIST       : 0)
    | (init->outInvert           ?   TIMER_CC_CTRL_OUTINV      : 0);
}

#if defined(_TIMER_DTCTRL_MASK)
/***************************************************************************//**
 * @brief
 *   Initialize the TIMER DTI unit.
 *
 * @param[in] timer
 *   Pointer to TIMER peripheral register block.
 *
 * @param[in] init
 *   Pointer to TIMER DTI initialization structure.
 ******************************************************************************/
void TIMER_InitDTI(TIMER_TypeDef *timer, const TIMER_InitDTI_TypeDef *init)
{
  EFM_ASSERT(TIMER0 == timer);

  /* Make sure the DTI unit is disabled while initializing. */
  TIMER_EnableDTI (timer, false);

  /* Setup the DTCTRL register.
     The enable bit will be set at the end of the function if specified. */
  timer->DTCTRL =
    (init->autoRestart              ?   TIMER_DTCTRL_DTDAS   : 0)
    | (init->activeLowOut           ?   TIMER_DTCTRL_DTIPOL  : 0)
    | (init->invertComplementaryOut ?   TIMER_DTCTRL_DTCINV  : 0)
    | (init->enablePrsSource        ?   TIMER_DTCTRL_DTPRSEN : 0)
    | ((uint32_t)(init->prsSel)     << _TIMER_DTCTRL_DTPRSSEL_SHIFT);

  /* Setup the DTTIME register. */
  timer->DTTIME =
    ((uint32_t)(init->prescale)   << _TIMER_DTTIME_DTPRESC_SHIFT)
    | ((uint32_t)(init->riseTime) << _TIMER_DTTIME_DTRISET_SHIFT)
    | ((uint32_t)(init->fallTime) << _TIMER_DTTIME_DTFALLT_SHIFT);

  /* Setup the DTFC register. */
  timer->DTFC =
    (init->enableFaultSourceCoreLockup      ?   TIMER_DTFC_DTLOCKUPFEN : 0)
    | (init->enableFaultSourceDebugger      ?   TIMER_DTFC_DTDBGFEN    : 0)
    | (init->enableFaultSourcePrsSel0       ?   TIMER_DTFC_DTPRS0FEN   : 0)
    | (init->enableFaultSourcePrsSel1       ?   TIMER_DTFC_DTPRS1FEN   : 0)
    | ((uint32_t)(init->faultAction)        << _TIMER_DTFC_DTFA_SHIFT)
    | ((uint32_t)(init->faultSourcePrsSel0) << _TIMER_DTFC_DTPRS0FSEL_SHIFT)
    | ((uint32_t)(init->faultSourcePrsSel1) << _TIMER_DTFC_DTPRS1FSEL_SHIFT);

  /* Setup the DTOGEN register. */
  timer->DTOGEN = init->outputsEnableMask;

  /* Clear any previous DTI faults.  */
  TIMER_ClearDTIFault(timer, TIMER_GetDTIFault(timer));

  /* Enable/disable before returning. */
  TIMER_EnableDTI (timer, init->enable);
}
#endif

/***************************************************************************//**
 * @brief
 *   Reset TIMER to same state as after a HW reset.
 *
 * @note
 *   The ROUTE register is NOT reset by this function, in order to allow for
 *   centralized setup of this feature.
 *
 * @param[in] timer
 *   Pointer to TIMER peripheral register block.
 ******************************************************************************/
void TIMER_Reset(TIMER_TypeDef *timer)
{
  int i;

  EFM_ASSERT(TIMER_REF_VALID(timer));

  /* Make sure disabled first, before resetting other registers */
  timer->CMD = TIMER_CMD_STOP;

  timer->CTRL = _TIMER_CTRL_RESETVALUE;
  timer->IEN  = _TIMER_IEN_RESETVALUE;
  timer->IFC  = _TIMER_IFC_MASK;
  timer->TOPB = _TIMER_TOPB_RESETVALUE;
  /* Write TOP after TOPB to invalidate TOPB (clear TIMER_STATUS_TOPBV) */
  timer->TOP  = _TIMER_TOP_RESETVALUE;
  timer->CNT  = _TIMER_CNT_RESETVALUE;
  /* Do not reset route register, setting should be done independently */
  /* (Note: ROUTE register may be locked by DTLOCK register.) */

  for (i = 0; TIMER_CH_VALID(i); i++)
  {
    timer->CC[i].CTRL = _TIMER_CC_CTRL_RESETVALUE;
    timer->CC[i].CCV  = _TIMER_CC_CCV_RESETVALUE;
    timer->CC[i].CCVB = _TIMER_CC_CCVB_RESETVALUE;
  }

  /* Reset dead time insertion module, no effect on timers without DTI */

#if defined(TIMER_DTLOCK_LOCKKEY_UNLOCK)
  /* Unlock DTI registers first in case locked */
  timer->DTLOCK = TIMER_DTLOCK_LOCKKEY_UNLOCK;

  timer->DTCTRL   = _TIMER_DTCTRL_RESETVALUE;
  timer->DTTIME   = _TIMER_DTTIME_RESETVALUE;
  timer->DTFC     = _TIMER_DTFC_RESETVALUE;
  timer->DTOGEN   = _TIMER_DTOGEN_RESETVALUE;
  timer->DTFAULTC = _TIMER_DTFAULTC_MASK;
#endif
}

/** @} (end addtogroup TIMER) */
/** @} (end addtogroup emlib) */
#endif /* defined(TIMER_COUNT) && (TIMER_COUNT > 0) */


text:
package org.apache.camel.component.jms;

import java.util.Set;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 *
 */
public class ManagedJmsEndpointTest extends AbstractPersistentJMSTest {

    @Override
    protected boolean useJmx() {
        return true;
    }

    protected MBeanServer getMBeanServer() {
        return context.getManagementStrategy().getManagementAgent().getMBeanServer();
    }

    @Test
    public void testJmsEndpoint() throws Exception {
        MBeanServer mbeanServer = getMBeanServer();

        Set<ObjectName> objectNames = mbeanServer.queryNames(
                new ObjectName(
                        "org.apache.camel:context=camel-*,type=endpoints,name=\"activemq://queue:ManagedJmsEndpointTest\""),
                null);
        assertEquals(1, objectNames.size());
        ObjectName name = objectNames.iterator().next();

        String uri = (String) mbeanServer.getAttribute(name, "EndpointUri");
        assertEquals("activemq://queue:ManagedJmsEndpointTest", uri);

        Boolean singleton = (Boolean) mbeanServer.getAttribute(name, "Singleton");
        assertTrue(singleton);

        Integer running = (Integer) mbeanServer.getAttribute(name, "RunningMessageListeners");
        assertEquals(1, running.intValue());

        Long size = (Long) mbeanServer.invoke(name, "queueSize", null, null);
        assertEquals(0, size.intValue());

        getMockEndpoint("mock:result").expectedMessageCount(2);

        template.sendBody("activemq:queue:ManagedJmsEndpointTest", "Hello World");
        template.sendBody("activemq:queue:ManagedJmsEndpointTest", "Bye World");

        MockEndpoint.assertIsSatisfied(context);

        // stop route
        context.getRouteController().stopRoute("foo");

        // send a message to queue
        template.sendBody("activemq:queue:ManagedJmsEndpointTest", "Hi World");

        size = (Long) mbeanServer.invoke(name, "queueSize", null, null);
        assertEquals(1, size.intValue());

        String body = (String) mbeanServer.invoke(name, "browseMessageBody", new Object[] { 0 },
                new String[] { "java.lang.Integer" });
        assertEquals("Hi World", body);
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("activemq:queue:ManagedJmsEndpointTest").routeId("foo").to("log:foo").to("mock:result");
            }
        };
    }

}


text:
package com.cloud.network;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

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

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;

import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network.Service;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.rules.StaticNat;
import com.cloud.network.rules.StaticNatImpl;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.user.AccountVO;
import com.cloud.utils.net.Ip;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class IpAddressManagerTest {

    @Mock
    IPAddressDao ipAddressDao;

    @Mock
    NetworkDao networkDao;

    @Mock
    NetworkOfferingDao networkOfferingDao;

    @Spy
    @InjectMocks
    IpAddressManagerImpl ipAddressManager;

    @InjectMocks
    NetworkModelImpl networkModel = Mockito.spy(new NetworkModelImpl());

    IPAddressVO ipAddressVO;

    AccountVO account;

    @Before
    public void setup() throws ResourceUnavailableException {

        ipAddressVO = new IPAddressVO(new Ip("192.0.0.1"), 1L, 1L, 1L,false);
        ipAddressVO.setAllocatedToAccountId(1L);

        account = new AccountVO("admin", 1L, null, (short) 1, 1L, "c65a73d5-ebbd-11e7-8f45-107b44277808");
        account.setId(1L);

        NetworkOfferingVO networkOfferingVO = Mockito.mock(NetworkOfferingVO.class);
        networkOfferingVO.setSharedSourceNat(false);

        Mockito.when(networkOfferingDao.findById(Mockito.anyLong())).thenReturn(networkOfferingVO);
    }

    @Test
    public void testGetStaticNatSourceIps() {
        String publicIpAddress = "192.168.1.3";
        IPAddressVO vo = mock(IPAddressVO.class);
        when(vo.getAddress()).thenReturn(new Ip(publicIpAddress));
        when(vo.getId()).thenReturn(1l);

        when(ipAddressDao.findById(anyLong())).thenReturn(vo);
        StaticNat snat = new StaticNatImpl(1, 1, 1, 1, publicIpAddress, false);

        List<IPAddressVO> ips = ipAddressManager.getStaticNatSourceIps(Collections.singletonList(snat));
        Assert.assertNotNull(ips);
        Assert.assertEquals(1, ips.size());

        IPAddressVO returnedVO = ips.get(0);
        Assert.assertEquals(vo, returnedVO);
    }

    @Test
    public void isIpEqualsGatewayOrNetworkOfferingsEmptyTestRequestedIpEqualsIp6Gateway() {
        Network network = setTestIsIpEqualsGatewayOrNetworkOfferingsEmpty(0l, "gateway", "ip6Gateway", null, new ArrayList<Service>());

        boolean result = ipAddressManager.isIpEqualsGatewayOrNetworkOfferingsEmpty(network, "ip6Gateway");

        Mockito.verify(networkModel, Mockito.times(0)).listNetworkOfferingServices(Mockito.anyLong());
        Assert.assertTrue(result);
    }

    @Test
    public void isIpEqualsGatewayOrNetworkOfferingsEmptyTestRequestedIpEqualsGateway() {
        Network network = setTestIsIpEqualsGatewayOrNetworkOfferingsEmpty(0l, "gateway", "ip6Gateway", null, new ArrayList<Service>());

        boolean result = ipAddressManager.isIpEqualsGatewayOrNetworkOfferingsEmpty(network, "gateway");

        Mockito.verify(networkModel, Mockito.times(0)).listNetworkOfferingServices(Mockito.anyLong());
        Assert.assertTrue(result);
    }

    @Test
    public void isIpEqualsGatewayOrNetworkOfferingsEmptyTestExpectFalseServicesNotEmpty() {
        List<Service> services = new ArrayList<Service>();
        Service serviceGateway = new Service("Gateway");
        services.add(serviceGateway);
        Network network = setTestIsIpEqualsGatewayOrNetworkOfferingsEmpty(0l, "gateway", "ip6Gateway", null, services);

        boolean result = ipAddressManager.isIpEqualsGatewayOrNetworkOfferingsEmpty(network, "requestedIp");

        Mockito.verify(networkModel).listNetworkOfferingServices(Mockito.anyLong());
        Assert.assertFalse(result);
    }

    @Test
    public void isIpEqualsGatewayOrNetworkOfferingsEmptyTestExpectFalseServicesCidrNotNull() {
        Network network = setTestIsIpEqualsGatewayOrNetworkOfferingsEmpty(0l, "gateway", "ip6Gateway", "cidr", new ArrayList<Service>());

        boolean result = ipAddressManager.isIpEqualsGatewayOrNetworkOfferingsEmpty(network, "requestedIp");

        Mockito.verify(networkModel).listNetworkOfferingServices(Mockito.anyLong());
        Assert.assertFalse(result);
    }

    @Test
    public void assertSourceNatImplementedNetwork() {

        NetworkVO networkImplemented = Mockito.mock(NetworkVO.class);
        when(networkImplemented.getTrafficType()).thenReturn(Networks.TrafficType.Guest);
        when(networkImplemented.getNetworkOfferingId()).thenReturn(8L);
        when(networkImplemented.getState()).thenReturn(Network.State.Implemented);
        when(networkImplemented.getGuestType()).thenReturn(Network.GuestType.Isolated);
        when(networkImplemented.getVpcId()).thenReturn(null);
        when(networkImplemented.getId()).thenReturn(1L);

        Mockito.when(networkDao.findById(1L)).thenReturn(networkImplemented);
        doReturn(null).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 1L);

        boolean isSourceNat = ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkImplemented);

        assertTrue("Source NAT should be true", isSourceNat);
    }

    @Test(expected = InvalidParameterValueException.class)
    public void assertSourceNatAllocatedNetwork() {

        NetworkVO networkAllocated = Mockito.mock(NetworkVO.class);
        when(networkAllocated.getTrafficType()).thenReturn(Networks.TrafficType.Guest);
        when(networkAllocated.getNetworkOfferingId()).thenReturn(8L);
        when(networkAllocated.getState()).thenReturn(Network.State.Allocated);
        when(networkAllocated.getGuestType()).thenReturn(Network.GuestType.Isolated);
        when(networkAllocated.getVpcId()).thenReturn(null);
        when(networkAllocated.getId()).thenReturn(2L);

        Mockito.when(networkDao.findById(2L)).thenReturn(networkAllocated);
        doReturn(null).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 2L);

        ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkAllocated);
    }

    @Test
    public void assertExistingSourceNatAllocatedNetwork() {

        NetworkVO networkNat = Mockito.mock(NetworkVO.class);
        when(networkNat.getTrafficType()).thenReturn(Networks.TrafficType.Guest);
        when(networkNat.getNetworkOfferingId()).thenReturn(8L);
        when(networkNat.getState()).thenReturn(Network.State.Implemented);
        when(networkNat.getGuestType()).thenReturn(Network.GuestType.Isolated);
        when(networkNat.getId()).thenReturn(3L);
        when(networkNat.getVpcId()).thenReturn(null);
        when(networkNat.getId()).thenReturn(3L);

        IPAddressVO sourceNat = new IPAddressVO(new Ip("192.0.0.2"), 1L, 1L, 1L,true);

        Mockito.when(networkDao.findById(3L)).thenReturn(networkNat);
        doReturn(sourceNat).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 3L);

        boolean isSourceNat = ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkNat);

        assertFalse("Source NAT should be false", isSourceNat);
    }

    @Test
    public void isIpEqualsGatewayOrNetworkOfferingsEmptyTestNetworkOfferingsEmptyAndCidrNull() {
        Network network = setTestIsIpEqualsGatewayOrNetworkOfferingsEmpty(0l, "gateway", "ip6Gateway", null, new ArrayList<Service>());

        boolean result = ipAddressManager.isIpEqualsGatewayOrNetworkOfferingsEmpty(network, "requestedIp");

        Mockito.verify(networkModel).listNetworkOfferingServices(Mockito.anyLong());
        Assert.assertTrue(result);
    }

    private Network setTestIsIpEqualsGatewayOrNetworkOfferingsEmpty(long networkOfferingId, String gateway, String ip6Gateway, String cidr, List<Service> services) {
        Network network = mock(Network.class);
        Mockito.when(network.getNetworkOfferingId()).thenReturn(networkOfferingId);
        Mockito.when(network.getGateway()).thenReturn(gateway);
        Mockito.when(network.getIp6Gateway()).thenReturn(ip6Gateway);
        Mockito.when(network.getCidr()).thenReturn(cidr);
        Mockito.doReturn(services).when(networkModel).listNetworkOfferingServices(Mockito.anyLong());
        return network;
    }

}


text:
using NeuroSystem.Workflow.UserData.UI.Html.Version1.Widgets.Panels;

namespace NeuroSystem.Workflow.UserData.UI.Html.Version1.Fluent.Widgets.Panels
{
    public class TabsFactory<T> : WidgetFactory<T>
    {
        public TabsFactory()
        {
            Widget = new TabsWidget();
        }

        public TabsWidget Tabs => Widget as TabsWidget;

        public TabFactory<T> AddTab(string tabName)
        {
            var factory = new TabFactory<T>();
            factory.Tab.Name = tabName;

            Tabs.Tabs.Add(factory.Tab);

            return factory;
        }
    }
}


text:
uint16_t LibreSensor_CalculateGlucoseReading(const uint8_t* pu8Data, const unsigned int offsetLowByte);

#endif // LIBRE_SENSOR_SECRET_H


text:
r"""Vizier for linear VRNN for MultiWoZSynthDataset.

"""

from uncertainty_baselines.experimental.language_structure.vrnn.experiments.linear_vrnn import multiwoz_synth_tmpl as tmpl

def get_config():
  """Returns the configuration for this experiment."""
  config = tmpl.get_config()

  config.max_task_failures = -1
  config.max_per_task_failures = 5

  return config

def get_sweep(hyper):
  """Returns hyperparameter sweep."""
  domain = [
      hyper.sweep('config.word_weights_file_weight',
                  hyper.discrete([0.25 * i for i in range(5)])),
      hyper.sweep('config.psl_constraint_learning_weight',
                  hyper.discrete([0., 0.001, 0.005, 0.01, 0.05, 0.1])),
      hyper.sweep('config.model.vae_cell.encoder_hidden_size',
                  hyper.discrete([200, 300, 400])),
      hyper.sweep('config.base_learning_rate', hyper.discrete([5e-4, 1e-3]))
  ]
  sweep = hyper.product(domain)
  return sweep


text:
import {Action} from './Action';
import {State} from '../reducer';

export interface Dispatch {
  (action: Action<any>): Promise<State>;
}


text:
package com.ttdevs.android.transformers;

import android.content.Context;
import androidx.viewpager.widget.ViewPager;
import android.util.AttributeSet;

import com.ttdevs.android.utils.LogUtils;

public class CustomViewPager extends ViewPager {

    public CustomViewPager(Context context) {
        this(context, null);
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    private void init() {
        setClipToPadding(false);
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    @Override
    protected int getChildDrawingOrder(int childCount, int n) {
        int result = n;

        // 最后一个
        if (n == childCount - 1) {
            result = getCurrentItem();
        } else if(n >= getCurrentItem()) {
            result = n + 1;
        }

        LogUtils.debug(String.format("ChildCount:%d n:%d result:%d getCurrentItem:%d", childCount, n, result, getCurrentItem()));

        return result;
    }
}


text:
#import "RCTTextViewManager.h"

#import <React/RCTAccessibilityManager.h>
#import <React/RCTShadowView+Layout.h>
#import <React/RCTShadowView.h>
#import <React/RCTUIManager.h>
#import <React/RCTUIManagerObserverCoordinator.h>

#import "RCTTextShadowView.h"
#import "RCTTextView.h"

@interface RCTTextViewManager () <RCTUIManagerObserver>

@end

@implementation RCTTextViewManager
{
  NSHashTable<RCTTextShadowView *> *_shadowViews;
  CGFloat _fontSizeMultiplier;
}

RCT_EXPORT_MODULE(RCTText)

RCT_REMAP_SHADOW_PROPERTY(numberOfLines, maximumNumberOfLines, NSInteger)
RCT_REMAP_SHADOW_PROPERTY(ellipsizeMode, lineBreakMode, NSLineBreakMode)
RCT_REMAP_SHADOW_PROPERTY(adjustsFontSizeToFit, adjustsFontSizeToFit, BOOL)
RCT_REMAP_SHADOW_PROPERTY(minimumFontScale, minimumFontScale, CGFloat)

RCT_EXPORT_VIEW_PROPERTY(selectable, BOOL)

- (void)setBridge:(RCTBridge *)bridge
{
  [super setBridge:bridge];
  _shadowViews = [NSHashTable weakObjectsHashTable];

  [bridge.uiManager.observerCoordinator addObserver:self];

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(handleDidUpdateMultiplierNotification)
                                               name:RCTAccessibilityManagerDidUpdateMultiplierNotification
                                             object:bridge.accessibilityManager];
}

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIView *)view
{
  return [RCTTextView new];
}

- (RCTShadowView *)shadowView
{
  RCTTextShadowView *shadowView = [[RCTTextShadowView alloc] initWithBridge:self.bridge];
  shadowView.textAttributes.fontSizeMultiplier = self.bridge.accessibilityManager.multiplier;
  [_shadowViews addObject:shadowView];
  return shadowView;
}

#pragma mark - RCTUIManagerObserver

- (void)uiManagerWillPerformMounting:(__unused RCTUIManager *)uiManager
{
  for (RCTTextShadowView *shadowView in _shadowViews) {
    [shadowView uiManagerWillPerformMounting];
  }
}

#pragma mark - Font Size Multiplier

- (void)handleDidUpdateMultiplierNotification
{
  CGFloat fontSizeMultiplier = self.bridge.accessibilityManager.multiplier;

  for (RCTTextShadowView *shadowView in _shadowViews) {
    shadowView.textAttributes.fontSizeMultiplier = fontSizeMultiplier;
    [shadowView dirtyLayout];
  }

  [self.bridge.uiManager setNeedsLayout];
}

@end


text:
module.exports.LASTFM_API_KEY  = 'lastfm_api_key';
module.exports.YOUTUBE_API_KEY = 'youtube_api_key';