text:
"""
Installs and configures neutron
"""

import logging
import os
import re
import uuid

from packstack.installer import utils
from packstack.installer import validators
from packstack.installer.utils import split_hosts

from packstack.modules.shortcuts import get_mq
from packstack.modules.ospluginutils import getManifestTemplate, appendManifestFile

# Controller object will be initialized from main flow
controller = None

# Plugin name
PLUGIN_NAME = "OS-NEUTRON"

logging.debug("plugin %s loaded", __name__)

def initConfig(controllerObject):
    global controller
    controller = controllerObject

    logging.debug("Adding OpenStack Neutron configuration")

    conf_params = {
        "NEUTRON" : [
            {"CMD_OPTION"      : "neutron-server-host",
             "USAGE"           : "The IP addresses of the server on which to install the Neutron server",
             "PROMPT"          : "Enter the IP address of the Neutron server",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_ip, validators.validate_ssh],
             "DEFAULT_VALUE"   : utils.get_localhost_ip(),
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_SERVER_HOST",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ks-password",
             "USAGE"           : "The password to use for Neutron to authenticate with Keystone",
             "PROMPT"          : "Enter the password for Neutron Keystone access",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_not_empty],
             "DEFAULT_VALUE"   : uuid.uuid4().hex[:16],
             "MASK_INPUT"      : True,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_KS_PW",
             "USE_DEFAULT"     : True,
             "NEED_CONFIRM"    : True,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-db-password",
             "USAGE"           : "The password to use for Neutron to access DB",
             "PROMPT"          : "Enter the password for Neutron DB access",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_not_empty],
             "DEFAULT_VALUE"   : uuid.uuid4().hex[:16],
             "MASK_INPUT"      : True,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_DB_PW",
             "USE_DEFAULT"     : True,
             "NEED_CONFIRM"    : True,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-l3-hosts",
             "USAGE"           : "A comma separated list of IP addresses on which to install Neutron L3 agent",
             "PROMPT"          : "Enter a comma separated list of IP addresses on which to install the Neutron L3 agent",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_multi_ssh],
             "DEFAULT_VALUE"   : utils.get_localhost_ip(),
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_L3_HOSTS",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-l3-ext-bridge",
             "USAGE"           : "The name of the bridge that the Neutron L3 agent will use for external traffic, or 'provider' if using provider networks",
             "PROMPT"          : "Enter the bridge the Neutron L3 agent will use for external traffic, or 'provider' if using provider networks",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_not_empty],
             "DEFAULT_VALUE"   : "br-ex",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_L3_EXT_BRIDGE",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-dhcp-hosts",
             "USAGE"           : "A comma separated list of IP addresses on which to install Neutron DHCP agent",
             "PROMPT"          : "Enter a comma separated list of IP addresses on which to install Neutron DHCP agent",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_multi_ssh],
             "DEFAULT_VALUE"   : utils.get_localhost_ip(),
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_DHCP_HOSTS",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-lbaas-hosts",
             "USAGE"           : "A comma separated list of IP addresses on which to install Neutron LBaaS agent",
             "PROMPT"          : "Enter a comma separated list of IP addresses on which to install Neutron LBaaS agent",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_multi_ssh],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_LBAAS_HOSTS",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-l2-plugin",
             "USAGE"           : "The name of the L2 plugin to be used with Neutron",
             "PROMPT"          : "Enter the name of the L2 plugin to be used with Neutron",
             "OPTION_LIST"     : ["linuxbridge", "openvswitch", "ml2"],
             "VALIDATORS"      : [validators.validate_options],
             "DEFAULT_VALUE"   : "openvswitch",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_L2_PLUGIN",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-metadata-hosts",
             "USAGE"           : "A comma separated list of IP addresses on which to install Neutron metadata agent",
             "PROMPT"          : "Enter a comma separated list of IP addresses on which to install the Neutron metadata agent",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_multi_ssh],
             "DEFAULT_VALUE"   : utils.get_localhost_ip(),
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_METADATA_HOSTS",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-metadata-pw",
             "USAGE"           : "A comma separated list of IP addresses on which to install Neutron metadata agent",
             "PROMPT"          : "Enter a comma separated list of IP addresses on which to install the Neutron metadata agent",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_not_empty],
             "DEFAULT_VALUE"   : uuid.uuid4().hex[:16],
             "MASK_INPUT"      : True,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_METADATA_PW",
             "USE_DEFAULT"     : True,
             "NEED_CONFIRM"    : True,
             "CONDITION"       : False },
            ],
        "NEUTRON_LB_PLUGIN" : [
            {"CMD_OPTION"      : "neutron-lb-tenant-network-type",
             "USAGE"           : "The type of network to allocate for tenant networks (eg. vlan, local)",
             "PROMPT"          : "Enter the type of network to allocate for tenant networks",
             "OPTION_LIST"     : ["local", "vlan"],
             "VALIDATORS"      : [validators.validate_options],
             "DEFAULT_VALUE"   : "local",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_LB_TENANT_NETWORK_TYPE",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-lb-vlan-ranges",
             "USAGE"           : "A comma separated list of VLAN ranges for the Neutron linuxbridge plugin (eg. physnet1:1:4094,physnet2,physnet3:3000:3999)",
             "PROMPT"          : "Enter a comma separated list of VLAN ranges for the Neutron linuxbridge plugin",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_LB_VLAN_RANGES",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_LB_PLUGIN_AND_AGENT" : [
            {"CMD_OPTION"      : "neutron-lb-interface-mappings",
             "USAGE"           : "A comma separated list of interface mappings for the Neutron linuxbridge plugin (eg. physnet1:br-eth1,physnet2:br-eth2,physnet3:br-eth3)",
             "PROMPT"          : "Enter a comma separated list of interface mappings for the Neutron linuxbridge plugin",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_LB_INTERFACE_MAPPINGS",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_OVS_PLUGIN" : [
            {"CMD_OPTION"      : "neutron-ovs-tenant-network-type",
             "USAGE"           : "Type of network to allocate for tenant networks (eg. vlan, local, gre, vxlan)",
             "PROMPT"          : "Enter the type of network to allocate for tenant networks",
             "OPTION_LIST"     : ["local", "vlan", "gre", "vxlan"],
             "VALIDATORS"      : [validators.validate_options],
             "DEFAULT_VALUE"   : "local",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ovs-vlan-ranges",
             "USAGE"           : "A comma separated list of VLAN ranges for the Neutron openvswitch plugin (eg. physnet1:1:4094,physnet2,physnet3:3000:3999)",
             "PROMPT"          : "Enter a comma separated list of VLAN ranges for the Neutron openvswitch plugin",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_VLAN_RANGES",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_OVS_PLUGIN_AND_AGENT" : [
            {"CMD_OPTION"      : "neutron-ovs-bridge-mappings",
             "USAGE"           : "A comma separated list of bridge mappings for the Neutron openvswitch plugin (eg. physnet1:br-eth1,physnet2:br-eth2,physnet3:br-eth3)",
             "PROMPT"          : "Enter a comma separated list of bridge mappings for the Neutron openvswitch plugin",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ovs-bridge-interfaces",
             "USAGE"           : "A comma separated list of colon-separated OVS bridge:interface pairs. The interface will be added to the associated bridge.",
             "PROMPT"          : "Enter a comma separated list of OVS bridge:interface pairs for the Neutron openvswitch plugin",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_BRIDGE_IFACES",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_OVS_PLUGIN_TUNNEL" : [
            {"CMD_OPTION"      : "neutron-ovs-tunnel-ranges",
             "USAGE"           : "A comma separated list of tunnel ranges for the Neutron openvswitch plugin (eg. 1:1000)",
             "PROMPT"          : "Enter a comma separated list of tunnel ranges for the Neutron openvswitch plugin",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_TUNNEL_RANGES",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_OVS_PLUGIN_AND_AGENT_TUNNEL" : [
            {"CMD_OPTION"      : "neutron-ovs-tunnel-if",
             "USAGE"           : "The interface for the OVS tunnel. Packstack will override the IP address used for tunnels on this hypervisor to the IP found on the specified interface. (eg. eth1) ",
             "PROMPT"          : "Enter interface with IP to override the default tunnel local_ip",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_TUNNEL_IF",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_OVS_PLUGIN_AND_AGENT_VXLAN" : [
            {"CMD_OPTION"      : "neutron-ovs-vxlan-udp-port",
             "CONF_NAME"       : "CONFIG_NEUTRON_OVS_VXLAN_UDP_PORT",
             "USAGE"           : "VXLAN UDP port",
             "PROMPT"          : "Enter VXLAN UDP port number",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [validators.validate_port],
             "DEFAULT_VALUE"   : 4789,
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": True,

             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        "NEUTRON_ML2_PLUGIN" : [
            {"CMD_OPTION"      : "neutron-ml2-type-drivers",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_TYPE_DRIVERS",
             "USAGE"           : ("A comma separated list of network type "
                                  "driver entrypoints to be loaded from the "
                                  "neutron.ml2.type_drivers namespace."),
             "PROMPT"          : ("Enter a comma separated list of network "
                                  "type driver entrypoints"),
             "OPTION_LIST"     : ["local", "flat", "vlan", "gre", "vxlan"],
             "VALIDATORS"      : [validators.validate_multi_options],
             "DEFAULT_VALUE"   : "local",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-tenant-network-types",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES",
             "USAGE"           : ("A comma separated ordered list of "
                                  "network_types to allocate as tenant "
                                  "networks. The value 'local' is only useful "
                                  "for single-box testing but provides no "
                                  "connectivity between hosts."),
             "PROMPT"          : ("Enter a comma separated ordered list of "
                                  "network_types to allocate as tenant "
                                  "networks"),
             "OPTION_LIST"     : ["local", "vlan", "gre", "vxlan"],
             "VALIDATORS"      : [validators.validate_multi_options],
             "DEFAULT_VALUE"   : "local",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-mechanism-drivers",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_MECHANISM_DRIVERS",
             "USAGE"           : ("A comma separated ordered list of "
                                  "networking mechanism driver entrypoints "
                                  "to be loaded from the "
                                  "neutron.ml2.mechanism_drivers namespace."),
             "PROMPT"          : ("Enter a comma separated ordered list of "
                                  "networking mechanism driver entrypoints"),
             "OPTION_LIST"     : ["logger", "test", "linuxbridge",
                                  "openvswitch", "hyperv", "ncs", "arista",
                                  "cisco_nexus", "l2population"],
             "VALIDATORS"      : [validators.validate_multi_options],
             "DEFAULT_VALUE"   : "openvswitch",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-flat-networks",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_FLAT_NETWORKS",
             "USAGE"           : ("A comma separated  list of physical_network"
                                  " names with which flat networks can be "
                                  "created. Use * to allow flat networks with "
                                  "arbitrary physical_network names."),
             "PROMPT"          : ("Enter a comma separated  list of "
                                  "physical_network names with which flat "
                                  "networks can be created"),
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "*",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-vlan-ranges",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_VLAN_RANGES",
             "USAGE"           : ("A comma separated list of "
                                  "<physical_network>:<vlan_min>:<vlan_max> "
                                  "or <physical_network> specifying "
                                  "physical_network names usable for VLAN "
                                  "provider and tenant networks, as well as "
                                  "ranges of VLAN tags on each available for "
                                  "allocation to tenant networks."),
             "PROMPT"          : ("Enter a comma separated list of "
                                  "physical_network names usable for VLAN"),
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-tunnel-id-ranges",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_TUNNEL_ID_RANGES",
             "USAGE"           : ("A comma separated list of <tun_min>:"
                                  "<tun_max> tuples enumerating ranges of GRE "
                                  "tunnel IDs that are available for tenant "
                                  "network allocation. Should be an array with"
                                  " tun_max +1 - tun_min > 1000000"),
             "PROMPT"          : ("Enter a comma separated list of <tun_min>:"
                                  "<tun_max> tuples enumerating ranges of GRE "
                                  "tunnel IDs that are available for tenant "
                                  "network allocation"),
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-vxlan-group",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_VXLAN_GROUP",
             "USAGE"           : ("Multicast group for VXLAN. If unset, "
                                  "disables VXLAN enable sending allocate "
                                  "broadcast traffic to this multicast group. "
                                  "When left unconfigured, will disable "
                                  "multicast VXLAN mode. Should be an "
                                  "Multicast IP (v4 or v6) address."),
             "PROMPT"          : "Enter a multicast group for VXLAN",
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-ml2-vni-ranges",
             "CONF_NAME"       : "CONFIG_NEUTRON_ML2_VNI_RANGES",
             "USAGE"           : ("A comma separated list of <vni_min>:"
                                  "<vni_max> tuples enumerating ranges of "
                                  "VXLAN VNI IDs that are available for tenant"
                                  " network allocation. Min value is 0 and Max"
                                  " value is 16777215."),
             "PROMPT"          : ("Enter a comma separated list of <vni_min>:"
                                  "<vni_max> tuples enumerating ranges of "
                                  "VXLAN VNI IDs that are available for tenant"
                                  " network allocation"),
             "OPTION_LIST"     : [],
             "VALIDATORS"      : [],
             "DEFAULT_VALUE"   : "",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            {"CMD_OPTION"      : "neutron-l2-agent", # We need to ask for this only in case of ML2 plugins
             "USAGE"           : "The name of the L2 agent to be used with Neutron",
             "PROMPT"          : "Enter the name of the L2 agent to be used with Neutron",
             "OPTION_LIST"     : ["linuxbridge", "openvswitch"],
             "VALIDATORS"      : [validators.validate_options],
             "DEFAULT_VALUE"   : "openvswitch",
             "MASK_INPUT"      : False,
             "LOOSE_VALIDATION": False,
             "CONF_NAME"       : "CONFIG_NEUTRON_L2_AGENT",
             "USE_DEFAULT"     : False,
             "NEED_CONFIRM"    : False,
             "CONDITION"       : False },
            ],
        }

    def use_ml2_plugin(config):
        return (config['CONFIG_NEUTRON_INSTALL'] == 'y' and
                config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2')

    def use_linuxbridge_plugin(config):
        result = (config['CONFIG_NEUTRON_INSTALL'] == 'y' and
                  config['CONFIG_NEUTRON_L2_PLUGIN'] == 'linuxbridge')
        if result:
            config["CONFIG_NEUTRON_L2_AGENT"] = 'linuxbridge'
        return result

    def use_linuxbridge_agent(config):
        ml2_used = (use_ml2_plugin(config) and
                    config["CONFIG_NEUTRON_L2_AGENT"] == 'linuxbridge')
        return use_linuxbridge_plugin(config) or ml2_used

    def use_openvswitch_plugin(config):
        result = (config['CONFIG_NEUTRON_INSTALL'] == 'y' and
                  config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch')
        if result:
            config["CONFIG_NEUTRON_L2_AGENT"] = 'openvswitch'
        return result

    def use_openvswitch_plugin_tunnel(config):
        tun_types = ('gre', 'vxlan')
        return (use_openvswitch_plugin(config) and
                config['CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE'] in tun_types)

    def use_ml2_with_ovs(config):
        return (use_ml2_plugin(config) and
                config["CONFIG_NEUTRON_L2_AGENT"] == 'openvswitch')

    def use_openvswitch_agent(config):
        return use_openvswitch_plugin(config) or use_ml2_with_ovs(config)

    def use_openvswitch_agent_tunnel(config):
        return use_openvswitch_plugin_tunnel(config) or use_ml2_with_ovs(config)

    def use_openvswitch_vxlan(config):
        return (use_openvswitch_plugin_tunnel(config) and
                config['CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE'] == 'vxlan')

    conf_groups = [
        { "GROUP_NAME"            : "NEUTRON",
          "DESCRIPTION"           : "Neutron config",
          "PRE_CONDITION"         : "CONFIG_NEUTRON_INSTALL",
          "PRE_CONDITION_MATCH"   : "y",
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_ML2_PLUGIN",
          "DESCRIPTION"           : "Neutron ML2 plugin config",
          "PRE_CONDITION"         : use_ml2_plugin,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_LB_PLUGIN",
          "DESCRIPTION"           : "Neutron LB plugin config",
          "PRE_CONDITION"         : use_linuxbridge_plugin,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_LB_PLUGIN_AND_AGENT",
          "DESCRIPTION"           : "Neutron LB agent config",
          "PRE_CONDITION"         : use_linuxbridge_agent,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_OVS_PLUGIN",
          "DESCRIPTION"           : "Neutron OVS plugin config",
          "PRE_CONDITION"         : use_openvswitch_plugin,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_OVS_PLUGIN_AND_AGENT",
          "DESCRIPTION"           : "Neutron OVS agent config",
          "PRE_CONDITION"         : use_openvswitch_agent,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_OVS_PLUGIN_TUNNEL",
          "DESCRIPTION"           : "Neutron OVS plugin config for tunnels",
          "PRE_CONDITION"         : use_openvswitch_plugin_tunnel,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_OVS_PLUGIN_AND_AGENT_TUNNEL",
          "DESCRIPTION"           : "Neutron OVS agent config for tunnels",
          "PRE_CONDITION"         : use_openvswitch_agent_tunnel,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        { "GROUP_NAME"            : "NEUTRON_OVS_PLUGIN_AND_AGENT_VXLAN",
          "DESCRIPTION"           : "Neutron OVS agent config for VXLAN",
          "PRE_CONDITION"         : use_openvswitch_vxlan,
          "PRE_CONDITION_MATCH"   : True,
          "POST_CONDITION"        : False,
          "POST_CONDITION_MATCH"  : True },
        ]

    for group in conf_groups:
        paramList = conf_params[group["GROUP_NAME"]]
        controller.addGroup(group, paramList)

def get_if_driver(config):
    agent = config['CONFIG_NEUTRON_L2_AGENT']
    if agent == "openvswitch":
        return 'neutron.agent.linux.interface.OVSInterfaceDriver'
    elif agent == 'linuxbridge':
        return 'neutron.agent.linux.interface.BridgeInterfaceDriver'

def initSequences(controller):
    config = controller.CONF
    if config['CONFIG_NEUTRON_INSTALL'] != 'y':
        return

    if config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch':
        plugin_db = 'ovs_neutron'
        plugin_path = ('neutron.plugins.openvswitch.ovs_neutron_plugin.'
                       'OVSNeutronPluginV2')
    elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'linuxbridge':
        plugin_db = 'neutron_linux_bridge'
        plugin_path = ('neutron.plugins.linuxbridge.lb_neutron_plugin.'
                       'LinuxBridgePluginV2')
    elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2':
        plugin_db = 'neutron'
        plugin_path = 'neutron.plugins.ml2.plugin.Ml2Plugin'
        # values modification
        for key in ('CONFIG_NEUTRON_ML2_TYPE_DRIVERS',
                    'CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES',
                    'CONFIG_NEUTRON_ML2_MECHANISM_DRIVERS',
                    'CONFIG_NEUTRON_ML2_FLAT_NETWORKS',
                    'CONFIG_NEUTRON_ML2_VLAN_RANGES',
                    'CONFIG_NEUTRON_ML2_TUNNEL_ID_RANGES',
                    'CONFIG_NEUTRON_ML2_VNI_RANGES'):
            config[key] = str([i.strip() for i in config[key].split(',') if i])
        key = 'CONFIG_NEUTRON_ML2_VXLAN_GROUP'
        config[key] = "'%s'" % config[key] if config[key] else 'undef'

    config['CONFIG_NEUTRON_L2_DBNAME']  = plugin_db
    config['CONFIG_NEUTRON_CORE_PLUGIN'] = plugin_path

    global api_hosts, l3_hosts, dhcp_hosts, lbaas_hosts, compute_hosts, meta_hosts, q_hosts
    api_hosts = split_hosts(config['CONFIG_NEUTRON_SERVER_HOST'])
    l3_hosts = split_hosts(config['CONFIG_NEUTRON_L3_HOSTS'])
    dhcp_hosts = split_hosts(config['CONFIG_NEUTRON_DHCP_HOSTS'])
    lbaas_hosts = split_hosts(config['CONFIG_NEUTRON_LBAAS_HOSTS'])
    meta_hosts = split_hosts(config['CONFIG_NEUTRON_METADATA_HOSTS'])
    compute_hosts = set()
    if config['CONFIG_NOVA_INSTALL'] == 'y':
        compute_hosts = split_hosts(config['CONFIG_NOVA_COMPUTE_HOSTS'])
    q_hosts = api_hosts | l3_hosts | dhcp_hosts | lbaas_hosts | compute_hosts | meta_hosts

    neutron_steps = [
        {'title': 'Adding Neutron API manifest entries',
         'functions': [create_manifests]},
        {'title': 'Adding Neutron Keystone manifest entries',
         'functions': [create_keystone_manifest]},
        {'title': 'Adding Neutron L3 manifest entries',
         'functions': [create_l3_manifests]},
        {'title': 'Adding Neutron L2 Agent manifest entries',
         'functions': [create_l2_agent_manifests]},
        {'title': 'Adding Neutron DHCP Agent manifest entries',
         'functions': [create_dhcp_manifests]},
        {'title': 'Adding Neutron LBaaS Agent manifest entries',
         'functions': [create_lbaas_manifests]},
        {'title': 'Adding Neutron Metadata Agent manifest entries',
         'functions': [create_metadata_manifests]},
    ]
    controller.addSequence("Installing OpenStack Neutron", [], [],
                           neutron_steps)

def create_manifests(config):
    global q_hosts

    service_plugins = []
    if config['CONFIG_NEUTRON_LBAAS_HOSTS']:
        service_plugins.append(
            'neutron.services.loadbalancer.plugin.LoadBalancerPlugin'
        )
    if config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2':
        # ML2 uses the L3 Router service plugin to implement l3 agent
        service_plugins.append(
            'neutron.services.l3_router.l3_router_plugin.L3RouterPlugin'
        )

    config['SERVICE_PLUGINS'] = (str(service_plugins) if service_plugins
                                 else 'undef')

    if config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch':
        nettype = config.get("CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE", "local")
        plugin_manifest = 'neutron_ovs_plugin_%s.pp' % nettype
    elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'linuxbridge':
        plugin_manifest = 'neutron_lb_plugin.pp'
    elif config['CONFIG_NEUTRON_L2_PLUGIN'] == 'ml2':
        plugin_manifest = 'neutron_ml2_plugin.pp'

    # host to which allow neutron server
    allowed_hosts = set(q_hosts)
    if config['CONFIG_CLIENT_INSTALL'] == 'y':
        allowed_hosts.add(config['CONFIG_OSCLIENT_HOST'])
    if config['CONFIG_HORIZON_INSTALL'] == 'y':
        allowed_hosts.add(config['CONFIG_HORIZON_HOST'])
    if config['CONFIG_NOVA_INSTALL'] == 'y':
        allowed_hosts.add(config['CONFIG_NOVA_API_HOST'])

    config['FIREWALL_SERVICE_NAME'] = "neutron server"
    config['FIREWALL_PORTS'] = "'9696'"
    config['FIREWALL_CHAIN'] = "INPUT"

    for host in q_hosts:
        manifest_file = "%s_neutron.pp" % (host,)
        manifest_data = getManifestTemplate("neutron.pp")
        manifest_data += getManifestTemplate(get_mq(config, "neutron"))
        appendManifestFile(manifest_file, manifest_data, 'neutron')

        if host in api_hosts:
            manifest_file = "%s_neutron.pp" % (host,)
            manifest_data = getManifestTemplate("neutron_api.pp")
            # Firewall Rules
            for f_host in q_hosts:
                config['FIREWALL_ALLOWED'] = "'%s'" % f_host
                config['FIREWALL_SERVICE_ID'] = "neutron_server_%s_%s" % (host, f_host)
                manifest_data += getManifestTemplate("firewall.pp")

            appendManifestFile(manifest_file, manifest_data, 'neutron')

        # Set up any l2 plugin configs we need anywhere we install neutron
        # XXX I am not completely sure about this, but it seems necessary:
        manifest_data = getManifestTemplate(plugin_manifest)
        appendManifestFile(manifest_file, manifest_data, 'neutron')

def create_keystone_manifest(config):
    manifestfile = "%s_keystone.pp" % config['CONFIG_KEYSTONE_HOST']
    manifestdata = getManifestTemplate("keystone_neutron.pp")
    appendManifestFile(manifestfile, manifestdata)

def find_mapping(haystack, needle):
    return needle in [x.split(':')[1].strip() for x in get_values(haystack)]

def create_l3_manifests(config):
    global l3_hosts

    plugin = config['CONFIG_NEUTRON_L2_PLUGIN']
    if config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] == 'provider':
        config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] = ''

    for host in l3_hosts:
        config['CONFIG_NEUTRON_L3_HOST'] = host
        config['CONFIG_NEUTRON_L3_INTERFACE_DRIVER'] = get_if_driver(config)
        manifestdata = getManifestTemplate("neutron_l3.pp")
        manifestfile = "%s_neutron.pp" % (host,)
        appendManifestFile(manifestfile, manifestdata + '\n')
        if (config['CONFIG_NEUTRON_L2_PLUGIN'] == 'openvswitch' and
                config['CONFIG_NEUTRON_L3_EXT_BRIDGE'] and
                not find_mapping(config['CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS'],
                                 config['CONFIG_NEUTRON_L3_EXT_BRIDGE'])):
            config['CONFIG_NEUTRON_OVS_BRIDGE'] = config['CONFIG_NEUTRON_L3_EXT_BRIDGE']
            manifestdata = getManifestTemplate('neutron_ovs_bridge.pp')
            appendManifestFile(manifestfile, manifestdata + '\n')

def create_dhcp_manifests(config):
    global dhcp_hosts

    plugin = config['CONFIG_NEUTRON_L2_PLUGIN']

    for host in dhcp_hosts:
        config["CONFIG_NEUTRON_DHCP_HOST"] = host
        config['CONFIG_NEUTRON_DHCP_INTERFACE_DRIVER'] = get_if_driver(config)
        manifest_data = getManifestTemplate("neutron_dhcp.pp")
        manifest_file = "%s_neutron.pp" % (host,)

        # Firewall Rules
        for f_host in q_hosts:
            config['FIREWALL_ALLOWED'] = "'%s'" % f_host
            config['FIREWALL_SERVICE_NAME'] = "neutron dhcp in"
            config['FIREWALL_SERVICE_ID'] = "neutron_dhcp_in_%s_%s" % (host, f_host)
            config['FIREWALL_PORTS'] = "'67'"
            config['FIREWALL_CHAIN'] = "INPUT"
            manifest_data += getManifestTemplate("firewall.pp")
            config['FIREWALL_SERVICE_NAME'] = "neutron dhcp out"
            config['FIREWALL_SERVICE_ID'] = "neutron_dhcp_out_%s_%s" % (host, f_host)
            config['FIREWALL_PORTS'] = "'68'"
            config['FIREWALL_CHAIN'] = "OUTPUT"
            manifest_data += getManifestTemplate("firewall.pp")

        appendManifestFile(manifest_file, manifest_data, 'neutron')

def create_lbaas_manifests(config):
    global lbaas_hosts
    for host in lbaas_hosts:
        controller.CONF['CONFIG_NEUTRON_LBAAS_INTERFACE_DRIVER'] = get_if_driver(config)
        manifestdata = getManifestTemplate("neutron_lbaas.pp")
        manifestfile = "%s_neutron.pp" % (host,)
        appendManifestFile(manifestfile, manifestdata + "\n")

def get_values(val):
    return [x.strip() for x in val.split(',')] if val else []

def get_agent_type(config):
    # The only real use case I can think of for multiples right now is to list
    # "vlan,gre" or "vlan,vxlan" so that VLANs are used if available,
    # but tunnels are used if not.
    tenant_types = config.get('CONFIG_NEUTRON_ML2_TENANT_NETWORK_TYPES',
                              "['local']").strip('[]')
    tenant_types = [i.strip('"\'') for i in tenant_types.split(',')]

    for i in ['gre', 'vxlan', 'vlan']:
        if i in tenant_types:
            return i
    return tenant_types[0]

def create_l2_agent_manifests(config):
    global api_hosts, compute_hosts, dhcp_host, l3_hosts

    plugin = config['CONFIG_NEUTRON_L2_PLUGIN']
    agent = config["CONFIG_NEUTRON_L2_AGENT"]

    if agent == "openvswitch":
        host_var = 'CONFIG_NEUTRON_OVS_HOST'
        if plugin == agent:
            # monolithic plugin installation
            ovs_type = 'CONFIG_NEUTRON_OVS_TENANT_NETWORK_TYPE'
            ovs_type = config.get(ovs_type, 'local')
        elif plugin == 'ml2':
            ovs_type = get_agent_type(config)
        else:
            raise RuntimeError('Invalid combination of plugin and agent.')
        template_name = "neutron_ovs_agent_%s.pp" % ovs_type

        bm_arr = get_values(config["CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS"])
        iface_arr = get_values(config["CONFIG_NEUTRON_OVS_BRIDGE_IFACES"])

        # The CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS parameter contains a
        # comma-separated list of bridge mappings. Since the puppet module
        # expects this parameter to be an array, this parameter must be properly
        # formatted by packstack, then consumed by the puppet module.
        # For example, the input string 'A, B, C' should formatted as '['A','B','C']'.
        config["CONFIG_NEUTRON_OVS_BRIDGE_MAPPINGS"] = str(bm_arr)
    elif agent == "linuxbridge":
        host_var = 'CONFIG_NEUTRON_LB_HOST'
        template_name = 'neutron_lb_agent.pp'
    else:
        raise KeyError("Unknown layer2 agent")

    # Install l2 agents on every compute host in addition to any hosts listed
    # specifically for the l2 agent
    for host in api_hosts | compute_hosts | dhcp_hosts | l3_hosts:
        config[host_var] = host
        manifestfile = "%s_neutron.pp" % (host,)
        manifestdata = getManifestTemplate(template_name)
        appendManifestFile(manifestfile, manifestdata + "\n")
        if agent == "openvswitch" and ovs_type == 'vlan':
            for if_map in iface_arr:
                config['CONFIG_NEUTRON_OVS_BRIDGE'], config['CONFIG_NEUTRON_OVS_IFACE'] = if_map.split(':')
                manifestdata = getManifestTemplate("neutron_ovs_port.pp")
                appendManifestFile(manifestfile, manifestdata + "\n")
        # Additional configurations required for compute hosts
        if host in compute_hosts:
            manifestdata = getManifestTemplate('neutron_bridge_module.pp')
            appendManifestFile(manifestfile, manifestdata + '\n')

def create_metadata_manifests(config):
    global meta_hosts
    if config.get('CONFIG_NOVA_INSTALL') == 'n':
        return
    for host in meta_hosts:
        controller.CONF['CONFIG_NEUTRON_METADATA_HOST'] = host
        manifestdata = getManifestTemplate('neutron_metadata.pp')
        manifestfile = "%s_neutron.pp" % (host,)
        appendManifestFile(manifestfile, manifestdata + "\n")


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "sample".
 *
 * @property integer $id
 * @property string $thought
 * @property integer $goodness
 * @property integer $rank
 * @property string $censorship
 * @property string $occurred
 */
class Sample extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sample';
    }

   public $captcha;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
      [['thought'], 'string', 'max' => 255],
      ['thought', 'match', 'pattern' => '/^[a-z][A-Za-z,;\"\\s]+[!?.]$/i','message'=>Yii::t('app','Your thoughts should form a complete sentence of alphabetic characters.')],
      [['email'], 'email'],
       ['censorship', 'in', 'range' => ['yes','no','Yes','No'],'message'=>Yii::t('app','The censors demand a yes or no answer.')],
      [['url'], 'url'],
      [['captcha'], 'captcha'],
      [['rank'], 'integer'],
      ['rank', 'compare', 'compareValue' => 0, 'operator' => '>'],
      ['rank', 'compare', 'compareValue' => 100, 'operator' => '<='],
    ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'thought' => Yii::t('app', 'Thought'),
            'goodness' => Yii::t('app', 'Goodness'),
            'rank' => Yii::t('app', 'Rank'),
            'censorship' => Yii::t('app', 'Censorship'),
            'occurred' => Yii::t('app', 'Occurred'),
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.deeplearning4j.nd4j.linalg.api.blas;

import lombok.val;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import org.nd4j.common.tests.tags.NativeTag;
import org.nd4j.linalg.BaseNd4jTestWithBackends;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;

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

/**
 * @author Adam Gibson
 */
@NativeTag
public class Level1Test extends BaseNd4jTestWithBackends {

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testDot(Nd4jBackend backend) {
        INDArray vec1 = Nd4j.create(new float[] {1, 2, 3, 4});
        INDArray vec2 = Nd4j.create(new float[] {1, 2, 3, 4});
        assertEquals(30, Nd4j.getBlasWrapper().dot(vec1, vec2), 1e-1);

        INDArray matrix = Nd4j.linspace(1, 4, 4, DataType.FLOAT).reshape(2, 2);
        INDArray row = matrix.getRow(1);
        double dot = Nd4j.getBlasWrapper().dot(row, row);
        assertEquals(20, dot, 1e-1);

    }

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testAxpy(Nd4jBackend backend) {
        INDArray matrix = Nd4j.linspace(1, 4, 4, DataType.DOUBLE).reshape(2, 2);
        INDArray row = matrix.getRow(1);
        Nd4j.getBlasWrapper().level1().axpy(row.length(), 1.0, row, row);
        assertEquals(Nd4j.create(new double[] {4, 8}), row,getFailureMessage(backend));

    }

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testAxpy2(Nd4jBackend backend) {
        val rowX = Nd4j.create(new double[]{1, 2, 3, 4});
        val rowY = Nd4j.create(new double[]{1, 2, 3, 4});
        val exp = Nd4j.create(new double[]{3, 6, 9, 12});

        val z = Nd4j.getBlasWrapper().axpy(2.0, rowX, rowY);
        assertEquals(exp, z);
    }

    @Override
    public char ordering() {
        return 'f';
    }
}


text:
package com.gzgd.taxiapp2.common.http.impl;

import com.gzgd.taxiapp2.common.http.IHttpClient;
import com.gzgd.taxiapp2.common.http.IRequest;
import com.gzgd.taxiapp2.common.http.IResponse;

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

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by imxilife on 2017/10/20.
 */

public class OkHttpImpl implements IHttpClient {

    @Override
    public IResponse get(IRequest request, boolean force) {

        request.setMethod(IRequest.GET);
        Map<String,String>header = request.getHeader();
        request.getHeader();
        Headers.Builder builder = new Headers.Builder();
        for (String key :
                request.getHeader().keySet()) {
            builder.add(key,header.get(key));
        }
        Request req = new Request.Builder()
                .headers(builder.build())
                .url(request.getUrl())
                .get()
                .build();
        return execute(req);
    }

    @Override
    public IResponse post(IRequest request, boolean force) {

        request.setMethod(IRequest.POST);
        Map<String,String>header = request.getHeader();
        Headers.Builder builder = new Headers.Builder();
        for (String key :
                request.getHeader().keySet()) {
            builder.add(key,header.get(key));
        }

        Request req = new Request.Builder()
                .headers(builder.build())
                .url(request.getUrl())
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"),request.getBody().toString()))
                .build();
        return execute(req);
    }

    private IResponse execute(Request request){
        OkHttpClient client = new OkHttpClient();
        IResponse result = new BaseResponse();
        Response response;
        try {
                response = client.newCall(request).execute();
                result.setCode(response.code());
                result.setData(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(IResponse.ERROR_CODE);
            result.setData(null);
        }
        return result;
    }
}


text:
class ConditionAnd: public Condition {
public:
	ConditionAnd(Condition * first, Condition * second);

	virtual bool Check() const;
private:
	Condition * m_firstCondition;
	Condition * m_secondCondition;
};

#endif//!_CONDITION_AND_H


text:
AetherStackingMulti
===================

Stacking implementation of the Aether API that wraps multiple Aether implementations and present a single API.


text:
package br.com.projeto_cine440.model;

public class Cadastro {
    private int id;
    private String nome;
    private String email;
    private String senha;
    private String endereco;
    private String cpf;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }
}


text:
from enum import Enum

class EventType(Enum):
    """Enum containing the various types of events that can occur."""
    CLIENT_READY = "CLIENT_READY"
    CLIENT_RESUMED = "CLIENT_RESUMED"

    MESSAGE_RECEIVED = "MESSAGE_RECEIVED"
    SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED"
    PRIVATE_MESSAGE_RECEIVED = "PRIVATE_MESSAGE_RECEIVED"
    COMMAND_RECEIVED = "COMMAND_RECEIVED"

    MESSAGE_DELETED = "MESSAGE_DELETED"
    MESSAGE_EDITED = "MESSAGE_EDITED"

    CHANNEL_DELETED = "CHANNEL_DELETED"
    CHANNEL_CREATED = "CHANNEL_CREATED"
    CHANNEL_UPDATED = "CHANNEL_UPDATED"

    MEMBER_JOINED = "MEMBER_JOINED"
    MEMBER_REMOVED = "MEMBER_REMOVED"
    MEMBER_UPDATED = "MEMBER_UPDATED"
    MEMBER_BANNED = "MEMBER_BANNED"
    MEMBER_UNBANNED = "MEMBER_UNBANNED"
    MEMBER_TYPING = "MEMBER_TYPING"

    SERVER_JOINED = "SERVER_JOINED"
    SERVER_REMOVED = "SERVER_REMOVED"
    SERVER_UPDATED = "SERVER_UPDATED"

    ROLE_CREATED = "ROLE_CREATED"
    ROLE_DELETED = "ROLE_DELETED"
    ROLE_UPDATED = "ROLE_UPDATED"

    SERVER_AVAILABLE = "SERVER_AVAILABLE"
    SERVER_UNAVAILABLE = "SERVER_UNAVAILABLE"

    VOICE_STATE_UPDATED = "VOICE_STATE_UPDATED"

    REACTION_ADDED = "REACTION_ADDED"
    REACTION_REMOVED = "REACTION_REMOVED"
    REACTIONS_CLEARED = "REACTIONS_CLEARED"

    MEMBER_JOINED_GROUP = "MEMBER_JOINED_GROUP"
    MEMBER_REMOVED_FROM_GROUP = "MEMBER_REMOVED_FROM_GROUP"

    SERVER_EMOJIS_UPDATED = "SERVER_EMOJIS_UPDATED"

class RedisStorageScope(Enum):
    """Enum containing the possible Redis storage scopes."""
    GLOBAL = "GLOBAL"
    PLUGIN = "PLUGIN"
    SERVER = "SERVER"
    CHANNEL = "CHANNEL"
    USER = "USER"


text:
import tensorflow as tf

from neupy.core.properties import ProperFractionProperty, Property
from .base import GradientDescent

__all__ = ('Momentum',)

class Momentum(GradientDescent):
    """
    Momentum algorithm.

    Parameters
    ----------
    momentum : float
        Control previous gradient ratio. Defaults to ``0.9``.

    nesterov : bool
        Instead of classic momentum computes Nesterov momentum.
        Defaults to ``False``.

    {GradientDescent.Parameters}

    Attributes
    ----------
    {GradientDescent.Attributes}

    Methods
    -------
    {GradientDescent.Methods}

    Examples
    --------
    >>> import numpy as np
    >>> from neupy import algorithms
    >>> from neupy.layers import *
    >>>
    >>> x_train = np.array([[1, 2], [3, 4]])
    >>> y_train = np.array([[1], [0]])
    >>>
    >>> network = Input(2) >> Sigmoid(3) >> Sigmoid(1)
    >>> optimizer = algorithms.Momentum(network)
    >>> optimizer.train(x_train, y_train)

    See Also
    --------
    :network:`GradientDescent` : GradientDescent algorithm.
    """
    momentum = ProperFractionProperty(default=0.9)
    nesterov = Property(default=False, expected_type=bool)

    def init_train_updates(self):
        optimizer = tf.train.MomentumOptimizer(
            use_nesterov=self.nesterov,
            momentum=self.momentum,
            learning_rate=self.step,
        )
        self.functions.optimizer = optimizer
        return [optimizer.minimize(self.variables.loss)]


text:
import java.nio.file.{Files, Path}

import ru.ifmo.ds.Database
import ru.ifmo.ds.io.Json
import ru.ifmo.ds.ops.FindDifferences

vars.stateFileName = "state.properties"
vars.singleStep = false
vars.dataRoot = "performance-data"

val DataSubdirectoryRaw = "raw"
val DataSubdirectoryConsolidated = "merged"
val ListOfAlgorithms = "changed.lst"
val BasicPValue = 1e-15
val KeyValue = "primaryMetric.rawData"
val KeyCats = Seq("benchmark", "params.d", "params.f", "params.n")
val KeyAlgorithm = "params.algorithmId"

class ComputeMinimal(useKey: String) extends Phase(s"phase.minimal-$useKey.compute") {
  override def execute(projectRoot: Path, curr: Path, prev: Option[Path]): Unit = {
    val currentPhaseOut = s"minimal-$useKey.json"
    val rawDir = curr.resolve(DataSubdirectoryRaw)
    Files.createDirectories(rawDir)
    val outputFile = rawDir.resolve(currentPhaseOut)
    val listOfAlgorithms = curr.resolve(ListOfAlgorithms)
    val algorithms = if (Files.exists(listOfAlgorithms)) {
      Utils.firstTokensOfUncommentedLines(listOfAlgorithms).mkString("--algo=", ",", "")
    } else ""
    if (algorithms == "--algo=") {
      // When an empty parameter list is given, JMH thinks one shall use the compiled-in parameters, which fails.
      // Write an empty JSON file instead.
      Utils.writeLines(outputFile, Seq("[]"))
    } else {
      Utils.runProcess(projectRoot,
        "sbt",
        "project benchmarking",
        s"jmh:runMain ru.ifmo.nds.jmh.main.Minimal $algorithms --use=$useKey --out=${outputFile.toAbsolutePath}")
    }
    Utils.gzipJson(outputFile)
  }
}

object CompareMinimal extends Phase("phase.minimal-min.compare") {
  override def execute(projectRoot: Path, curr: Path, prevOption: Option[Path]): Unit = {
    val currentPhaseIn = "minimal-min.json.gz"
    val listOfAlgorithms = curr.resolve(ListOfAlgorithms)
    prevOption match {
      case Some(prev) =>
        val oldDB = Json.fromFile(prev.resolve(DataSubdirectoryConsolidated).resolve(currentPhaseIn).toFile)
        val newDB = Json.fromFile(curr.resolve(DataSubdirectoryRaw).resolve(currentPhaseIn).toFile)
        val commonAlgorithms = oldDB.valuesUnderKey(KeyAlgorithm).intersect(newDB.valuesUnderKey(KeyAlgorithm))
        val listener = new CompareListener(BasicPValue / commonAlgorithms.size, KeyAlgorithm)
        FindDifferences.traverse(oldDB, newDB, KeyAlgorithm +: KeyCats, KeyValue, listener)
        Utils.writeLines(listOfAlgorithms, listener.result())
      case None =>
        // No previous runs detected. Need to write all algorithms to the file
        val file = curr.resolve(DataSubdirectoryRaw).resolve(currentPhaseIn)
        val allAlgorithms = Json.fromFile(file.toFile).valuesUnderKey(KeyAlgorithm).flatten.toIndexedSeq.sorted
        Utils.writeLines(listOfAlgorithms, allAlgorithms)
    }
  }
}

class Consolidate(key: String) extends Phase(s"phase.$key.consolidate") {
  override def execute(projectRoot: Path, curr: Path, prevOption: Option[Path]): Unit = {
    val target = curr.resolve(DataSubdirectoryConsolidated)
    val currentPhaseOut = key + ".json.gz"
    Files.createDirectories(target)
    val trg = target.resolve(currentPhaseOut)
    prevOption match {
      case None =>
        // no previous runs - just copy a file over
        val src = curr.resolve(DataSubdirectoryRaw).resolve(currentPhaseOut)
        if (!Files.exists(trg) || !Files.isSameFile(trg, src)) {
          Files.deleteIfExists(trg)
          Files.createLink(trg, src)
        }
      case Some(prev) =>
        val oldDB = Json.fromFile(prev.resolve(DataSubdirectoryConsolidated).resolve(currentPhaseOut).toFile)
        val newDB = Json.fromFile(curr.resolve(DataSubdirectoryRaw).resolve(currentPhaseOut).toFile)
        val differingAlgorithms = Utils.firstTokensOfUncommentedLines(curr.resolve(ListOfAlgorithms))
        val oldDBFiltered = oldDB.filter(e => e.contains(KeyAlgorithm) && !differingAlgorithms.contains(e(KeyAlgorithm)))
        val merged = Database.merge(oldDBFiltered, newDB)
        Json.writeToFile(merged, trg.toFile)
    }
  }
}

vars.phases = Seq(
  new ComputeMinimal("min"),
  CompareMinimal,
  new Consolidate("minimal-min"),
  new ComputeMinimal("more-d"),
  new Consolidate("minimal-more-d"),
  new ComputeMinimal("more-n"),
  new Consolidate("minimal-more-n")
)


text:
package org.scribble.del.global;

import org.scribble.ast.ScribNode;
import org.scribble.del.InteractionNodeDel;
import org.scribble.del.ScribDelBase;
import org.scribble.main.ScribbleException;
import org.scribble.visit.context.Projector;

public interface GInteractionNodeDel extends InteractionNodeDel
{
	//public abstract LNode project(GNode n, Role self);  // Generalised return, e.g. returning a seq

	@Override
	default void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException
	{
		ScribDelBase.pushVisitorEnv(this, proj);
	}

	@Override
	default ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException
	{
		return ScribDelBase.popAndSetVisitorEnv(this, proj, visited);
	}
}


text:
package de.cosmocode.palava.core.inject;

import java.util.UUID;

import org.junit.Assert;
import org.junit.Test;

import com.google.inject.TypeLiteral;

import de.cosmocode.junit.UnitProvider;

/**
 * Tests {@link UUIDConverter}.
 *
 * @since 2.4
 * @author Willi Schoenborn
 */
public final class UUIDConverterTest implements UnitProvider<UUIDConverter> {

    private static final TypeLiteral<UUID> LITERAL = TypeLiteral.get(UUID.class);

    @Override
    public UUIDConverter unit() {
        return new UUIDConverter();
    }

    /**
     * Tests {@link UUIDConverter#convert(String, TypeLiteral)} with a valid uuid.
     */
    @Test
    public void valid() {
        final UUID uuid = UUID.randomUUID();
        Assert.assertEquals(uuid, unit().convert(uuid.toString(), LITERAL));
    }

    /**
     * Tests {@link UUIDConverter#convert(String, TypeLiteral)} with an invalid uuid.
     */
    @Test(expected = RuntimeException.class)
    public void invalid() {
        unit().convert("", LITERAL);
    }

}


text:
'use strict'

// DO NOT RUN HAPI TESTS FOR NODE LESS THAN 4.0.0
if (process.version < 'v4.0.0') {
  return
}

var Assert = require('assert')

var Lab = require('lab')
var lab = exports.lab = Lab.script()
var suite = lab.suite
var test = lab.test
var before = lab.before
var after = lab.after

var Util = require('./hapi-util')

suite('Hapi register-login-logout suite tests ', function () {
  var server
  var user = {nick: 'u1', name: 'nu1', email: 'u1@example.com', password: 'u1', active: true}
  var cookie

  before({}, function (done) {
    Util.init({}, function (err, srv) {
      Assert.ok(!err)

      server = srv
      done()
    })
  })

  after({}, function (done) {
    server.seneca.close()
    done()
  })

  test('auth/register test', function (done) {
    var url = '/auth/register'

    server.inject({
      url: url,
      method: 'POST',
      payload: user
    }, function (res) {
      Assert.equal(200, res.statusCode)
      Assert(JSON.parse(res.payload).ok)
      Assert(JSON.parse(res.payload).user)
      Assert(JSON.parse(res.payload).login)

      cookie = Util.checkCookie(res)

      done()
    })
  })

  test('auth/logout test', function (done) {
    var url = '/auth/logout'

    server.inject({
      url: url,
      method: 'GET',
      headers: {cookie: 'seneca-login=' + cookie}
    }, function (res) {
      Assert.equal(200, res.statusCode)
      Assert(JSON.parse(res.payload).ok)
      Assert(!JSON.parse(res.payload).user)
      Assert(!JSON.parse(res.payload).login)

      done()
    })
  })

  test('auth/login test', function (done) {
    var url = '/auth/login'

    server.inject({
      url: url,
      method: 'POST',
      payload: user
    }, function (res) {
      Assert.equal(200, res.statusCode)
      Assert(JSON.parse(res.payload).ok)
      Assert(JSON.parse(res.payload).user)
      Assert(JSON.parse(res.payload).login)

      cookie = Util.checkCookie(res)

      done()
    })
  })

  test('auth/user after register', function (done) {
    var url = '/auth/user'

    server.inject({
      url: url,
      method: 'POST',
      headers: {cookie: 'seneca-login=' + cookie}
    }, function (res) {
      Assert.equal(200, res.statusCode)
      Assert(JSON.parse(res.payload).ok)
      Assert(JSON.parse(res.payload).user)
      done()
    })
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/background_dark">

    <com.dzyjy.nfc.view.TitleLayout
        android:id="@+id/photo_show"
        android:layout_width="match_parent"
        android:layout_height="50dip" >
    </com.dzyjy.nfc.view.TitleLayout>

    <ImageView
        android:id="@+id/show_imageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ImageView>

</LinearLayout>


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgbAccordion, NgbPanel, NgbPanelTitle, NgbPanelContent } from './accordion';
import { NgbAccordionConfig } from './accordion-config';
export { NgbAccordion, NgbPanel, NgbPanelTitle, NgbPanelContent } from './accordion';
export { NgbAccordionConfig } from './accordion-config';
var NGB_ACCORDION_DIRECTIVES = [NgbAccordion, NgbPanel, NgbPanelTitle, NgbPanelContent];
export var NgbAccordionModule = (function () {
    function NgbAccordionModule() {
    }
    NgbAccordionModule.forRoot = function () { return { ngModule: NgbAccordionModule, providers: [NgbAccordionConfig] }; };
    NgbAccordionModule.decorators = [
        { type: NgModule, args: [{ declarations: NGB_ACCORDION_DIRECTIVES, exports: NGB_ACCORDION_DIRECTIVES, imports: [CommonModule] },] },
    ];
    /** @nocollapse */
    NgbAccordionModule.ctorParameters = [];
    return NgbAccordionModule;
}());
//# sourceMappingURL=accordion.module.js.map


text:
/***
	Demo Styles

	These do not need to be included if you are not using the demo features. These include
	items like the skin slider for dynamic theme changing, etc.
***/

/* skin slider */
.ui-state-default, .ui-widget-content .ui-state-default { border:1px solid #4A4A4A; color:#4A4A4A; font-weight:bold; outline-style:none; outline-width:medium; }
.ui-slider { position:relative; text-align:left; }
.ui-widget-content { background:#eee; border:1px solid #ddd; color:#333; }
.ui-slider-horizontal .ui-slider-handle { background: transparent url("../images/icons/slider-handle.gif") no-repeat 0 0; height:18px; margin-left: -13px; top: -6px; width:27px; }
.ui-slider .ui-slider-handle { cursor:default; position:absolute; z-index:2; }
.ui-slider-horizontal { height:8px; background: #343434; border-color: #4A4A4A; }
#SkinSlider .ui-state-hover, #SkinSlider .ui-state-active, #SkinSlider .ui-state-focus	{ border-color: #8A8A8A; }
#SkinPreviewWrapper { position: relative;  height:428px; margin: 0 0 1em; }
#SkinPreview { width: 247px; height:298px; overflow:hidden;}
#SkinPreviewOverlay { width: 273px; height:428px; position: absolute; top: 0; z-index:29; background: transparent url(../images/content/skin-changer/skin-changer-overlay.png) no-repeat 0 0;}
#SkinScreenShots {position: absolute; top: 42px; left: 13px; }
#SkinSlider { margin: 20px 0 0 35px; width:200px; z-index: 30; position:absolute; bottom: 50px; }
#SkinPreviewWrapper h4 {position: relative; z-index: 30; text-align:center; top:19px; color: #ccc;}
#SkinPreviewWrapper #SkinSliderHelpText { bottom:12px; color:#888; font-size:0.9em; position:absolute; text-align:center; width:273px; z-index:30;}


text:
/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"C7D81C36-DD36-4C76-9F11-B462B1CEFB4F"}
 */
var _license_dsa_mosaic_WEB_cms_blocks = 'Module: _dsa_mosaic_WEB_cms_blocks \
									Copyright (C) 2011-2013 Data Mosaic \
									MIT Licensed';

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"346FEC3F-F398-4D41-AAED-610CCBB58F0B"}
 */
var _link = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"346FEC3F-F398-6D41-AAED-610CCBB58F0B"}
 */
var _name = null;

/**
 * @properties={typeid:24,uuid:"6E5DBDB8-F58E-40AB-9E1F-CF96F2CAD453"}
 * @AllowToRunInFind
 */
function INIT_data(data) {
	if (!(data instanceof Array)) {
		data = new Array(data)
	}

	for (var i = 0; i < data.length; i++) {
		var row = data[i]

		if (row && row.link && row.name) {
			var pageName = ''

			if (row.link.data) {
				var fsPage = databaseManager.getFoundSet('sutra_cms','web_page')
				fsPage.find()
				fsPage.id_page = row.link.data
				var results = fsPage.search()

				if (results) {
					pageName = fsPage.page_name
				}
			}

			_link = pageName
			_name = (row.name.data) ? row.name.data : pageName

			elements.lbl_link.text = row.link.label || solutionModel.getForm(controller.getName()).getLabel('lbl_link').text
			elements.lbl_name.text = row.name.label || solutionModel.getForm(controller.getName()).getLabel('lbl_name').text
		}
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"B106DA14-241E-41A0-946A-FCB31366D1DE"}
 */
function PAGE_picker(event,record) {
	if (event instanceof JSEvent) {
		globals.WEBc_page_picker(PAGE_picker,elements.lbl_link)
	}
	else {
		//if page name was same as old page selected, update display with new page name
		if (_link == _name || !_name) {
			var resetName = true
		}

		//actual page
		forms.WEB_0F__block_builder._blockList[forms.WEB_0F__block_builder._blockSelected].record.link.data = event
		_link = record.page_name

		//display value for page
		if (resetName) {
			forms.WEB_0F__block_builder._blockList[forms.WEB_0F__block_builder._blockSelected].record.name.data = record.page_name
			_name = record.page_name
		}
	}
}

/**
 * Handle changed data.
 *
 * @param {Object} oldValue old value
 * @param {Object} newValue new value
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"A330C9C7-36EF-43FD-83AC-A5EBBD2BD0C4"}
 */
function onDataChange(oldValue, newValue, event) {
	forms.WEB_0F__block_builder._blockList[forms.WEB_0F__block_builder._blockSelected].record.name.data = newValue
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("makemodule")]
[assembly: AssemblyDescription("Module generation tool")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sam Saint-Pettersen")]
[assembly: AssemblyProduct("makemodule")]
[assembly: AssemblyCopyright("Copyright ©  2015 Sam Saint-Pettersen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("33d526cb-4760-4dcc-bae8-7afbe2aad799")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
Silo
====

Silo is command-line utility and Ruby API for Git-based backups. With Silo you
can backup arbitrary files into one or more Git repositories and take advantage
of Git's compression, speed and other features. No Git knowledge needed.

## Concept

To backup files into a repository Silo uses the well-known and established
version control system (VCS) Git. Instead of using Git's frontend commands for
the end-user, so called *"porcelain"* commands, Silo makes use of the more
low-level *"plumbing"* commands. These can be used to write directly to the Git
repository, bypassing the automatisms tailored for source code histories.

## Requirements

* Grit – a Ruby API for Git
* Rubikon – a Ruby framework for console applications
* Git >= 1.6

## Installation

You can install Silo using RubyGems. This is the easiest way of installing
and recommended for most users.

    $ gem install silo

If you want to use the development code you can add the following dependency
to your Gemfile:

    gem 'silo', :git => git://github.com/koraktor/silo.git

If you want to work with the development code you should clone the Git
repository:

    $ git clone git://github.com/koraktor/silo.git
    $ cd silo
    $ bundle install

Or even better, create your own fork.

The current status of the development code:
[![Build Status](http://travis-ci.org/koraktor/silo.png)][6]

## Basic usage

### Configuration files

Silo searches for configuration files (`.silo`) in the current working
directory, your home directory and your systems global configuration directory
(i.e. /etc on Unix).

They can be used to set Silo-specific options globally or for single
directories. That way you may have one general Silo repository for common
backups and another Silo repository for e.g. work-related files.

Configuration files are expected in a Git-like format and
may contain the following sections and variables:

* repository

  * path – The path of the default repository to use
  * prefix – The path inside the repository to store files to per default

#### Sample

    [repository]
      path   = /Users/jondoe/backup.git
      prefix = work

This would usually save and restore files to and from
`/Users/jondoe/backup.git` and save files into the directory `work` inside the
repository.

### Initialize a repository

    $ silo init [repository path]

### Add files or directories to the repository

    $ silo add file [file ...] [--prefix <prefix>]

The prefix allows to organize the files inside the repository.

### Restore files or directories from the repository

    $ silo restore file [file ...] [--prefix <prefix>]

The prefix is the directory inside your file system where the restored files
will be saved.

### Remove files or directories from the repository

    $ silo remove file [file ...]
    $ silo rm file [file ...]

### Completely purge files or directories from the repository

    $ silo purge file [file ...] [--no-clean]

This will completely remove the specified files from the repository and thus
reduce the required disk space.

**WARNING**: There's no method built-in to Silo or Git to recover files after
purging.

The `--no-clean` flag will cause Git commits to persist even after their
contents have been purged.

### Manage remote repositories for mirrored backups

    $ silo remote [-v]
    $ silo remote add name url
    $ silo remote rm name

Add or remove a remote repository with the specified name. When adding a remote
repository the specified location may be given as any location Git understands
– including file system paths.

### Distribute the state of your repository to all mirror repositories

    $ silo distribute

### List repository contents

    $ silo list [file ...] [-l] [-r]

The `-l` flag will list each directory and file in a separate line, `-r` will
reverse the listing.

### Display info about repository contents

    $ silo info [file ...] [-v]

## Using the Ruby API

The documentation of the Ruby API can be seen at [RubyDoc.info][1]. The API
documentation of the current development version is also available [there][5].

## License

This code is free software; you can redistribute it and/or modify it under the
terms of the new BSD License. A copy of this license can be found in the
LICENSE file.

## Credits

* Sebastian Staudt – koraktor(at)gmail.com

## See Also

* [API documentation][1]
* [Silo's homepage][2]
* [GitHub project page][3]
* [GitHub issue tracker][4]

Follow Silo on Twitter [@silorb](http://twitter.com/silorb).

 [1]: http://rubydoc.info/gems/silo/frames
 [2]: http://koraktor.github.com/silo
 [3]: http://github.com/koraktor/silo
 [4]: http://github.com/koraktor/silo/issues
 [5]: http://rubydoc.info/github/koraktor/silo/master/frames
 [6]: http://travis-ci.org/koraktor/silo


text:
from six.moves.urllib.parse import parse_qs
from xml.dom.minidom import parseString
import json

class XeroException(Exception):
    """ Xero exceptions.
    """
    def __init__(self, response, msg=None):
        self.response = response
        super(XeroException, self).__init__(msg)

class XeroNotVerified(Exception):
    """ Credentials haven't been verified.
    """
    pass

class XeroBadRequest(XeroException):
    """ HTTP 400: Bad Request.
    """
    def __init__(self, response):
        if response.headers['content-type'].startswith('application/json'):
            data = json.loads(response.text)
            msg = "%s: %s" % (data['Type'], data['Message'])
            self.errors = [err['Message']
                for elem in data['Elements']
                for err in elem['ValidationErrors']
            ]
            self.problem = self.errors[0]
            super(XeroBadRequest, self).__init__(response, msg=msg)

        elif response.headers['content-type'].startswith('text/html'):
            payload = parse_qs(response.text)
            self.errors = [
                payload['oauth_problem'][0],
            ]
            self.problem = self.errors[0]
            super(XeroBadRequest, self).__init__(
                response, payload['oauth_problem_advice'][0]
            )

        else:
            # Extract the messages from the text.
            # parseString takes byte content, not unicode.
            dom = parseString(response.text.encode(response.encoding))
            messages = dom.getElementsByTagName('Message')

            msg = messages[0].childNodes[0].data
            self.errors = [
                m.childNodes[0].data for m in messages[1:]
            ]
            self.problem = self.errors[0]
            super(XeroBadRequest, self).__init__(response, msg)

class XeroUnauthorized(XeroException):
    """ HTTP 401: Unauthorized.
    """
    def __init__(self, response):
        payload = parse_qs(response.text)
        self.problem = payload['oauth_problem'][0]
        super(XeroUnauthorized, self).__init__(
            response, payload['oauth_problem_advice'][0]
        )

class XeroForbidden(XeroException):
    """ HTTP 403: Forbidden.
    """
    def __init__(self, response):
        super(XeroForbidden, self).__init__(response, response.text)

class XeroNotFound(XeroException):
    """ HTTP 404: Not Found.
    """
    def __init__(self, response):
        super(XeroNotFound, self).__init__(response, response.text)

class XeroUnsupportedMediaType(XeroException):
    """ HTTP 415: UnsupportedMediaType.
    """
    def __init__(self, response):
        super(XeroUnsupportedMediaType, self).__init__(response, response.text)

class XeroInternalError(XeroException):
    """ HTTP 500: Internal Error.
    """
    def __init__(self, response):
        super(XeroInternalError, self).__init__(response, response.text)

class XeroNotImplemented(XeroException):
    """ HTTP 501.
    """
    def __init__(self, response):
        # Extract the useful error message from the text.
        # parseString takes byte content, not unicode.
        dom = parseString(response.text.encode(response.encoding))
        messages = dom.getElementsByTagName('Message')

        msg = messages[0].childNodes[0].data
        super(XeroNotImplemented, self).__init__(response, msg)

class XeroRateLimitExceeded(XeroException):
    """ HTTP 503 - Rate limit exceeded.
    """
    def __init__(self, response, payload):
        self.problem = payload['oauth_problem'][0]
        super(XeroRateLimitExceeded, self).__init__(
            response, payload['oauth_problem_advice'][0]
        )

class XeroNotAvailable(XeroException):
    """ HTTP 503 - Not available.
    """
    def __init__(self, response):
        super(XeroNotAvailable, self).__init__(response, response.text)

class XeroExceptionUnknown(XeroException):
    """ Any other exception.
    """
    pass


text:
export default function AppRouting($stateProvider, $urlRouterProvider, $locationProvider) {
    'ngInject';

    let defaultPath = ''
    // if ($location.host().match('github.io')) {
    // let defaultPath = '/LunAppAngular';
    // }
    $urlRouterProvider.otherwise(defaultPath);
    $locationProvider.html5Mode(true);

    $stateProvider
    // Dashboard
        .state('basic', {
            url: defaultPath + '/',
            templateUrl: 'app/routes/UserBasicInfo/UserBasicInfo.html',
            controller: 'UserBasicInfoController',
            controllerAs: 'ctrl',
            data: {
                pageTitle: 'Basic Info',
                state: 1,
                description: '1. Insert your name and email'
            },
            resolve: {

            }
        })
        .state('geo', {
            url: defaultPath + '/geo',
            templateUrl: 'app/routes/UserGeo/UserGeo.html',
            controller: 'UserGeoController',
            controllerAs: 'ctrl',
            data: {
                pageTitle: 'Geo Info',
                state: 2,
                description: '2. Select your country and city'
            },
            resolve: {

            }
        })
        .state('social', {
            url: defaultPath + '/social',
            templateUrl: 'app/routes/UserSocial/UserSocial.html',
            controller: 'UserSocialController',
            controllerAs: 'ctrl',
            data: {
                pageTitle: 'Social Info',
                state: 3,
                description: '3. Select your social networks'
            },
            resolve: {}
        })
        .state('pet', {
            url: defaultPath + '/pet',
            templateUrl: 'app/routes/UserPet/UserPet.html',
            controller: 'UserPetController',
            controllerAs: 'ctrl',
            data: {
                pageTitle: 'Pet Info',
                state: 4,
                description: '4. Select your favorite cat'

            },
            resolve: {}
        })
        .state('summary', {
            url: defaultPath + '/summary',
            templateUrl: 'app/routes/UserSummary/UserSummary.html',
            controller: 'UserSummaryController',
            controllerAs: 'ctrl',
            data: {
                pageTitle: 'Summary',
                state: 5
            },
            resolve: {}
        })
}


text:
layout: post
title: 392 - Is Subsequence
date: 2017-11-11
tags:
- Leetcode
categories:
- String
author: Jason
---
**Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).**

```python
class Solution(object):
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        if not s:
            return True
        s_index = t_index = 0
        while t_index < len(t):
            if s[s_index] == t[t_index]:
                s_index += 1
                if s_index == len(s):
                    return True
            t_index += 1
        return False
```


text:
import merge from 'lodash/merge';
import getMuiTheme from '../styles/getMuiTheme';
import warning from 'warning';

export default
  {
    getMuiTheme(baseTheme, muiTheme) {
      warning(false, 'ThemeManager is deprecated. please import getMuiTheme' +
        ' directly from "material-ui/styles/getMuiTheme"');
      return getMuiTheme(baseTheme, muiTheme);
    },
    modifyRawThemeSpacing(muiTheme, spacing) {
      warning(false, 'modifyRawThemeSpacing is deprecated. please use getMuiTheme ' +
        ' to modify your theme directly. http://www.material-ui.com/#/customization/themes');
      return getMuiTheme(merge({}, muiTheme.baseTheme, {spacing}));
    },
    modifyRawThemePalette(muiTheme, palette) {
      warning(false, 'modifyRawThemePalette is deprecated. please use getMuiTheme ' +
        ' to modify your theme directly. http://www.material-ui.com/#/customization/themes');
      return getMuiTheme(merge({}, muiTheme.baseTheme, {baseTheme: {palette}}));
    },
    modifyRawThemeFontFamily(muiTheme, fontFamily) {
      warning(false, 'modifyRawThemeFontFamily is deprecated. please use getMuiTheme ' +
        ' to modify your theme directly. http://www.material-ui.com/#/customization/themes');
      return getMuiTheme(merge({}, muiTheme.baseTheme, {fontFamily}));
    },
  };


text:
module.exports = {
    actionWrapper: require('./action-wrapper'),
    cartridge: require('./cartridge'),
    summary: require('./summary'),
    mixin: require('./mixin')
};


text:
<?php

namespace Stakhanovist\Queue\Parameter;

use Stakhanovist\Queue\Exception;
use Zend\Stdlib\Parameters;

/**
 * Class SendParameters
 */
class SendParameters extends Parameters implements SendParametersInterface
{
    /**
     * Set message schedule time
     *
     * $scheduleTime must be an unix timestamp or null (to disable this feature)
     * If $scheduleTime is setted, the message will be "invisibile" to readers
     * until the scheduled time.
     *
     * @param int $scheduleTime
     * @throws Exception\InvalidArgumentException
     * @return $this
     */
    public function setSchedule($scheduleTime = null)
    {
        if (($scheduleTime !== null) && !is_int($scheduleTime)) {
            throw new Exception\InvalidArgumentException('$scheduleTime must be a int or null');
        }
        $this->set(self::SCHEDULE, $scheduleTime);
        return $this;
    }

    /**
     * Get message schedule time
     *
     * @see setSchedule()
     *
     * @return int|null
     */
    public function getSchedule()
    {
        return $this->get(self::SCHEDULE, false);
    }

    /**
     * Set message repeating interval
     *
     * $repeatingInterval must be an int (seconds) or null (to disable this feature)
     * If $repeatingInterval is setted, each time the message is acknowledged by a reader
     * the message will be auto scheduled at current time plus interval seconds
     *
     * @param int $repeatingInterval
     * @throws Exception\InvalidArgumentException
     * @return $this
     */
    public function setRepeatingInterval($repeatingInterval = null)
    {
        if (($repeatingInterval !== null) && !is_int($repeatingInterval)) {
            throw new Exception\InvalidArgumentException('$repeatingInterval must be a int or null');
        }
        $this->set(self::REPEATING_INTERVAL, $repeatingInterval);
        return $this;
    }

    /**
     * Get message repeating interval
     *
     * @see setRepeatingInterval()
     *
     * @return int|boolean
     */
    public function getRepeatingInterval()
    {
        return $this->get(self::REPEATING_INTERVAL, false);
    }
}


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

using System.Threading;
using System.Threading.Tasks;

namespace RedFoxMQ
{
    interface IReceiveMessageFrame
    {
        Task<MessageFrame> ReceiveAsync(CancellationToken cancellationToken);
    }
}


text:
package com.backpackcloud.trugger.predicate;

import org.junit.Test;

import static com.backpackcloud.trugger.TruggerTest.assertMatch;
import static com.backpackcloud.trugger.TruggerTest.assertNotMatch;
import static com.backpackcloud.trugger.reflection.ClassPredicates.subtypeOf;
import static com.backpackcloud.trugger.reflection.ClassPredicates.ofType;

public class ClassPredicatesTest {

  @Test
  public void testSubtypePredicate() {
    assertMatch(Exception.class, subtypeOf(Throwable.class));
    assertNotMatch(Throwable.class, subtypeOf(Exception.class));
    assertNotMatch(Throwable.class, subtypeOf(Throwable.class));
  }

  @Test
  public void testTypePredicate() {
    assertNotMatch(Exception.class, ofType(Throwable.class));
    assertNotMatch(Throwable.class, ofType(Exception.class));
    assertMatch(Throwable.class, ofType(Throwable.class));
  }

}


text:
using System.IO;
using Antlr4.StringTemplate;
using Krypton.LibProtocol.File;

namespace Krypton.LibProtocol.Target
{
    public abstract class LanguageGenerator<TS>
    {
        protected abstract string TemplatesPath { get; }

        protected DefinitionFile File { get; }

        protected LanguageGenerator(DefinitionFile file)
        {
            File = file;
        }

        public abstract void Generate(TS settings);

        protected void WriteFile(string data, string filepath)
        {
            using (var f = new FileStream(filepath, FileMode.Create))
            {
                using (var s = new StreamWriter(f))
                {
                    s.Write(data);
                }
            }
        }

        public TemplateGroupString ReadTemplate(string template)
        {
            var full = Path.Combine(TemplatesPath, template);
            var resource = full.Replace('/', '.');

            var s = new TemplateGroupString(ReadResource(resource));
            s.Load();
            return s;
        }

        public static Stream OpenResource(string path)
        {
            return TargetResources.Assembly.GetManifestResourceStream(path);
        }

        public static string ReadResource(string path)
        {
            var ss = new StringWriter();
            using (var stream = OpenResource(path))
            {
                while (stream.Position < stream.Length)
                    ss.Write((char) stream.ReadByte());
            }
            return ss.ToString();
        }
    }
}


text:
package ca.farrelltonsolar.uicomponents;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

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

public abstract class AbstractSeries {
	//////////////////////////////////////////////////////////////////////////////////////
	// PRIVATE MEMBERS
	//////////////////////////////////////////////////////////////////////////////////////

	protected Paint mPaint = new Paint();

	protected float mScaleX = 1;
	protected float mScaleY = 1;

	private List<AbstractPoint> mPoints;
	private boolean mPointsSorted = false;

	private double mMinX = Double.MAX_VALUE;
	private double mMaxX = Double.MIN_VALUE;
	private double mMinY = Double.MAX_VALUE;
	private double mMaxY = Double.MIN_VALUE;

	private double mRangeX = 0;
	private double mRangeY = 0;

	protected abstract void drawPoint(Canvas canvas, AbstractPoint point, float scaleX, float scalY, Rect gridBounds);

	//////////////////////////////////////////////////////////////////////////////////////
	// CONSTRUCTORS
	//////////////////////////////////////////////////////////////////////////////////////

	public AbstractSeries() {
		mPaint.setAntiAlias(true);
	}

	//////////////////////////////////////////////////////////////////////////////////////
	// PUBLIC METHODS
	//////////////////////////////////////////////////////////////////////////////////////

	public List<AbstractPoint> getPoints() {
		Collections.sort(mPoints);
		return mPoints;
	}

	public void setPoints(List<? extends AbstractPoint> points) {
		mPoints = new ArrayList<AbstractPoint>();
		mPoints.addAll(points);

		sortPoints();
		resetRange();

		for (AbstractPoint point : mPoints) {
			extendRange(point.getX(), point.getY());
		}
	}

	public void addPoint(AbstractPoint point) {
		if (mPoints == null) {
			mPoints = new ArrayList<AbstractPoint>();
		}

		extendRange(point.getX(), point.getY());
		mPoints.add(point);

		mPointsSorted = false;
	}

	// Line properties

	public void setLineColor(int color) {
		mPaint.setColor(color);
	}

	public void setLineWidth(float width) {
		mPaint.setStrokeWidth(width);
	}

	//////////////////////////////////////////////////////////////////////////////////////
	// PRIVATE METHODS
	//////////////////////////////////////////////////////////////////////////////////////

	private void sortPoints() {
		if (!mPointsSorted) {
			Collections.sort(mPoints);
			mPointsSorted = true;
		}
	}

	private void resetRange() {
		mMinX = Double.MAX_VALUE;
		mMaxX = Double.MIN_VALUE;
		mMinY = Double.MAX_VALUE;
		mMaxY = Double.MIN_VALUE;

		mRangeX = 0;
		mRangeY = 0;
	}

	private void extendRange(double x, double y) {
		if (x < mMinX) {
			mMinX = x;
		}

		if (x > mMaxX) {
			mMaxX = x;
		}

		if (y < mMinY) {
			mMinY = y;
		}

		if (y > mMaxY) {
			mMaxY = y;
		}

		mRangeX = mMaxX - mMinX;
		mRangeY = mMaxY - mMinY;
	}

	double getMinX() {
		return mMinX;
	}

	double getMaxX() {
		return mMaxX;
	}

	double getMinY() {
		return mMinY;
	}

	double getMaxY() {
		return mMaxY;
	}

	double getRangeX() {
		return mRangeX;
	}

	double getRangeY() {
		return mRangeY;
	}

	void draw(Canvas canvas, Rect gridBounds, RectD valueBounds) {
		sortPoints();

		final float scaleX = (float) gridBounds.width() / (float) valueBounds.width();
		final float scaleY = (float) gridBounds.height() / (float) valueBounds.height();

		for (AbstractPoint point : mPoints) {
			drawPoint(canvas, point, scaleX, scaleY, gridBounds);
		}

		onDrawingComplete();
	}

	protected void onDrawingComplete() {
	}

	//////////////////////////////////////////////////////////////////////////////////////
	// PUBLIC CLASSES
	//////////////////////////////////////////////////////////////////////////////////////

	public static abstract class AbstractPoint implements Comparable<AbstractPoint> {
		private double mX;
		private double mY;

		public AbstractPoint() {
		}

		public AbstractPoint(double x, double y) {
			mX = x;
			mY = y;
		}

		public double getX() {
			return mX;
		}

		public double getY() {
			return mY;
		}

		public void set(double x, double y) {
			mX = x;
			mY = y;
		}

		@Override
		public int compareTo(AbstractPoint another) {
			return Double.compare(mX, another.mX);
		}
	}
}


text:
001
017
018    package org.apache.commons.codec.language;
019
020    import org.apache.commons.codec.EncoderException;
021    import org.apache.commons.codec.StringEncoder;
022
023    /**
024     * Encodes a string into a Refined Soundex value. A refined soundex code is
025     * optimized for spell checking words. Soundex method originally developed by
026     * <CITE>Margaret Odell</CITE> and <CITE>Robert Russell</CITE>.
027     *
028     * <p>This class is immutable and thread-safe.</p>
029     *
030     * @version $Id: RefinedSoundex.java 1429868 2013-01-07 16:08:05Z ggregory $
031     */
032    public class RefinedSoundex implements StringEncoder {
033
034        /**
035         * @since 1.4
036         */
037        public static final String US_ENGLISH_MAPPING_STRING = "01360240043788015936020505";
038
039       /**
040         * RefinedSoundex is *refined* for a number of reasons one being that the
041         * mappings have been altered. This implementation contains default
042         * mappings for US English.
043         */
044        private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray();
045
046        /**
047         * Every letter of the alphabet is "mapped" to a numerical value. This char
048         * array holds the values to which each letter is mapped. This
049         * implementation contains a default map for US_ENGLISH
050         */
051        private final char[] soundexMapping;
052
053        /**
054         * This static variable contains an instance of the RefinedSoundex using
055         * the US_ENGLISH mapping.
056         */
057        public static final RefinedSoundex US_ENGLISH = new RefinedSoundex();
058
059         /**
060         * Creates an instance of the RefinedSoundex object using the default US
061         * English mapping.
062         */
063        public RefinedSoundex() {
064            this.soundexMapping = US_ENGLISH_MAPPING;
065        }
066
067        /**
068         * Creates a refined soundex instance using a custom mapping. This
069         * constructor can be used to customize the mapping, and/or possibly
070         * provide an internationalized mapping for a non-Western character set.
071         *
072         * @param mapping
073         *                  Mapping array to use when finding the corresponding code for
074         *                  a given character
075         */
076        public RefinedSoundex(final char[] mapping) {
077            this.soundexMapping = new char[mapping.length];
078            System.arraycopy(mapping, 0, this.soundexMapping, 0, mapping.length);
079        }
080
081        /**
082         * Creates a refined Soundex instance using a custom mapping. This constructor can be used to customize the mapping,
083         * and/or possibly provide an internationalized mapping for a non-Western character set.
084         *
085         * @param mapping
086         *            Mapping string to use when finding the corresponding code for a given character
087         * @since 1.4
088         */
089        public RefinedSoundex(final String mapping) {
090            this.soundexMapping = mapping.toCharArray();
091        }
092
093        /**
094         * Returns the number of characters in the two encoded Strings that are the
095         * same. This return value ranges from 0 to the length of the shortest
096         * encoded String: 0 indicates little or no similarity, and 4 out of 4 (for
097         * example) indicates strong similarity or identical values. For refined
098         * Soundex, the return value can be greater than 4.
099         *
100         * @param s1
101         *                  A String that will be encoded and compared.
102         * @param s2
103         *                  A String that will be encoded and compared.
104         * @return The number of characters in the two encoded Strings that are the
105         *             same from 0 to to the length of the shortest encoded String.
106         *
107         * @see SoundexUtils#difference(StringEncoder,String,String)
108         * @see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp">
109         *          MS T-SQL DIFFERENCE</a>
110         *
111         * @throws EncoderException
112         *                  if an error occurs encoding one of the strings
113         * @since 1.3
114         */
115        public int difference(final String s1, final String s2) throws EncoderException {
116            return SoundexUtils.difference(this, s1, s2);
117        }
118
119        /**
120         * Encodes an Object using the refined soundex algorithm. This method is
121         * provided in order to satisfy the requirements of the Encoder interface,
122         * and will throw an EncoderException if the supplied object is not of type
123         * java.lang.String.
124         *
125         * @param obj
126         *                  Object to encode
127         * @return An object (or type java.lang.String) containing the refined
128         *             soundex code which corresponds to the String supplied.
129         * @throws EncoderException
130         *                  if the parameter supplied is not of type java.lang.String
131         */
132        @Override
133        public Object encode(final Object obj) throws EncoderException {
134            if (!(obj instanceof String)) {
135                throw new EncoderException("Parameter supplied to RefinedSoundex encode is not of type java.lang.String");
136            }
137            return soundex((String) obj);
138        }
139
140        /**
141         * Encodes a String using the refined soundex algorithm.
142         *
143         * @param str
144         *                  A String object to encode
145         * @return A Soundex code corresponding to the String supplied
146         */
147        @Override
148        public String encode(final String str) {
149            return soundex(str);
150        }
151
152        /**
153         * Returns the mapping code for a given character. The mapping codes are
154         * maintained in an internal char array named soundexMapping, and the
155         * default values of these mappings are US English.
156         *
157         * @param c
158         *                  char to get mapping for
159         * @return A character (really a numeral) to return for the given char
160         */
161        char getMappingCode(final char c) {
162            if (!Character.isLetter(c)) {
163                return 0;
164            }
165            return this.soundexMapping[Character.toUpperCase(c) - 'A'];
166        }
167
168        /**
169         * Retrieves the Refined Soundex code for a given String object.
170         *
171         * @param str
172         *                  String to encode using the Refined Soundex algorithm
173         * @return A soundex code for the String supplied
174         */
175        public String soundex(String str) {
176            if (str == null) {
177                return null;
178            }
179            str = SoundexUtils.clean(str);
180            if (str.length() == 0) {
181                return str;
182            }
183
184            final StringBuilder sBuf = new StringBuilder();
185            sBuf.append(str.charAt(0));
186
187            char last, current;
188            last = '*';
189
190            for (int i = 0; i < str.length(); i++) {
191
192                current = getMappingCode(str.charAt(i));
193                if (current == last) {
194                    continue;
195                } else if (current != 0) {
196                    sBuf.append(current);
197                }
198
199                last = current;
200
201            }
202
203            return sBuf.toString();
204        }
205    }