text:
// load all controllers here

require('controllers/application');
require('controllers/login_controller');
require('controllers/wizard');
require('controllers/installer');
require('controllers/global/background_operations_controller');
require('controllers/main');
require('controllers/main/dashboard');
require('controllers/main/dashboard/config_history_controller');
require('controllers/main/admin');
require('controllers/main/admin/highAvailability_controller');
require('controllers/main/admin/highAvailability/nameNode/wizard_controller');
require('controllers/main/admin/highAvailability/progress_controller');
require('controllers/main/admin/highAvailability/progress_popup_controller');
require('controllers/main/admin/highAvailability/nameNode/rollback_controller');
require('controllers/main/admin/highAvailability/nameNode/step1_controller');
require('controllers/main/admin/highAvailability/nameNode/step2_controller');
require('controllers/main/admin/highAvailability/nameNode/step3_controller');
require('controllers/main/admin/highAvailability/nameNode/step4_controller');
require('controllers/main/admin/highAvailability/nameNode/step5_controller');
require('controllers/main/admin/highAvailability/nameNode/step6_controller');
require('controllers/main/admin/highAvailability/nameNode/step7_controller');
require('controllers/main/admin/highAvailability/nameNode/step8_controller');
require('controllers/main/admin/highAvailability/nameNode/step9_controller');
require('controllers/main/admin/highAvailability/nameNode/rollbackHA/step1_controller');
require('controllers/main/admin/highAvailability/nameNode/rollbackHA/step2_controller');
require('controllers/main/admin/highAvailability/nameNode/rollbackHA/step3_controller');
require('controllers/main/admin/highAvailability/nameNode/rollbackHA/rollback_wizard_controller');
require('controllers/main/admin/highAvailability/resourceManager/wizard_controller');
require('controllers/main/admin/highAvailability/resourceManager/step1_controller');
require('controllers/main/admin/highAvailability/resourceManager/step2_controller');
require('controllers/main/admin/highAvailability/resourceManager/step3_controller');
require('controllers/main/admin/highAvailability/resourceManager/step4_controller');
require('controllers/main/admin/repositories');
require('controllers/main/admin/stack_upgrade_controller');
require('controllers/main/admin/serviceAccounts_controller');
require('controllers/main/admin/advanced');
require('utils/polling');
require('controllers/main/admin/security');
require('controllers/main/admin/security/security_progress_controller');
require('controllers/main/admin/security/disable');
require('controllers/main/admin/security/add/addSecurity_controller');
require('controllers/main/admin/security/add/step1');
require('controllers/main/admin/security/add/step2');
require('controllers/main/admin/security/add/step3');
require('controllers/main/admin/security/add/step4');
require('controllers/main/admin/authentication');
require('controllers/main/alerts_controller');
require('controllers/main/service');
require('controllers/main/service/item');
require('controllers/main/service/info/summary');
require('controllers/main/service/info/configs');
require('controllers/main/service/info/audit');
require('controllers/main/service/add_controller');
require('controllers/main/service/reassign_controller');
require('controllers/main/service/reassign/step1_controller');
require('controllers/main/service/reassign/step2_controller');
require('controllers/main/service/reassign/step3_controller');
require('controllers/main/service/reassign/step4_controller');
require('controllers/main/service/reassign/step5_controller');
require('controllers/main/service/reassign/step6_controller');
require('controllers/main/service/manage_config_groups_controller');
require('controllers/main/host');
require('controllers/main/host/details');
require('controllers/main/host/configs_service');
require('controllers/main/host/add_controller');
require('controllers/main/host/addHost/step4_controller');
require('controllers/main/charts');
require('controllers/main/charts/heatmap_metrics/heatmap_metric');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_processrun');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_diskspaceused');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_cpuWaitIO');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_memoryused');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_dfs');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_dfs_bytesread');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_dfs_byteswritten');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_dfs_gctime');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_dfs_memHeapUsed');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_mapreduce');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_mapreduce_gctime');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_mapreduce_mapsRunning');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_mapreduce_reducesRunning');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_mapreduce_memHeapUsed');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_yarn');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_yarn_gctime');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_yarn_memHeapUsed');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_yarn_ResourceUsed');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_hbase');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_hbase_readrequest');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_hbase_writerequest');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_hbase_compactionqueue');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_hbase_regions');
require('controllers/main/charts/heatmap_metrics/heatmap_metric_hbase_memstoresize');
require('controllers/main/charts/heatmap');
require('controllers/main/apps_controller');
require('controllers/main/apps/item_controller');
require('controllers/main/mirroring_controller');
require('controllers/main/mirroring/edit_dataset_controller');
require('controllers/main/mirroring/datasets_controller');
require('controllers/main/mirroring/jobs_controller');
require('controllers/main/mirroring/manage_clusters_controller');
require('controllers/main/views_controller');
require('controllers/main/views/details_controller');
require('controllers/wizard/slave_component_groups_controller');
require('controllers/wizard/step0_controller');
require('controllers/wizard/step1_controller');
require('controllers/wizard/step2_controller');
require('controllers/wizard/step3_controller');
require('controllers/wizard/step4_controller');
require('controllers/wizard/step5_controller');
require('controllers/wizard/step6_controller');
require('controllers/wizard/step7_controller');
require('controllers/wizard/step8_controller');
require('controllers/wizard/step9_controller');
require('controllers/wizard/step10_controller');
require('controllers/wizard/stack_upgrade/step1_controller');
require('controllers/wizard/stack_upgrade/step2_controller');
require('controllers/wizard/stack_upgrade/step3_controller');
require('controllers/global/cluster_controller');
require('controllers/global/update_controller');
require('controllers/global/configuration_controller');


text:
#include "bgp/evpn/evpn_route.h"

#include <algorithm>
#include <sstream>

#include "base/string_util.h"
#include "bgp/bgp_server.h"
#include "bgp/evpn/evpn_table.h"

using std::copy;
using std::string;
using std::vector;

const EvpnPrefix EvpnPrefix::kNullPrefix;

const uint32_t EvpnPrefix::kInvalidLabel = 0x00100000;
const uint32_t EvpnPrefix::kNullTag = 0;
const uint32_t EvpnPrefix::kMaxTag = 0xFFFFFFFF;
const uint32_t EvpnPrefix::kMaxVni = 0x00FFFFFF;

const size_t EvpnPrefix::kRdSize = RouteDistinguisher::kSize;
const size_t EvpnPrefix::kEsiSize = EthernetSegmentId::kSize;
const size_t EvpnPrefix::kTagSize = 4;
const size_t EvpnPrefix::kIp4AddrSize = 4;
const size_t EvpnPrefix::kIp6AddrSize = 16;
const size_t EvpnPrefix::kMacSize = MacAddress::size();
const size_t EvpnPrefix::kLabelSize = BgpProtoPrefix::kLabelSize;

const size_t EvpnPrefix::kMinAutoDiscoveryRouteSize =
    kRdSize + kEsiSize + kTagSize;
const size_t EvpnPrefix::kMinMacAdvertisementRouteSize =
    kRdSize + kEsiSize + kTagSize + 1 + kMacSize + 1;
const size_t EvpnPrefix::kMinInclusiveMulticastRouteSize =
    kRdSize + kTagSize + 1;
const size_t EvpnPrefix::kMinSelectiveMulticastRouteSize =
    kRdSize + kTagSize + 3;
const size_t EvpnPrefix::kMinSegmentRouteSize =
    kRdSize + kEsiSize + 1;
const size_t EvpnPrefix::kMinInetPrefixRouteSize =
    kRdSize + kEsiSize + kTagSize + 1 + 2 * kIp4AddrSize;
const size_t EvpnPrefix::kMinInet6PrefixRouteSize =
    kRdSize + kEsiSize + kTagSize + 1 + 2 * kIp6AddrSize;

//
// Read label from the BgpProtoPrefix.
// If the encapsulation is VXLAN and ethernet tag is non-zero use that as
// the label for backward compatibility with older JUNOS code.
//
// Note that Ethernet AD Routes per ESI always set ethernet tag to kMaxTag
// and their label is supposed to be set to 0 on write and ignored on read.
//
static uint32_t ReadLabel(const BgpProtoPrefix &proto_prefix,
    const BgpAttr *attr, size_t offset, uint32_t tag = EvpnPrefix::kNullTag) {
    if (!attr)
        return 0;
    const ExtCommunity *extcomm = attr->ext_community();
    if (extcomm && extcomm->ContainsTunnelEncapVxlan()) {
        if (tag) {
            if (tag == EvpnPrefix::kMaxTag) {
                return 0;
            } else if (tag <= EvpnPrefix::kMaxVni) {
                return tag;
            } else {
                return proto_prefix.ReadLabel(offset, true);
            }
        } else {
            return proto_prefix.ReadLabel(offset, true);
        }
    } else {
        return proto_prefix.ReadLabel(offset, false);
    }
}

//
// Write label to the BgpProtoPrefix.
//
static void WriteLabel(BgpProtoPrefix *proto_prefix,
    const BgpAttr *attr, size_t offset, uint32_t label) {
    const ExtCommunity *extcomm = attr ? attr->ext_community() : NULL;
    if (extcomm && extcomm->ContainsTunnelEncapVxlan()) {
        proto_prefix->WriteLabel(offset, label, true);
    } else {
        proto_prefix->WriteLabel(offset, label, false);
    }
}

//
// Read gateway address from the BgpProtoPrefix.
//
static IpAddress ReadGwAddress(const BgpProtoPrefix &proto_prefix,
    size_t gw_offset, size_t ip_size) {
    assert(ip_size == EvpnPrefix::kIp4AddrSize ||
        ip_size == EvpnPrefix::kIp6AddrSize);
    if (ip_size == EvpnPrefix::kIp4AddrSize) {
        Ip4Address::bytes_type bytes;
        copy(proto_prefix.prefix.begin() + gw_offset,
            proto_prefix.prefix.begin() + gw_offset + ip_size, bytes.begin());
        return Ip4Address(bytes);
    } else {
        Ip6Address::bytes_type bytes;
        copy(proto_prefix.prefix.begin() + gw_offset,
            proto_prefix.prefix.begin() + gw_offset + ip_size, bytes.begin());
        return Ip6Address(bytes);
    }
    return IpAddress();
}

