text:
/**
* @file GameSymbols.cpp
*
* @author Heinrich Mellmann
* Implementation of class GameSymbols
*/

#include "GameSymbols.h"

using namespace naoth;
using namespace std;

void GameSymbols::registerSymbols(xabsl::Engine& engine)
{
  // enum for the competition type
  engine.registerEnumElement("game.type", "game.type.normal" , GameData::competition_normal);
  engine.registerEnumElement("game.type", "game.type.challenge_shield", GameData::competition_challenge_shield);
  engine.registerEnumElement("game.type", "game.type.game_7v7" ,  GameData::competition_7v7);
  engine.registerEnumElement("game.type", "game.type.dynamic_ball_handling" , GameData::competition_dynamic_ball_handling);

  engine.registerEnumeratedInputSymbol("game.type", "game.type", &getCompetitionType);

  // enum type for game state (spl)
  engine.registerEnumElement("game.state","game.state._initial_", PlayerInfo::initial);
  engine.registerEnumElement("game.state","game.state.ready", PlayerInfo::ready);
  engine.registerEnumElement("game.state","game.state.set", PlayerInfo::set);
  engine.registerEnumElement("game.state","game.state.playing", PlayerInfo::playing);
  engine.registerEnumElement("game.state","game.state.penalized", PlayerInfo::penalized);
  engine.registerEnumElement("game.state","game.state.finished", PlayerInfo::finished);
  engine.registerEnumElement("game.state","game.state.unstiff", PlayerInfo::unstiff);

  // current game state
  engine.registerEnumeratedInputSymbol("game.state", "game.state", &getGameState);

  engine.registerDecimalInputSymbol("game.player_number", &getPlayerNumber);
  engine.registerDecimalInputSymbol("game.msecsRemaining", &getMsecsRemaining);
  engine.registerDecimalInputSymbol("game.msecsRemainingSecondary", &getMsecsRemainingSecondary);
  engine.registerBooleanInputSymbol("game.own_kickoff", &getOwnKickOff);

  // HACK: is only true when the game state plaing was set by the game controller
  //       we assume this message comes with a delay of >10s
  //       it's used to prevent waiting of additional 10s in case it's opponents kickoff
  engine.registerBooleanInputSymbol("game.state.playing_is_set_by_game_controller", &getPlayingIsSetByGameController);

  engine.registerEnumElement("game.set_play","game.set_play.none", PlayerInfo::set_none);
  engine.registerEnumElement("game.set_play","game.set_play.goal_free_kick", PlayerInfo::goal_free_kick);
  engine.registerEnumElement("game.set_play","game.set_play.pushing_free_kick", PlayerInfo::pushing_free_kick);
  engine.registerEnumElement("game.set_play","game.set_play.corner_kick", PlayerInfo::corner_kick);
  engine.registerEnumElement("game.set_play","game.set_play.kick_in", PlayerInfo::kick_in);

  engine.registerEnumeratedInputSymbol("game.set_play", "game.set_play", &getSetPlay);

  // enum type for game phase
  engine.registerEnumElement("game.phase", "game.phase.normal", PlayerInfo::normal);
  engine.registerEnumElement("game.phase", "game.phase.penaltyshoot", PlayerInfo::penaltyshoot);
  engine.registerEnumElement("game.phase", "game.phase.overtime", PlayerInfo::overtime);
  engine.registerEnumElement("game.phase", "game.phase.timeout", PlayerInfo::timeout);

  // current game phase
  engine.registerEnumeratedInputSymbol("game.phase", "game.phase", &getGamePhase);

}//end registerSymbols

GameSymbols* GameSymbols::theInstance = NULL;
bool GameSymbols::playingIsSetByGameController = false;

int GameSymbols::getCompetitionType() {
  return theInstance->getGameData().competitionType;
}

bool GameSymbols::getPlayingIsSetByGameController() {
  if (theInstance->getGameData().valid) {
    playingIsSetByGameController = (theInstance->getGameData().gameState == GameData::playing);
  }
  return playingIsSetByGameController;
}

bool GameSymbols::getOwnKickOff() {
  return theInstance->getPlayerInfo().kickoff;
}

double GameSymbols::getPlayerNumber() {
  return theInstance->getPlayerInfo().playerNumber;
}

double GameSymbols::getMsecsRemaining() {
  return theInstance->getGameData().secsRemaining*1000.0;
}

double GameSymbols::getMsecsRemainingSecondary() {
  return theInstance->getGameData().secondaryTime*1000.0;
}

int GameSymbols::getGameState() {
  return theInstance->getPlayerInfo().robotState;
}

int GameSymbols::getSetPlay() {
  return theInstance->getPlayerInfo().robotSetPlay;
}

int GameSymbols::getGamePhase(){
  return theInstance->getPlayerInfo().gamePhase;
}


text:
<!DOCTYPE html>

  <title>Jen Trudell | Blog</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../css/main.css">

Ruby: Arrays and Hashes

All my dogs

August 16, 2015

My dogs

I have had four dogs in my life: my current dog, Sophie; the dog my mom got while I was in law school, Tobey; the dog I had for the longest while growing up, Jesse; and Nick, who was around when I was a toddler. Sophie is part black lab mixed with something (ok, I admit it, I know because we ran a DNA test: whippet). Tobey and Jesse were golden retrievers. From what I have been told, Nick was a real devil of a mutt (sweet dog, but he ran away a lot and almost chewed through our back door). I could arrange my dogs in various ways using ruby. If I wanted to just list out their names, I could use a simple array. Think of an array as just another name for a list. Each item in the array-list is separated by a comma, and the whole list is encapsulated with square brackets. You can put anything into an array (numbers, strings, other arrays, etc.), but since we are talking about my dogs, we are going to make the my_dogs_array an array of dog names:

my_dogs_array = ["Sophie", "Tobey", "Jesse", "Nick"]

That's a nice list, but it doesn't really tell us anything other than the names of my dogs. What if you wanted to know what breed they are? We could use a hash, which is like a list of pairs. One member of the pair is a key, and the other member of the pair is the value that the key points to. Think of each key/value pair in a hash as a dog cage (big, roomy cages, with a dog bed, naturally). Each cage has a name tag with the name of the dog (the key) and in each cage is a certain breed of dog (the value). The cages are lined up in a row, in a room between two walls (the walls are curly braces in a hash). Here are my dogs and their breeds as a hash:

my_dogs_hash = {"Sophie" => "lab mix", "Tobey" => "golden retriever", "Jesse" => "golden retriever", "Nick" => "devil mutt"} # You can use colons instead of those arrow looking things (hash rockets), like "Sophie": "lab mix"

In a hash, there can only be one of each key (I can't have more than one Sophie--I mean, I guess in real life I could have two dogs named Sophie, but they wouldn't be clones of each other), but different keys can have the same value. It is perfectly ok that both Tobey and Jesse are golden retrievers, for example.

Call the dogs

So now we know what an array is, and what a hash is, but what if we want to get one piece of information out of the array or the hash? What if we don't want the whole list of names (in the case of an array) or list of key/value pairs (in the case of a hash)? We can call the dogs by their number in line for the array (called an index number) or, in the case of a hash, by the name of the key (in this case, literally the dog's name), as follows:

my_dogs_array[0] # Each item in an array is numbered left to right and starts with 0

          => "Sophie"

my_dogs_array[2] # Remember, starts with 0, so while Jesse is actually the third dog in the array, her index number for purposes of the array is 2

          => "Jesse"

my_dogs_hash["Tobey"]

         => "golden retriever"

my_dogs_hash["Nick"]

          => "devil mutt"

Mixing it up: Arrays and Hashes