EvpnPrefix::EvpnPrefix()
    : type_(Unspecified),
      tag_(EvpnPrefix::kNullTag),
      family_(Address::UNSPEC),
      ip_prefixlen_(0) {
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd,
    const EthernetSegmentId &esi, uint32_t tag)
    : type_(AutoDiscoveryRoute),
      rd_(rd),
      esi_(esi),
      tag_(tag),
      family_(Address::UNSPEC),
      ip_prefixlen_(0) {
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd,
    const MacAddress &mac_addr, const IpAddress &ip_address)
    : type_(MacAdvertisementRoute),
      rd_(rd),
      tag_(EvpnPrefix::kNullTag),
      mac_addr_(mac_addr),
      family_(Address::UNSPEC),
      ip_address_(ip_address),
      ip_prefixlen_(0) {
    if (ip_address_.is_v4() && !ip_address_.is_unspecified()) {
        family_ = Address::INET;
    } else if (ip_address_.is_v6() && !ip_address_.is_unspecified()) {
        family_ = Address::INET6;
    }
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd, uint32_t tag,
    const MacAddress &mac_addr, const IpAddress &ip_address)
    : type_(MacAdvertisementRoute), rd_(rd), tag_(tag),
      mac_addr_(mac_addr), family_(Address::UNSPEC),
      ip_address_(ip_address), ip_prefixlen_(0) {
    if (ip_address_.is_v4() && !ip_address_.is_unspecified()) {
        family_ = Address::INET;
    } else if (ip_address_.is_v6() && !ip_address_.is_unspecified()) {
        family_ = Address::INET6;
    }
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd, uint32_t tag,
    const IpAddress &ip_address)
    : type_(InclusiveMulticastRoute),
      rd_(rd),
      tag_(tag),
      family_(Address::UNSPEC),
      ip_address_(ip_address),
      ip_prefixlen_(0) {
    if (ip_address_.is_v4() && !ip_address_.is_unspecified()) {
        family_ = Address::INET;
    } else if (ip_address_.is_v6() && !ip_address_.is_unspecified()) {
        family_ = Address::INET6;
    }
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd,
    const EthernetSegmentId &esi, const IpAddress &ip_address)
    : type_(SegmentRoute),
      rd_(rd),
      esi_(esi),
      tag_(EvpnPrefix::kNullTag),
      family_(Address::UNSPEC),
      ip_address_(ip_address),
      ip_prefixlen_(0) {
    if (ip_address_.is_v4() && !ip_address_.is_unspecified()) {
        family_ = Address::INET;
    } else if (ip_address_.is_v6() && !ip_address_.is_unspecified()) {
        family_ = Address::INET6;
    }
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd, uint32_t tag,
    const IpAddress &ip_address, uint8_t ip_prefixlen)
    : type_(IpPrefixRoute),
      rd_(rd),
      tag_(tag),
      family_(Address::UNSPEC),
      ip_address_(ip_address),
      ip_prefixlen_(ip_prefixlen) {
    assert(ip_address_.is_v4() || ip_address_.is_v6());
    if (ip_address_.is_v4()) {
        family_ = Address::INET;
    } else if (ip_address_.is_v6()) {
        family_ = Address::INET6;
    }
}

EvpnPrefix::EvpnPrefix(const RouteDistinguisher &rd, uint32_t tag,
    const IpAddress &source, const IpAddress &group,
    const IpAddress &ip_address)
    : type_(SelectiveMulticastRoute),
      rd_(rd),
      tag_(tag),
      family_(Address::UNSPEC),
      ip_address_(ip_address),
      source_(source),
      group_(group),
      ip_prefixlen_(0), flags_(0x2) {
    if (ip_address_.is_v4() && !ip_address_.is_unspecified()) {
        family_ = Address::INET;
    } else if (ip_address_.is_v6() && !ip_address_.is_unspecified()) {
        family_ = Address::INET6;
    }
    string ip = group.to_v4().to_string();
    char *str = const_cast<char *>(ip.c_str());
    char * mac_ip = strstr(str, ".");
    std::ostringstream oss;
    oss << "01:00:5e:" << strtok(mac_ip, ".");
    oss << ":" << strtok(NULL, ".");
    oss << ":" << strtok(NULL, "");
    mac_addr_ = MacAddress::FromString(oss.str(), NULL);
}

int EvpnPrefix::FromProtoPrefix(BgpServer *server,
    const BgpProtoPrefix &proto_prefix, const BgpAttr *attr,
    const Address::Family family, EvpnPrefix *prefix, BgpAttrPtr *new_attr,
    uint32_t *label, uint32_t *l3_label) {
    *new_attr = attr;
    *label = 0;
    if (l3_label)
        *l3_label = 0;
    prefix->type_ = proto_prefix.type;
    size_t nlri_size = proto_prefix.prefix.size();

    switch (prefix->type_) {
    case AutoDiscoveryRoute: {
        size_t expected_min_nlri_size =
            kMinAutoDiscoveryRouteSize + (attr ? kLabelSize : 0);
        if (nlri_size < expected_min_nlri_size)
            return -1;
        size_t rd_offset = 0;
        prefix->rd_ = RouteDistinguisher(&proto_prefix.prefix[rd_offset]);
        size_t esi_offset = rd_offset + kRdSize;
        prefix->esi_ = EthernetSegmentId(&proto_prefix.prefix[esi_offset]);
        size_t tag_offset = esi_offset + kEsiSize;
        prefix->tag_ = get_value(&proto_prefix.prefix[tag_offset], kTagSize);
        size_t label_offset = tag_offset + kTagSize;
        *label = ReadLabel(proto_prefix, attr, label_offset, prefix->tag_);
        break;
    }
    case MacAdvertisementRoute: {
        size_t expected_min_nlri_size =
            kMinMacAdvertisementRouteSize + (attr ? kLabelSize : 0);
        if (nlri_size < expected_min_nlri_size)
            return -1;
        size_t rd_offset = 0;
        prefix->rd_ = RouteDistinguisher(&proto_prefix.prefix[rd_offset]);
        size_t esi_offset = rd_offset + kRdSize;
        if (attr) {
            EthernetSegmentId esi(&proto_prefix.prefix[esi_offset]);
            *new_attr = server->attr_db()->ReplaceEsiAndLocate(attr, esi);
        }
        size_t tag_offset = esi_offset + kEsiSize;
        prefix->tag_ = get_value(&proto_prefix.prefix[tag_offset], kTagSize);
        size_t mac_len_offset = tag_offset + kTagSize;
        size_t mac_len = proto_prefix.prefix[mac_len_offset];
        if (mac_len != 48)
            return -1;
        size_t mac_offset = mac_len_offset + 1;
        prefix->mac_addr_ = MacAddress(&proto_prefix.prefix[mac_offset]);
        size_t ip_len_offset = mac_offset + kMacSize;
        size_t ip_len = proto_prefix.prefix[ip_len_offset];
        if (ip_len != 0 && ip_len != 32 && ip_len != 128)
            return -1;
        size_t ip_size = ip_len / 8;
        if (nlri_size < expected_min_nlri_size + ip_size)
            return -1;
        size_t ip_offset = ip_len_offset + 1;
        prefix->ReadIpAddress(proto_prefix, ip_offset, ip_size, ip_size);
        size_t label_offset = ip_offset + ip_size;
        *label = ReadLabel(proto_prefix, attr, label_offset, prefix->tag_);
        size_t l3_label_offset = label_offset + kLabelSize;
        if (l3_label && nlri_size >= l3_label_offset + kLabelSize) {
            *l3_label = ReadLabel(proto_prefix, attr, l3_label_offset);
        }
        break;
    }
    case InclusiveMulticastRoute: {
        if (nlri_size < kMinInclusiveMulticastRouteSize)
            return -1;
        size_t rd_offset = 0;
        prefix->rd_ = RouteDistinguisher(&proto_prefix.prefix[rd_offset]);
        size_t tag_offset = rd_offset + kRdSize;
        prefix->tag_ = get_value(&proto_prefix.prefix[tag_offset], kTagSize);
        size_t ip_len_offset = tag_offset + kTagSize;
        size_t ip_len = proto_prefix.prefix[ip_len_offset];
        if (ip_len != 32 && ip_len != 128)
            return -1;
        size_t ip_size = ip_len / 8;
        if (nlri_size < kMinInclusiveMulticastRouteSize + ip_size)
            return -1;
        size_t ip_offset = ip_len_offset + 1;
        prefix->ReadIpAddress(proto_prefix, ip_offset, ip_size, ip_size);
        const PmsiTunnel *pmsi_tunnel = attr ? attr->pmsi_tunnel() : NULL;
        if (pmsi_tunnel &&
            (pmsi_tunnel->tunnel_type() == PmsiTunnelSpec::IngressReplication ||
             pmsi_tunnel->tunnel_type() ==
             PmsiTunnelSpec::AssistedReplicationContrail)) {
            const ExtCommunity *extcomm = attr ? attr->ext_community() : NULL;
            if (extcomm && extcomm->ContainsTunnelEncapVxlan()) {
                if (prefix->tag_ && prefix->tag_ <= kMaxVni) {
                    *label = prefix->tag_;
                } else {
                    *label = pmsi_tunnel->GetLabel(extcomm);
                }
            } else {
                *label = pmsi_tunnel->GetLabel(extcomm);
            }
        }
        break;
    }
    case SegmentRoute: {
        if (nlri_size < kMinSegmentRouteSize)
            return -1;
        size_t rd_offset = 0;
        prefix->rd_ = RouteDistinguisher(&proto_prefix.prefix[rd_offset]);
        size_t esi_offset = rd_offset + kRdSize;
        prefix->esi_ = EthernetSegmentId(&proto_prefix.prefix[esi_offset]);
        size_t ip_len_offset = esi_offset + kEsiSize;
        size_t ip_len = proto_prefix.prefix[ip_len_offset];
        if (ip_len != 32 && ip_len != 128)
            return -1;
        size_t ip_size = ip_len / 8;
        if (nlri_size < kMinSegmentRouteSize + ip_size)
            return -1;
        size_t ip_offset = ip_len_offset + 1;
        prefix->ReadIpAddress(proto_prefix, ip_offset, ip_size, ip_size);
        break;
    }
    case IpPrefixRoute: {
        size_t ip_size;
        if (attr) {
            if (nlri_size == kMinInet6PrefixRouteSize + kLabelSize) {
                ip_size = kIp6AddrSize;
            } else if (nlri_size == kMinInetPrefixRouteSize + kLabelSize) {
                ip_size = kIp4AddrSize;
            } else {
                return -1;
            }
        } else {
            if (nlri_size == kMinInet6PrefixRouteSize ||
                nlri_size == kMinInet6PrefixRouteSize + kLabelSize) {
                ip_size = kIp6AddrSize;
            } else if (nlri_size == kMinInetPrefixRouteSize ||
                nlri_size == kMinInetPrefixRouteSize + kLabelSize) {
                ip_size = kIp4AddrSize;
            } else {
                return -1;
            }
        }

        size_t rd_offset = 0;
        prefix->rd_ = RouteDistinguisher(&proto_prefix.prefix[rd_offset]);
        size_t esi_offset = rd_offset + kRdSize;
        EthernetSegmentId esi(&proto_prefix.prefix[esi_offset]);
        if (!esi.IsZero())
            return -1;
        size_t tag_offset = esi_offset + kEsiSize;
        prefix->tag_ = get_value(&proto_prefix.prefix[tag_offset], kTagSize);
        size_t ip_plen_offset = tag_offset + kTagSize;
        prefix->ip_prefixlen_ = proto_prefix.prefix[ip_plen_offset];
        if (ip_size == kIp4AddrSize && prefix->ip_prefixlen_ > 32)
            return -1;
        if (ip_size == kIp6AddrSize && prefix->ip_prefixlen_ > 128)
            return -1;
        size_t ip_offset = ip_plen_offset + 1;
        size_t ip_psize = (prefix->ip_prefixlen_ + 7) / 8;
        prefix->ReadIpAddress(proto_prefix, ip_offset, ip_size, ip_psize);
        size_t gw_offset = ip_offset + ip_size;
        IpAddress gw_address = ReadGwAddress(proto_prefix, gw_offset, ip_size);
        if (!gw_address.is_unspecified())
            return -1;
        size_t label_offset = gw_offset + ip_size;
        *label = ReadLabel(proto_prefix, attr, label_offset);
        break;
    }
    case SelectiveMulticastRoute: {
        if (nlri_size < kMinSelectiveMulticastRouteSize)
            return -1;
        size_t rd_offset = 0;
        prefix->rd_ = RouteDistinguisher(&proto_prefix.prefix[rd_offset]);
        size_t tag_offset = rd_offset + kRdSize;
        prefix->tag_ = get_value(&proto_prefix.prefix[tag_offset], kTagSize);
        size_t src_len_offset = tag_offset + kTagSize;
        size_t src_len = proto_prefix.prefix[src_len_offset];
        if (src_len != 32 && src_len != 128)
            return -1;
        size_t src_size = src_len / 8;
        size_t src_offset = src_len_offset + 1;
        if (nlri_size < src_offset + src_size)
            return -1;
        prefix->ReadSource(proto_prefix, src_offset, src_size, src_size);
        size_t grp_len_offset = src_offset + src_size;
        size_t grp_len = proto_prefix.prefix[grp_len_offset];
        if (grp_len != 32 && grp_len != 128)
            return -1;
        size_t grp_size = grp_len / 8;
        size_t grp_offset = grp_len_offset + 1;
        if (nlri_size < grp_offset + grp_size)
            return -1;
        prefix->ReadGroup(proto_prefix, grp_offset, grp_size, grp_size);
        size_t ip_len_offset = grp_offset + grp_size;
        size_t ip_len = proto_prefix.prefix[ip_len_offset];
        if (ip_len != 32 && ip_len != 128)
            return -1;
        size_t ip_size = ip_len / 8;
        size_t ip_offset = ip_len_offset + 1;
        if (nlri_size < ip_offset + ip_size)
            return -1;
        prefix->ReadIpAddress(proto_prefix, ip_offset, ip_size, ip_size);
        size_t flag_offset = ip_offset + ip_size;
        if (nlri_size <= flag_offset + 4)
            prefix->flags_ = get_value(&proto_prefix.prefix[flag_offset], 4);
        break;
    }
    default: {
        return -1;
        break;
    }
    }
    return 0;
}