What if you wanted to know even more about my dogs? The my_dogs_hash only returns one value (the breed) for each key (the dog's name). What if you wanted to know something else about the dog, like its personality? We can have each key return more than one value by making the value an array, like so:

my_dogs_super_hash = {"Sophie" => ["lab mix", "great with kids"], "Tobey" => ["golden retriever", "gentle giant"], "Jesse" => ["golden retriever", "afraid of thunderstorms"], "Nick" => ["devil mutt", "nuts"]}

my_dogs_super_hash["Jesse"]

          => ["golden retriever", "afraid of thunderstorms"]

As you can see above, when we call the key "Jesse" from the my_dogs_super_hash, the value we get is an array which includes both that Jesse was a golden retriever and that she was afraid of thunderstorms. Not only can you mix arrays in with hashes (and vice versa, you could have an array OF hashes), you can also mix the methods you use to get values from them. Say you just wanted to know the personality of Sophie, which is the second item of the array in the hash value with the key "Sophie" (remember that the second item of the array is actually index number 1 for our purposes, since the first item is index number 0):

my_dogs_super_hash["Sophie"][1]

        => "great with kids"

There you have it! Thanks Dev Bootcamp, now I'm missing Tobey and Jesse and, yes, even Nick.

Main

Blog

Portfolio

Contact

Copyright 2015 Jen Trudell

redpajama_set_name: RedPajamaGithub


text:
package apple.uikit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.coreanimation.*;
import apple.coredata.*;
import apple.coreimage.*;
import apple.coretext.*;
import apple.corelocation.*;

@Library("UIKit/UIKit.h") @Mapping("UIPrintInteractionControllerDelegate")
public interface UIPrintInteractionControllerDelegate
    extends NSObjectProtocol {

    @Mapping("printInteractionControllerParentViewController:")
    UIViewController getParentViewController(UIPrintInteractionController printInteractionController);
    @Mapping("printInteractionController:choosePaper:")
    UIPrintPaper choosePaper(UIPrintInteractionController printInteractionController, NSArray<?> paperList);
    @Mapping("printInteractionControllerWillPresentPrinterOptions:")
    void willPresentPrinterOptions(UIPrintInteractionController printInteractionController);
    @Mapping("printInteractionControllerDidPresentPrinterOptions:")
    void didPresentPrinterOptions(UIPrintInteractionController printInteractionController);
    @Mapping("printInteractionControllerWillDismissPrinterOptions:")
    void willDismissPrinterOptions(UIPrintInteractionController printInteractionController);
    @Mapping("printInteractionControllerDidDismissPrinterOptions:")
    void didDismissPrinterOptions(UIPrintInteractionController printInteractionController);
    @Mapping("printInteractionControllerWillStartJob:")
    void willStartJob(UIPrintInteractionController printInteractionController);
    @Mapping("printInteractionControllerDidFinishJob:")
    void didFinishJob(UIPrintInteractionController printInteractionController);
    /**
     * @since Available in iOS 7.0 and later.
     */
    @Mapping("printInteractionController:cutLengthForPaper:")
    @MachineSizedFloat double getCutLength(UIPrintInteractionController printInteractionController, UIPrintPaper paper);

    /*<adapter>*/
    /*</adapter>*/
}


text:
package org.jvnet.jaxb2_commons.xjc;

import org.apache.tools.ant.BuildException;

public class XJC2Task extends com.sun.tools.xjc.XJC2Task {

	private boolean disableXmlSecurity = true;

	public void setDisableXmlSecurity(boolean disableXmlSecurity) {
		this.disableXmlSecurity = disableXmlSecurity;
	}

	private String accessExternalSchema = "all";

	public void setAccessExternalSchema(String accessExternalSchema) {
		this.accessExternalSchema = accessExternalSchema;
	}

	private String accessExternalDTD = "all";

	public void setAccessExternalDTD(String accessExternalDTD) {
		this.accessExternalDTD = accessExternalDTD;
	}

	@Override
	public void execute() throws BuildException {
		this.options.disableXmlSecurity = this.disableXmlSecurity;
		if (accessExternalSchema != null) {
			System.setProperty("javax.xml.accessExternalSchema",
					accessExternalSchema);
		}
		if (accessExternalDTD != null) {
			System.setProperty("javax.xml.accessExternalDTD", accessExternalDTD);
		}
		super.execute();
	}

}


text:
import copy
import functools

import mock
import netaddr
from neutron_lib import constants as lib_constants
import testtools

from neutron.agent.l3 import agent as neutron_l3_agent
from neutron.agent.l3 import dvr_fip_ns
from neutron.agent.l3 import dvr_snat_ns
from neutron.agent.l3 import namespaces
from neutron.agent.linux import ip_lib
from neutron.agent.linux import iptables_manager
from neutron.common import constants as n_const
from neutron.common import utils
from neutron.extensions import portbindings
from neutron.tests.common import l3_test_common
from neutron.tests.common import machine_fixtures
from neutron.tests.common import net_helpers
from neutron.tests.functional.agent.l3 import framework

DEVICE_OWNER_COMPUTE = lib_constants.DEVICE_OWNER_COMPUTE_PREFIX + 'fake'

class TestDvrRouter(framework.L3AgentTestFramework):
    def manage_router(self, agent, router):
        def _safe_fipnamespace_delete_on_ext_net(ext_net_id):
            try:
                agent.fipnamespace_delete_on_ext_net(None, ext_net_id)
            except RuntimeError:
                pass
        if router['gw_port']:
            self.addCleanup(
                _safe_fipnamespace_delete_on_ext_net,
                router['gw_port']['network_id'])

        return super(TestDvrRouter, self).manage_router(agent, router)

    def test_dvr_update_floatingip_statuses(self):
        self.agent.conf.agent_mode = 'dvr'
        self._test_update_floatingip_statuses(self.generate_dvr_router_info())

    def test_dvr_router_lifecycle_without_ha_without_snat_with_fips(self):
        self._dvr_router_lifecycle(enable_ha=False, enable_snat=False)

    def test_dvr_router_lifecycle_without_ha_with_snat_with_fips(self):
        self._dvr_router_lifecycle(enable_ha=False, enable_snat=True)

    def test_dvr_router_lifecycle_ha_with_snat_with_fips(self):
        self._dvr_router_lifecycle(enable_ha=True, enable_snat=True)

    def _helper_create_dvr_router_fips_for_ext_network(
            self, agent_mode, **dvr_router_kwargs):
        self.agent.conf.agent_mode = agent_mode
        router_info = self.generate_dvr_router_info(**dvr_router_kwargs)
        self.mock_plugin_api.get_external_network_id.return_value = (
            router_info['_floatingips'][0]['floating_network_id'])
        router = self.manage_router(self.agent, router_info)
        fip_ns = router.fip_ns.get_name()
        return router, fip_ns

    def _validate_fips_for_external_network(self, router, fip_ns):
        self.assertTrue(self._namespace_exists(router.ns_name))
        self.assertTrue(self._namespace_exists(fip_ns))
        self._assert_dvr_floating_ips(router)
        self._assert_snat_namespace_does_not_exist(router)

    def test_dvr_gateway_move_does_not_remove_redirect_rules(self):
        """Test to validate snat redirect rules not cleared with snat move."""
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info(enable_snat=True)
        router_info[lib_constants.FLOATINGIP_KEY] = []
        router_info[n_const.FLOATINGIP_AGENT_INTF_KEY] = []
        router1 = self.manage_router(self.agent, router_info)
        router1.router['gw_port_host'] = ""
        self.agent._process_updated_router(router1.router)
        router_updated = self.agent.router_info[router1.router['id']]
        self.assertTrue(self._namespace_exists(router_updated.ns_name))
        ns_ipr = ip_lib.IPRule(namespace=router1.ns_name)
        ip4_rules_list = ns_ipr.rule.list_rules(lib_constants.IP_VERSION_4)
        self.assertEqual(5, len(ip4_rules_list))
        # IPRule list should have 5 entries.
        # Three entries from 'default', 'main' and 'local' table.
        # The remaining 2 is for the two router interfaces(csnat ports).
        default_rules_list_count = 0
        interface_rules_list_count = 0
        for ip_rule in ip4_rules_list:
            tbl_index = ip_rule['table']
            if tbl_index in ['local', 'default', 'main']:
                default_rules_list_count = default_rules_list_count + 1
            else:
                interface_rules_list_count = interface_rules_list_count + 1
        self.assertEqual(3, default_rules_list_count)
        self.assertEqual(2, interface_rules_list_count)

    def test_dvr_router_fips_stale_gw_port(self):
        self.agent.conf.agent_mode = 'dvr'

        # Create the router with external net
        dvr_router_kwargs = {'ip_address': '19.4.4.3',
                             'subnet_cidr': '19.4.4.0/24',
                             'gateway_ip': '19.4.4.1',
                             'gateway_mac': 'ca:fe:de:ab:cd:ef'}
        router_info = self.generate_dvr_router_info(**dvr_router_kwargs)
        external_gw_port = router_info['gw_port']
        ext_net_id = router_info['_floatingips'][0]['floating_network_id']
        self.mock_plugin_api.get_external_network_id.return_value(ext_net_id)

        # Create the fip namespace up front
        stale_fip_ns = dvr_fip_ns.FipNamespace(ext_net_id,
                                               self.agent.conf,
                                               self.agent.driver,
                                               self.agent.use_ipv6)
        stale_fip_ns.create()

        # Add a stale fg port to the namespace
        fixed_ip = external_gw_port['fixed_ips'][0]
        float_subnet = external_gw_port['subnets'][0]
        fip_gw_port_ip = str(netaddr.IPAddress(fixed_ip['ip_address']) + 10)
        prefixlen = netaddr.IPNetwork(float_subnet['cidr']).prefixlen
        stale_agent_gw_port = {
            'subnets': [{'cidr': float_subnet['cidr'],
                         'gateway_ip': float_subnet['gateway_ip'],
                         'id': fixed_ip['subnet_id']}],
            'network_id': external_gw_port['network_id'],
            'device_owner': lib_constants.DEVICE_OWNER_AGENT_GW,
            'mac_address': 'fa:16:3e:80:8f:89',
            portbindings.HOST_ID: self.agent.conf.host,
            'fixed_ips': [{'subnet_id': fixed_ip['subnet_id'],
                           'ip_address': fip_gw_port_ip,
                           'prefixlen': prefixlen}],
            'id': framework._uuid(),
            'device_id': framework._uuid()}
        stale_fip_ns.create_gateway_port(stale_agent_gw_port)

        stale_dev_exists = self.device_exists_with_ips_and_mac(
                stale_agent_gw_port,
                stale_fip_ns.get_ext_device_name,
                stale_fip_ns.get_name())
        self.assertTrue(stale_dev_exists)

        # Create the router, this shouldn't allow the duplicate port to stay
        router = self.manage_router(self.agent, router_info)

        # Assert the device no longer exists
        stale_dev_exists = self.device_exists_with_ips_and_mac(
                stale_agent_gw_port,
                stale_fip_ns.get_ext_device_name,
                stale_fip_ns.get_name())
        self.assertFalse(stale_dev_exists)

        # Validate things are looking good and clean up
        self._validate_fips_for_external_network(
            router, router.fip_ns.get_name())
        ext_gateway_port = router_info['gw_port']
        self._delete_router(self.agent, router.router_id)
        self._assert_fip_namespace_deleted(ext_gateway_port)

    def test_dvr_router_gateway_redirect_cleanup_on_agent_restart(self):
        """Test to validate the router namespace gateway redirect rule cleanup.

        This test checks for the non existence of the gateway redirect
        rules in the router namespace after the agent restarts while the
        gateway is removed for the router.
        """
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info()
        router1 = self.manage_router(self.agent, router_info)
        self._assert_snat_namespace_exists(router1)
        self.assertTrue(self._namespace_exists(router1.ns_name))
        restarted_agent = neutron_l3_agent.L3NATAgentWithStateReport(
            self.agent.host, self.agent.conf)
        router1.router['gw_port'] = ""
        router1.router['gw_port_host'] = ""
        router1.router['external_gateway_info'] = ""
        restarted_router = self.manage_router(restarted_agent, router1.router)
        self.assertTrue(self._namespace_exists(restarted_router.ns_name))
        ns_ipr = ip_lib.IPRule(namespace=router1.ns_name)
        ip4_rules_list = ns_ipr.rule.list_rules(lib_constants.IP_VERSION_4)
        ip6_rules_list = ns_ipr.rule.list_rules(lib_constants.IP_VERSION_6)
        # Just make sure the basic set of rules are there in the router
        # namespace
        self.assertEqual(3, len(ip4_rules_list))
        self.assertEqual(2, len(ip6_rules_list))

    def test_dvr_unused_snat_ns_deleted_when_agent_restarts_after_move(self):
        """Test to validate the stale snat namespace delete with snat move.

        This test validates the stale snat namespace cleanup when
        the agent restarts after the gateway port has been moved
        from the agent.
        """
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info()
        router1 = self.manage_router(self.agent, router_info)
        self._assert_snat_namespace_exists(router1)
        restarted_agent = neutron_l3_agent.L3NATAgentWithStateReport(
            self.agent.host, self.agent.conf)
        router1.router['gw_port_host'] = "my-new-host"
        restarted_router = self.manage_router(restarted_agent, router1.router)
        self._assert_snat_namespace_does_not_exist(restarted_router)

    def test_dvr_router_fips_for_multiple_ext_networks(self):
        agent_mode = 'dvr'
        # Create the first router fip with external net1
        dvr_router1_kwargs = {'ip_address': '19.4.4.3',
                              'subnet_cidr': '19.4.4.0/24',
                              'gateway_ip': '19.4.4.1',
                              'gateway_mac': 'ca:fe:de:ab:cd:ef'}
        router1, fip1_ns = (
            self._helper_create_dvr_router_fips_for_ext_network(
                agent_mode, **dvr_router1_kwargs))
        # Validate the fip with external net1
        self._validate_fips_for_external_network(router1, fip1_ns)

        # Create the second router fip with external net2
        dvr_router2_kwargs = {'ip_address': '19.4.5.3',
                              'subnet_cidr': '19.4.5.0/24',
                              'gateway_ip': '19.4.5.1',
                              'gateway_mac': 'ca:fe:de:ab:cd:fe'}
        router2, fip2_ns = (
            self._helper_create_dvr_router_fips_for_ext_network(
                agent_mode, **dvr_router2_kwargs))
        # Validate the fip with external net2
        self._validate_fips_for_external_network(router2, fip2_ns)

    def _dvr_router_lifecycle(self, enable_ha=False, enable_snat=False,
                              custom_mtu=2000, ip_version=4, dual_stack=False):
        '''Test dvr router lifecycle

        :param enable_ha: sets the ha value for the router.
        :param enable_snat:  the value of enable_snat is used
        to  set the  agent_mode.
        '''

        # The value of agent_mode can be dvr, dvr_snat, or legacy.
        # Since by definition this is a dvr (distributed = true)
        # only dvr and dvr_snat are applicable
        self.agent.conf.agent_mode = 'dvr_snat' if enable_snat else 'dvr'

        # We get the router info particular to a dvr router
        router_info = self.generate_dvr_router_info(
            enable_ha, enable_snat, extra_routes=True)
        for key in ('_interfaces', '_snat_router_interfaces',
                    '_floatingip_agent_interfaces'):
            for port in router_info[key]:
                port['mtu'] = custom_mtu
        router_info['gw_port']['mtu'] = custom_mtu
        if enable_ha:
            router_info['_ha_interface']['mtu'] = custom_mtu

        # We need to mock the get_agent_gateway_port return value
        # because the whole L3PluginApi is mocked and we need the port
        # gateway_port information before the l3_agent will create it.
        # The port returned needs to have the same information as
        # router_info['gw_port']
        self.mock_plugin_api.get_agent_gateway_port.return_value = router_info[
            'gw_port']

        # We also need to mock the get_external_network_id method to
        # get the correct fip namespace.
        self.mock_plugin_api.get_external_network_id.return_value = (
            router_info['_floatingips'][0]['floating_network_id'])

        # With all that set we can now ask the l3_agent to
        # manage the router (create it, create namespaces,
        # attach interfaces, etc...)
        router = self.manage_router(self.agent, router_info)
        if enable_ha:
            port = router.get_ex_gw_port()
            interface_name = router.get_external_device_name(port['id'])
            self._assert_no_ip_addresses_on_interface(router.ha_namespace,
                                                      interface_name)
            utils.wait_until_true(lambda: router.ha_state == 'master')

            # Keepalived notifies of a state transition when it starts,
            # not when it ends. Thus, we have to wait until keepalived finishes
            # configuring everything. We verify this by waiting until the last
            # device has an IP address.
            device = router.router[lib_constants.INTERFACE_KEY][-1]
            device_exists = functools.partial(
                self.device_exists_with_ips_and_mac,
                device,
                router.get_internal_device_name,
                router.ns_name)
            utils.wait_until_true(device_exists)
            name = router.get_internal_device_name(device['id'])
            self.assertEqual(custom_mtu,
                             ip_lib.IPDevice(name, router.ns_name).link.mtu)

        ext_gateway_port = router_info['gw_port']
        self.assertTrue(self._namespace_exists(router.ns_name))
        utils.wait_until_true(
            lambda: self._metadata_proxy_exists(self.agent.conf, router))
        self._assert_internal_devices(router)
        self._assert_dvr_external_device(router)
        self._assert_dvr_gateway(router)
        self._assert_dvr_floating_ips(router)
        self._assert_snat_chains(router)
        self._assert_floating_ip_chains(router)
        self._assert_metadata_chains(router)
        self._assert_rfp_fpr_mtu(router, custom_mtu)
        if enable_snat:
            ip_versions = [4, 6] if (ip_version == 6 or dual_stack) else [4]
            snat_ns_name = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
                router.router_id)
            self._assert_onlink_subnet_routes(
                router, ip_versions, snat_ns_name)
            self._assert_extra_routes(router, namespace=snat_ns_name)

        # During normal operation, a router-gateway-clear followed by
        # a router delete results in two notifications to the agent.  This
        # code flow simulates the exceptional case where the notification of
        # the clearing of the gateway hast been missed, so we are checking
        # that the L3 agent is robust enough to handle that case and delete
        # the router correctly.
        self._delete_router(self.agent, router.router_id)
        self._assert_fip_namespace_deleted(ext_gateway_port)
        self._assert_router_does_not_exist(router)
        self._assert_snat_namespace_does_not_exist(router)

    def generate_dvr_router_info(self,
                                 enable_ha=False,
                                 enable_snat=False,
                                 enable_gw=True,
                                 agent=None,
                                 extra_routes=False,
                                 **kwargs):
        if not agent:
            agent = self.agent
        router = l3_test_common.prepare_router_data(
            enable_snat=enable_snat,
            enable_floating_ip=True,
            enable_ha=enable_ha,
            extra_routes=extra_routes,
            num_internal_ports=2,
            enable_gw=enable_gw,
            **kwargs)
        internal_ports = router.get(lib_constants.INTERFACE_KEY, [])
        router['distributed'] = True
        router['gw_port_host'] = agent.conf.host

        floating_ip = router['_floatingips'][0]
        floating_ip['host'] = agent.conf.host
        if enable_gw:
            external_gw_port = router['gw_port']
            router['gw_port'][portbindings.HOST_ID] = agent.conf.host
            floating_ip['floating_network_id'] = external_gw_port['network_id']
            floating_ip['port_id'] = internal_ports[0]['id']
            floating_ip['status'] = 'ACTIVE'

            self._add_snat_port_info_to_router(router, internal_ports)
            # FIP has a dependency on external gateway. So we need to create
            # the snat_port info and fip_agent_gw_port_info irrespective of
            # the agent type the dvr supports. The namespace creation is
            # dependent on the agent_type.
            self._add_fip_agent_gw_port_info_to_router(router,
                                                       external_gw_port)
        return router

    def _add_fip_agent_gw_port_info_to_router(self, router, external_gw_port):
        # Add fip agent gateway port information to the router_info
        fip_gw_port_list = router.get(
            n_const.FLOATINGIP_AGENT_INTF_KEY, [])
        if not fip_gw_port_list and external_gw_port:
            # Get values from external gateway port
            fixed_ip = external_gw_port['fixed_ips'][0]
            float_subnet = external_gw_port['subnets'][0]
            port_ip = fixed_ip['ip_address']
            # Pick an ip address which is not the same as port_ip
            fip_gw_port_ip = str(netaddr.IPAddress(port_ip) + 5)
            # Add floatingip agent gateway port info to router
            prefixlen = netaddr.IPNetwork(float_subnet['cidr']).prefixlen
            router[n_const.FLOATINGIP_AGENT_INTF_KEY] = [
                {'subnets': [
                    {'cidr': float_subnet['cidr'],
                     'gateway_ip': float_subnet['gateway_ip'],
                     'id': fixed_ip['subnet_id']}],
                 'network_id': external_gw_port['network_id'],
                 'device_owner': lib_constants.DEVICE_OWNER_AGENT_GW,
                 'mac_address': 'fa:16:3e:80:8d:89',
                 portbindings.HOST_ID: self.agent.conf.host,
                 'fixed_ips': [{'subnet_id': fixed_ip['subnet_id'],
                                'ip_address': fip_gw_port_ip,
                                'prefixlen': prefixlen}],
                 'id': framework._uuid(),
                 'device_id': framework._uuid()}
            ]

    def _add_snat_port_info_to_router(self, router, internal_ports):
        # Add snat port information to the router
        snat_port_list = router.get(n_const.SNAT_ROUTER_INTF_KEY, [])
        if not snat_port_list and internal_ports:
            router[n_const.SNAT_ROUTER_INTF_KEY] = []
            for port in internal_ports:
                # Get values from internal port
                fixed_ip = port['fixed_ips'][0]
                snat_subnet = port['subnets'][0]
                port_ip = fixed_ip['ip_address']
                # Pick an ip address which is not the same as port_ip
                snat_ip = str(netaddr.IPAddress(port_ip) + 5)
                # Add the info to router as the first snat port
                # in the list of snat ports
                prefixlen = netaddr.IPNetwork(snat_subnet['cidr']).prefixlen
                snat_router_port = {
                    'subnets': [
                        {'cidr': snat_subnet['cidr'],
                         'gateway_ip': snat_subnet['gateway_ip'],
                         'id': fixed_ip['subnet_id']}],
                    'network_id': port['network_id'],
                    'device_owner': lib_constants.DEVICE_OWNER_ROUTER_SNAT,
                    'mac_address': 'fa:16:3e:80:8d:89',
                    'fixed_ips': [{'subnet_id': fixed_ip['subnet_id'],
                                   'ip_address': snat_ip,
                                   'prefixlen': prefixlen}],
                    'id': framework._uuid(),
                    'device_id': framework._uuid()}
                # Get the address scope if there is any
                if 'address_scopes' in port:
                    snat_router_port['address_scopes'] = port['address_scopes']
                router[n_const.SNAT_ROUTER_INTF_KEY].append(
                    snat_router_port)

    def _assert_dvr_external_device(self, router):
        external_port = router.get_ex_gw_port()
        snat_ns_name = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router.router_id)

        # if the agent is in dvr_snat mode, then we have to check
        # that the correct ports and ip addresses exist in the
        # snat_ns_name namespace
        if self.agent.conf.agent_mode == 'dvr_snat':
            device_exists = functools.partial(
                self.device_exists_with_ips_and_mac,
                external_port,
                router.get_external_device_name,
                snat_ns_name)
            utils.wait_until_true(device_exists)
        # if the agent is in dvr mode then the snat_ns_name namespace
        # should not be present at all:
        elif self.agent.conf.agent_mode == 'dvr':
            self.assertFalse(
                self._namespace_exists(snat_ns_name),
                "namespace %s was found but agent is in dvr mode not dvr_snat"
                % (str(snat_ns_name))
            )
        # if the agent is anything else the test is misconfigured
        # we force a test failure with message
        else:
            self.assertTrue(False, " agent not configured for dvr or dvr_snat")

    def _assert_dvr_gateway(self, router):
        gateway_expected_in_snat_namespace = (
            self.agent.conf.agent_mode == 'dvr_snat'
        )
        if gateway_expected_in_snat_namespace:
            self._assert_dvr_snat_gateway(router)
            self._assert_removal_of_already_deleted_gateway_device(router)

        snat_namespace_should_not_exist = (
            self.agent.conf.agent_mode == 'dvr'
        )
        if snat_namespace_should_not_exist:
            self._assert_snat_namespace_does_not_exist(router)

    def _assert_dvr_snat_gateway(self, router):
        namespace = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router.router_id)
        external_port = router.get_ex_gw_port()
        external_device_name = router.get_external_device_name(
            external_port['id'])
        external_device = ip_lib.IPDevice(external_device_name,
                                          namespace=namespace)
        existing_gateway = (
            external_device.route.get_gateway().get('gateway'))
        expected_gateway = external_port['subnets'][0]['gateway_ip']
        self.assertEqual(expected_gateway, existing_gateway)

    def _assert_removal_of_already_deleted_gateway_device(self, router):
        namespace = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router.router_id)
        device = ip_lib.IPDevice("fakedevice",
                                 namespace=namespace)

        # Assert that no exception is thrown for this case
        self.assertIsNone(router._delete_gateway_device_if_exists(
                          device, "192.168.0.1", 0))

    def _assert_snat_namespace_does_not_exist(self, router):
        namespace = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router.router_id)
        self.assertFalse(self._namespace_exists(namespace))

    def _assert_dvr_floating_ips(self, router):
        # in the fip namespace:
        # Check that the fg-<port-id> (floatingip_agent_gateway)
        # is created with the ip address of the external gateway port
        floating_ips = router.router[lib_constants.FLOATINGIP_KEY]
        self.assertTrue(floating_ips)
        # We need to fetch the floatingip agent gateway port info
        # from the router_info
        floating_agent_gw_port = (
            router.router[n_const.FLOATINGIP_AGENT_INTF_KEY])
        self.assertTrue(floating_agent_gw_port)

        external_gw_port = floating_agent_gw_port[0]
        fip_ns = self.agent.get_fip_ns(floating_ips[0]['floating_network_id'])
        fip_ns_name = fip_ns.get_name()
        fg_port_created_successfully = ip_lib.device_exists_with_ips_and_mac(
            fip_ns.get_ext_device_name(external_gw_port['id']),
            [self._port_first_ip_cidr(external_gw_port)],
            external_gw_port['mac_address'],
            namespace=fip_ns_name)
        self.assertTrue(fg_port_created_successfully)
        # Check fpr-router device has been created
        device_name = fip_ns.get_int_device_name(router.router_id)
        fpr_router_device_created_successfully = ip_lib.device_exists(
            device_name, namespace=fip_ns_name)
        self.assertTrue(fpr_router_device_created_successfully)

        # In the router namespace
        # Check rfp-<router-id> is created correctly
        for fip in floating_ips:
            device_name = fip_ns.get_rtr_ext_device_name(router.router_id)
            self.assertTrue(ip_lib.device_exists(
                device_name, namespace=router.ns_name))

        # In the router namespace, check the iptables rules are set correctly
        for fip in floating_ips:
            floatingip = fip['floating_ip_address']
            fixedip = fip['fixed_ip_address']
            expected_rules = router.floating_forward_rules(floatingip,
                                                           fixedip)
            self._assert_iptables_rules_exist(
                router.iptables_manager, 'nat', expected_rules)

    def test_dvr_router_rem_fips_on_restarted_agent(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info()
        router1 = self.manage_router(self.agent, router_info)
        fip_ns = router1.fip_ns.get_name()
        self.assertTrue(self._namespace_exists(fip_ns))
        restarted_agent = neutron_l3_agent.L3NATAgentWithStateReport(
            self.agent.host, self.agent.conf)
        router1.router[lib_constants.FLOATINGIP_KEY] = []
        self.manage_router(restarted_agent, router1.router)
        self._assert_dvr_snat_gateway(router1)
        self.assertTrue(self._namespace_exists(fip_ns))

    def test_dvr_router_add_fips_on_restarted_agent(self):
        self.agent.conf.agent_mode = 'dvr'
        router_info = self.generate_dvr_router_info()
        router = self.manage_router(self.agent, router_info)
        floating_ips = router.router[lib_constants.FLOATINGIP_KEY]
        router_ns = router.ns_name
        fip_rule_prio_1 = self._get_fixed_ip_rule_priority(
            router_ns, floating_ips[0]['fixed_ip_address'])
        restarted_agent = neutron_l3_agent.L3NATAgent(
            self.agent.host, self.agent.conf)
        floating_ips[0]['floating_ip_address'] = '21.4.4.2'
        floating_ips[0]['fixed_ip_address'] = '10.0.0.2'
        self.manage_router(restarted_agent, router_info)
        fip_rule_prio_2 = self._get_fixed_ip_rule_priority(
            router_ns, floating_ips[0]['fixed_ip_address'])
        self.assertNotEqual(fip_rule_prio_1, fip_rule_prio_2)

    def test_dvr_router_floating_ip_moved(self):
        self.agent.conf.agent_mode = 'dvr'
        router_info = self.generate_dvr_router_info()
        router = self.manage_router(self.agent, router_info)
        floating_ips = router.router[lib_constants.FLOATINGIP_KEY]
        router_ns = router.ns_name
        fixed_ip = floating_ips[0]['fixed_ip_address']
        self.assertTrue(self._fixed_ip_rule_exists(router_ns, fixed_ip))
        # Floating IP reassigned to another fixed IP
        new_fixed_ip = '10.0.0.2'
        self.assertNotEqual(new_fixed_ip, fixed_ip)
        floating_ips[0]['fixed_ip_address'] = new_fixed_ip
        self.agent._process_updated_router(router.router)
        self.assertFalse(self._fixed_ip_rule_exists(router_ns, fixed_ip))
        self.assertTrue(self._fixed_ip_rule_exists(router_ns, new_fixed_ip))

    def _assert_iptables_rules_exist(
        self, router_iptables_manager, table_name, expected_rules):
        rules = router_iptables_manager.get_rules_for_table(table_name)
        for rule in expected_rules:
            self.assertIn(
                str(iptables_manager.IptablesRule(rule[0], rule[1])), rules)

    def test_prevent_snat_rule_exist_on_restarted_agent(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info()
        router = self.manage_router(self.agent, router_info)
        ext_port = router.get_ex_gw_port()
        rfp_devicename = router.get_external_device_interface_name(ext_port)
        prevent_snat_rule = router._prevent_snat_for_internal_traffic_rule(
            rfp_devicename)

        self._assert_iptables_rules_exist(
            router.iptables_manager, 'nat', [prevent_snat_rule])

        restarted_agent = neutron_l3_agent.L3NATAgentWithStateReport(
            self.agent.host, self.agent.conf)
        restarted_router = self.manage_router(restarted_agent, router_info)

        self._assert_iptables_rules_exist(
            restarted_router.iptables_manager, 'nat', [prevent_snat_rule])

    def _get_fixed_ip_rule_priority(self, namespace, fip):
        iprule = ip_lib.IPRule(namespace)
        lines = iprule.rule._as_root([4], ['show']).splitlines()
        for line in lines:
            if fip in line:
                info = iprule.rule._parse_line(4, line)
                return info['priority']

    def _fixed_ip_rule_exists(self, namespace, ip):
        iprule = ip_lib.IPRule(namespace)
        lines = iprule.rule._as_root([4], ['show']).splitlines()
        for line in lines:
            if ip in line:
                info = iprule.rule._parse_line(4, line)
                if info['from'] == ip:
                    return True

        return False

    def test_dvr_router_add_internal_network_set_arp_cache(self):
        # Check that, when the router is set up and there are
        # existing ports on the uplinked subnet, the ARP
        # cache is properly populated.
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = l3_test_common.prepare_router_data()
        router_info['distributed'] = True
        expected_neighbor = '35.4.1.10'
        port_data = {
            'fixed_ips': [{'ip_address': expected_neighbor}],
            'mac_address': 'fa:3e:aa:bb:cc:dd',
            'device_owner': DEVICE_OWNER_COMPUTE
        }
        self.agent.plugin_rpc.get_ports_by_subnet.return_value = [port_data]
        router1 = self.manage_router(self.agent, router_info)
        internal_device = router1.get_internal_device_name(
            router_info['_interfaces'][0]['id'])
        neighbors = ip_lib.IPDevice(internal_device, router1.ns_name).neigh
        self.assertEqual(expected_neighbor,
                         neighbors.show(ip_version=4).split()[0])

    def _assert_rfp_fpr_mtu(self, router, expected_mtu=1500):
        dev_mtu = self.get_device_mtu(
            router.router_id, router.fip_ns.get_rtr_ext_device_name,
            router.ns_name)
        self.assertEqual(expected_mtu, dev_mtu)
        dev_mtu = self.get_device_mtu(
            router.router_id, router.fip_ns.get_int_device_name,
            router.fip_ns.get_name())
        self.assertEqual(expected_mtu, dev_mtu)

    def test_dvr_router_fip_agent_mismatch(self):
        """Test to validate the floatingip agent mismatch.

        This test validates the condition where floatingip agent
        gateway port host mismatches with the agent and so the
        binding will not be there.

        """
        self.agent.conf.agent_mode = 'dvr'
        router_info = self.generate_dvr_router_info()
        floating_ip = router_info['_floatingips'][0]
        floating_ip['host'] = 'my_new_host'
        # In this case the floatingip binding is different and so it
        # should not create the floatingip namespace on the given agent.
        # This is also like there is no current binding.
        router1 = self.manage_router(self.agent, router_info)
        fip_ns = router1.fip_ns.get_name()
        self.assertTrue(self._namespace_exists(router1.ns_name))
        self.assertFalse(self._namespace_exists(fip_ns))
        self._assert_snat_namespace_does_not_exist(router1)

    def test_dvr_router_fip_create_for_migrating_port(self):
        """Test to validate the floatingip create on port migrate.

        This test validates the condition where floatingip host
        mismatches with the agent, but the 'dest_host' variable
        matches with the agent host, due to port pre-migrate
        phase.

        """
        self.agent.conf.agent_mode = 'dvr'
        router_info = self.generate_dvr_router_info()
        floating_ip = router_info['_floatingips'][0]
        floating_ip['host'] = 'my_new_host'
        floating_ip['dest_host'] = self.agent.host
        # Now we have the floatingip 'host' pointing to host that
        # does not match to the 'agent.host' and the floatingip
        # 'dest_host' matches with the agent.host in the case
        # of live migration due to the port_profile update from
        # nova.
        router1 = self.manage_router(self.agent, router_info)
        fip_ns = router1.fip_ns.get_name()
        self.assertTrue(self._namespace_exists(router1.ns_name))
        self.assertTrue(self._namespace_exists(fip_ns))

    def test_dvr_router_fip_late_binding(self):
        """Test to validate the floatingip migration or latebinding.

        This test validates the condition where floatingip private
        port changes while migration or when the private port host
        binding is done later after floatingip association.

        """
        self.agent.conf.agent_mode = 'dvr'
        router_info = self.generate_dvr_router_info()
        fip_agent_gw_port = router_info[n_const.FLOATINGIP_AGENT_INTF_KEY]
        # Now let us not pass the FLOATINGIP_AGENT_INTF_KEY, to emulate
        # that the server did not create the port, since there was no valid
        # host binding.
        router_info[n_const.FLOATINGIP_AGENT_INTF_KEY] = []
        self.mock_plugin_api.get_agent_gateway_port.return_value = (
            fip_agent_gw_port[0])
        router1 = self.manage_router(self.agent, router_info)
        fip_ns = router1.fip_ns.get_name()
        self.assertTrue(self._namespace_exists(router1.ns_name))
        self.assertTrue(self._namespace_exists(fip_ns))
        self._assert_snat_namespace_does_not_exist(router1)

    def _assert_snat_namespace_exists(self, router):
        namespace = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router.router_id)
        self.assertTrue(self._namespace_exists(namespace))

    def _get_dvr_snat_namespace_device_status(
        self, router, internal_dev_name=None):
        """Function returns the internal and external device status."""
        snat_ns = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router.router_id)
        external_port = router.get_ex_gw_port()
        external_device_name = router.get_external_device_name(
            external_port['id'])
        qg_device_created_successfully = ip_lib.device_exists(
            external_device_name, namespace=snat_ns)
        sg_device_created_successfully = ip_lib.device_exists(
            internal_dev_name, namespace=snat_ns)
        return qg_device_created_successfully, sg_device_created_successfully

    def test_dvr_router_snat_namespace_with_interface_remove(self):
        """Test to validate the snat namespace with interface remove.

        This test validates the snat namespace for all the external
        and internal devices. It also validates if the internal
        device corresponding to the router interface is removed
        when the router interface is deleted.
        """
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info()
        snat_internal_port = router_info[n_const.SNAT_ROUTER_INTF_KEY]
        router1 = self.manage_router(self.agent, router_info)
        csnat_internal_port = (
            router1.router[n_const.SNAT_ROUTER_INTF_KEY])
        # Now save the internal device name to verify later
        internal_device_name = router1._get_snat_int_device_name(
            csnat_internal_port[0]['id'])
        self._assert_snat_namespace_exists(router1)
        qg_device, sg_device = self._get_dvr_snat_namespace_device_status(
            router1, internal_dev_name=internal_device_name)
        self.assertTrue(qg_device)
        self.assertTrue(sg_device)
        self.assertEqual(router1.snat_ports, snat_internal_port)
        # Now let us not pass INTERFACE_KEY, to emulate
        # the interface has been removed.
        router1.router[lib_constants.INTERFACE_KEY] = []
        # Now let us not pass the SNAT_ROUTER_INTF_KEY, to emulate
        # that the server did not send it, since the interface has been
        # removed.
        router1.router[n_const.SNAT_ROUTER_INTF_KEY] = []
        self.agent._process_updated_router(router1.router)
        router_updated = self.agent.router_info[router_info['id']]
        self._assert_snat_namespace_exists(router_updated)
        qg_device, sg_device = self._get_dvr_snat_namespace_device_status(
            router_updated, internal_dev_name=internal_device_name)
        self.assertFalse(sg_device)
        self.assertTrue(qg_device)

    def _mocked_dvr_ha_router(self, agent, enable_gw=True):
        r_info = self.generate_dvr_router_info(enable_ha=True,
                                               enable_snat=True,
                                               agent=agent,
                                               enable_gw=enable_gw)

        r_snat_ns_name = namespaces.build_ns_name(dvr_snat_ns.SNAT_NS_PREFIX,
                                                  r_info['id'])

        mocked_r_snat_ns_name = r_snat_ns_name + '@' + agent.host
        r_ns_name = namespaces.build_ns_name(namespaces.NS_PREFIX,
                                             r_info['id'])

        mocked_r_ns_name = r_ns_name + '@' + agent.host

        return r_info, mocked_r_ns_name, mocked_r_snat_ns_name

    def _setup_dvr_ha_agents(self):
        self.agent.conf.agent_mode = 'dvr_snat'

        conf = self._configure_agent('agent2')
        self.failover_agent = neutron_l3_agent.L3NATAgentWithStateReport(
            'agent2', conf)
        self.failover_agent.conf.agent_mode = 'dvr_snat'

    def _setup_dvr_ha_bridges(self):
        br_int_1 = self._get_agent_ovs_integration_bridge(self.agent)
        br_int_2 = self._get_agent_ovs_integration_bridge(self.failover_agent)

        veth1, veth2 = self.useFixture(net_helpers.VethFixture()).ports
        br_int_1.add_port(veth1.name)
        br_int_2.add_port(veth2.name)

    def _create_dvr_ha_router(self, agent, enable_gw=True):
        get_ns_name = mock.patch.object(namespaces.RouterNamespace,
                                        '_get_ns_name').start()
        get_snat_ns_name = mock.patch.object(dvr_snat_ns.SnatNamespace,
                                             'get_snat_ns_name').start()
        (r_info,
         mocked_r_ns_name,
         mocked_r_snat_ns_name) = self._mocked_dvr_ha_router(agent, enable_gw)
        get_ns_name.return_value = mocked_r_ns_name
        get_snat_ns_name.return_value = mocked_r_snat_ns_name
        router = self.manage_router(agent, r_info)
        return router

    def _assert_ip_addresses_in_dvr_ha_snat_namespace(self, router):
        namespace = router.ha_namespace
        ex_gw_port = router.get_ex_gw_port()
        snat_ports = router.get_snat_interfaces()
        if not snat_ports:
            return

        snat_port = snat_ports[0]
        ex_gw_port_name = router.get_external_device_name(
            ex_gw_port['id'])
        snat_port_name = router._get_snat_int_device_name(
            snat_port['id'])

        ip = ex_gw_port["fixed_ips"][0]['ip_address']
        prefix_len = ex_gw_port["fixed_ips"][0]['prefixlen']
        ex_gw_port_cidr = ip + "/" + str(prefix_len)
        ip = snat_port["fixed_ips"][0]['ip_address']
        prefix_len = snat_port["fixed_ips"][0]['prefixlen']
        snat_port_cidr = ip + "/" + str(prefix_len)

        self._assert_ip_address_on_interface(namespace,
                                             ex_gw_port_name,
                                             ex_gw_port_cidr)
        self._assert_ip_address_on_interface(namespace,
                                             snat_port_name,
                                             snat_port_cidr)

    def _assert_no_ip_addresses_in_dvr_ha_snat_namespace(self, router):
        namespace = router.ha_namespace
        ex_gw_port = router.get_ex_gw_port()
        snat_ports = router.get_snat_interfaces()
        if not snat_ports:
            return

        snat_port = snat_ports[0]
        ex_gw_port_name = router.get_external_device_name(
            ex_gw_port['id'])
        snat_port_name = router._get_snat_int_device_name(
            snat_port['id'])

        self._assert_no_ip_addresses_on_interface(namespace,
                                                  snat_port_name)
        self._assert_no_ip_addresses_on_interface(namespace,
                                                  ex_gw_port_name)

    def _test_dvr_ha_router_failover(self, enable_gw):
        self._setup_dvr_ha_agents()
        self._setup_dvr_ha_bridges()

        router1 = self._create_dvr_ha_router(self.agent, enable_gw=enable_gw)
        router2 = self._create_dvr_ha_router(self.failover_agent, enable_gw)

        utils.wait_until_true(lambda: router1.ha_state == 'master')
        utils.wait_until_true(lambda: router2.ha_state == 'backup')

        self._assert_ip_addresses_in_dvr_ha_snat_namespace(router1)
        self._assert_no_ip_addresses_in_dvr_ha_snat_namespace(router2)

        self.fail_ha_router(router1)

        utils.wait_until_true(lambda: router2.ha_state == 'master')
        utils.wait_until_true(lambda: router1.ha_state == 'backup')

        self._assert_ip_addresses_in_dvr_ha_snat_namespace(router2)
        self._assert_no_ip_addresses_in_dvr_ha_snat_namespace(router1)

    def test_dvr_ha_router_failover_with_gw(self):
        self._test_dvr_ha_router_failover(enable_gw=True)

    def test_dvr_ha_router_failover_without_gw(self):
        self._test_dvr_ha_router_failover(enable_gw=False)

    def test_dvr_router_static_routes(self):
        """Test to validate the extra routes on dvr routers."""
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info(enable_snat=True)
        router1 = self.manage_router(self.agent, router_info)
        self.assertTrue(self._namespace_exists(router1.ns_name))
        self._assert_snat_namespace_exists(router1)
        snat_ns_name = dvr_snat_ns.SnatNamespace.get_snat_ns_name(
            router1.router_id)
        # Now try to add routes that are suitable for both the
        # router namespace and the snat namespace.
        router1.router['routes'] = [{'destination': '8.8.4.0/24',
                                     'nexthop': '35.4.0.20'}]
        self.agent._process_updated_router(router1.router)
        router_updated = self.agent.router_info[router_info['id']]
        self._assert_extra_routes(router_updated, namespace=snat_ns_name)
        self._assert_extra_routes(router_updated)

    def test_dvr_router_gateway_update_to_none(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info(enable_snat=True)
        router = self.manage_router(self.agent, router_info)
        gw_port = router.get_ex_gw_port()
        ex_gw_port_name = router.get_external_device_name(gw_port['id'])
        ex_gw_device = ip_lib.IPDevice(ex_gw_port_name,
                                       namespace=router.snat_namespace.name)
        fg_port = router.fip_ns.agent_gateway_port
        fg_port_name = router.fip_ns.get_ext_device_name(fg_port['id'])
        fg_device = ip_lib.IPDevice(fg_port_name,
                                    namespace=router.fip_ns.name)
        self.assertIn('gateway', ex_gw_device.route.get_gateway())
        self.assertIn('gateway', fg_device.route.get_gateway())

        # Make this copy to make agent think gw_port changed.
        router.ex_gw_port = copy.deepcopy(router.ex_gw_port)
        for subnet in gw_port['subnets']:
            subnet['gateway_ip'] = None
        new_fg_port = copy.deepcopy(fg_port)
        for subnet in new_fg_port['subnets']:
            subnet['gateway_ip'] = None

        router.router[n_const.FLOATINGIP_AGENT_INTF_KEY] = [new_fg_port]
        router.process(self.agent)
        self.assertIsNone(ex_gw_device.route.get_gateway())
        self.assertIsNone(fg_device.route.get_gateway())

    def _assert_fip_namespace_deleted(self, ext_gateway_port):
        ext_net_id = ext_gateway_port['network_id']
        fip_ns = self.agent.get_fip_ns(ext_net_id)
        fip_ns.unsubscribe = mock.Mock()
        self.agent.fipnamespace_delete_on_ext_net(
            self.agent.context, ext_net_id)
        self._assert_interfaces_deleted_from_ovs()
        fip_ns_name = fip_ns.get_name()
        self.assertFalse(self._namespace_exists(fip_ns_name))
        self.assertTrue(fip_ns.destroyed)
        self.assertTrue(fip_ns.unsubscribe.called)

    def _setup_address_scope(self, internal_address_scope1,
                             internal_address_scope2, gw_address_scope=None):
        router_info = self.generate_dvr_router_info(enable_snat=True)
        address_scope1 = {
            str(lib_constants.IP_VERSION_4): internal_address_scope1}
        address_scope2 = {
            str(lib_constants.IP_VERSION_4): internal_address_scope2}
        if gw_address_scope:
            router_info['gw_port']['address_scopes'] = {
                str(lib_constants.IP_VERSION_4): gw_address_scope}
        router_info[lib_constants.INTERFACE_KEY][0]['address_scopes'] = (
            address_scope1)
        router_info[lib_constants.INTERFACE_KEY][1]['address_scopes'] = (
            address_scope2)
        # Renew the address scope
        router_info[n_const.SNAT_ROUTER_INTF_KEY] = []
        self._add_snat_port_info_to_router(
            router_info, router_info[lib_constants.INTERFACE_KEY])

        router = self.manage_router(self.agent, router_info)
        router_ip_cidr1 = self._port_first_ip_cidr(router.internal_ports[0])
        router_ip1 = router_ip_cidr1.partition('/')[0]
        router_ip_cidr2 = self._port_first_ip_cidr(router.internal_ports[1])
        router_ip2 = router_ip_cidr2.partition('/')[0]

        br_int = framework.get_ovs_bridge(
            self.agent.conf.ovs_integration_bridge)
        test_machine1 = self.useFixture(
            machine_fixtures.FakeMachine(
                br_int,
                net_helpers.increment_ip_cidr(router_ip_cidr1, 10),
                router_ip1))
        test_machine2 = self.useFixture(
            machine_fixtures.FakeMachine(
                br_int,
                net_helpers.increment_ip_cidr(router_ip_cidr2, 10),
                router_ip2))

        return test_machine1, test_machine2, router

    def test_connection_from_same_address_scope(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        test_machine1, test_machine2, _ = self._setup_address_scope(
            'scope1', 'scope1')
        # Internal networks that are in the same address scope can connected
        # each other
        net_helpers.assert_ping(test_machine1.namespace, test_machine2.ip)
        net_helpers.assert_ping(test_machine2.namespace, test_machine1.ip)

    def test_connection_from_diff_address_scope(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        test_machine1, test_machine2, _ = self._setup_address_scope(
            'scope1', 'scope2')
        # Internal networks that are not in the same address scope should
        # not reach each other
        test_machine1.assert_no_ping(test_machine2.ip)
        test_machine2.assert_no_ping(test_machine1.ip)

    @testtools.skip('bug/1543885')
    def test_fip_connection_for_address_scope(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        (machine_same_scope, machine_diff_scope,
            router) = self._setup_address_scope('scope1', 'scope2', 'scope1')

        router.router[lib_constants.FLOATINGIP_KEY] = []
        fip_same_scope = '19.4.4.10'
        self._add_fip(router, fip_same_scope,
                      fixed_address=machine_same_scope.ip,
                      host=self.agent.conf.host,
                      fixed_ip_address_scope='scope1')
        fip_diff_scope = '19.4.4.11'
        self._add_fip(router, fip_diff_scope,
                      fixed_address=machine_diff_scope.ip,
                      host=self.agent.conf.host,
                      fixed_ip_address_scope='scope2')
        router.process(self.agent)

        br_ex = framework.get_ovs_bridge(
            self.agent.conf.external_network_bridge)
        src_machine = self.useFixture(
            machine_fixtures.FakeMachine(br_ex, '19.4.4.12/24'))
        # Floating ip should work no matter of address scope
        net_helpers.assert_ping(src_machine.namespace, fip_same_scope)
        net_helpers.assert_ping(src_machine.namespace, fip_diff_scope)

    def test_direct_route_for_address_scope(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        (machine_same_scope, machine_diff_scope,
            router) = self._setup_address_scope('scope1', 'scope2', 'scope1')

        gw_port = router.get_ex_gw_port()
        gw_ip = self._port_first_ip_cidr(gw_port).partition('/')[0]
        br_ex = framework.get_ovs_bridge(
            self.agent.conf.external_network_bridge)

        src_machine = self.useFixture(
            machine_fixtures.FakeMachine(br_ex, '19.4.4.12/24', gw_ip))
        # For the internal networks that are in the same address scope as
        # external network, they can directly route to external network
        net_helpers.assert_ping(src_machine.namespace, machine_same_scope.ip)
        # For the internal networks that are not in the same address scope as
        # external networks. SNAT will be used. Direct route will not work
        # here.
        src_machine.assert_no_ping(machine_diff_scope.ip)

    def test_dvr_snat_namespace_has_ip_nonlocal_bind_disabled(self):
        self.agent.conf.agent_mode = 'dvr_snat'
        router_info = self.generate_dvr_router_info(
            enable_ha=True, enable_snat=True)
        router = self.manage_router(self.agent, router_info)
        try:
            ip_nonlocal_bind_value = ip_lib.get_ip_nonlocal_bind(
                router.snat_namespace.name)
        except RuntimeError as rte:
            stat_message = 'cannot stat /proc/sys/net/ipv4/ip_nonlocal_bind'
            if stat_message in str(rte):
                raise self.skipException(
                    "This kernel doesn't support %s in network namespaces." % (
                        ip_lib.IP_NONLOCAL_BIND))
            raise
        self.assertEqual(0, ip_nonlocal_bind_value)


text:
process.env.NODE_ENV = 'test';
require('should');
var request = require('./support/http'), json = JSON.stringify, express = require('express'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    rest = require('../index.js'), compat = require('../lib/compat'), app;

var UserSchema = new Schema({
    username: String,
    groups: [{type: Schema.Types.ObjectId, ref: 'grouptest', deleteRef: true}],
    stuff: [
        String
    ],
    noDeleteRef: [{type: Schema.Types.ObjectId, ref: 'grouptest', deleteRef: false}]
});
UserSchema.statics.current = function (session$user) {
    return this.findById(session$user);
}

var GroupSchema = new Schema({
    name: String
});
var uid;
describe('user like routes', function () {
    var connection;
    before(function onBefore(done) {
        connection = mongoose.createConnection();
        var User = connection.model('usertest', UserSchema),
            Group = connection.model('grouptest', GroupSchema),
            u;
        app = express();
        app.use(compat.bodyParser());
        //fake login session.
        app.use(function (req, res, next) {
            var session = req.session || (req.session = {});
            uid = session.user = u._id;
            next();
        });
        app.use('/rest', rest({mongoose: connection}).rest());

        connection.on('connected', function () {

            this.db.dropDatabase(function () {

                var g = new Group({
                    name: 'No Delete'
                });
                g.save(function (e, o) {
                    u = new User({username: 'bob', stuff: ['stuff', 'then stuff', 'other stuff'], noDeleteRef:[g]});
                    u.save(function (e, o) {
                        if (e) {
                            return done(e);
                        }
                        done();
                    });
                });
            });
        });

        if (connection.readyState === 1) connection.close();
        connection.open('mongodb://localhost/routes-mocha-user');

    });
    after(function onAfter(done) {
        connection.on('disconnected', function () {
            done();
        });
        connection.close();

    });
    it('should return current', function (done) {
        request(app).get('/rest/usertest/current').end(function (err, resp) {
            resp.body.should.have.property('payload');
            resp.body.payload.should.have.property('username', 'bob');
            done();
        })
    });
    it('should put current', function (done) {
        request(app).put('/rest/usertest/current').set('Content-Type', 'application/json')
            .send(json({"username": "Robert"})).end(function (err, resp) {
                resp.body.should.have.property('payload');
                resp.body.payload.should.have.property('username', 'Robert');
                done();
            })
    });
    it('should post current refs', function (done) {
        request(app).post('/rest/usertest/current/groups').set('Content-Type', 'application/json')
            .send(json({"name": "G1"})).end(function (err, resp) {
                resp.body.should.have.property('payload');
                resp.body.payload.should.have.property('name', 'G1');
                done();
            })
    });
    it('should delete stuff', function (done) {
        request(app).delete('/rest/usertest/current/stuff/1').set('Content-Type', 'application/json')
            .end(function (err, resp) {
                var payload = resp.body.should.have.property('payload').obj;
                request(app).get('/rest/usertest/current').set('Content-Type', 'application/json').end(function (e, o) {
                    o.body.should.have.property('status', 0);
                    var obj = o.body.should.have.property('payload').obj;
                    obj.stuff.should.have.property('length', 2);
                    obj.stuff.should.have.property('0', "stuff");
                    obj.stuff.should.have.property('1', "other stuff");

                    done();
                })

            })
    });
    it('should delete current without deleting ref', function (done) {
        request(app).delete('/rest/usertest/current/noDeleteRef/0').set('Content-Type', 'application/json')
            .end(function (err, resp) {
                var payload = resp.body.should.have.property('payload').obj;
                payload.should.have.property('name', 'No Delete');
                var gid = payload._id;
                request(app).get('/rest/usertest/current?populate=noDeleteRef').set('Content-Type', 'application/json').end(function (e, o) {
                    o.body.should.have.property('status', 0);
                    payload = o.body.should.have.property('payload').obj;
                    var groups = payload.should.have.property('noDeleteRef').obj;
                    groups.should.have.property('length', 0);
                    request(app).get('/rest/grouptest/' + gid).set('Content-Type', 'application/json').end(function (e, o) {
                        payload = o.body.should.have.property('payload').obj;
                        payload.should.have.property('_id', gid);
                        done();
                    });
                })
                // resp.body.should.have.property('payload');
                // resp.body.payload.should.have.property('name', 'G1');
//                done();
            })
    });
    it('should delete current group 0', function (done) {
        request(app).delete('/rest/usertest/current/groups/0').set('Content-Type', 'application/json')
            .end(function (err, resp) {
                var payload = resp.body.should.have.property('payload').obj;
                payload.should.have.property('name', 'G1');
                var gid = payload._id;
                request(app).get('/rest/usertest/current?populate=groups').set('Content-Type', 'application/json').end(function (e, o) {
                    o.body.should.have.property('status', 0);
                    payload = o.body.should.have.property('payload').obj;
                    var groups = payload.should.have.property('groups').obj;
                    groups.should.have.property('length', 0);
                    request(app).get('/rest/grouptest/' + gid).set('Content-Type', 'application/json').end(function (e, o) {
                        o.should.not.have.property('payload');
                        done();
                    });
                })
                // resp.body.should.have.property('payload');
                // resp.body.payload.should.have.property('name', 'G1');
//                done();
            })
    });
    it('should delete current', function (done) {
        request(app).delete('/rest/usertest/current').set('Content-Type', 'application/json')
            .end(function (err, resp) {
                var payload = resp.body.should.have.property('payload').obj;
                payload.should.have.property('_id', uid + '');
                request(app).get('/rest/usertest/current').set('Content-Type', 'application/json').end(function (e, o) {
                    o.body.should.have.property('status', 0);
                    done();
                })
                // resp.body.should.have.property('payload');
                // resp.body.payload.should.have.property('name', 'G1');
//                done();
            })
    })

});


text:
.browsehappy {
  margin: 0.2em 0;
  background: #ccc;
  color: #000;
  padding: 0.2em 0;
}

body {
  padding: 0;
}

/* Everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
  padding-left: 15px;
  padding-right: 15px;
}

/* Custom page header */
/*.header {
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 10px;
}*/
/* Make the masthead heading the same height as the navigation */
.header h3 {
  margin-top: 0;
  margin-bottom: 0;
  line-height: 40px;
  padding-bottom: 19px;
}

/* Custom page footer */
.footer {
  padding-top: 19px;
  color: #777;
  border-top: 1px solid #e5e5e5;
}

.container-narrow > hr {
  margin: 30px 0;
}

/* Main marketing message and sign up button */
.jumbotron {
  text-align: center;
  border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
  font-size: 21px;
  padding: 14px 24px;
}

/* Supporting marketing content */
.marketing {
  margin: 40px 0;
}
.marketing p + h4 {
  margin-top: 28px;
}

html.login, body.login {
    height: 100%;
}
ng-atomic-notify {
  z-index: 9999 !important;
}
.atomic-notify .atomic-notify-item {
    margin: 50px auto 0 !important;
}
.atomic-notify .atomic-notify-item .icon {
    width: 60px !important;
    display: table-cell !important;
    padding: 20px !important;
}
.atomic-notify .atomic-notify-item .body {
    display: table !important;
    padding: 15px 10px!important;
}
.cropArea {
  background: #E4E4E4;
  overflow: hidden;
  width:500px;
  height:350px;
}
.preview img {
    width: 50%;
}
/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
  .container {
    max-width: 730px;
  }

  /* Remove the padding we set earlier */
  .header,
  .marketing,
  .footer {
    padding-left: 0;
    padding-right: 0;
  }
  /* Space out the masthead */
  .header {
    margin-bottom: 30px;
  }
  /* Remove the bottom border on the jumbotron for visual effect */
  .jumbotron {
    border-bottom: 0;
  }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**allianceTaxRate** | **Float** | Only present if alliance access is allowed |  [optional]
**allowAccessWithStandings** | **Boolean** | standing_level and any standing related tax rate only present when this is true |
**allowAllianceAccess** | **Boolean** | allow_alliance_access boolean |
**badStandingTaxRate** | **Float** | bad_standing_tax_rate number |  [optional]
**corporationTaxRate** | **Float** | corporation_tax_rate number |  [optional]
**excellentStandingTaxRate** | **Float** | Tax rate for entities with excellent level of standing, only present if this level is allowed, same for all other standing related tax rates |  [optional]
**goodStandingTaxRate** | **Float** | good_standing_tax_rate number |  [optional]
**neutralStandingTaxRate** | **Float** | neutral_standing_tax_rate number |  [optional]
**officeId** | **Long** | unique ID of this customs office |
**reinforceExitEnd** | **Integer** | reinforce_exit_end integer |
**reinforceExitStart** | **Integer** | Together with reinforce_exit_end, marks a 2-hour period where this customs office could exit reinforcement mode during the day after initial attack |
**standingLevel** | [**StandingLevelEnum**](#StandingLevelEnum) | Access is allowed only for entities with this level of standing or better |  [optional]
**systemId** | **Integer** | ID of the solar system this customs office is located in |
**terribleStandingTaxRate** | **Float** | terrible_standing_tax_rate number |  [optional]

## Enum: StandingLevelEnum
Name | Value
---- | -----
BAD | "bad"
EXCELLENT | "excellent"
GOOD | "good"
NEUTRAL | "neutral"
TERRIBLE | "terrible"


text:
import json

import numpy as np
from pandas import DataFrame, Series
from shapely.geometry import mapping, shape
from shapely.geometry.base import BaseGeometry
from six import string_types, PY3

from geopandas.base import GeoPandasBase, _CoordinateIndexer
from geopandas.geoseries import GeoSeries
from geopandas.plotting import plot_dataframe
import geopandas.io

DEFAULT_GEO_COLUMN_NAME = 'geometry'

class GeoDataFrame(GeoPandasBase, DataFrame):
    """
    A GeoDataFrame object is a pandas.DataFrame that has a column
    with geometry. In addition to the standard DataFrame constructor arguments,
    GeoDataFrame also accepts the following keyword arguments:

    Keyword Arguments
    -----------------
    crs : str (optional)
        Coordinate system
    geometry : str or array (optional)
        If str, column to use as geometry. If array, will be set as 'geometry'
        column on GeoDataFrame.
    """

    # XXX: This will no longer be necessary in pandas 0.17
    _internal_names = ['_data', '_cacher', '_item_cache', '_cache',
                       'is_copy', '_subtyp', '_index',
                       '_default_kind', '_default_fill_value', '_metadata',
                       '__array_struct__', '__array_interface__']

    _metadata = ['crs', '_geometry_column_name']

    _geometry_column_name = DEFAULT_GEO_COLUMN_NAME

    def __init__(self, *args, **kwargs):
        crs = kwargs.pop('crs', None)
        geometry = kwargs.pop('geometry', None)
        super(GeoDataFrame, self).__init__(*args, **kwargs)
        self.crs = crs
        if geometry is not None:
            self.set_geometry(geometry, inplace=True)
        self._invalidate_sindex()

    # Serialize metadata (will no longer be necessary in pandas 0.17+)
    # See https://github.com/pydata/pandas/pull/10557
    def __getstate__(self):
        meta = dict((k, getattr(self, k, None)) for k in self._metadata)
        return dict(_data=self._data, _typ=self._typ,
                    _metadata=self._metadata, **meta)

    def __setattr__(self, attr, val):
        # have to special case geometry b/c pandas tries to use as column...
        if attr == 'geometry':
            object.__setattr__(self, attr, val)
        else:
            super(GeoDataFrame, self).__setattr__(attr, val)

    def _get_geometry(self):
        if self._geometry_column_name not in self:
            raise AttributeError("No geometry data set yet (expected in"
                                 " column '%s'." % self._geometry_column_name)
        return self[self._geometry_column_name]

    def _set_geometry(self, col):
        # TODO: Use pandas' core.common.is_list_like() here.
        if not isinstance(col, (list, np.ndarray, Series)):
            raise ValueError("Must use a list-like to set the geometry"
                             " property")
        self.set_geometry(col, inplace=True)

    geometry = property(fget=_get_geometry, fset=_set_geometry,
                        doc="Geometry data for GeoDataFrame")

    def set_geometry(self, col, drop=False, inplace=False, crs=None):
        """
        Set the GeoDataFrame geometry using either an existing column or
        the specified input. By default yields a new object.

        The original geometry column is replaced with the input.

        Parameters
        ----------
        keys : column label or array
        drop : boolean, default True
            Delete column to be used as the new geometry
        inplace : boolean, default False
            Modify the GeoDataFrame in place (do not create a new object)
        crs : str/result of fion.get_crs (optional)
            Coordinate system to use. If passed, overrides both DataFrame and
            col's crs. Otherwise, tries to get crs from passed col values or
            DataFrame.

        Examples
        --------
        >>> df1 = df.set_geometry([Point(0,0), Point(1,1), Point(2,2)])
        >>> df2 = df.set_geometry('geom1')

        Returns
        -------
        geodataframe : GeoDataFrame
        """
        # Most of the code here is taken from DataFrame.set_index()
        if inplace:
            frame = self
        else:
            frame = self.copy()

        if not crs:
            crs = getattr(col, 'crs', self.crs)

        to_remove = None
        geo_column_name = self._geometry_column_name
        if isinstance(col, (Series, list, np.ndarray)):
            level = col
        elif hasattr(col, 'ndim') and col.ndim != 1:
            raise ValueError("Must pass array with one dimension only.")
        else:
            try:
                level = frame[col].values
            except KeyError:
                raise ValueError("Unknown column %s" % col)
            except:
                raise
            if drop:
                to_remove = col
                geo_column_name = self._geometry_column_name
            else:
                geo_column_name = col

        if to_remove:
            del frame[to_remove]

        if isinstance(level, GeoSeries) and level.crs != crs:
            # Avoids caching issues/crs sharing issues
            level = level.copy()
            level.crs = crs

        # Check that we are using a listlike of geometries
        if not all(isinstance(item, BaseGeometry) or not item for item in level):
            raise TypeError("Input geometry column must contain valid geometry objects.")
        frame[geo_column_name] = level
        frame._geometry_column_name = geo_column_name
        frame.crs = crs
        frame._invalidate_sindex()
        if not inplace:
            return frame

    @classmethod
    def from_file(cls, filename, **kwargs):
        """Alternate constructor to create a ``GeoDataFrame`` from a file.

        Can load a ``GeoDataFrame`` from a file in any format recognized by
        `fiona`. See http://toblerity.org/fiona/manual.html for details.

        Parameters
        ----------

        filename : str
            File path or file handle to read from. Depending on which kwargs
            are included, the content of filename may vary. See
            http://toblerity.org/fiona/README.html#usage for usage details.
        kwargs : key-word arguments
            These arguments are passed to fiona.open, and can be used to
            access multi-layer data, data stored within archives (zip files),
            etc.

        Examples
        --------

        >>> df = geopandas.GeoDataFrame.from_file('nybb.shp')
        """
        return geopandas.io.file.read_file(filename, **kwargs)

    @classmethod
    def from_features(cls, features, crs=None):
        """
        Alternate constructor to create GeoDataFrame from an iterable of
        features or a feature collection.

        Parameters
        ----------
        features
            - Iterable of features, where each element must be a feature
              dictionary or implement the __geo_interface__.
            - Feature collection, where the 'features' key contains an
              iterable of features.
            - Object holding a feature collection that implements the
              ``__geo_interface__``.
        crs : str or dict (optional)
            Coordinate reference system to set on the resulting frame.

        Returns
        -------
        GeoDataFrame

        Notes
        -----
        For more information about the ``__geo_interface__``, see
        https://gist.github.com/sgillies/2217756

        """
        # Handle feature collections
        if hasattr(features, "__geo_interface__"):
            fs = features.__geo_interface__
        else:
            fs = features

        if isinstance(fs, dict) and fs.get('type') == 'FeatureCollection':
            features_lst = fs['features']
        else:
            features_lst = features

        rows = []
        for f in features_lst:
            if hasattr(f, "__geo_interface__"):
                f = f.__geo_interface__
            else:
                f = f

            d = {'geometry': shape(f['geometry']) if f['geometry'] else None}
            d.update(f['properties'])
            rows.append(d)
        df = GeoDataFrame.from_dict(rows)
        df.crs = crs
        return df

    @classmethod
    def from_postgis(cls, sql, con, geom_col='geom', crs=None, index_col=None,
                     coerce_float=True, params=None):
        """Alternate constructor to create a ``GeoDataFrame`` from a sql query
        containing a geometry column.

        Parameters
        ----------
        sql : string
        con : DB connection object or SQLAlchemy engine
        geom_col : string, default 'geom'
            column name to convert to shapely geometries
        crs : optional
            Coordinate reference system to use for the returned GeoDataFrame
        index_col : string or list of strings, optional, default: None
            Column(s) to set as index(MultiIndex)
        coerce_float : boolean, default True
            Attempt to convert values of non-string, non-numeric objects (like
            decimal.Decimal) to floating point, useful for SQL result sets
        params : list, tuple or dict, optional, default: None
            List of parameters to pass to execute method.

        Examples
        --------

        >>> sql = "SELECT geom, highway FROM roads;"
        >>> df = geopandas.GeoDataFrame.from_postgis(sql, con)
        """
        return geopandas.io.sql.read_postgis(sql, con, geom_col, crs, index_col,
                     coerce_float, params)

    def to_json(self, na='null', show_bbox=False, **kwargs):
        """Returns a GeoJSON representation of the ``GeoDataFrame`` as a string.

        Parameters
        ----------
        na : {'null', 'drop', 'keep'}, default 'null'
            Indicates how to output missing (NaN) values in the GeoDataFrame.
            See below.
        show_bbox : bool, optional, default: False
            Include bbox (bounds) in the geojson

        Notes
        -----
        The remaining *kwargs* are passed to json.dumps().

        Missing (NaN) values in the GeoDataFrame can be represented as follows:

        - ``null``: output the missing entries as JSON null.
        - ``drop``: remove the property from the feature. This applies to each
          feature individually so that features may have different properties.
        - ``keep``: output the missing entries as NaN.
        """
        return json.dumps(self._to_geo(na=na, show_bbox=show_bbox), **kwargs)

    @property
    def __geo_interface__(self):
        """Returns a ``GeoDataFrame`` as a python feature collection.

        Implements the `geo_interface`. The returned python data structure
        represents the ``GeoDataFrame`` as a GeoJSON-like
        ``FeatureCollection``.

        This differs from `_to_geo()` only in that it is a property with
        default args instead of a method
        """
        return self._to_geo(na='null', show_bbox=True)

    def iterfeatures(self, na='null', show_bbox=False):
        """
        Returns an iterator that yields feature dictionaries that comply with
        __geo_interface__

        Parameters
        ----------
        na : {'null', 'drop', 'keep'}, default 'null'
            Indicates how to output missing (NaN) values in the GeoDataFrame
            * null: ouput the missing entries as JSON null
            * drop: remove the property from the feature. This applies to
                    each feature individually so that features may have
                    different properties
            * keep: output the missing entries as NaN

        show_bbox : include bbox (bounds) in the geojson. default False

        """
        def fill_none(row):
            """
            Takes in a Series, converts to a dictionary with null values
            set to None

            """
            na_keys = row.index[row.isnull()]
            d = row.to_dict()
            for k in na_keys:
                d[k] = None
            return d

        # na_methods must take in a Series and return dict
        na_methods = {'null': fill_none,
                      'drop': lambda row: row.dropna().to_dict(),
                      'keep': lambda row: row.to_dict()}

        if na not in na_methods:
            raise ValueError('Unknown na method {0}'.format(na))
        f = na_methods[na]

        for name, row in self.iterrows():
            properties = f(row)
            del properties[self._geometry_column_name]

            feature = {
                'id': str(name),
                'type': 'Feature',
                'properties': properties,
                'geometry': mapping(row[self._geometry_column_name])
                            if row[self._geometry_column_name] else None
            }

            if show_bbox:
                feature['bbox'] = row.geometry.bounds

            yield feature

    def _to_geo(self, **kwargs):
        """
        Returns a python feature collection (i.e. the geointerface)
        representation of the GeoDataFrame.

        """
        geo = {'type': 'FeatureCollection',
               'features': list(self.iterfeatures(**kwargs))}

        if kwargs.get('show_bbox', False):
            geo['bbox'] = tuple(self.total_bounds)

        return geo

    def to_file(self, filename, driver="ESRI Shapefile", schema=None,
                **kwargs):
        """Write the ``GeoDataFrame`` to a file.

        By default, an ESRI shapefile is written, but any OGR data source
        supported by Fiona can be written. A dictionary of supported OGR
        providers is available via:

        >>> import fiona
        >>> fiona.supported_drivers

        Parameters
        ----------
        filename : string
            File path or file handle to write to.
        driver : string, default: 'ESRI Shapefile'
            The OGR format driver used to write the vector file.
        schema : dict, default: None
            If specified, the schema dictionary is passed to Fiona to
            better control how the file is written.

        Notes
        -----
        The extra keyword arguments ``**kwargs`` are passed to fiona.open and
        can be used to write to multi-layer data, store data within archives
        (zip files), etc.
        """
        from geopandas.io.file import to_file
        to_file(self, filename, driver, schema, **kwargs)

    def to_crs(self, crs=None, epsg=None, inplace=False):
        """Transform geometries to a new coordinate reference system.

        Transform all geometries in a GeoSeries to a different coordinate
        reference system.  The ``crs`` attribute on the current GeoSeries must
        be set.  Either ``crs`` in string or dictionary form or an EPSG code
        may be specified for output.

        This method will transform all points in all objects.  It has no notion
        or projecting entire geometries.  All segments joining points are
        assumed to be lines in the current projection, not geodesics.  Objects
        crossing the dateline (or other projection boundary) will have
        undesirable behavior.

        Parameters
        ----------
        crs : dict or str
            Output projection parameters as string or in dictionary form.
        epsg : int
            EPSG code specifying output projection.
        inplace : bool, optional, default: False
            Whether to return a new GeoDataFrame or do the transformation in
            place.
        """
        if inplace:
            df = self
        else:
            df = self.copy()
        geom = df.geometry.to_crs(crs=crs, epsg=epsg)
        df.geometry = geom
        df.crs = geom.crs
        if not inplace:
            return df

    def __getitem__(self, key):
        """
        If the result is a column containing only 'geometry', return a
        GeoSeries. If it's a DataFrame with a 'geometry' column, return a
        GeoDataFrame.
        """
        result = super(GeoDataFrame, self).__getitem__(key)
        geo_col = self._geometry_column_name
        if isinstance(key, string_types) and key == geo_col:
            result.__class__ = GeoSeries
            result.crs = self.crs
            result._invalidate_sindex()
        elif isinstance(result, DataFrame) and geo_col in result:
            result.__class__ = GeoDataFrame
            result.crs = self.crs
            result._geometry_column_name = geo_col
            result._invalidate_sindex()
        elif isinstance(result, DataFrame) and geo_col not in result:
            result.__class__ = DataFrame
        return result

    #
    # Implement pandas methods
    #

    def merge(self, *args, **kwargs):
        result = DataFrame.merge(self, *args, **kwargs)
        geo_col = self._geometry_column_name
        if isinstance(result, DataFrame) and geo_col in result:
            result.__class__ = GeoDataFrame
            result.crs = self.crs
            result._geometry_column_name = geo_col
            result._invalidate_sindex()
        elif isinstance(result, DataFrame) and geo_col not in result:
            result.__class__ = DataFrame
        return result

    @property
    def _constructor(self):
        return GeoDataFrame

    def __finalize__(self, other, method=None, **kwargs):
        """propagate metadata from other to self """
        # merge operation: using metadata of the left object
        if method == 'merge':
            for name in self._metadata:
                object.__setattr__(self, name, getattr(other.left, name, None))
        # concat operation: using metadata of the first object
        elif method == 'concat':
            for name in self._metadata:
                object.__setattr__(self, name, getattr(other.objs[0], name, None))
        else:
            for name in self._metadata:
                object.__setattr__(self, name, getattr(other, name, None))
        return self

    def copy(self, deep=True):
        """
        Make a copy of this GeoDataFrame object

        Parameters
        ----------
        deep : boolean, default True
            Make a deep copy, i.e. also copy data

        Returns
        -------
        copy : GeoDataFrame
        """
        # FIXME: this will likely be unnecessary in pandas >= 0.13
        data = self._data
        if deep:
            data = data.copy()
        return GeoDataFrame(data).__finalize__(self)

    def plot(self, *args, **kwargs):
        """Generate a plot of the geometries in the ``GeoDataFrame``.

        If the ``column`` parameter is given, colors plot according to values
        in that column, otherwise calls ``GeoSeries.plot()`` on the
        ``geometry`` column.

        Wraps the ``plot_dataframe()`` function, and documentation is copied
        from there.
        """
        return plot_dataframe(self, *args, **kwargs)

    plot.__doc__ = plot_dataframe.__doc__

    def dissolve(self, by=None, aggfunc='first', as_index=True):
        """
        Dissolve geometries within `groupby` into single observation.
        This is accomplished by applying the `unary_union` method
        to all geometries within a groupself.

        Observations associated with each `groupby` group will be aggregated
        using the `aggfunc`.

        Parameters
        ----------
        by : string, default None
            Column whose values define groups to be dissolved
        aggfunc : function or string, default "first"
            Aggregation function for manipulation of data associated
            with each group. Passed to pandas `groupby.agg` method.
        as_index : boolean, default True
            If true, groupby columns become index of result.

        Returns
        -------
        GeoDataFrame
        """

        # Process non-spatial component
        data = self.drop(labels=self.geometry.name, axis=1)
        aggregated_data = data.groupby(by=by).agg(aggfunc)

        # Process spatial component
        def merge_geometries(block):
            merged_geom = block.unary_union
            return merged_geom

        g = self.groupby(by=by, group_keys=False)[self.geometry.name].agg(merge_geometries)

        # Aggregate
        aggregated_geometry = GeoDataFrame(g, geometry=self.geometry.name, crs=self.crs)
        # Recombine
        aggregated = aggregated_geometry.join(aggregated_data)

        # Reset if requested
        if not as_index:
            aggregated = aggregated.reset_index()

        return aggregated

def _dataframe_set_geometry(self, col, drop=False, inplace=False, crs=None):
    if inplace:
        raise ValueError("Can't do inplace setting when converting from"
                         " DataFrame to GeoDataFrame")
    gf = GeoDataFrame(self)
    # this will copy so that BlockManager gets copied
    return gf.set_geometry(col, drop=drop, inplace=False, crs=crs)

if PY3:
    DataFrame.set_geometry = _dataframe_set_geometry
else:
    import types
    DataFrame.set_geometry = types.MethodType(_dataframe_set_geometry, None,
                                              DataFrame)

GeoDataFrame._create_indexer('cx', _CoordinateIndexer)


text:
package com.moac.android.interceptordemo.interceptor;

import com.moac.android.interceptordemo.config.IDebugConfigurationProvider;

import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;

import java.io.IOException;
import java.util.Random;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public final class DelayDebugInterceptor implements Interceptor {

    @NonNull
    private final IDebugConfigurationProvider mDebugConfigurationProvider;

    @NonNull
    private final Random mRandom;

    public DelayDebugInterceptor(
            @NonNull final IDebugConfigurationProvider debugConfigurationProvider) {
        this(debugConfigurationProvider, new Random());
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (shouldDelay()) {
            performDelay();
        }

        return chain.proceed(request).networkResponse();
    }

    private boolean shouldDelay() {
        return isEnabled() && isDelay();
    }

    private boolean isEnabled() {
        return mDebugConfigurationProvider.isNetworkDelayEnabled();
    }

    private boolean isDelay() {
        return mRandom.nextInt(99) <= mDebugConfigurationProvider.getNetworkDelayPercentage() - 1;
    }

    private void performDelay() {
        try {
            long delay = mRandom.nextLong() % mDebugConfigurationProvider.maxDelayInMillis();
            Thread.sleep(delay);
        } catch (InterruptedException ignored) {
            // Do nothing, just proceed.
        }
    }

    @VisibleForTesting
    DelayDebugInterceptor(
            @NonNull final IDebugConfigurationProvider debugConfigurationProvider,
            @NonNull final Random random) {
        mDebugConfigurationProvider = debugConfigurationProvider;
        mRandom = random;
    }
}


text:
import GradientStopNode from './gradient-stop-node';
import BaseNode from '../core/base-node';
import Node from './node';
import renderAllAttr from './utils/render-all-attributes';

var GradientNode = (function (Node) {
    function GradientNode(srcElement) {
        Node.call(this, srcElement);

        this.id = srcElement.id;

        this.loadStops();
    }

    if ( Node ) GradientNode.__proto__ = Node;
    GradientNode.prototype = Object.create( Node && Node.prototype );
    GradientNode.prototype.constructor = GradientNode;

    GradientNode.prototype.loadStops = function loadStops () {
        var this$1 = this;

        var stops = this.srcElement.stops;
        var element = this.element;

        for (var idx = 0; idx < stops.length; idx++) {
            var stopNode = new GradientStopNode(stops[idx]);
            this$1.append(stopNode);
            if (element) {
                stopNode.attachTo(element);
            }
        }
    };

    GradientNode.prototype.optionsChange = function optionsChange (e) {
        if (e.field === "gradient.stops") {
            BaseNode.prototype.clear.call(this);
            this.loadStops();
        } else if (e.field === "gradient") {
            this.allAttr(this.mapCoordinates());
        }
    };

    GradientNode.prototype.renderCoordinates = function renderCoordinates () {
        return renderAllAttr(this.mapCoordinates());
    };

    GradientNode.prototype.mapSpace = function mapSpace () {
        return [ "gradientUnits", this.srcElement.userSpace() ? "userSpaceOnUse" : "objectBoundingBox" ];
    };

    return GradientNode;
}(Node));

export default GradientNode;
//# sourceMappingURL=gradient-node.js.map