//
// Build the BgpProtoPrefix for this EvpnPrefix.
//
// The ESI for MacAdvertisementRoute is not part of the key and hence
// must be obtained from the BgpAttr. The BgpAttr is NULL and label is
// 0 when withdrawing the route.
//
void EvpnPrefix::BuildProtoPrefix(BgpProtoPrefix *proto_prefix,
    const BgpAttr *attr, uint32_t label, uint32_t l3_label) const {
    proto_prefix->type = type_;
    proto_prefix->prefix.clear();

    switch (type_) {
    case AutoDiscoveryRoute: {
        size_t nlri_size = kMinAutoDiscoveryRouteSize + kLabelSize;
        proto_prefix->prefixlen = nlri_size * 8;
        proto_prefix->prefix.resize(nlri_size, 0);

        size_t rd_offset = 0;
        copy(rd_.GetData(), rd_.GetData() + kRdSize,
            proto_prefix->prefix.begin() + rd_offset);
        size_t esi_offset = rd_offset + kRdSize;
        copy(esi_.GetData(), esi_.GetData() + kEsiSize,
            proto_prefix->prefix.begin() + esi_offset);
        size_t tag_offset = esi_offset + kEsiSize;
        put_value(&proto_prefix->prefix[tag_offset], kTagSize, tag_);
        size_t label_offset = tag_offset + kTagSize;
        WriteLabel(proto_prefix, attr, label_offset, label);
        break;
    }
    case MacAdvertisementRoute: {
        size_t ip_size = GetIpAddressSize();
        size_t nlri_size = kMinMacAdvertisementRouteSize + ip_size + kLabelSize;
        if (l3_label)
            nlri_size += kLabelSize;
        proto_prefix->prefixlen = nlri_size * 8;
        proto_prefix->prefix.resize(nlri_size, 0);

        size_t rd_offset = 0;
        copy(rd_.GetData(), rd_.GetData() + kRdSize,
            proto_prefix->prefix.begin() + rd_offset);
        size_t esi_offset = rd_offset + kRdSize;
        if (attr) {
            copy(attr->esi().GetData(), attr->esi().GetData() + kEsiSize,
                proto_prefix->prefix.begin() + esi_offset);
        }
        size_t tag_offset = esi_offset + kEsiSize;
        put_value(&proto_prefix->prefix[tag_offset], kTagSize, tag_);
        size_t mac_len_offset = tag_offset + kTagSize;
        proto_prefix->prefix[mac_len_offset] = 48;
        size_t mac_offset = mac_len_offset + 1;
        copy(mac_addr_.GetData(), mac_addr_.GetData() + kMacSize,
            proto_prefix->prefix.begin() + mac_offset);
        size_t ip_len_offset = mac_offset + kMacSize;
        proto_prefix->prefix[ip_len_offset] = ip_size * 8;
        size_t ip_offset = ip_len_offset + 1;
        WriteIpAddress(proto_prefix, ip_offset);
        size_t label_offset = ip_offset + ip_size;
        WriteLabel(proto_prefix, attr, label_offset, label);
        if (l3_label) {
            size_t l3_label_offset = label_offset + kLabelSize;
            WriteLabel(proto_prefix, attr, l3_label_offset, l3_label);
        }
        break;
    }
    case InclusiveMulticastRoute: {
        size_t ip_size = GetIpAddressSize();
        size_t nlri_size = kMinInclusiveMulticastRouteSize + ip_size;
        proto_prefix->prefixlen = nlri_size * 8;
        proto_prefix->prefix.resize(nlri_size, 0);

        size_t rd_offset = 0;
        copy(rd_.GetData(), rd_.GetData() + kRdSize,
            proto_prefix->prefix.begin() + rd_offset);
        size_t tag_offset = rd_offset + kRdSize;
        put_value(&proto_prefix->prefix[tag_offset], kTagSize, tag_);
        size_t ip_len_offset = tag_offset + kTagSize;
        proto_prefix->prefix[ip_len_offset] = ip_size * 8;
        size_t ip_offset = ip_len_offset + 1;
        WriteIpAddress(proto_prefix, ip_offset);
        break;
    }
    case SegmentRoute: {
        size_t ip_size = GetIpAddressSize();
        size_t nlri_size = kMinSegmentRouteSize + ip_size;
        proto_prefix->prefixlen = nlri_size * 8;
        proto_prefix->prefix.resize(nlri_size, 0);

        size_t rd_offset = 0;
        copy(rd_.GetData(), rd_.GetData() + kRdSize,
            proto_prefix->prefix.begin() + rd_offset);
        size_t esi_offset = rd_offset + kRdSize;
        copy(esi_.GetData(), esi_.GetData() + kEsiSize,
            proto_prefix->prefix.begin() + esi_offset);
        size_t ip_len_offset = esi_offset + kEsiSize;
        proto_prefix->prefix[ip_len_offset] = ip_size * 8;
        size_t ip_offset = ip_len_offset + 1;
        WriteIpAddress(proto_prefix, ip_offset);
        break;
    }
    case IpPrefixRoute: {
        size_t ip_size, nlri_size;
        if (family_ == Address::INET) {
            ip_size = kIp4AddrSize;
            nlri_size = kMinInetPrefixRouteSize + kLabelSize;
        } else {
            ip_size = kIp6AddrSize;
            nlri_size = kMinInet6PrefixRouteSize + kLabelSize;
        }
        proto_prefix->prefixlen = nlri_size * 8;
        proto_prefix->prefix.resize(nlri_size, 0);

        size_t rd_offset = 0;
        copy(rd_.GetData(), rd_.GetData() + kRdSize,
            proto_prefix->prefix.begin() + rd_offset);
        size_t esi_offset = rd_offset + kRdSize;
        if (attr) {
            copy(attr->esi().GetData(), attr->esi().GetData() + kEsiSize,
                proto_prefix->prefix.begin() + esi_offset);
        }
        size_t tag_offset = esi_offset + kEsiSize;
        put_value(&proto_prefix->prefix[tag_offset], kTagSize, tag_);
        size_t ip_plen_offset = tag_offset + kTagSize;
        proto_prefix->prefix[ip_plen_offset] = ip_prefixlen_;
        size_t ip_offset = ip_plen_offset + 1;
        WriteIpAddress(proto_prefix, ip_offset);
        size_t gw_offset = ip_offset + ip_size;
        size_t label_offset = gw_offset + ip_size;
        WriteLabel(proto_prefix, attr, label_offset, label);
        break;
    }
    case SelectiveMulticastRoute: {
        size_t ip_size = GetIpAddressSize();
        size_t nlri_size = kMinSelectiveMulticastRouteSize + 3 * ip_size + 1;
        proto_prefix->prefixlen = nlri_size * 8;
        proto_prefix->prefix.resize(nlri_size, 0);

        size_t rd_offset = 0;
        copy(rd_.GetData(), rd_.GetData() + kRdSize,
            proto_prefix->prefix.begin() + rd_offset);
        size_t tag_offset = rd_offset + kRdSize;
        put_value(&proto_prefix->prefix[tag_offset], kTagSize, tag_);
        size_t src_len_offset = tag_offset + kTagSize;
        proto_prefix->prefix[src_len_offset] = ip_size * 8;
        size_t src_offset = src_len_offset + 1;
        WriteSource(proto_prefix, src_offset);
        size_t grp_len_offset = src_offset + ip_size;
        proto_prefix->prefix[grp_len_offset] = ip_size * 8;
        size_t grp_offset = grp_len_offset + 1;
        WriteGroup(proto_prefix, grp_offset);
        size_t ip_len_offset = grp_offset + ip_size;
        proto_prefix->prefix[ip_len_offset] = ip_size * 8;
        size_t ip_offset = ip_len_offset + 1;
        WriteIpAddress(proto_prefix, ip_offset);
        size_t flag_offset = ip_offset + ip_size;
        put_value(&proto_prefix->prefix[flag_offset], 1, flags_);
        break;
    }
    default: {
        assert(false);
        break;
    }
    }
}

int EvpnPrefix::CompareTo(const EvpnPrefix &rhs) const {
    KEY_COMPARE(type_, rhs.type_);

    switch (type_) {
    case AutoDiscoveryRoute:
        KEY_COMPARE(rd_, rhs.rd_);
        KEY_COMPARE(esi_, rhs.esi_);
        KEY_COMPARE(tag_, rhs.tag_);
        break;
    case MacAdvertisementRoute:
        KEY_COMPARE(rd_, rhs.rd_);
        KEY_COMPARE(tag_, rhs.tag_);
        KEY_COMPARE(mac_addr_, rhs.mac_addr_);
        KEY_COMPARE(ip_address_, rhs.ip_address_);
        break;
    case InclusiveMulticastRoute:
        KEY_COMPARE(rd_, rhs.rd_);
        KEY_COMPARE(tag_, rhs.tag_);
        KEY_COMPARE(ip_address_, rhs.ip_address_);
        break;
    case SegmentRoute:
        KEY_COMPARE(rd_, rhs.rd_);
        KEY_COMPARE(esi_, rhs.esi_);
        KEY_COMPARE(ip_address_, rhs.ip_address_);
        break;
    case IpPrefixRoute:
        KEY_COMPARE(rd_, rhs.rd_);
        KEY_COMPARE(tag_, rhs.tag_);
        KEY_COMPARE(ip_address_, rhs.ip_address_);
        KEY_COMPARE(ip_prefixlen_, rhs.ip_prefixlen_);
        break;
    case SelectiveMulticastRoute:
        KEY_COMPARE(rd_, rhs.rd_);
        KEY_COMPARE(tag_, rhs.tag_);
        KEY_COMPARE(source_, rhs.source_);
        KEY_COMPARE(group_, rhs.group_);
        KEY_COMPARE(ip_address_, rhs.ip_address_);
    default:
        break;
    }

    return 0;
}

bool EvpnPrefix::GetSourceFromString(EvpnPrefix *prefix, const string &str,
        size_t pos1, size_t *pos2, boost::system::error_code *errorp) {
    *pos2 = str.find('-', pos1 + 1);
    if (*pos2 == string::npos) {
        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return false;
    }
    string temp_str = str.substr(pos1 + 1, *pos2 - pos1 - 1);
    boost::system::error_code source_err;
    prefix->source_ = Ip4Address::from_string(temp_str, source_err);
    if (source_err != 0) {
        if (errorp != NULL) {
            *errorp = source_err;
        }
        return false;
    }
    return true;
}

bool EvpnPrefix::GetGroupFromString(EvpnPrefix *prefix, const string &str,
        size_t pos1, size_t *pos2, boost::system::error_code *errorp) {
    *pos2 = str.find('-', pos1 + 1);
    if (*pos2 == string::npos) {
        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return false;
    }
    string temp_str = str.substr(pos1 + 1, *pos2 - pos1 - 1);
    boost::system::error_code group_err;
    prefix->group_ = Ip4Address::from_string(temp_str, group_err);
    if (group_err != 0) {
        if (errorp != NULL) {
            *errorp = group_err;
        }
        return false;
    }
    return true;
}

EvpnPrefix EvpnPrefix::FromString(const string &str,
    boost::system::error_code *errorp) {
    EvpnPrefix prefix;

    // Parse type.
    size_t pos1 = str.find('-');
    if (pos1 == string::npos) {
        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return EvpnPrefix::kNullPrefix;
    }

    string type_str = str.substr(0, pos1);
    bool ret = stringToInteger(type_str, prefix.type_);
    if (!ret) {
        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return EvpnPrefix::kNullPrefix;
    }

    if (prefix.type_ < EvpnPrefix::AutoDiscoveryRoute ||
        prefix.type_ > EvpnPrefix::SelectiveMulticastRoute) {
        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return EvpnPrefix::kNullPrefix;
    }

    // Parse RD.
    size_t pos2 = str.find('-', pos1 + 1);
    if (pos2 == string::npos) {
        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return EvpnPrefix::kNullPrefix;
    }
    string rd_str = str.substr(pos1 + 1, pos2 - pos1 - 1);
    boost::system::error_code rd_err;
    prefix.rd_ = RouteDistinguisher::FromString(rd_str, &rd_err);
    if (rd_err != 0) {
        if (errorp != NULL) {
            *errorp = rd_err;
        }
        return EvpnPrefix::kNullPrefix;
    }

    switch (prefix.type_) {
    case AutoDiscoveryRoute: {
        // Parse ESI.
        size_t pos3 = str.find('-', pos2 + 1);
        if (pos3 == string::npos) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }
        string esi_str = str.substr(pos2 + 1, pos3 - pos2 - 1);
        boost::system::error_code esi_err;
        prefix.esi_ = EthernetSegmentId::FromString(esi_str, &esi_err);
        if (esi_err != 0) {
            if (errorp != NULL) {
                *errorp = esi_err;
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Parse tag.
        string tag_str = str.substr(pos3 + 1, string::npos);
        bool ret = stringToInteger(tag_str, prefix.tag_);
        if (!ret) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }

        break;
    }

    case MacAdvertisementRoute: {
        // Parse tag.
        size_t pos3 = str.find('-', pos2 + 1);
        if (pos3 == string::npos) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }
        string tag_str = str.substr(pos2 + 1, pos3 - pos2 - 1);
        bool ret = stringToInteger(tag_str, prefix.tag_);
        if (!ret) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Parse MAC.
        size_t pos4 = str.rfind(',');
        string mac_str = str.substr(pos3 + 1, pos4 - pos3 -1);
        boost::system::error_code mac_err;
        prefix.mac_addr_ = MacAddress::FromString(mac_str, &mac_err);
        if (mac_err != 0) {
            if (errorp != NULL) {
                *errorp = mac_err;
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Parse IP - treat all 0s as unspecified.
        string ip_str = str.substr(pos4 + 1, string::npos);
        boost::system::error_code ip_err;
        prefix.ip_address_ = IpAddress::from_string(ip_str, ip_err);
        if (ip_err != 0) {
            if (errorp != NULL) {
                *errorp = ip_err;
            }
            return EvpnPrefix::kNullPrefix;
        }
        if (prefix.ip_address_.is_v4() && !prefix.ip_address_.is_unspecified())
            prefix.family_ = Address::INET;
        if (prefix.ip_address_.is_v6() && !prefix.ip_address_.is_unspecified())
            prefix.family_ = Address::INET6;

        break;
    }

    case InclusiveMulticastRoute: {
        // Parse tag.
        size_t pos3 = str.find('-', pos2 + 1);
        if (pos3 == string::npos) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }
        string tag_str = str.substr(pos2 + 1, pos3 - pos2 - 1);
        bool ret = stringToInteger(tag_str, prefix.tag_);
        if (!ret) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Parse IP.
        string ip_str = str.substr(pos3 + 1, string::npos);
        boost::system::error_code ip_err;
        prefix.ip_address_ = IpAddress::from_string(ip_str, ip_err);
        if (ip_err != 0) {
            if (errorp != NULL) {
                *errorp = ip_err;
            }
            return EvpnPrefix::kNullPrefix;
        }
        prefix.family_ =
            prefix.ip_address_.is_v4() ? Address::INET : Address::INET6;

        break;
    }

    case SegmentRoute: {
        // Parse ESI.
        size_t pos3 = str.find('-', pos2 + 1);
        if (pos3 == string::npos) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }
        string esi_str = str.substr(pos2 + 1, pos3 - pos2 - 1);
        boost::system::error_code esi_err;
        prefix.esi_ = EthernetSegmentId::FromString(esi_str, &esi_err);
        if (esi_err != 0) {
            if (errorp != NULL) {
                *errorp = esi_err;
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Parse IP.
        string ip_str = str.substr(pos3 + 1, string::npos);
        boost::system::error_code ip_err;
        prefix.ip_address_ = IpAddress::from_string(ip_str, ip_err);
        if (ip_err != 0) {
            if (errorp != NULL) {
                *errorp = ip_err;
            }
            return EvpnPrefix::kNullPrefix;
        }
        prefix.family_ =
            prefix.ip_address_.is_v4() ? Address::INET : Address::INET6;

        break;
    }

    case IpPrefixRoute: {
        // Parse tag.
        size_t pos3 = str.find('-', pos2 + 1);
        if (pos3 == string::npos) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }
        string tag_str = str.substr(pos2 + 1, pos3 - pos2 - 1);
        bool ret = stringToInteger(tag_str, prefix.tag_);
        if (!ret) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Parse IP prefix - first try v4, then v6.
        string ip_str = str.substr(pos3 + 1, string::npos);
        boost::system::error_code ip_err;

        Ip4Prefix inet_prefix = Ip4Prefix::FromString(ip_str, &ip_err);
        if (ip_err == 0) {
            prefix.family_ = Address::INET;
            prefix.ip_address_ = inet_prefix.addr();
            prefix.ip_prefixlen_ = inet_prefix.prefixlen();
            return prefix;
        }

        Inet6Prefix inet6_prefix = Inet6Prefix::FromString(ip_str, &ip_err);
        if (ip_err == 0) {
            prefix.family_ = Address::INET6;
            prefix.ip_address_ = inet6_prefix.addr();
            prefix.ip_prefixlen_ = inet6_prefix.prefixlen();
            return prefix;
        }

        if (errorp != NULL) {
            *errorp = make_error_code(boost::system::errc::invalid_argument);
        }
        return EvpnPrefix::kNullPrefix;
        break;
    }

    case SelectiveMulticastRoute: {
        // Parse tag.
        size_t pos3 = str.find('-', pos2 + 1);
        if (pos3 == string::npos) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }
        string tag_str = str.substr(pos2 + 1, pos3 - pos2 - 1);
        bool ret = stringToInteger(tag_str, prefix.tag_);
        if (!ret) {
            if (errorp != NULL) {
                *errorp =
                    make_error_code(boost::system::errc::invalid_argument);
            }
            return EvpnPrefix::kNullPrefix;
        }

        // Look for source.
        size_t pos4;
        if (!GetSourceFromString(&prefix, str, pos3, &pos4, errorp))
            return EvpnPrefix::kNullPrefix;

        // Look for group.
        size_t pos5;
        if (!GetGroupFromString(&prefix, str, pos4, &pos5, errorp))
            return EvpnPrefix::kNullPrefix;

        // Parse IP.
        string ip_str = str.substr(pos5 + 1, string::npos);
        boost::system::error_code ip_err;
        prefix.ip_address_ = IpAddress::from_string(ip_str, ip_err);
        if (ip_err != 0) {
            if (errorp != NULL) {
                *errorp = ip_err;
            }
            return EvpnPrefix::kNullPrefix;
        }
        prefix.family_ =
            prefix.ip_address_.is_v4() ? Address::INET : Address::INET6;

        break;
    }

    }

    return prefix;
}

string EvpnPrefix::ToString() const {
    string str = integerToString(type_);
    str += "-" + rd_.ToString();
    switch (type_) {
    case AutoDiscoveryRoute:
        str += "-" + esi_.ToString();
        str += "-" + integerToString(tag_);
        break;
    case MacAdvertisementRoute:
        str += "-" + integerToString(tag_);
        str += "-" + mac_addr_.ToString();
        str += "," + ip_address_.to_string();
        break;
    case InclusiveMulticastRoute:
        str += "-" + integerToString(tag_);
        str += "-" + ip_address_.to_string();
        break;
    case SegmentRoute:
        str += "-" + esi_.ToString();
        str += "-" + ip_address_.to_string();
        break;
    case IpPrefixRoute:
        str += "-" + integerToString(tag_);
        if (family_ == Address::INET) {
            str += "-" + inet_prefix().ToString();
        } else {
            str += "-" + inet6_prefix().ToString();
        }
        break;
    case SelectiveMulticastRoute:
        str += "-" + integerToString(tag_);
        str += "-" + source_.to_string();
        str += "-" + group_.to_string();
        str += "-" + ip_address_.to_string();
        break;
    default:
        break;
    }

    return str;
}

string EvpnPrefix::ToXmppIdString() const {
    string str;
    if (tag_ != 0)
        str += integerToString(tag_) + "-";
    str += mac_addr_.ToString();
    str += "," + ip_address_.to_string() + "/" +
        integerToString(ip_address_length());
    return str;
}

uint8_t EvpnPrefix::ip_address_length() const {
    if (type_ == IpPrefixRoute)
        return ip_prefixlen_;
    if (family_ == Address::INET)
        return 32;
    if (family_ == Address::INET6)
        return 128;
    return 32;
}

size_t EvpnPrefix::GetIpAddressSize() const {
    if (family_ == Address::INET)
        return kIp4AddrSize;
    if (family_ == Address::INET6)
        return kIp6AddrSize;
    return 0;
}

void EvpnPrefix::ReadSource(const BgpProtoPrefix &proto_prefix,
    size_t ip_offset, size_t ip_size, size_t ip_psize) {
    assert(ip_psize <= ip_size);
    if (ip_size == 0) {
        family_ = Address::UNSPEC;
    } else if (ip_size == kIp4AddrSize) {
        family_ = Address::INET;
        Ip4Address::bytes_type bytes = { { 0 } };
        copy(proto_prefix.prefix.begin() + ip_offset,
            proto_prefix.prefix.begin() + ip_offset + ip_psize, bytes.begin());
        source_ = Ip4Address(bytes);
    } else if (ip_size == kIp6AddrSize) {
        family_ = Address::INET6;
        Ip6Address::bytes_type bytes = { { 0 } };
        copy(proto_prefix.prefix.begin() + ip_offset,
            proto_prefix.prefix.begin() + ip_offset + ip_psize, bytes.begin());
        source_ = Ip6Address(bytes);
    }
}

void EvpnPrefix::ReadGroup(const BgpProtoPrefix &proto_prefix,
    size_t ip_offset, size_t ip_size, size_t ip_psize) {
    assert(ip_psize <= ip_size);
    if (ip_size == 0) {
        family_ = Address::UNSPEC;
    } else if (ip_size == kIp4AddrSize) {
        family_ = Address::INET;
        Ip4Address::bytes_type bytes = { { 0 } };
        copy(proto_prefix.prefix.begin() + ip_offset,
            proto_prefix.prefix.begin() + ip_offset + ip_psize, bytes.begin());
        group_ = Ip4Address(bytes);
    } else if (ip_size == kIp6AddrSize) {
        family_ = Address::INET6;
        Ip6Address::bytes_type bytes = { { 0 } };
        copy(proto_prefix.prefix.begin() + ip_offset,
            proto_prefix.prefix.begin() + ip_offset + ip_psize, bytes.begin());
        group_ = Ip6Address(bytes);
    }
}

void EvpnPrefix::ReadIpAddress(const BgpProtoPrefix &proto_prefix,
    size_t ip_offset, size_t ip_size, size_t ip_psize) {
    assert(ip_psize <= ip_size);
    if (ip_size == 0) {
        family_ = Address::UNSPEC;
    } else if (ip_size == kIp4AddrSize) {
        family_ = Address::INET;
        Ip4Address::bytes_type bytes = { { 0 } };
        copy(proto_prefix.prefix.begin() + ip_offset,
            proto_prefix.prefix.begin() + ip_offset + ip_psize, bytes.begin());
        ip_address_ = Ip4Address(bytes);
    } else if (ip_size == kIp6AddrSize) {
        family_ = Address::INET6;
        Ip6Address::bytes_type bytes = { { 0 } };
        copy(proto_prefix.prefix.begin() + ip_offset,
            proto_prefix.prefix.begin() + ip_offset + ip_psize, bytes.begin());
        ip_address_ = Ip6Address(bytes);
    }
}

void EvpnPrefix::WriteIpAddress(BgpProtoPrefix *proto_prefix,
                                size_t ip_offset) const {
    if (family_ == Address::INET) {
        const Ip4Address::bytes_type &bytes = ip_address_.to_v4().to_bytes();
        copy(bytes.begin(), bytes.begin() + kIp4AddrSize,
            proto_prefix->prefix.begin() + ip_offset);
    } else if (family_ == Address::INET6) {
        const Ip6Address::bytes_type &bytes = ip_address_.to_v6().to_bytes();
        copy(bytes.begin(), bytes.begin() + kIp6AddrSize,
            proto_prefix->prefix.begin() + ip_offset);
    }
}

void EvpnPrefix::WriteSource(BgpProtoPrefix *proto_prefix,
                             size_t ip_offset) const {
    if (family_ == Address::INET) {
        const Ip4Address::bytes_type &bytes = source_.to_v4().to_bytes();
        copy(bytes.begin(), bytes.begin() + kIp4AddrSize,
            proto_prefix->prefix.begin() + ip_offset);
    } else if (family_ == Address::INET6) {
        const Ip6Address::bytes_type &bytes = source_.to_v6().to_bytes();
        copy(bytes.begin(), bytes.begin() + kIp6AddrSize,
            proto_prefix->prefix.begin() + ip_offset);
    }
}

void EvpnPrefix::WriteGroup(BgpProtoPrefix *proto_prefix,
                            size_t ip_offset) const {
    if (family_ == Address::INET) {
        const Ip4Address::bytes_type &bytes = group_.to_v4().to_bytes();
        copy(bytes.begin(), bytes.begin() + kIp4AddrSize,
            proto_prefix->prefix.begin() + ip_offset);
    } else if (family_ == Address::INET6) {
        const Ip6Address::bytes_type &bytes = group_.to_v6().to_bytes();
        copy(bytes.begin(), bytes.begin() + kIp6AddrSize,
            proto_prefix->prefix.begin() + ip_offset);
    }
}

EvpnRoute::EvpnRoute(const EvpnPrefix &prefix)
    : prefix_(prefix) {
}

int EvpnRoute::CompareTo(const Route &rhs) const {
    const EvpnRoute &evpn_rhs = static_cast<const EvpnRoute &>(rhs);
    return prefix_.CompareTo(evpn_rhs.prefix_);
}

string EvpnRoute::ToString() const {
    return prefix_.ToString();
}

string EvpnRoute::ToXmppIdString() const {
    if (xmpp_id_str_.empty())
        xmpp_id_str_ = prefix_.ToXmppIdString();
    return xmpp_id_str_;
}

bool EvpnRoute::IsValid() const {
    if (!BgpRoute::IsValid())
        return false;

    const BgpAttr *attr = BestPath()->GetAttr();
    switch (prefix_.type()) {
    case EvpnPrefix::AutoDiscoveryRoute: {
        if (prefix_.tag() == EvpnPrefix::kMaxTag)
            return true;
        break;
    }
    case EvpnPrefix::MacAdvertisementRoute: {
        return true;
    }
    case EvpnPrefix::InclusiveMulticastRoute: {
        const PmsiTunnel *pmsi_tunnel = attr->pmsi_tunnel();
        if (!pmsi_tunnel)
            return false;
        uint8_t tunnel_type = pmsi_tunnel->tunnel_type();
        uint8_t tunnel_flags = pmsi_tunnel->tunnel_flags();
        uint8_t ar_type =
            tunnel_flags & PmsiTunnelSpec::AssistedReplicationType;
        if (tunnel_type == PmsiTunnelSpec::IngressReplication) {
            if (ar_type == PmsiTunnelSpec::RegularNVE)
                return true;
            if (ar_type == PmsiTunnelSpec::ARReplicator &&
                (tunnel_flags & PmsiTunnelSpec::LeafInfoRequired)) {
                return true;
            }
            return false;
        }
        if (tunnel_type == PmsiTunnelSpec::AssistedReplicationContrail &&
            ar_type == PmsiTunnelSpec::ARLeaf) {
            return true;
        }
        return false;
    }
    case EvpnPrefix::SegmentRoute: {
        return false;
    }
    case EvpnPrefix::IpPrefixRoute: {
        return false;
    }
    case EvpnPrefix::SelectiveMulticastRoute: {
        return false;
    }
    default: {
        break;
    }
    }

    return false;
}

void EvpnRoute::SetKey(const DBRequestKey *reqkey) {
    const EvpnTable::RequestKey *key =
        static_cast<const EvpnTable::RequestKey *>(reqkey);
    prefix_ = key->prefix;
}

void EvpnRoute::BuildProtoPrefix(BgpProtoPrefix *proto_prefix,
    const BgpAttr *attr, uint32_t label, uint32_t l3_label) const {
    prefix_.BuildProtoPrefix(proto_prefix, attr, label, l3_label);
}

void EvpnRoute::BuildBgpProtoNextHop(vector<uint8_t> &nh,
        IpAddress nexthop) const {
    nh.resize(4);
    const Ip4Address::bytes_type &addr_bytes = nexthop.to_v4().to_bytes();
    copy(addr_bytes.begin(), addr_bytes.end(), nh.begin());
}

DBEntryBase::KeyPtr EvpnRoute::GetDBRequestKey() const {
    EvpnTable::RequestKey *key = new EvpnTable::RequestKey(GetPrefix(), NULL);
    return KeyPtr(key);
}

redpajama_set_name: RedPajamaGithub


text:
class SkedplusPairing::FlightAttendant < SkedplusPairing::Crewmember
end


text:
export function Abc() {
};

export default function Def() {
};


text:
namespace mi
{
	class OffScreenRenderer::Impl {
	public:
		Impl ( void ) : _isOk (true), _width (128), _height(128), _window (NULL) {
			return;
		}

		~Impl ( void ) {
			return;
		}

		void setNg( void ) {
			this->_isOk = false;
			return;
		}

		bool isOk ( void ) {
			return this->_isOk;
		}

		void setSize ( const int width, const int height ) {
			this->_width  = width;
			this->_height = height;
			return;
		}

		int getWidth ( void ) const {
			return this->_width;
		}

		int getHeight ( void ) const {
			return this->_height;
		}

		void getWindow ( GLFWwindow* window ) {
			window = this->_window;
		}

	private:
                bool _isOk;
                int _width;
                int _height;
                GLFWwindow* _window;
	};

        OffScreenRenderer::OffScreenRenderer ( const int width, const int height ) : _impl ( new Impl())
        {
                if ( this->init ( width,height ) ) this->_impl->setNg();
                return;
        }

        OffScreenRenderer::~OffScreenRenderer ( void )
        {
                return;
        }

        bool
        OffScreenRenderer::init ( const int width, const int height )
        {
		GLFWwindow* window = NULL;
		this->_impl->getWindow(window);
		this->_impl->setSize( width, height);
                if ( ::glfwInit() == GL_FALSE )  return false;
                ::glfwWindowHint( GLFW_VISIBLE, 0 );
		window = ::glfwCreateWindow( width, height, "tmp", NULL, NULL );
                ::glfwMakeContextCurrent( window );
                if ( !window ) return false;
                return true;
        }

        int
        OffScreenRenderer::getWidth( void ) const
        {
                return this->_impl->getWidth();
        }

        int
        OffScreenRenderer::getHeight( void ) const
        {
                return this->_impl->getHeight();
        }

        void
        OffScreenRenderer::swapBuffers( void )
        {
		GLFWwindow* window = NULL;
		this->_impl->getWindow(window);
                ::glfwSwapBuffers( window );
        }

        void
        OffScreenRenderer::getImage ( std::vector<unsigned char>& image )
        {
                const int &width = this->getWidth();
                const int &height = this->getHeight();
                const int npixels = width * height;

                image.assign ( npixels * 3 , 0x00 );
                unsigned char *buf = new unsigned char [ npixels * 4 ];

                ::glReadPixels ( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buf );

                for ( int y = 0 ; y < height ; ++y ) {
                        for ( int x = 0 ; x < width ; ++x ) {
				const int idx = y * width + x ;
                                const int idxBuf = 4 * idx;
                                const int idxImg = 3 * idx;
                                for ( int i = 0 ; i < 3 ; ++i ) {
                                        image[idxImg+i] = buf[idxBuf+i];
                                }
                        }
                }
                delete[] buf;
                return;
        }

        void
        OffScreenRenderer::getDepth ( std::vector<float>& depth )
        {
                const int &width = this->getWidth();
                const int &height = this->getHeight();
                const int npixels = width * height;

                depth.assign( npixels , 0 );
                float *buf = new float [ npixels ];
                ::glReadPixels ( 0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, buf );
                for ( int i = 0 ; i < npixels ; ++i ) {
                        depth[i] = buf[i];
                }
                delete[] buf;
                return;
        }
}


text:
"""
MagPy
Auxiliary input filter - WIC/WIK
Written by Roman Leonhardt June 2012
- contains test and read function, toDo: write function
"""

from magpy.stream import *

def isSFDMI(filename):
    """
    Checks whether a file is spanish DMI format.
    Time is in seconds relative to one day
    """
    try:
        temp = open(filename, 'rt').readline()
    except:
        return False
    if len(temp) >= 9:
        if temp[9] in ['o','+','-']: # Prevent errors with GFZ kp
            return False
    sp = temp.split()
    if not len(sp) == 6:
        return False
    if not isNumber(sp[0]):
        return False
    #logging.info(" Found SFS file")
    return True

def isSFGSM(filename):
    """
    Checks whether a file is spanish GSM format.
    Time is in seconds relative to one day
    """
    try:
        fh = open(filename, 'rt')
        temp = fh.readline()
    except:
        return False

    sp = temp.split()
    if len(sp) != 2:
        return False
    if not isNumber(sp[0]):
        return False
    try:
        if not 20000 < float(sp[1]) < 80000:
            return False
    except:
        return False
    return True

def readSFDMI(filename, headonly=False, **kwargs):
    """
    Reading SF DMI format data.
    Looks like:
    0.03          99.11         -29.76        26.14         22.05         30.31
    5.04          98.76         -29.78        26.20         22.04         30.31
    10.01         98.85         -29.76        26.04         22.04         30.31
    15.15         98.63         -29.79        26.20         22.04         30.31
    20.12         98.85         -29.78        26.11         22.04         30.31
    first column are seconds of day
    """
    starttime = kwargs.get('starttime')
    endtime = kwargs.get('endtime')
    getfile = True

    fh = open(filename, 'rt')

    # read file and split text into channels
    stream = DataStream()
    if stream.header is None:
        headers = {}
    else:
        headers = stream.header

    data = []
    key = None
    # get day from filename (platform independent)
    splitpath = os.path.split(filename)
    daystring = splitpath[1].split('.')
    try:
        day = datetime.strftime(datetime.strptime(daystring[0], "%d%m%Y"),"%Y-%m-%d")
    except:
        logging.warning("Wrong dateformat in Filename %s" % daystring[0])
        fh.close()
        return DataStream([], headers)

    # Select only files within eventually defined time range
    if starttime:
        if not datetime.strptime(day,'%Y-%m-%d') >= datetime.strptime(datetime.strftime(stream._testtime(starttime),'%Y-%m-%d'),'%Y-%m-%d'):
            getfile = False
    if endtime:
        if not datetime.strptime(day,'%Y-%m-%d') <= datetime.strptime(datetime.strftime(stream._testtime(endtime),'%Y-%m-%d'),'%Y-%m-%d'):
            getfile = False

    if getfile:
        for line in fh:
            if line.isspace():
                # blank line
                continue
            else:
                row = LineStruct()
                elem = line.split()
                if (len(elem) == 6):
                    row.time=date2num(datetime.strptime(day,"%Y-%m-%d"))+ float(elem[0])/86400
                    xval = float(elem[1])
                    yval = float(elem[2])
                    zval = float(elem[3])
                    row.x = xval
                    row.y = yval
                    row.z = zval
                    row.t1 = float(elem[4])
                    row.t2 = float(elem[5])
                    stream.add(row)
        stream.header['col-x'] = 'x'
        stream.header['col-y'] = 'y'
        stream.header['col-z'] = 'z'
        stream.header['col-t1'] = 'T1'
        stream.header['col-t2'] = 'T2'
        stream.header['unit-col-x'] = 'nT'
        stream.header['unit-col-y'] = 'nT'
        stream.header['unit-col-z'] = 'nT'
        stream.header['unit-col-t1'] = 'deg C'
        stream.header['unit-col-t2'] = 'deg C'
    else:
        headers = stream.header
        stream =[]

    fh.close()

    return DataStream(stream, headers)

def readSFGSM(filename, headonly=False, **kwargs):
    """
    Reading SF GSM format data.
    Looks like:
     22            42982.35
     52            42982.43
     82            42982.47
    first column are seconds of day
    """
    starttime = kwargs.get('starttime')
    endtime = kwargs.get('endtime')
    getfile = True

    fh = open(filename, 'rt')
    # read file and split text into channels
    stream = DataStream()
    if stream.header is None:
        headers = {}
    else:
        headers = stream.header
    data = []
    key = None
    # get day from filename (platform independent)
    splitpath = os.path.split(filename)
    daystring = splitpath[1].split('.')
    try:
        day = datetime.strftime(datetime.strptime(daystring[0], "%d%m%Y"),"%Y-%m-%d")
    except:
        logging.warning("Wrong dateformat in Filename %s" % daystring[0])
        return []
    # Select only files within eventually defined time range
    if starttime:
        if not datetime.strptime(day,'%Y-%m-%d') >= datetime.strptime(datetime.strftime(stream._testtime(starttime),'%Y-%m-%d'),'%Y-%m-%d'):
            getfile = False
    if endtime:
        if not datetime.strptime(day,'%Y-%m-%d') <= datetime.strptime(datetime.strftime(stream._testtime(endtime),'%Y-%m-%d'),'%Y-%m-%d'):
            getfile = False

    if getfile:
        for line in fh:
            if line.isspace():
                # blank line
                continue
            else:
                row = LineStruct()
                elem = line.split()
                if (len(elem) == 2):
                    row.time=date2num(datetime.strptime(day,"%Y-%m-%d"))+ float(elem[0])/86400
                    row.f = float(elem[1])
                    stream.add(row)
        stream.header['col-f'] = 'f'
        stream.header['unit-col-f'] = 'nT'
    else:
        headers = stream.header
        stream =[]

    fh.close()

    return DataStream(stream, headers)


text:
namespace base {
class TaskRunner;
}

namespace content {

// ChannelInit handles creation and destruction of the Mojo channel. It is not
// thread-safe, but may be used on any single thread with a MessageLoop.
class CONTENT_EXPORT ChannelInit {
 public:
  ChannelInit();
  ~ChannelInit();

  // Initializes the channel. This takes ownership of |file|. Returns the
  // primordial MessagePipe for the channel.
  mojo::ScopedMessagePipeHandle Init(
      base::PlatformFile file,
      scoped_refptr<base::TaskRunner> io_thread_task_runner);

  // Notifies the channel that we (hence it) will soon be destroyed.
  void WillDestroySoon();

 private:
  // Invoked on the thread on which this object lives once the channel has been
  // established. This is a static method that takes a weak pointer to self,
  // since we want to destroy the channel if we were destroyed first.
  static void OnCreatedChannel(
      base::WeakPtr<ChannelInit> self,
      scoped_ptr<IPC::ScopedIPCSupport> ipc_support,
      mojo::embedder::ChannelInfo* channel);

  // If non-null the channel has been established.
  mojo::embedder::ChannelInfo* channel_info_;

  scoped_ptr<IPC::ScopedIPCSupport> ipc_support_;
  base::WeakPtrFactory<ChannelInit> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ChannelInit);
};

}  // namespace content

#endif  // CONTENT_COMMON_MOJO_CHANNEL_INIT_H_


text:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ContentViewController *contentViewController = [[ContentViewController alloc] init];
    contentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"content.png"]];

    UINavigationController *contentNavigationController = [[UINavigationController alloc] initWithRootViewController:contentViewController];
    contentNavigationController.view.layer.shadowColor = [UIColor blackColor].CGColor;
    contentNavigationController.view.layer.shadowOffset = (CGSize){0.0, 0.0};
    contentNavigationController.view.layer.shadowOpacity = 0.8;
    contentNavigationController.view.layer.shadowRadius = 10.0;

    LeftSidebarViewController *leftSidebarViewController = [[LeftSidebarViewController alloc] init];
    leftSidebarViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"left-menu.png"]];

    RightSidebarViewController *rightSidebarViewController = [[RightSidebarViewController alloc] init];
    rightSidebarViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"right-menu.png"]];

    TheSidebarController *sidebarController = [[TheSidebarController alloc] initWithContentViewController:contentNavigationController
                                                                                leftSidebarViewController:leftSidebarViewController
                                                                               rightSidebarViewController:rightSidebarViewController];
    sidebarController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.jpg"]];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = sidebarController;
    [self.window makeKeyAndVisible];
    return YES;
}

@end


text:
001
032
033    package com.jeantessier.dependency;
034
035    import java.util.*;
036
037    public interface CyclePrinter {
038        public void visitCycles(Collection<Cycle> cycles);
039        public void visitCycle(Cycle cycle);
040
041        public void setIndentText(String indentText);
042    }


text:
BRAINVILLE Arthur, CLEMENT Vincent, GATTOLIN Nicolas

Build et lancement du programme :

mvn clean install && java -jar *.jar

Les features faites / ajoutés :

- toutes les fonctionnalités de la grille et des tetrominos
- boucle de jeu qui fait tomber les blocs
- vue de la grille

Un paragraphe expliquant comment jouer avec votre Tetris :

flèche gauche/droite : déplacer latéralament la pièce
flèche bas : faire descendre la pièce
s : rotation antihoraire
d : rotation horaire

L'exercice d'architecture :

Le pattern général utilisé pour l'architecture est le MVC: séparation Model (données) View (vues) Controler (lien entre vue et données, logique de l'application).
Nous avons respecté au mieux chacun des principes SOLID, meme si nous aurions pu écrire plus d'interfaces.
Un tétromino est représenté par les quatre positions de ses quatre blocs.
La grille est la seule à pouvoir modifier sa représentation interne. Une fonction permettant de "plaquer" un tetromino dans la grille permet d'afficher le tétromino courant sans modifier réellemnt la grille.
La class Game a pour responsabilité de mettre à jour le jeu tour par tour, c'est-à-dire :
- demander à la grille de faire tomber les pièces et de détruire les lignes complètes (le nombre de lignes détruites est retourné pour calculer le score),
- de choisir le prochain tétromino selon l'algorithme classique du Tétris,
- de gérer les deux joueurs et leurs scores associés

L'exercice Design Pattern / SOLID

- GameLoop http://gameprogrammingpatterns.com/game-loop.html :
pattern très courant pour la programmation de jeux, composé d'une boucle infinie et d'un timer qui appelle une fonction update mettant à jour l'état du jeu
- Observer : la vue est notifiée des changements du modèle (score et grille)
- Data Access Object : abstrait les ressources et offre une interface générique (DAO score)
- Iterator : permet l'itération générique sur une collection (implémenté pour itérer sur les blocs composant les tétrominos)


text:
package log

import (
	"context"

	"github.com/sirupsen/logrus"
)

var (
	// G is an alias for GetLogger.
	//
	// We may want to define this locally to a package to get package tagged log
	// messages.
	G = GetLogger

	// L is an alias for the standard logger.
	L = logrus.NewEntry(logrus.StandardLogger())
)

type (
	loggerKey struct{}
)

// RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to
// ensure the formatted time is always the same number of characters.
const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"

// WithLogger returns a new context with the provided logger. Use in
// combination with logger.WithField(s) for great effect.
func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
	return context.WithValue(ctx, loggerKey{}, logger)
}

// GetLogger retrieves the current logger from the context. If no logger is
// available, the default logger is returned.
func GetLogger(ctx context.Context) *logrus.Entry {
	logger := ctx.Value(loggerKey{})

	if logger == nil {
		return L
	}

	return logger.(*logrus.Entry)
}


text:
package org.apereo.portal.api.permissions;

import java.util.Set;

public interface PermissionsService {
    Set<Assignment> getAssignmentsForPerson(String username, boolean includeInherited);
}


text:
BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

set -e

# useful functions
source $AHR_HOME/bin/ahr-lib.sh

check_envvars "AHR_HOME PROJECT GCP_OS_USERNAME AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_REGION HYBRID_HOME"

export PATH=$AHR_HOME/bin:$PATH

./bs-prerequisites.sh

export PATH=~/bin:$PATH

# gcp
gcloud config set project $PROJECT

# enable required APIs
ahr-verify-ctl api-enable

# infrastructure setup
cd $HYBRID_HOME

# Build GCP/AWS VPC/VPN Infrastructure
./bs-networking.sh

pushd gcp-aws-vpc-infra-tf
terraform init
terraform apply -auto-approve
popd

./bs-cluster-infra.sh

pushd gke-eks-cluster-infra-tf
terraform init
terraform apply -auto-approve
popd

# eks to a parallel fork, join before eks hybrid deploy
export EKS_CLUSTER_LOG=${EKS_CLUSTER_LOG:-$HYBRID_HOME/mc-install-eks-`date -u +"%Y-%m-%dT%H:%M:%SZ"`.log}
echo "Building EKS cluser in background; progress log: $EKS_CLUSTER_LOG"

nohup bash <<EOS &> $EKS_CLUSTER_LOG &
./ci-eks.sh
EOS
export EKS_CLUSTER_PID=$!

./ci-gke.sh

./hi-gke.sh

source $HYBRID_HOME/source.env
$AHR_HOME/proxies/deploy.sh

echo "Making sure EKS cluster is ready before progressing [pid: $EKS_CLUSTER_PID]..."
wait $EKS_CLUSTER_PID

./hi-eks.sh


text:
/*
 ** ModuloByZeroException.cpp for cpp_abstractvm in /var/projects/cpp_abstractvm/include/ModuloByZeroException.cpp
 **
 ** Made by kevin labbe
 ** Login   <labbe_k@epitech.net>
 **
 ** Started on  Mar 2, 2014 7:40:22 PM 2014 kevin labbe
 ** Last update Mar 2, 2014 7:40:22 PM 2014 kevin labbe
 */
#include "ModuloByZeroException.hpp"

namespace Exception
{
  ModuloByZeroException::ModuloByZeroException(
      const std::string& errmsg) throw () :
    AVMException("Modulo by zero not allowed: " + errmsg)
  {
  }

  ModuloByZeroException::ModuloByZeroException(const std::string& errmsg,
      const int line) throw () :
    AVMException("Modulo by zero not allowed: " + errmsg, line)
  {
  }

  ModuloByZeroException::~ModuloByZeroException() throw()
  {
  }
} /* namespace Exception */


text:
import {convertObjectWithTemplates} from './utils'

function signInWithGoogleFactory (options = {}) {
  function signInWithGoogle ({firebase, path, resolveArg}) {
    return firebase.signInWithGoogle(convertObjectWithTemplates(options, resolveArg))
      .then(path.success)
      .catch(path.error)
  }

  return signInWithGoogle
}

export default signInWithGoogleFactory


text:
using Shop.Domain.Entities.Cards;
using Shop.Domain.Entities.Proof;

namespace Shop.Domain.Entities.Shop
{
    public class ProofOrder : IOrder
    {
        public IProof Proof { get; set; }
        public ICreditCard Card { get; set; }

        public ProofOrder(IProof proof,ICreditCard card)
        {
            Proof = proof;
            Card = card;
        }
    }
}


text:
import { call, put } from 'redux-saga/effects';
import { tracklistRequestActions } from '../tracklists/actions';
import { userRequestActions } from '../users';
import { api } from './api-service';

function* fetchEntities(apiFunction, actions, id, param) {
  try {
    yield put(actions.pending(id));
    const data = yield call(apiFunction, param || id);
    yield put(actions.fulfilled(id, data));
  }
  catch (error) {
    yield put(actions.failed(error));
  }
}

export const fetchNextTracks = fetchEntities.bind(null, api.fetch, tracklistRequestActions);
export const fetchSearchResults = fetchEntities.bind(null, api.fetchSearchResults, tracklistRequestActions);
export const fetchUser = fetchEntities.bind(null, api.fetchUser, userRequestActions);
export const fetchUserLikes = fetchEntities.bind(null, api.fetchUserLikes, tracklistRequestActions);
export const fetchUserTracks = fetchEntities.bind(null, api.fetchUserTracks, tracklistRequestActions);


text:
<?php
  include_once('../grid_product_detail/grid_product_detail.php');
?>


text:
Perambulate is a physics-based, VR construction game inspired by sodaplay.

Use actuators to build machines and set them loose.

To try Perambulate, you need a [WebVR compatible browser](http://webvr.info/) and a Leap Motion
controller attached to your HMD.

Perambulate was developed in [Firefox Nightly](http://mozvr.com/) with an Oculus Rift DK2 but
it should work with Chrome WebVR builds and with a DK1.

## Usage and Tips

Watch the video to get an idea of how Perambulate works: http://youtu.be/qLC8L-58Juk

Bend the middle and ring fingers on your left hand to display the control panels :metal:.

The main control panel appears when your palm is facing up. The actuator control panel appears when your palm is facing down. The main control panel lets you add new actuators, which appear in the center of the environment, activate the actuator animations and enable gravity. The actuator control panel lets you change the amplitude (the y-axis) and the phase (the x-axis) of the actuator's animation. Select actuators to control by poking them with your index finger.

Be deliberate with your hand movements. The pose and grab detection isn't very intelligent and the Leap Motion can be very glitchy.

Get the most out of your Leap Motion by following the VR troubleshooting guide: http://blog.leapmotion.com/troubleshooting-guide-vr-tracking/

## Known Issues

The app can sometimes start in a bad state. You'll notice that lights are much darker or that only one eye is lit up in VR mode. Just refresh once or twice until it starts correctly.

Your construction can sometimes go crazy if two actuators join at weird angles or when you don't mean to. This can probably be improved but it's partly due to the Leap Motion's glitches. See the link to the troubleshooting guide above.

The slider widget on the actuator control panel kinda sucks. It doesn't behave as you'd expect and doesn't like being angled in odd positions. I'm going to have to submit some patches to Leap Motion's widget library.

## Attributions

- Three.js by mrdoob et al. - https://github.com/mrdoob/three.js
- Cannon.js by schteppe - https://github.com/schteppe/cannon.js
- WebVR boilerplate by borismus - https://github.com/borismus/webvr-boilerplate
- LeapJS library, plugins and widgets - https://github.com/leapmotion/leapjs
- Glam by tparisi - https://github.com/tparisi/glam
- Backbone and Underscore by jasenkas et al. - https://github.com/jashkenas/underscore
- Icons by http://glyphicons.com/


text:
#pragma once

#include <RateControl.hpp>

#include <lib/matrix/matrix/math.hpp>
#include <lib/perf/perf_counter.h>
#include <px4_platform_common/defines.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/module_params.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/px4_work_queue/ScheduledWorkItem.hpp>
#include <uORB/Publication.hpp>
#include <uORB/PublicationMulti.hpp>
#include <uORB/Subscription.hpp>
#include <uORB/SubscriptionCallback.hpp>
#include <uORB/topics/actuator_controls.h>
#include <uORB/topics/battery_status.h>
#include <uORB/topics/landing_gear.h>
#include <uORB/topics/manual_control_setpoint.h>
#include <uORB/topics/multirotor_motor_limits.h>
#include <uORB/topics/parameter_update.h>
#include <uORB/topics/rate_ctrl_status.h>
#include <uORB/topics/vehicle_angular_acceleration.h>
#include <uORB/topics/vehicle_angular_velocity.h>
#include <uORB/topics/vehicle_control_mode.h>
#include <uORB/topics/vehicle_land_detected.h>
#include <uORB/topics/vehicle_rates_setpoint.h>
#include <uORB/topics/vehicle_status.h>

class MulticopterRateControl : public ModuleBase<MulticopterRateControl>, public ModuleParams, public px4::WorkItem
{
public:
	MulticopterRateControl(bool vtol = false);
	~MulticopterRateControl() override;

	/** @see ModuleBase */
	static int task_spawn(int argc, char *argv[]);

	/** @see ModuleBase */
	static int custom_command(int argc, char *argv[]);

	/** @see ModuleBase */
	static int print_usage(const char *reason = nullptr);

	bool init();

private:
	void Run() override;

	/**
	 * initialize some vectors/matrices from parameters
	 */
	void		parameters_updated();

	RateControl _rate_control; ///< class for rate control calculations

	uORB::Subscription _battery_status_sub{ORB_ID(battery_status)};
	uORB::Subscription _landing_gear_sub{ORB_ID(landing_gear)};
	uORB::Subscription _manual_control_setpoint_sub{ORB_ID(manual_control_setpoint)};
	uORB::Subscription _motor_limits_sub{ORB_ID(multirotor_motor_limits)};
	uORB::Subscription _parameter_update_sub{ORB_ID(parameter_update)};
	uORB::Subscription _v_control_mode_sub{ORB_ID(vehicle_control_mode)};
	uORB::Subscription _v_rates_sp_sub{ORB_ID(vehicle_rates_setpoint)};
	uORB::Subscription _vehicle_angular_acceleration_sub{ORB_ID(vehicle_angular_acceleration)};
	uORB::Subscription _vehicle_land_detected_sub{ORB_ID(vehicle_land_detected)};
	uORB::Subscription _vehicle_status_sub{ORB_ID(vehicle_status)};

	uORB::SubscriptionCallbackWorkItem _vehicle_angular_velocity_sub{this, ORB_ID(vehicle_angular_velocity)};

	uORB::Publication<actuator_controls_s>		_actuators_0_pub;
	uORB::PublicationMulti<rate_ctrl_status_s>	_controller_status_pub{ORB_ID(rate_ctrl_status)};	/**< controller status publication */
	uORB::Publication<landing_gear_s>		_landing_gear_pub{ORB_ID(landing_gear)};
	uORB::Publication<vehicle_rates_setpoint_s>	_v_rates_sp_pub{ORB_ID(vehicle_rates_setpoint)};			/**< rate setpoint publication */

	manual_control_setpoint_s	_manual_control_setpoint{};
	vehicle_control_mode_s		_v_control_mode{};
	vehicle_status_s		_vehicle_status{};

	bool _actuators_0_circuit_breaker_enabled{false};	/**< circuit breaker to suppress output */
	bool _landed{true};
	bool _maybe_landed{true};

	float _battery_status_scale{0.0f};

	perf_counter_t	_loop_perf;			/**< loop duration performance counter */

	matrix::Vector3f _rates_sp;			/**< angular rates setpoint */

	float		_thrust_sp{0.0f};		/**< thrust setpoint */

	hrt_abstime _last_run{0};

	int8_t _landing_gear{landing_gear_s::GEAR_DOWN};

	DEFINE_PARAMETERS(
		(ParamFloat<px4::params::MC_ROLLRATE_P>) _param_mc_rollrate_p,
		(ParamFloat<px4::params::MC_ROLLRATE_I>) _param_mc_rollrate_i,
		(ParamFloat<px4::params::MC_RR_INT_LIM>) _param_mc_rr_int_lim,
		(ParamFloat<px4::params::MC_ROLLRATE_D>) _param_mc_rollrate_d,
		(ParamFloat<px4::params::MC_ROLLRATE_FF>) _param_mc_rollrate_ff,
		(ParamFloat<px4::params::MC_ROLLRATE_K>) _param_mc_rollrate_k,

		(ParamFloat<px4::params::MC_PITCHRATE_P>) _param_mc_pitchrate_p,
		(ParamFloat<px4::params::MC_PITCHRATE_I>) _param_mc_pitchrate_i,
		(ParamFloat<px4::params::MC_PR_INT_LIM>) _param_mc_pr_int_lim,
		(ParamFloat<px4::params::MC_PITCHRATE_D>) _param_mc_pitchrate_d,
		(ParamFloat<px4::params::MC_PITCHRATE_FF>) _param_mc_pitchrate_ff,
		(ParamFloat<px4::params::MC_PITCHRATE_K>) _param_mc_pitchrate_k,

		(ParamFloat<px4::params::MC_YAWRATE_P>) _param_mc_yawrate_p,
		(ParamFloat<px4::params::MC_YAWRATE_I>) _param_mc_yawrate_i,
		(ParamFloat<px4::params::MC_YR_INT_LIM>) _param_mc_yr_int_lim,
		(ParamFloat<px4::params::MC_YAWRATE_D>) _param_mc_yawrate_d,
		(ParamFloat<px4::params::MC_YAWRATE_FF>) _param_mc_yawrate_ff,
		(ParamFloat<px4::params::MC_YAWRATE_K>) _param_mc_yawrate_k,

		(ParamFloat<px4::params::MPC_MAN_Y_MAX>) _param_mpc_man_y_max,			/**< scaling factor from stick to yaw rate */

		(ParamFloat<px4::params::MC_ACRO_R_MAX>) _param_mc_acro_r_max,
		(ParamFloat<px4::params::MC_ACRO_P_MAX>) _param_mc_acro_p_max,
		(ParamFloat<px4::params::MC_ACRO_Y_MAX>) _param_mc_acro_y_max,
		(ParamFloat<px4::params::MC_ACRO_EXPO>) _param_mc_acro_expo,				/**< expo stick curve shape (roll & pitch) */
		(ParamFloat<px4::params::MC_ACRO_EXPO_Y>) _param_mc_acro_expo_y,				/**< expo stick curve shape (yaw) */
		(ParamFloat<px4::params::MC_ACRO_SUPEXPO>) _param_mc_acro_supexpo,			/**< superexpo stick curve shape (roll & pitch) */
		(ParamFloat<px4::params::MC_ACRO_SUPEXPOY>) _param_mc_acro_supexpoy,			/**< superexpo stick curve shape (yaw) */

		(ParamFloat<px4::params::MC_RATT_TH>) _param_mc_ratt_th,

		(ParamBool<px4::params::MC_BAT_SCALE_EN>) _param_mc_bat_scale_en,

		(ParamInt<px4::params::CBRK_RATE_CTRL>) _param_cbrk_rate_ctrl
	)

	matrix::Vector3f _acro_rate_max;	/**< max attitude rates in acro mode */

};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace GalaSoft.MvvmLight.Internal
{
    class CommandManagerHelper : ICommandManagerHelper
    {
        public void InvalidateRequerySuggested()
        {
            CommandManager.InvalidateRequerySuggested();
        }

        public event EventHandler RequerySuggested
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}


text:
var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    autoprefixer = require('gulp-autoprefixer'),
    notify = require('gulp-notify'),
    minifycss = require('gulp-minify-css'),
    clean = require('gulp-clean');

gulp.task('styles', function() {
  return gulp.src('scss/whipcream.scss')
    .pipe(sass({ style: 'expanded', 'errLogToConsole': true }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(gulp.dest('css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

gulp.task('clean', function() {
  return gulp.src(['css'], {read: false})
    .pipe(clean());
});

gulp.task('default', ['clean'], function() {
  gulp.start('styles');
});

gulp.task('watch', function() {
  gulp.watch('scss/**/*.scss', ['styles']);
});


text:
class AdController < ApplicationController

  layout 'ad'

  # before_action :authenticate_store!, :except => [:api_promotions]
  before_action :authenticate_store!

  private

  def after_sign_in_path_for(resource)
    ad_root_path
  end

end