text:
#ifndef vnsw_agent_vm_interface_hpp
#define vnsw_agent_vm_interface_hpp

#include <oper/oper_dhcp_options.h>
#include <oper/audit_list.h>
#include <oper/ecmp_load_balance.h>

/////////////////////////////////////////////////////////////////////////////
// Implementation of VM Port interfaces
/////////////////////////////////////////////////////////////////////////////
typedef std::vector<boost::uuids::uuid> SgUuidList;
typedef std::vector<SgEntryRef> SgList;
struct VmInterfaceData;
struct VmInterfaceConfigData;
struct VmInterfaceNovaData;
struct VmInterfaceIpAddressData;
struct VmInterfaceOsOperStateData;
struct VmInterfaceMirrorData;
class OperDhcpOptions;
class PathPreference;
class MetaDataIp;
class HealthCheckInstance;

class LocalVmPortPeer;

/////////////////////////////////////////////////////////////////////////////
// Definition for VmInterface
// Agent supports multiple type of VMInterfaces
// - VMI for a virtual-machine spawned on KVM compute node. It will have a TAP
//   interface associated with it. Agent also expects a INSTANCE_MSG from
//    nova-compute/equivalent to add this port
//    DeviceType = VM_ON_TAP, VmiType = INSTANCE
// - VMI for a virtual-machine spawned on VMware ESXi. All virtual-machines
//   are connected on a physical-port and VLAN is used to distinguish them
//   DeviceType = VM_PHYSICAL_VLAN, VmiType = INTANCE, agent->hypervisor_mode = ESXi
// - VMI for a virtual-machine spawned on VMWare VCenter . All virtual-machines
//   are connected on a physical-port and they are classified by the smac
//   DeviceType = VM_PHYSICAL_MAC, VmiType = INTANCE and
//   agent hypervisor mode = VCenter
// - VMI for service-chain virtual-machines
// - VMI for service-chain virtual-machine spawned on KVM compute node.
//   It will have a TAP interface associated with it. Agent also expects a
//   INSTANCE_MSG from interface associated with it.
//   DeviceType = VM_ON_TAP, VmiType = SERVICE_CHAIN
// - VMI for service-instances spawned by agent itself.
//   It will have a TAP interface associated with it. Agent also expects a
//   INSTANCE_MSG from interface associated with it.
//   DeviceType = VM, VmiType = SERVICE_INTANCE
//
/////////////////////////////////////////////////////////////////////////////
class VmInterface : public Interface {
public:
    static const uint32_t kInvalidVlanId = 0xFFFF;
    static const uint32_t kInvalidPmdId = 0xFFFF;

    enum Configurer {
        INSTANCE_MSG,
        CONFIG
    };

    // Type of VMI Port
    enum DeviceType {
        DEVICE_TYPE_INVALID,
        VM_ON_TAP,          // VMI on TAP/physial port interface
                            // VMI is created based on the INSTANCE_MSG
        VM_VLAN_ON_VMI,     // VMI on TAP port with VLAN as classifier
                            // VMI is created based on config message
        VM_PHYSICAL_VLAN,   // VMI classified with VLAN on a physical-port
                            // (used in VMWare ESXi)
                            // VMI is created based on the INSTANCE_MSG
        VM_PHYSICAL_MAC,    // VMI classified with MAC on a physical-port
                            // (used in VMWare VCenter)
                            // VMI is created based on the INSTANCE_MSG
        TOR,                // Baremetal connected to ToR
        LOCAL_DEVICE,       // VMI on a local port. Used in GATEWAY
        VM_SRIOV            // VMI on an SRIOV VM
    };

    // Type of VM on the VMI
    enum VmiType {
        VMI_TYPE_INVALID,
        INSTANCE,
        SERVICE_CHAIN,
        SERVICE_INSTANCE,
        BAREMETAL,
        GATEWAY,
        SRIOV
    };

    struct ListEntry {
        ListEntry() : installed_(false), del_pending_(false) { }
        ListEntry(bool installed, bool del_pending) :
            installed_(installed), del_pending_(del_pending) { }
        virtual ~ListEntry()  {}

        bool installed() const { return installed_; }
        bool del_pending() const { return del_pending_; }
        void set_installed(bool val) const { installed_ = val; }
        void set_del_pending(bool val) const { del_pending_ = val; }

        mutable bool installed_;
        mutable bool del_pending_;
    };

    // A unified structure for storing FloatingIp information for both
    // operational and config elements
    struct FloatingIp : public ListEntry {
        FloatingIp();
        FloatingIp(const FloatingIp &rhs);
        FloatingIp(const IpAddress &addr, const std::string &vrf,
                   const boost::uuids::uuid &vn_uuid, const IpAddress &ip);
        virtual ~FloatingIp();

        bool operator() (const FloatingIp &lhs, const FloatingIp &rhs) const;
        bool IsLess(const FloatingIp *rhs) const;
        void L3Activate(VmInterface *interface, bool force_update) const;
        void L3DeActivate(VmInterface *interface) const;
        void L2Activate(VmInterface *interface, bool force_update,
                        uint32_t old_ethernet_tag) const;
        void L2DeActivate(VmInterface *interface,
                          uint32_t ethernet_tag) const;
        void DeActivate(VmInterface *interface, bool l2,
                        uint32_t old_ethernet_tag) const;
        void Activate(VmInterface *interface, bool force_update,
                      bool l2, uint32_t old_ethernet_tag) const;
        const IpAddress GetFixedIp(const VmInterface *) const;

        IpAddress floating_ip_;
        mutable VnEntryRef vn_;
        mutable VrfEntryRef vrf_;
        std::string vrf_name_;
        boost::uuids::uuid vn_uuid_;
        mutable bool l2_installed_;
        mutable IpAddress fixed_ip_;
        mutable bool force_l3_update_;
        mutable bool force_l2_update_;
    };
    typedef std::set<FloatingIp, FloatingIp> FloatingIpSet;
    typedef std::map<Ip4Address, MetaDataIp*> MetaDataIpMap;
    typedef std::set<HealthCheckInstance *> HealthCheckInstanceSet;

    struct FloatingIpList {
        FloatingIpList() : v4_count_(0), v6_count_(0), list_() { }
        ~FloatingIpList() { }

        void Insert(const FloatingIp *rhs);
        void Update(const FloatingIp *lhs, const FloatingIp *rhs);
        void Remove(FloatingIpSet::iterator &it);

        uint16_t v4_count_;
        uint16_t v6_count_;
        FloatingIpSet list_;
    };

    struct ServiceVlan : ListEntry {
        ServiceVlan();
        ServiceVlan(const ServiceVlan &rhs);
        ServiceVlan(uint16_t tag, const std::string &vrf_name,
                    const Ip4Address &addr, const Ip6Address &addr6,
                    const MacAddress &smac, const MacAddress &dmac);
        virtual ~ServiceVlan();

        bool operator() (const ServiceVlan &lhs, const ServiceVlan &rhs) const;
        bool IsLess(const ServiceVlan *rhs) const;
        void Activate(VmInterface *interface, bool force_change,
                      bool old_ipv4_active, bool old_ipv6_active) const;
        void DeActivate(VmInterface *interface) const;
        void V4RouteDelete(const Peer *peer) const;
        void V6RouteDelete(const Peer *peer) const;

        uint16_t tag_;
        std::string vrf_name_;
        Ip4Address addr_;
        Ip6Address addr6_;
        MacAddress smac_;
        MacAddress dmac_;
        mutable VrfEntryRef vrf_;
        mutable uint32_t label_;
        mutable bool v4_rt_installed_;
        mutable bool v6_rt_installed_;
    };
    typedef std::set<ServiceVlan, ServiceVlan> ServiceVlanSet;

    struct ServiceVlanList {
        ServiceVlanList() : list_() { }
        ~ServiceVlanList() { }
        void Insert(const ServiceVlan *rhs);
        void Update(const ServiceVlan *lhs, const ServiceVlan *rhs);
        void Remove(ServiceVlanSet::iterator &it);

        ServiceVlanSet list_;
    };

    struct StaticRoute : ListEntry {
        StaticRoute();
        StaticRoute(const StaticRoute &rhs);
        StaticRoute(const std::string &vrf, const IpAddress &addr,
                    uint32_t plen, const IpAddress &gw,
                    const CommunityList &communities);
        virtual ~StaticRoute();

        bool operator() (const StaticRoute &lhs, const StaticRoute &rhs) const;
        bool IsLess(const StaticRoute *rhs) const;
        void Activate(VmInterface *interface, bool force_update,
                      bool policy_change) const;
        void DeActivate(VmInterface *interface) const;

        mutable std::string vrf_;
        IpAddress  addr_;
        uint32_t    plen_;
        IpAddress  gw_;
        CommunityList communities_;
    };
    typedef std::set<StaticRoute, StaticRoute> StaticRouteSet;

    struct StaticRouteList {
        StaticRouteList() : list_() { }
        ~StaticRouteList() { }
        void Insert(const StaticRoute *rhs);
        void Update(const StaticRoute *lhs, const StaticRoute *rhs);
        void Remove(StaticRouteSet::iterator &it);

        StaticRouteSet list_;
    };

    struct AllowedAddressPair : ListEntry {
        AllowedAddressPair();
        AllowedAddressPair(const AllowedAddressPair &rhs);
        AllowedAddressPair(const std::string &vrf, const IpAddress &addr,
                           uint32_t plen, bool ecmp, const MacAddress &mac);
        virtual ~AllowedAddressPair();

        bool operator() (const AllowedAddressPair &lhs,
                         const AllowedAddressPair &rhs) const;
        bool IsLess(const AllowedAddressPair *rhs) const;
        void Activate(VmInterface *interface, bool force_update,
                      bool policy_change) const;
        void DeActivate(VmInterface *interface) const;
        void L2Activate(VmInterface *interface, bool force_update,
                        bool policy_change, bool old_layer2_forwarding,
                        bool old_layer3_forwarding) const;
        void L2DeActivate(VmInterface *interface) const;

        mutable std::string vrf_;
        IpAddress   addr_;
        uint32_t    plen_;
        bool        ecmp_;
        MacAddress  mac_;
        mutable bool        l2_entry_installed_;
        mutable uint32_t    ethernet_tag_;
        mutable VrfEntryRef vrf_ref_;
        mutable IpAddress  service_ip_;
    };
    typedef std::set<AllowedAddressPair, AllowedAddressPair>
        AllowedAddressPairSet;

    struct AllowedAddressPairList {
        AllowedAddressPairList() : list_() { }
        ~AllowedAddressPairList() { }
        void Insert(const AllowedAddressPair *rhs);
        void Update(const AllowedAddressPair *lhs,
                    const AllowedAddressPair *rhs);
        void Remove(AllowedAddressPairSet::iterator &it);

        AllowedAddressPairSet list_;
    };

    struct SecurityGroupEntry : ListEntry {
        SecurityGroupEntry();
        SecurityGroupEntry(const SecurityGroupEntry &rhs);
        SecurityGroupEntry(const boost::uuids::uuid &uuid);
        virtual ~SecurityGroupEntry();

        bool operator == (const SecurityGroupEntry &rhs) const;
        bool operator() (const SecurityGroupEntry &lhs,
                         const SecurityGroupEntry &rhs) const;
        bool IsLess(const SecurityGroupEntry *rhs) const;
        void Activate(VmInterface *interface) const;
        void DeActivate(VmInterface *interface) const;

        mutable SgEntryRef sg_;
        boost::uuids::uuid uuid_;
    };
    typedef std::set<SecurityGroupEntry, SecurityGroupEntry>
        SecurityGroupEntrySet;
    typedef std::vector<boost::uuids::uuid> SecurityGroupUuidList;

    struct SecurityGroupEntryList {
        SecurityGroupEntryList() : list_() { }
        ~SecurityGroupEntryList() { }

        void Insert(const SecurityGroupEntry *rhs);
        void Update(const SecurityGroupEntry *lhs,
                    const SecurityGroupEntry *rhs);
        void Remove(SecurityGroupEntrySet::iterator &it);

        SecurityGroupEntrySet list_;
    };

    struct VrfAssignRule : ListEntry {
        VrfAssignRule();
        VrfAssignRule(const VrfAssignRule &rhs);
        VrfAssignRule(uint32_t id,
                      const autogen::MatchConditionType &match_condition_,
                      const std::string &vrf_name, bool ignore_acl);
        ~VrfAssignRule();
        bool operator == (const VrfAssignRule &rhs) const;
        bool operator() (const VrfAssignRule &lhs,
                         const VrfAssignRule &rhs) const;
        bool IsLess(const VrfAssignRule *rhs) const;

        const uint32_t id_;
        const std::string vrf_name_;
        const VrfEntryRef vrf_;
        bool ignore_acl_;
        autogen::MatchConditionType match_condition_;
    };
    typedef std::set<VrfAssignRule, VrfAssignRule> VrfAssignRuleSet;

    struct VrfAssignRuleList {
        VrfAssignRuleList() : list_() { }
        ~VrfAssignRuleList() { };
        void Insert(const VrfAssignRule *rhs);
        void Update(const VrfAssignRule *lhs, const VrfAssignRule *rhs);
        void Remove(VrfAssignRuleSet::iterator &it);

        VrfAssignRuleSet list_;
    };

    struct InstanceIp : ListEntry {
        InstanceIp();
        InstanceIp(const InstanceIp &rhs);
        InstanceIp(const IpAddress &ip, bool ecmp, bool is_primary);
        ~InstanceIp();
        bool operator == (const InstanceIp &rhs) const;
        bool operator() (const InstanceIp &lhs,
                         const InstanceIp &rhs) const;
        bool IsLess(const InstanceIp *rhs) const;
        void L3Activate(VmInterface *interface, bool force_update) const;
        void L3DeActivate(VmInterface *interface, VrfEntry *old_vrf) const;
        void L2Activate(VmInterface *interface, bool force_update,
                        uint32_t old_ethernet_tag) const;
        void L2DeActivate(VmInterface *interface, VrfEntry *old_vrf,
                          uint32_t old_ethernet_tag) const;
        void DeActivate(VmInterface *interface, bool l2,
                        VrfEntry *old_vrf, uint32_t old_ethernet_tag) const;
        void Activate(VmInterface *interface, bool force_update, bool l2,
                      int old_ethernet_tag) const;
        bool installed() const {
            if (l2_installed_ || installed_) {
                return true;
            }
            return false;
        }

        const IpAddress ip_;
        mutable bool ecmp_;
        mutable bool l2_installed_;
        mutable bool old_ecmp_;
        mutable bool is_primary_;
    };
    typedef std::set<InstanceIp, InstanceIp> InstanceIpSet;

    struct InstanceIpList {
        InstanceIpList() : list_() { }
        ~InstanceIpList() { };
        void Insert(const InstanceIp *rhs);
        void Update(const InstanceIp *lhs, const InstanceIp *rhs);
        void Remove(InstanceIpSet::iterator &it);

        InstanceIpSet list_;
    };

    struct FatFlowEntry : ListEntry {
        FatFlowEntry(): protocol(0), port(0) {}
        FatFlowEntry(const FatFlowEntry &rhs):
            protocol(rhs.protocol), port(rhs.port) {}
        FatFlowEntry(const uint8_t proto, const uint16_t p):
            protocol(proto), port(p) {}
        virtual ~FatFlowEntry(){}
        bool operator == (const FatFlowEntry &rhs) const {
            return (rhs.protocol == protocol && rhs.port == port);
        }

        bool operator() (const FatFlowEntry  &lhs,
                         const FatFlowEntry &rhs) const {
            return lhs.IsLess(&rhs);
        }

        bool IsLess(const FatFlowEntry *rhs) const {
            if (protocol != rhs->protocol) {
                return protocol < rhs->protocol;
            }
            return port < rhs->port;
        }
        uint8_t protocol;
        uint16_t port;
    };
    typedef std::set<FatFlowEntry, FatFlowEntry> FatFlowEntrySet;

    struct FatFlowList {
        FatFlowList(): list_() {}
        ~FatFlowList() {}
        void Insert(const FatFlowEntry *rhs);
        void Update(const FatFlowEntry *lhs, const FatFlowEntry *rhs);
        void Remove(FatFlowEntrySet::iterator &it);

        FatFlowEntrySet list_;
    };

    enum Trace {
        ADD,
        DELETE,
        ACTIVATED_IPV4,
        ACTIVATED_IPV6,
        ACTIVATED_L2,
        DEACTIVATED_IPV4,
        DEACTIVATED_IPV6,
        DEACTIVATED_L2,
        FLOATING_IP_CHANGE,
        SERVICE_CHANGE,
    };

    enum Preference {
        INVALID = 0,
        LOW     = 100,
        HIGH    = 200
    };

    VmInterface(const boost::uuids::uuid &uuid);
    VmInterface(const boost::uuids::uuid &uuid, const std::string &name,
                const Ip4Address &addr, const std::string &mac,
                const std::string &vm_name,
                const boost::uuids::uuid &vm_project_uuid, uint16_t tx_vlan_id,
                uint16_t rx_vlan_id, Interface *parent,
                const Ip6Address &addr6, DeviceType dev_type, VmiType vmi_type);
    virtual ~VmInterface();

    virtual bool CmpInterface(const DBEntry &rhs) const;
    virtual void GetOsParams(Agent *agent);
    void SendTrace(const AgentDBTable *table, Trace event) const;

    // DBEntry vectors
    KeyPtr GetDBRequestKey() const;
    std::string ToString() const;
    bool Resync(const InterfaceTable *table, const VmInterfaceData *data);
    bool OnChange(VmInterfaceData *data);
    void PostAdd();

    // Accessor functions
    const VmEntry *vm() const { return vm_.get(); }
    const VnEntry *vn() const { return vn_.get(); }
    const MirrorEntry *mirror_entry() const { return mirror_entry_.get(); }
    const Ip4Address &primary_ip_addr() const { return primary_ip_addr_; }
    bool policy_enabled() const { return policy_enabled_; }
    const Ip4Address &subnet_bcast_addr() const { return subnet_bcast_addr_; }
    const Ip6Address &primary_ip6_addr() const { return primary_ip6_addr_; }
    const std::string &vm_mac() const { return vm_mac_; }
    bool fabric_port() const { return fabric_port_; }
    bool need_linklocal_ip() const { return  need_linklocal_ip_; }
    bool dhcp_enable_config() const { return dhcp_enable_; }
    void set_dhcp_enable_config(bool dhcp_enable) {
        dhcp_enable_= dhcp_enable;
    }
    bool do_dhcp_relay() const { return do_dhcp_relay_; }
    int vxlan_id() const { return vxlan_id_; }
    bool bridging() const { return bridging_; }
    bool layer3_forwarding() const { return layer3_forwarding_; }
    const std::string &vm_name() const { return vm_name_; }
    const boost::uuids::uuid &vm_project_uuid() const { return vm_project_uuid_; }
    const std::string &cfg_name() const { return cfg_name_; }
    Preference local_preference() const { return local_preference_; }
    uint16_t tx_vlan_id() const { return tx_vlan_id_; }
    uint16_t rx_vlan_id() const { return rx_vlan_id_; }
    const Interface *parent() const { return parent_.get(); }
    bool ecmp() const { return ecmp_;}
    bool ecmp6() const { return ecmp6_;}
    const OperDhcpOptions &oper_dhcp_options() const { return oper_dhcp_options_; }
    uint8_t configurer() const {return configurer_;}
    bool IsConfigurerSet(VmInterface::Configurer type);
    void SetConfigurer(VmInterface::Configurer type);
    void ResetConfigurer(VmInterface::Configurer type);
    bool CanBeDeleted() const {return (configurer_ == 0);}
    const Ip4Address& subnet() const { return subnet_;}
    const uint8_t subnet_plen() const { return subnet_plen_;}
    const MacAddress& GetVifMac(const Agent*) const;
    const boost::uuids::uuid &logical_interface() const {
        return logical_interface_;
    }
    bool flood_unknown_unicast() const {
        return flood_unknown_unicast_;
    }

    Interface::MirrorDirection mirror_direction() const {
        return mirror_direction_;
    }
    const FloatingIpList &floating_ip_list() const {
        return floating_ip_list_;
    }
    const ServiceVlanList &service_vlan_list() const {
        return service_vlan_list_;
    }

    const StaticRouteList &static_route_list() const {
        return static_route_list_;
    }

    const SecurityGroupEntryList &sg_list() const {
        return sg_list_;
    }

    const VrfAssignRuleList &vrf_assign_rule_list() const {
        return vrf_assign_rule_list_;
    }

    const AllowedAddressPairList &allowed_address_pair_list() const {
        return allowed_address_pair_list_;
    }

    const InstanceIpList &instance_ipv4_list() const {
        return instance_ipv4_list_;
    }

    const InstanceIpList &instance_ipv6_list() const {
        return instance_ipv6_list_;
    }

    const FatFlowList &fat_flow_list() const {
        return fat_flow_list_;
    }

    bool IsFatFlow(uint8_t protocol, uint16_t port) const;
    void set_vxlan_id(int vxlan_id) { vxlan_id_ = vxlan_id; }
    void set_subnet_bcast_addr(const Ip4Address &addr) {
        subnet_bcast_addr_ = addr;
    }
    void set_mirror_entry (MirrorEntry *mirror_entry) {
        mirror_entry_ = mirror_entry;
    }
    void set_mirror_direction(Interface::MirrorDirection mirror_direction) {
        mirror_direction_ = mirror_direction;
    }
    void set_primary_ip_addr(const Ip4Address &addr) { primary_ip_addr_ = addr; }

    const std::string GetAnalyzer() const;

    void SetPathPreference(PathPreference *pref, bool ecmp,
                           const IpAddress &dependent_ip) const;
    void CopySgIdList(SecurityGroupList *sg_id_list) const;
    bool NeedMplsLabel() const;
    bool IsVxlanMode() const;
    bool SgExists(const boost::uuids::uuid &id, const SgList &sg_l);
    bool IsMirrorEnabled() const { return mirror_entry_.get() != NULL; }
    bool HasFloatingIp(Address::Family family) const;
    bool HasFloatingIp() const;
    bool IsFloatingIp(const IpAddress &ip) const;
    Ip4Address mdata_ip_addr() const;
    MetaDataIp *GetMetaDataIp(const Ip4Address &ip) const;

    void InsertMetaDataIpInfo(MetaDataIp *mip);
    void DeleteMetaDataIpInfo(MetaDataIp *mip);
    void UpdateMetaDataIpInfo();

    void InsertHealthCheckInstance(HealthCheckInstance *hc_inst);
    void DeleteHealthCheckInstance(HealthCheckInstance *hc_inst);

    size_t GetFloatingIpCount() const { return floating_ip_list_.list_.size(); }
    bool HasServiceVlan() const { return service_vlan_list_.list_.size() != 0; }

    uint32_t GetServiceVlanLabel(const VrfEntry *vrf) const;
    uint32_t GetServiceVlanTag(const VrfEntry *vrf) const;
    const VrfEntry* GetServiceVlanVrf(uint16_t vlan_tag) const;
    bool Delete(const DBRequest *req);
    void Add();
    bool OnResyncServiceVlan(VmInterfaceConfigData *data);
    void UpdateAllRoutes();

    bool IsL2Active() const;
    bool IsIpv6Active() const;
    bool NeedDevice() const;
    VmInterface::DeviceType device_type() const {return device_type_;}
    VmInterface::VmiType vmi_type() const {return vmi_type_;}

    // Add a vm-interface
    static void NovaAdd(InterfaceTable *table,
                        const boost::uuids::uuid &intf_uuid,
                        const std::string &os_name, const Ip4Address &addr,
                        const std::string &mac, const std::string &vn_name,
                        const boost::uuids::uuid &vm_project_uuid,
                        uint16_t tx_vlan_id, uint16_t rx_vlan_id,
                        const std::string &parent, const Ip6Address &ipv6,
                        Interface::Transport transport);
    // Del a vm-interface
    static void Delete(InterfaceTable *table,
                       const boost::uuids::uuid &intf_uuid,
                       VmInterface::Configurer configurer);

    void AllocL2MplsLabel(bool force_update, bool policy_change);
    void DeleteL2MplsLabel();
    void UpdateL2(bool force_update);
    const AclDBEntry* vrf_assign_acl() const { return vrf_assign_acl_.get();}
    bool WaitForTraffic() const;
    bool GetInterfaceDhcpOptions(
            std::vector<autogen::DhcpOptionType> *options) const;
    bool GetSubnetDhcpOptions(
            std::vector<autogen::DhcpOptionType> *options, bool ipv6) const;
    bool GetIpamDhcpOptions(
            std::vector<autogen::DhcpOptionType> *options, bool ipv6) const;
    const Peer *peer() const;
    IpAddress GetServiceIp(const IpAddress &ip) const;
    void UpdateL2InterfaceRoute(bool old_l2_active, bool force_update,
                                VrfEntry *vrf,
                                const Ip4Address &old_addr,
                                const Ip6Address &old_v6_addr,
                                int ethernet_tag,
                                bool old_layer3_forwarding,
                                bool policy_change,
                                const Ip4Address &new_addr,
                                const Ip6Address &new_v6_addr,
                                const MacAddress &mac,
                                const IpAddress &dependent_ip) const;
    uint32_t ethernet_tag() const {return ethernet_tag_;}
    void UpdateVxLan();
    bool IsActive() const;
    const VmiEcmpLoadBalance &ecmp_load_balance() const {return ecmp_load_balance_;}
    Agent *agent() const {
        return (static_cast<InterfaceTable *>(get_table()))->agent();
    }

private:
    friend struct VmInterfaceConfigData;
    friend struct VmInterfaceNovaData;
    friend struct VmInterfaceIpAddressData;
    friend struct VmInterfaceOsOperStateData;
    friend struct VmInterfaceMirrorData;
    friend struct VmInterfaceGlobalVrouterData;
    friend struct VmInterfaceHealthCheckData;

    bool IsMetaDataIPActive() const;
    bool IsIpv4Active() const;
    bool PolicyEnabled() const;
    void AddRoute(const std::string &vrf_name, const IpAddress &ip,
                  uint32_t plen, const std::string &vn_name, bool policy,
                  bool ecmp, const IpAddress &service_ip,
                  const IpAddress &dependent_ip,
                  const CommunityList &communties);
    void DeleteRoute(const std::string &vrf_name, const IpAddress &ip,
                     uint32_t plen);
    void ResolveRoute(const std::string &vrf_name, const Ip4Address &addr,
                      uint32_t plen, const std::string &dest_vn, bool policy);
    void ServiceVlanAdd(ServiceVlan &entry);
    void ServiceVlanDel(ServiceVlan &entry);
    void ServiceVlanRouteAdd(const ServiceVlan &entry);
    void ServiceVlanRouteDel(const ServiceVlan &entry);

    bool OnResyncFloatingIp(VmInterfaceConfigData *data, bool new_ipv4_active);
    bool OnResyncSecurityGroupList(VmInterfaceConfigData *data,
                                   bool new_ipv4_active);
    bool OnResyncStaticRoute(VmInterfaceConfigData *data, bool new_ipv4_active);
    bool ResyncIpAddress(const VmInterfaceIpAddressData *data);
    bool ResyncOsOperState(const VmInterfaceOsOperStateData *data);
    bool ResyncConfig(VmInterfaceConfigData *data);
    bool CopyIpAddress(Ip4Address &addr);
    bool CopyIp6Address(const Ip6Address &addr);
    void ApplyMacVmBindingConfig(const VrfEntry *old_vrf,
                                bool old_l2_active,
                                bool old_dhcp_enable);
    void ApplyConfigCommon(const VrfEntry *old_vrf,
                           bool old_l2_active,
                           bool old_dhcp_enable);
    bool CopyConfig(const InterfaceTable *table,
                    const VmInterfaceConfigData *data, bool *sg_changed,
                    bool *ecmp_changed, bool *local_pref_changed,
                    bool *ecmp_load_balance_changed,
                    bool *static_route_config_changed);
    void ApplyConfig(bool old_ipv4_active,bool old_l2_active,  bool old_policy,
                     VrfEntry *old_vrf, const Ip4Address &old_addr,
                     int old_ethernet_tag, bool old_need_linklocal_ip,
                     bool old_ipv6_active, const Ip6Address &old_v6_addr,
                     const Ip4Address &old_subnet, const uint8_t old_subnet_plen,
                     bool old_dhcp_enable, bool old_layer3_forwarding,
                     bool force_update, const Ip4Address &old_dhcp_addr,
                     bool old_metadata_ip_active);
    void UpdateL3MetadataIp(VrfEntry *old_vrf, bool force_update,
                            bool policy_change, bool old_metadata_ip_active);
    void DeleteL3MetadataIp(VrfEntry *old_vrf, bool force_update,
                            bool policy_change, bool old_metadata_ip_active,
                            bool old_need_linklocal_ip);
    void UpdateL3(bool old_ipv4_active, VrfEntry *old_vrf,
                  const Ip4Address &old_addr, int old_ethernet_tag,
                  bool force_update, bool policy_change,
                  bool old_ipv6_active, const Ip6Address &old_v6_addr,
                  const Ip4Address &subnet, const uint8_t old_subnet_plen,
                  const Ip4Address &old_dhcp_addr);
    void DeleteL3(bool old_ipv4_active, VrfEntry *old_vrf,
                  const Ip4Address &old_addr, bool old_need_linklocal_ip,
                  bool old_ipv6_active, const Ip6Address &old_v6_addr,
                  const Ip4Address &old_subnet, const uint8_t old_subnet_plen,
                  int old_ethernet_tag, const Ip4Address &old_dhcp_addr);
    void UpdateL2(bool old_l2_active, VrfEntry *old_vrf, int old_ethernet_tag,
                  bool force_update, bool policy_change,
                  const Ip4Address &old_addr, const Ip6Address &old_v6_addr,
                  bool old_layer3_forwarding);
    void DeleteL2(bool old_l2_active, VrfEntry *old_vrf, int old_ethernet_tag,
                  const Ip4Address &old_addr, const Ip6Address &old_v6_addr,
                  bool old_layer3_forwarding);

    void AllocL3MplsLabel(bool force_update, bool policy_change);
    void DeleteL3MplsLabel();
    void UpdateL3TunnelId(bool force_update, bool policy_change);
    void DeleteL3TunnelId();
    void UpdateMulticastNextHop(bool old_ipv4_active, bool old_l2_active);
    void DeleteMulticastNextHop();
    void UpdateMacVmBinding();
    void UpdateL2NextHop(bool old_l2_active);
    void UpdateFlowKeyNextHop();
    void DeleteL2NextHop(bool old_l2_active);
    void DeleteMacVmBinding(const VrfEntry *old_vrf);
    bool L2Activated(bool old_l2_active);
    bool Ipv4Activated(bool old_ipv4_active);
    bool Ipv6Activated(bool old_ipv6_active);
    bool L2Deactivated(bool old_l2_active);
    bool Ipv4Deactivated(bool old_ipv4_active);
    bool Ipv6Deactivated(bool old_ipv6_active);
    void UpdateIpv4InterfaceRoute(bool old_ipv4_active, bool force_update,
                             bool policy_change, VrfEntry * old_vrf,
                             const Ip4Address &old_addr);
    void DeleteIpv4InterfaceRoute(VrfEntry *old_vrf,
                                  const Ip4Address &old_addr);
    void UpdateResolveRoute(bool old_ipv4_active, bool force_update,
                            bool policy_change, VrfEntry * old_vrf,
                            const Ip4Address &old_addr, uint8_t old_plen);
    void DeleteResolveRoute(VrfEntry *old_vrf,
                            const Ip4Address &old_addr, const uint8_t old_plen);
    void DeleteInterfaceNH();
    void UpdateMetadataRoute(bool old_ipv4_active, VrfEntry *old_vrf);
    void DeleteMetadataRoute(bool old_ipv4_active, VrfEntry *old_vrf,
                             bool old_need_linklocal_ip);
    void CleanupFloatingIpList();
    void UpdateFloatingIp(bool force_update, bool policy_change, bool l2,
                          uint32_t old_ethernet_tag);
    void DeleteFloatingIp(bool l2, uint32_t old_ethernet_tag);
    void UpdateServiceVlan(bool force_update, bool policy_change,
                           bool old_ipv4_active, bool old_ipv6_active);
    void DeleteServiceVlan();
    void UpdateStaticRoute(bool force_update, bool policy_change);
    void DeleteStaticRoute();
    void UpdateAllowedAddressPair(bool force_update, bool policy_change,
                                  bool l2, bool old_l2_forwarding,
                                  bool old_l3_forwarding);
    void DeleteAllowedAddressPair(bool l2);
    void UpdateSecurityGroup();
    void DeleteSecurityGroup();
    void UpdateFatFlow();
    void DeleteFatFlow();
    void UpdateL2TunnelId(bool force_update, bool policy_change);
    void DeleteL2TunnelId();
    void DeleteL2InterfaceRoute(bool old_l2_active, VrfEntry *old_vrf,
                                const Ip4Address &old_v4_addr,
                                const Ip6Address &old_v6_addr,
                                int old_ethernet_tag,
                                const MacAddress &mac) const;

    void DeleteL2Route(const std::string &vrf_name,
                       const MacAddress &mac);
    void UpdateVrfAssignRule();
    void DeleteVrfAssignRule();
    void UpdateIpv4InstanceIp(bool force_update, bool policy_change,
                              bool l2, uint32_t old_ethernet_tag);
    void DeleteIpv4InstanceIp(bool l2, uint32_t old_ethernet_tag,
                              VrfEntry *old_vrf);
    void UpdateIpv6InstanceIp(bool force_update, bool policy_change,
                              bool l2, uint32_t old_ethernet_tag);
    void DeleteIpv6InstanceIp(bool l2, uint32_t old_ethernet_tag,
                              VrfEntry *old_vrf);

    void AddL2ReceiveRoute(bool old_l2_active);
    void DeleteL2ReceiveRoute(const VrfEntry *old_vrf, bool old_l2_active);

    bool UpdateIsHealthCheckActive();
    void CopyEcmpLoadBalance(EcmpLoadBalance &ecmp_load_balance);

    VmEntryRef vm_;
    VnEntryRef vn_;
    Ip4Address primary_ip_addr_;
    std::auto_ptr<MetaDataIp> mdata_ip_;
    Ip4Address subnet_bcast_addr_;
    Ip6Address primary_ip6_addr_;
    std::string vm_mac_;
    bool policy_enabled_;
    MirrorEntryRef mirror_entry_;
    Interface::MirrorDirection mirror_direction_;
    std::string cfg_name_;
    bool fabric_port_;
    bool need_linklocal_ip_;
    // DHCP flag - set according to the dhcp option in the ifmap subnet object.
    // It controls whether the vrouter sends the DHCP requests from VM interface
    // to agent or if it would flood the request in the VN.
    bool dhcp_enable_;
    // true if IP is to be obtained from DHCP Relay and not learnt from fabric
    bool do_dhcp_relay_;
    // VM-Name. Used by DNS
    std::string vm_name_;
    // project uuid of the vm to which the interface belongs
    boost::uuids::uuid vm_project_uuid_;
    int vxlan_id_;
    bool bridging_;
    bool layer3_forwarding_;
    bool flood_unknown_unicast_;
    bool mac_set_;
    bool ecmp_;
    bool ecmp6_;
    // VLAN Tag and the parent interface when VLAN is enabled
    uint16_t tx_vlan_id_;
    uint16_t rx_vlan_id_;
    InterfaceRef parent_;
    Preference local_preference_;
    // DHCP options defined for the interface
    OperDhcpOptions oper_dhcp_options_;

    // Lists
    SecurityGroupEntryList sg_list_;
    FloatingIpList floating_ip_list_;
    ServiceVlanList service_vlan_list_;
    StaticRouteList static_route_list_;
    AllowedAddressPairList allowed_address_pair_list_;
    InstanceIpList instance_ipv4_list_;
    InstanceIpList instance_ipv6_list_;
    FatFlowList fat_flow_list_;

    // Peer for interface routes
    std::auto_ptr<LocalVmPortPeer> peer_;
    VrfAssignRuleList vrf_assign_rule_list_;
    AclDBEntryRef vrf_assign_acl_;
    Ip4Address vm_ip_service_addr_;
    VmInterface::DeviceType device_type_;
    VmInterface::VmiType vmi_type_;
    uint8_t configurer_;
    Ip4Address subnet_;
    uint8_t subnet_plen_;
    int ethernet_tag_;
    // Logical interface uuid to which the interface belongs
    boost::uuids::uuid logical_interface_;
    Ip4Address nova_ip_addr_;
    Ip6Address nova_ip6_addr_;
    Ip4Address dhcp_addr_;
    MetaDataIpMap metadata_ip_map_;
    HealthCheckInstanceSet hc_instance_set_;
    VmiEcmpLoadBalance ecmp_load_balance_;
    DISALLOW_COPY_AND_ASSIGN(VmInterface);
};

/////////////////////////////////////////////////////////////////////////////
// Key for VM Interfaces
/////////////////////////////////////////////////////////////////////////////
struct VmInterfaceKey : public InterfaceKey {
    VmInterfaceKey(AgentKey::DBSubOperation sub_op,
                   const boost::uuids::uuid &uuid, const std::string &name);
    virtual ~VmInterfaceKey() { }

    Interface *AllocEntry(const InterfaceTable *table) const;
    Interface *AllocEntry(const InterfaceTable *table,
                          const InterfaceData *data) const;
    InterfaceKey *Clone() const;
};

/////////////////////////////////////////////////////////////////////////////
// The base class for different type of InterfaceData used for VmInterfaces.
//
// Request for VM-Interface data are of 3 types
// - ADD_DEL_CHANGE
//   Message for ADD/DEL/CHANGE of an interface
// - MIRROR
//   Data for mirror enable/disable
// - IP_ADDR
//   In one of the modes, the IP address for an interface is not got from IFMap
//   or Nova. Agent will relay DHCP Request in such cases to IP Fabric network.
//   The IP address learnt with DHCP in this case is confgured with this type
// - OS_OPER_STATE
//   Update to oper state of the interface
/////////////////////////////////////////////////////////////////////////////
struct VmInterfaceData : public InterfaceData {
    enum Type {
        CONFIG,
        INSTANCE_MSG,
        MIRROR,
        IP_ADDR,
        OS_OPER_STATE,
        GLOBAL_VROUTER,
        HEALTH_CHECK
    };

    VmInterfaceData(Agent *agent, IFMapNode *node, Type type,
            Interface::Transport transport) :
        InterfaceData(agent, node, transport), type_(type) {
        VmPortInit();
    }
    virtual ~VmInterfaceData() { }

    virtual VmInterface *OnAdd(const InterfaceTable *table,
                               const VmInterfaceKey *key) const {
        return NULL;
    }
    virtual bool OnDelete(const InterfaceTable *table,
                          VmInterface *entry) const {
        return true;
    }
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const = 0;

    Type type_;
};

// Structure used when type=IP_ADDR. Used to update IP-Address of VM-Interface
// The IP Address is picked up from the DHCP Snoop table
struct VmInterfaceIpAddressData : public VmInterfaceData {
    VmInterfaceIpAddressData() : VmInterfaceData(NULL, NULL, IP_ADDR,
                                     Interface::TRANSPORT_INVALID) { }
    virtual ~VmInterfaceIpAddressData() { }
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;
};

// Structure used when type=OS_OPER_STATE Used to update interface os oper-state
// The current oper-state is got by querying the device
struct VmInterfaceOsOperStateData : public VmInterfaceData {
    VmInterfaceOsOperStateData() :
        VmInterfaceData(NULL, NULL, OS_OPER_STATE,
                        Interface::TRANSPORT_INVALID) { }
    virtual ~VmInterfaceOsOperStateData() { }
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;
};

// Structure used when type=MIRROR. Used to update IP-Address of VM-Interface
struct VmInterfaceMirrorData : public VmInterfaceData {
    VmInterfaceMirrorData(bool mirror_enable, const std::string &analyzer_name):
        VmInterfaceData(NULL, NULL, MIRROR, Interface::TRANSPORT_INVALID),
        mirror_enable_(mirror_enable),
        analyzer_name_(analyzer_name) {
    }
    virtual ~VmInterfaceMirrorData() { }
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;

    bool mirror_enable_;
    std::string analyzer_name_;
};

// Definition for structures when request queued from IFMap config.
struct VmInterfaceConfigData : public VmInterfaceData {
    VmInterfaceConfigData(Agent *agent, IFMapNode *node);
    virtual ~VmInterfaceConfigData() { }
    virtual VmInterface *OnAdd(const InterfaceTable *table,
                               const VmInterfaceKey *key) const;
    virtual bool OnDelete(const InterfaceTable *table,
                          VmInterface *entry) const;
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;

    Ip4Address addr_;
    Ip6Address ip6_addr_;
    std::string vm_mac_;
    std::string cfg_name_;
    boost::uuids::uuid vm_uuid_;
    std::string vm_name_;
    boost::uuids::uuid vn_uuid_;
    std::string vrf_name_;

    // Is this port on IP Fabric
    bool fabric_port_;
    // Does the port need link-local IP to be allocated
    bool need_linklocal_ip_;
    bool bridging_;
    bool layer3_forwarding_;
    bool mirror_enable_;
    //Is interface in active-active mode or active-backup mode
    bool ecmp_;
    bool ecmp6_;
    bool dhcp_enable_; // is DHCP enabled for the interface (from subnet config)
    bool admin_state_;
    std::string analyzer_name_;
    VmInterface::Preference local_preference_;
    OperDhcpOptions oper_dhcp_options_;
    Interface::MirrorDirection mirror_direction_;
    VmInterface::SecurityGroupEntryList sg_list_;
    VmInterface::FloatingIpList floating_ip_list_;
    VmInterface::ServiceVlanList service_vlan_list_;
    VmInterface::StaticRouteList static_route_list_;
    VmInterface::VrfAssignRuleList vrf_assign_rule_list_;
    VmInterface::AllowedAddressPairList allowed_address_pair_list_;
    VmInterface::InstanceIpList instance_ipv4_list_;
    VmInterface::InstanceIpList instance_ipv6_list_;
    VmInterface::FatFlowList fat_flow_list_;
    VmInterface::DeviceType device_type_;
    VmInterface::VmiType vmi_type_;
    // Parent physical-interface. Used in VMWare/ ToR logical-interface
    std::string physical_interface_;
    // Parent VMI. Set only for VM_VLAN_ON_VMI
    boost::uuids::uuid parent_vmi_;
    Ip4Address subnet_;
    uint8_t subnet_plen_;
    uint16_t rx_vlan_id_;
    uint16_t tx_vlan_id_;
    boost::uuids::uuid logical_interface_;
    VmiEcmpLoadBalance ecmp_load_balance_;
};

// Definition for structures when request queued from Nova
struct VmInterfaceNovaData : public VmInterfaceData {
    VmInterfaceNovaData();
    VmInterfaceNovaData(const Ip4Address &ipv4_addr,
                        const Ip6Address &ipv6_addr,
                        const std::string &mac_addr,
                        const std::string vm_name,
                        boost::uuids::uuid vm_uuid,
                        boost::uuids::uuid vm_project_uuid,
                        const std::string &parent,
                        uint16_t tx_vlan_id,
                        uint16_t rx_vlan_id,
                        VmInterface::DeviceType device_type,
                        VmInterface::VmiType vmi_type,
                        Interface::Transport transport);
    virtual ~VmInterfaceNovaData();
    virtual VmInterface *OnAdd(const InterfaceTable *table,
                               const VmInterfaceKey *key) const;
    virtual bool OnDelete(const InterfaceTable *table,
                          VmInterface *entry) const;
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;

    Ip4Address ipv4_addr_;
    Ip6Address ipv6_addr_;
    std::string mac_addr_;
    std::string vm_name_;
    boost::uuids::uuid vm_uuid_;
    boost::uuids::uuid vm_project_uuid_;
    std::string physical_interface_;
    uint16_t tx_vlan_id_;
    uint16_t rx_vlan_id_;
    VmInterface::DeviceType device_type_;
    VmInterface::VmiType vmi_type_;
};

struct VmInterfaceGlobalVrouterData : public VmInterfaceData {
    VmInterfaceGlobalVrouterData(bool bridging,
                                 bool layer3_forwarding,
                                 int vxlan_id) :
        VmInterfaceData(NULL, NULL, GLOBAL_VROUTER, Interface::TRANSPORT_INVALID),
        bridging_(bridging),
        layer3_forwarding_(layer3_forwarding),
        vxlan_id_(vxlan_id) {
    }
    virtual ~VmInterfaceGlobalVrouterData() { }
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;

    bool bridging_;
    bool layer3_forwarding_;
    int vxlan_id_;
};

struct VmInterfaceHealthCheckData : public VmInterfaceData {
    VmInterfaceHealthCheckData();
    virtual ~VmInterfaceHealthCheckData();
    virtual bool OnResync(const InterfaceTable *table, VmInterface *vmi,
                          bool *force_update) const;
};

#endif // vnsw_agent_vm_interface_hpp


text:
require 'rubygems'
require 'pathname'

root_path = Pathname(__FILE__).dirname.join('..').expand_path
lib_path  = root_path.join('lib')
$:.unshift(lib_path)

require 'adapter/postgres'

# say we are working inside of an existing Rails application
client = ActiveRecord::Base.connection.instance_variable_get("@connection")

# check and see if our table exists yet
table = client.exec("SELECT COUNT(relname) FROM pg_class WHERE relname='generic_hstore_table'").getvalue(0,0)
if table == 0
  # then create the table we want and seed it
  client.exec("CREATE TABLE generic_hstore_table (data hstore)")
  client.exec("INSERT INTO generic_hstore_table VALUES (''::hstore)")
end

# start the adapter
adapter = Adapter[:postgres].new(client)
adapter.clear

adapter['foo'] = 'bar'
puts 'Should be bar: ' + adapter['foo'].inspect

adapter.delete('foo')
puts 'Should be nil: ' + adapter['foo'].inspect

adapter['foo'] = 'bar'
adapter.clear
puts 'Should be nil: ' + adapter['foo'].inspect

puts 'Should be bar: ' + adapter.fetch('foo', 'bar')

redpajama_set_name: RedPajamaGithub


text:
#include "first.h"

#include "base.h"
#include "log.h"
#include "buffer.h"
#include "base64.h"

#include "plugin.h"

#include <stdlib.h>
#include <string.h>

#if defined HAVE_LIBSSL && defined HAVE_OPENSSL_SSL_H
#define USE_OPENSSL_CRYPTO
#endif

#ifdef USE_OPENSSL_CRYPTO
#include <openssl/evp.h>
#include <openssl/hmac.h>
#endif

#include "md5.h"

#define HASHLEN 16
typedef unsigned char HASH[HASHLEN];
#define HASHHEXLEN 32
typedef char HASHHEX[HASHHEXLEN+1];

/*
 * mod_secdownload verifies a checksum associated with a timestamp
 * and a path.
 *
 * It takes an URL of the form:
 *   securl := <uri-prefix> <mac> <protected-path>
 *   uri-prefix := '/' any*         # whatever was configured: must start with a '/')
 *   mac := [a-zA-Z0-9_-]{mac_len}  # mac length depends on selected algorithm
 *   protected-path := '/' <timestamp> <rel-path>
 *   timestamp := [a-f0-9]{8}       # timestamp when the checksum was calculated
 *                                  # to prevent access after timeout (active requests
 *                                  # will finish successfully even after the timeout)
 *   rel-path := '/' any*           # the protected path; changing the path breaks the
 *                                  # checksum
 *
 * The timestamp is the `epoch` timestamp in hex, i.e. time in seconds
 * since 00:00:00 UTC on 1 January 1970.
 *
 * mod_secdownload supports various MAC algorithms:
 *
 * # md5
 * mac_len := 32 (and hex only)
 * mac := md5-hex(<secrect><rel-path><timestamp>)   # lowercase hex
 * perl example:
    use Digest::MD5 qw(md5_hex);
    my $secret = "verysecret";
    my $rel_path = "/index.html"
    my $xtime = sprintf("%08x", time);
    my $url = '/'. md5_hex($secret . $rel_path . $xtime) . '/' . $xtime . $rel_path;
 *
 * # hmac-sha1
 * mac_len := 27  (no base64 padding)
 * mac := base64-url(hmac-sha1(<secret>, <protected-path>))
 * perl example:
    use Digest::SHA qw(hmac_sha1);
    use MIME::Base64 qw(encode_base64url);
    my $secret = "verysecret";
    my $rel_path = "/index.html"
    my $protected_path = '/' . sprintf("%08x", time) . $rel_path;
    my $url = '/'. encode_base64url(hmac_sha1($protected_path, $secret)) . $protected_path;
 *
 * # hmac-256
 * mac_len := 43  (no base64 padding)
 * mac := base64-url(hmac-256(<secret>, <protected-path>))
    use Digest::SHA qw(hmac_sha256);
    use MIME::Base64 qw(encode_base64url);
    my $secret = "verysecret";
    my $rel_path = "/index.html"
    my $protected_path = '/' . sprintf("%08x", time) . $rel_path;
    my $url = '/'. encode_base64url(hmac_sha256($protected_path, $secret)) . $protected_path;
 *
 */

/* plugin config for all request/connections */

typedef enum {
	SECDL_INVALID = 0,
	SECDL_MD5 = 1,
	SECDL_HMAC_SHA1 = 2,
	SECDL_HMAC_SHA256 = 3,
} secdl_algorithm;

typedef struct {
	buffer *doc_root;
	buffer *secret;
	buffer *uri_prefix;
	secdl_algorithm algorithm;

	unsigned int timeout;
	unsigned short path_segments;
	unsigned short hash_querystr;
} plugin_config;

typedef struct {
	PLUGIN_DATA;

	plugin_config **config_storage;

	plugin_config conf;
} plugin_data;

static int const_time_memeq(const char *a, const char *b, size_t len) {
	/* constant time memory compare, unless the compiler figures it out */
	char diff = 0;
	size_t i;
	for (i = 0; i < len; ++i) {
		diff |= (a[i] ^ b[i]);
	}
	return 0 == diff;
}

static const char* secdl_algorithm_names[] = {
	"invalid",
	"md5",
	"hmac-sha1",
	"hmac-sha256",
};

static secdl_algorithm algorithm_from_string(buffer *name) {
	size_t ndx;

	if (buffer_string_is_empty(name)) return SECDL_INVALID;

	for (ndx = 1; ndx < sizeof(secdl_algorithm_names)/sizeof(secdl_algorithm_names[0]); ++ndx) {
		if (0 == strcmp(secdl_algorithm_names[ndx], name->ptr)) return (secdl_algorithm)ndx;
	}

	return SECDL_INVALID;
}

static size_t secdl_algorithm_mac_length(secdl_algorithm alg) {
	switch (alg) {
	case SECDL_INVALID:
		break;
	case SECDL_MD5:
		return 32;
	case SECDL_HMAC_SHA1:
		return 27;
	case SECDL_HMAC_SHA256:
		return 43;
	}
	return 0;
}

static int secdl_verify_mac(server *srv, plugin_config *config, const char* protected_path, const char* mac, size_t maclen) {
	UNUSED(srv);
	if (0 == maclen || secdl_algorithm_mac_length(config->algorithm) != maclen) return 0;

	switch (config->algorithm) {
	case SECDL_INVALID:
		break;
	case SECDL_MD5:
		{
			li_MD5_CTX Md5Ctx;
			HASH HA1;
			char hexmd5[33];
			const char *ts_str;
			const char *rel_uri;

			/* legacy message:
			 *   protected_path := '/' <timestamp-hex> <rel-path>
			 *   timestamp-hex := [0-9a-f]{8}
			 *   rel-path := '/' any*
			 *   (the protected path was already verified)
			 * message = <secret><rel-path><timestamp-hex>
			 */
			ts_str = protected_path + 1;
			rel_uri = ts_str + 8;

			li_MD5_Init(&Md5Ctx);
			li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(config->secret));
			li_MD5_Update(&Md5Ctx, rel_uri, strlen(rel_uri));
			li_MD5_Update(&Md5Ctx, ts_str, 8);
			li_MD5_Final(HA1, &Md5Ctx);

			li_tohex(hexmd5, sizeof(hexmd5), (const char *)HA1, 16);

			return (32 == maclen) && const_time_memeq(mac, hexmd5, 32);
		}
	case SECDL_HMAC_SHA1:
#ifdef USE_OPENSSL_CRYPTO
		{
			unsigned char digest[20];
			char base64_digest[27];

			if (NULL == HMAC(
					EVP_sha1(),
					(unsigned char const*) CONST_BUF_LEN(config->secret),
					(unsigned char const*) protected_path, strlen(protected_path),
					digest, NULL)) {
				log_error_write(srv, __FILE__, __LINE__, "s",
					"hmac-sha1: HMAC() failed");
				return 0;
			}

			li_to_base64_no_padding(base64_digest, 27, digest, 20, BASE64_URL);

			return (27 == maclen) && const_time_memeq(mac, base64_digest, 27);
		}
#endif
		break;
	case SECDL_HMAC_SHA256:
#ifdef USE_OPENSSL_CRYPTO
		{
			unsigned char digest[32];
			char base64_digest[43];

			if (NULL == HMAC(
					EVP_sha256(),
					(unsigned char const*) CONST_BUF_LEN(config->secret),
					(unsigned char const*) protected_path, strlen(protected_path),
					digest, NULL)) {
				log_error_write(srv, __FILE__, __LINE__, "s",
					"hmac-sha256: HMAC() failed");
				return 0;
			}

			li_to_base64_no_padding(base64_digest, 43, digest, 32, BASE64_URL);

			return (43 == maclen) && const_time_memeq(mac, base64_digest, 43);
		}
#endif
		break;
	}

	return 0;
}

/* init the plugin data */
INIT_FUNC(mod_secdownload_init) {
	plugin_data *p;

	p = calloc(1, sizeof(*p));

	return p;
}

/* detroy the plugin data */
FREE_FUNC(mod_secdownload_free) {
	plugin_data *p = p_d;
	UNUSED(srv);

	if (!p) return HANDLER_GO_ON;

	if (p->config_storage) {
		size_t i;
		for (i = 0; i < srv->config_context->used; i++) {
			plugin_config *s = p->config_storage[i];

			if (NULL == s) continue;

			buffer_free(s->secret);
			buffer_free(s->doc_root);
			buffer_free(s->uri_prefix);

			free(s);
		}
		free(p->config_storage);
	}

	free(p);

	return HANDLER_GO_ON;
}

/* handle plugin config and check values */

SETDEFAULTS_FUNC(mod_secdownload_set_defaults) {
	plugin_data *p = p_d;
	size_t i = 0;

	config_values_t cv[] = {
		{ "secdownload.secret",        NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
		{ "secdownload.document-root", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
		{ "secdownload.uri-prefix",    NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
		{ "secdownload.timeout",       NULL, T_CONFIG_INT,    T_CONFIG_SCOPE_CONNECTION }, /* 3 */
		{ "secdownload.algorithm",     NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
		{ "secdownload.path-segments", NULL, T_CONFIG_SHORT,  T_CONFIG_SCOPE_CONNECTION }, /* 5 */
		{ "secdownload.hash-querystr", NULL, T_CONFIG_BOOLEAN,T_CONFIG_SCOPE_CONNECTION }, /* 6 */
		{ NULL,                        NULL, T_CONFIG_UNSET,  T_CONFIG_SCOPE_UNSET      }
	};

	if (!p) return HANDLER_ERROR;

	p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));

	for (i = 0; i < srv->config_context->used; i++) {
		data_config const* config = (data_config const*)srv->config_context->data[i];
		plugin_config *s;
		buffer *algorithm = buffer_init();

		s = calloc(1, sizeof(plugin_config));
		s->secret        = buffer_init();
		s->doc_root      = buffer_init();
		s->uri_prefix    = buffer_init();
		s->timeout       = 60;
		s->path_segments = 0;
		s->hash_querystr = 0;

		cv[0].destination = s->secret;
		cv[1].destination = s->doc_root;
		cv[2].destination = s->uri_prefix;
		cv[3].destination = &(s->timeout);
		cv[4].destination = algorithm;
		cv[5].destination = &(s->path_segments);
		cv[6].destination = &(s->hash_querystr);

		p->config_storage[i] = s;

		if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
			buffer_free(algorithm);
			return HANDLER_ERROR;
		}

		if (!buffer_is_empty(algorithm)) {
			s->algorithm = algorithm_from_string(algorithm);
			switch (s->algorithm) {
			case SECDL_INVALID:
				log_error_write(srv, __FILE__, __LINE__, "sb",
					"invalid secdownload.algorithm:",
					algorithm);
				buffer_free(algorithm);
				return HANDLER_ERROR;
#ifndef USE_OPENSSL_CRYPTO
			case SECDL_HMAC_SHA1:
			case SECDL_HMAC_SHA256:
				log_error_write(srv, __FILE__, __LINE__, "sb",
					"unsupported secdownload.algorithm:",
					algorithm);
#endif
			default:
				break;
			}
		}

		buffer_free(algorithm);
	}

	return HANDLER_GO_ON;
}

/**
 * checks if the supplied string is a hex string
 *
 * @param str a possible hex string
 * @return if the supplied string is a valid hex string 1 is returned otherwise 0
 */

static int is_hex_len(const char *str, size_t len) {
	size_t i;

	if (NULL == str) return 0;

	for (i = 0; i < len && *str; i++, str++) {
		/* illegal characters */
		if (!((*str >= '0' && *str <= '9') ||
		      (*str >= 'a' && *str <= 'f') ||
		      (*str >= 'A' && *str <= 'F'))
		    ) {
			return 0;
		}
	}

	return i == len;
}

/**
 * checks if the supplied string is a base64 (modified URL) string
 *
 * @param str a possible base64 (modified URL) string
 * @return if the supplied string is a valid base64 (modified URL) string 1 is returned otherwise 0
 */

static int is_base64_len(const char *str, size_t len) {
	size_t i;

	if (NULL == str) return 0;

	for (i = 0; i < len && *str; i++, str++) {
		/* illegal characters */
		if (!((*str >= '0' && *str <= '9') ||
		      (*str >= 'a' && *str <= 'z') ||
		      (*str >= 'A' && *str <= 'Z') ||
		      (*str == '-') || (*str == '_'))
		    ) {
			return 0;
		}
	}

	return i == len;
}

#define PATCH(x) \
	p->conf.x = s->x;
static int mod_secdownload_patch_connection(server *srv, connection *con, plugin_data *p) {
	size_t i, j;
	plugin_config *s = p->config_storage[0];

	PATCH(secret);
	PATCH(doc_root);
	PATCH(uri_prefix);
	PATCH(timeout);
	PATCH(algorithm);
	PATCH(path_segments);
	PATCH(hash_querystr);

	/* skip the first, the global context */
	for (i = 1; i < srv->config_context->used; i++) {
		data_config *dc = (data_config *)srv->config_context->data[i];
		s = p->config_storage[i];

		/* condition didn't match */
		if (!config_check_cond(srv, con, dc)) continue;

		/* merge config */
		for (j = 0; j < dc->value->used; j++) {
			data_unset *du = dc->value->data[j];

			if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.secret"))) {
				PATCH(secret);
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.document-root"))) {
				PATCH(doc_root);
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.uri-prefix"))) {
				PATCH(uri_prefix);
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.timeout"))) {
				PATCH(timeout);
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.algorithm"))) {
				PATCH(algorithm);
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.path-segments"))) {
				PATCH(path_segments);
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.hash-querystr"))) {
				PATCH(hash_querystr);
			}
		}
	}

	return 0;
}
#undef PATCH

URIHANDLER_FUNC(mod_secdownload_uri_handler) {
	plugin_data *p = p_d;
	const char *rel_uri, *ts_str, *mac_str, *protected_path;
	time_t ts = 0;
	size_t i, mac_len;

	if (con->mode != DIRECT) return HANDLER_GO_ON;

	if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON;

	mod_secdownload_patch_connection(srv, con, p);

	if (buffer_string_is_empty(p->conf.uri_prefix)) return HANDLER_GO_ON;

	if (buffer_string_is_empty(p->conf.secret)) {
		log_error_write(srv, __FILE__, __LINE__, "s",
				"secdownload.secret has to be set");
		con->http_status = 500;
		return HANDLER_FINISHED;
	}

	if (buffer_string_is_empty(p->conf.doc_root)) {
		log_error_write(srv, __FILE__, __LINE__, "s",
				"secdownload.document-root has to be set");
		con->http_status = 500;
		return HANDLER_FINISHED;
	}

	if (SECDL_INVALID == p->conf.algorithm) {
		log_error_write(srv, __FILE__, __LINE__, "s",
				"secdownload.algorithm has to be set");
		con->http_status = 500;
		return HANDLER_FINISHED;
	}

	mac_len = secdl_algorithm_mac_length(p->conf.algorithm);

	if (0 != strncmp(con->uri.path->ptr, p->conf.uri_prefix->ptr, buffer_string_length(p->conf.uri_prefix))) return HANDLER_GO_ON;

	mac_str = con->uri.path->ptr + buffer_string_length(p->conf.uri_prefix);

	if (!is_base64_len(mac_str, mac_len)) return HANDLER_GO_ON;

	protected_path = mac_str + mac_len;
	if (*protected_path != '/') return HANDLER_GO_ON;

	ts_str = protected_path + 1;
	if (!is_hex_len(ts_str, 8)) return HANDLER_GO_ON;
	if (*(ts_str + 8) != '/') return HANDLER_GO_ON;

	for (i = 0; i < 8; i++) {
		ts = (ts << 4) + hex2int(ts_str[i]);
	}

	/* timed-out */
	if ( (srv->cur_ts > ts && (unsigned int) (srv->cur_ts - ts) > p->conf.timeout) ||
	     (srv->cur_ts < ts && (unsigned int) (ts - srv->cur_ts) > p->conf.timeout) ) {
		/* "Gone" as the url will never be valid again instead of "408 - Timeout" where the request may be repeated */
		con->http_status = 410;

		return HANDLER_FINISHED;
	}

	rel_uri = ts_str + 8;

	if (p->conf.path_segments) {
		const char *rel_uri_end = rel_uri;
		unsigned int count = p->conf.path_segments;
		do {
			rel_uri_end = strchr(rel_uri_end+1, '/');
		} while (rel_uri_end && --count);
		if (rel_uri_end) {
			buffer_copy_string_len(srv->tmp_buf, protected_path,
					       rel_uri_end - protected_path);
			protected_path = srv->tmp_buf->ptr;
		}
	}

	if (p->conf.hash_querystr && !buffer_is_empty(con->uri.query)) {
		buffer *b = srv->tmp_buf;
		if (protected_path != b->ptr) {
			buffer_copy_string(b, protected_path);
		}
		buffer_append_string_len(b, CONST_STR_LEN("?"));
		buffer_append_string_buffer(b, con->uri.query);
		/* assign last in case b->ptr is reallocated */
		protected_path = b->ptr;
	}

	if (!secdl_verify_mac(srv, &p->conf, protected_path, mac_str, mac_len)) {
		con->http_status = 403;

		if (con->conf.log_request_handling) {
			log_error_write(srv, __FILE__, __LINE__, "sb",
				"mac invalid:",
				con->uri.path);
		}

		return HANDLER_FINISHED;
	}

	/* starting with the last / we should have relative-path to the docroot
	 */

	buffer_copy_buffer(con->physical.doc_root, p->conf.doc_root);
	buffer_copy_buffer(con->physical.basedir, p->conf.doc_root);
	buffer_copy_string(con->physical.rel_path, rel_uri);
	buffer_copy_buffer(con->physical.path, con->physical.doc_root);
	buffer_append_string_buffer(con->physical.path, con->physical.rel_path);

	return HANDLER_GO_ON;
}

/* this function is called at dlopen() time and inits the callbacks */

int mod_secdownload_plugin_init(plugin *p);
int mod_secdownload_plugin_init(plugin *p) {
	p->version     = LIGHTTPD_VERSION_ID;
	p->name        = buffer_init_string("secdownload");

	p->init        = mod_secdownload_init;
	p->handle_physical  = mod_secdownload_uri_handler;
	p->set_defaults  = mod_secdownload_set_defaults;
	p->cleanup     = mod_secdownload_free;

	p->data        = NULL;

	return 0;
}


text:
package com.github.nisrulz.sensey;

import static android.hardware.Sensor.TYPE_ACCELEROMETER;

import android.hardware.SensorEvent;

public class ChopDetector extends SensorDetector {

    public interface ChopListener {

        void onChop();
    }

    private final ChopListener chopListener;

    private boolean isGestureInProgress = false;

    private long lastTimeChopDetected = System.currentTimeMillis();

    private final float threshold;

    private final long timeForChopGesture;

    public ChopDetector(ChopListener chopListener) {
        this(35f, 700, chopListener);
    }

    public ChopDetector(float threshold, long timeForChopGesture, ChopListener chopListener) {
        super(TYPE_ACCELEROMETER);
        this.chopListener = chopListener;
        this.threshold = threshold;
        this.timeForChopGesture = timeForChopGesture;
    }

    @Override
    protected void onSensorEvent(SensorEvent sensorEvent) {
        float x = sensorEvent.values[0];
        float y = sensorEvent.values[1];
        float z = sensorEvent.values[2];

        // Make this higher or lower according to how much
        // motion you want to detect
        if (x > threshold && y < (-threshold) && z > threshold) {
            lastTimeChopDetected = System.currentTimeMillis();
            isGestureInProgress = true;
        } else {
            long timeDelta = (System.currentTimeMillis() - lastTimeChopDetected);
            if (timeDelta > timeForChopGesture && isGestureInProgress) {
                isGestureInProgress = false;
                chopListener.onChop();
            }
        }
    }
}


text:
pyseqlogo : A versatile sequence logo plotter

Website: https://www.saket-choudhary.me/pyseqlogo/
License: MIT

Sequence logos have long been used to visualize conservation of nucleotides and amino acids in Bioinformatics and


text:
package org.yaz4j;

import org.yaz4j.jni.SWIGTYPE_p_ZOOM_options_p;
import org.yaz4j.jni.SWIGTYPE_p_ZOOM_package_p;
import org.yaz4j.jni.yaz4jlib;

/**
 * Offers an interface to a subset of the Z39.50 extended services as well as a
 * few privately defined ones. E.g, Z59.50 ILL, record update, database drop,
 * create, commit.
 *
 * @see ZOOM Extended Services
 *
 * @author jakub
 */
public class ConnectionExtended extends Connection {

  public ConnectionExtended(String host, int port) {
    super(host, port);
  }

  /**
   * Creates an extended-services package for the connection.
   * @param type type of package (operation)
   * @return
   */
  public Package getPackage(String type) {
    if (closed) {
      throw new IllegalStateException("Connection is closed.");
    }
    Package pack = null;
    SWIGTYPE_p_ZOOM_options_p options = yaz4jlib.ZOOM_options_create();
    SWIGTYPE_p_ZOOM_package_p yazPackage = yaz4jlib.ZOOM_connection_package(
      zoomConnection, options);
    pack = new Package(yazPackage, this, type);
    return pack;
  }
}


text:
#import "NSObject.h"

@class NSArray, NSString;

@interface MKSearchCompleter : NSObject
{
    NSString *_fragment;
    CDStruct_feeb6407 _boundingRegion;
    id <MKSearchCompleterDelegate> _delegate;
    id _context;
    NSString *_identifier;
    long long _entriesType;
    long long _listType;
    double _timeSinceLastInBoundingRegion;
}

+ (id)alloc;
@property(nonatomic) double timeSinceLastInBoundingRegion; // @synthesize timeSinceLastInBoundingRegion=_timeSinceLastInBoundingRegion;
@property(nonatomic) long long listType; // @synthesize listType=_listType;
@property(nonatomic) long long entriesType; // @synthesize entriesType=_entriesType;
@property(copy, nonatomic) NSString *identifier; // @synthesize identifier=_identifier;
@property(nonatomic) id context; // @synthesize context=_context;
@property(nonatomic) id <MKSearchCompleterDelegate> delegate; // @synthesize delegate=_delegate;
@property(nonatomic) CDStruct_90e2a262 boundingRegion; // @synthesize boundingRegion=_boundingRegion;
@property(copy, nonatomic) NSString *fragment; // @synthesize fragment=_fragment;
@property(readonly, nonatomic) NSArray *results;
- (void)retry;
- (void)cancel;
- (_Bool)isSearching;
- (_Bool)resultsAreCurrent;
- (void)dealloc;
- (id)init;

@end


text:
package main

import (
	"encoding/xml"
	"fmt"
	"os/exec"
	"strings"
)

type Executable struct {
	Title            string           `xml:"title"`
	Description      string           `xml:"description"`
	Version          string           `xml:"version"`
	DocumentationURL string           `xml:"documentation-url"`
	License          string           `xml:"license"`
	Contributor      string           `xml:"contributor"`
	Acknowledgements string           `xml:"acknowledgements"`
	ParameterGroups  []ParameterGroup `xml:"parameters"`
}

type ParameterGroup struct {
	Parameters []Parameter `xml:",any"`
}

type Parameter struct {
	Name        string `xml:"name"`
	Longflag    string `xml:"longflag"`
	Flag        string `xml:"flag"`
	Description string `xml:"description"`
	Default     string `xml:"default"`
	Index       int    `xml:"index"`
	Channel     string `xml:"channel"`
}

// Run the executable at path, and return a service
func CreateService(path string) (*Service, error) {
	out, err := exec.Command(path, "--xml").Output()
	if err != nil {
		return nil, fmt.Errorf("failed to execute %v: %v", path, err.Error())
	}

	return CreateServiceFromXML(path, string(out))
}

func CreateServiceFromXML(path string, out string) (*Service, error) {

	var executable Executable
	parser := xml.NewDecoder(strings.NewReader(out))
	err := parser.Decode(&executable)
	if err != nil {
		return nil, fmt.Errorf("failed to parse %v", err.Error())
	}

	service := NewService()

	service.Description = executable.Description

	positional := make([]string, 20, 20)

	// Parse all the arguments
	for _, group := range executable.ParameterGroups {
		for _, p := range group.Parameters {

			// Not valid
			if p.Name == "" {
				continue
			}

			// Positional argument
			if p.Longflag == "" && p.Flag == "" {
				n := p.Name
				if p.Channel == "input" {
					n = "<" + n
				}
				if p.Channel == "output" {
					n = ">" + n
				}
				if p.Default != "" {
					service.Defaults[n] = p.Default
				}
				positional[p.Index] = n
			} else {
				// Flag
				n := "#" + p.Name
				if p.Channel == "output" {
					n = ">" + p.Name
				}
				if p.Channel == "input" {
					n = "<" + p.Name
				}
				f := ""
				if p.Longflag != "" {
					// Sometimes, the "--" is left on long flags...
					p.Longflag = strings.TrimPrefix(p.Longflag, "--")
					f = "--" + p.Longflag
				}
				if p.Flag != "" {
					// Sometimes, the "-" is left on flags...
					p.Flag = strings.TrimPrefix(p.Flag, "-")
					f = "-" + p.Flag
				}
				if p.Default != "" {
					service.Defaults[p.Name] = p.Default
				}
				service.CommandLine = append(service.CommandLine, f, n)
			}
		}
	}

	// Prepend the path, append the positional arguments
	service.CommandLine = append([]string{path}, service.CommandLine...)
	for _, arg := range positional {
		if arg != "" {
			service.CommandLine = append(service.CommandLine, arg)
		}
	}

	service.setup()
	return service, nil
}


text:
use std::collections::HashMap;

fn check_thing(analysis: &HashMap<String, u32>,
               thing: &str,
               count: u32,
               part: u32)
               -> bool {
    let real_count = analysis.get(thing).unwrap();
    if part == 2 && (thing == "cats:" || thing == "trees:") {
        &count > real_count
    } else if part == 2 && (thing == "pomeranians:" || thing == "goldfish:") {
        &count < real_count
    } else {
        &count == real_count
    }
}

fn process_part(analysis: &HashMap<String, u32>, path: &str, part: u32) {
    use std::fs::File;
    use std::io::prelude::*;
    use std::io::BufReader;

    let file = File::open(path).unwrap();
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        let words: Vec<_> = line.split(" ").collect();

        let thing = words[2].to_owned();
        let count = words[3].trim_matches(',').parse::<u32>().unwrap();
        if !check_thing(&analysis, &thing, count, part) {
            continue;
        }

        let thing = words[4].to_owned();
        let count = words[5].trim_matches(',').parse::<u32>().unwrap();
        if !check_thing(&analysis, &thing, count, part) {
            continue;
        }

        let thing = words[6].to_owned();
        let count = words[7].trim_matches(',').parse::<u32>().unwrap();
        if !check_thing(&analysis, &thing, count, part) {
            continue;
        }

        println!("Part {}: {}", part, words[1].trim_matches(':').to_owned());
        break;
    }

}

pub fn process_file(path: &str) {
    let mut analysis: HashMap<String, u32> = HashMap::new();
    analysis.insert("children:".to_owned(), 3);
    analysis.insert("cats:".to_owned(), 7);
    analysis.insert("samoyeds:".to_owned(), 2);
    analysis.insert("pomeranians:".to_owned(), 3);
    analysis.insert("akitas:".to_owned(), 0);
    analysis.insert("vizslas:".to_owned(), 0);
    analysis.insert("goldfish:".to_owned(), 5);
    analysis.insert("trees:".to_owned(), 3);
    analysis.insert("cars:".to_owned(), 2);
    analysis.insert("perfumes:".to_owned(), 1);

    process_part(&analysis, path, 1);
    process_part(&analysis, path, 2);
}


text:
package com.dci.intellij.dbn.execution.statement.options;

import com.dci.intellij.dbn.common.options.Configuration;
import com.dci.intellij.dbn.common.options.setting.SettingsUtil;
import com.dci.intellij.dbn.common.options.ui.ConfigurationEditorForm;
import com.dci.intellij.dbn.execution.statement.options.ui.StatementExecutionSettingsForm;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;

public class StatementExecutionSettings extends Configuration{
    private int resultSetFetchBlockSize = 100;
    private int executionTimeout = 20;
    private boolean focusResult = false;

    public String getDisplayName() {
        return "Data editor general settings";
    }

    public String getHelpTopic() {
        return "executionEngine";
    }

    /*********************************************************
    *                       Settings                        *
    *********************************************************/

    public int getResultSetFetchBlockSize() {
        return resultSetFetchBlockSize;
    }

    public void setResultSetFetchBlockSize(int resultSetFetchBlockSize) {
        this.resultSetFetchBlockSize = resultSetFetchBlockSize;
    }

    public int getExecutionTimeout() {
        return executionTimeout;
    }

    public void setExecutionTimeout(int executionTimeout) {
        this.executionTimeout = executionTimeout;
    }

    public void setFocusResult(boolean focusResult) {
        this.focusResult = focusResult;
    }

    public boolean isFocusResult() {
        return focusResult;
    }

    /****************************************************
     *                   Configuration                  *
     ****************************************************/
    public ConfigurationEditorForm createConfigurationEditor() {
        return new StatementExecutionSettingsForm(this);
    }

    @Override
    public String getConfigElementName() {
        return "statement-execution";
    }

    public void readConfiguration(Element element) throws InvalidDataException {
        resultSetFetchBlockSize = SettingsUtil.getInteger(element, "fetch-block-size", resultSetFetchBlockSize);
        executionTimeout = SettingsUtil.getInteger(element, "execution-timeout", executionTimeout);
        focusResult = SettingsUtil.getBoolean(element, "focus-result", focusResult);

    }

    public void writeConfiguration(Element element) throws WriteExternalException {
        SettingsUtil.setInteger(element, "fetch-block-size", resultSetFetchBlockSize);
        SettingsUtil.setInteger(element, "execution-timeout", executionTimeout);
        SettingsUtil.setBoolean(element, "focus-result", focusResult);
    }
}


text:
gradle-opencover-plugin [![Build status](https://ci.appveyor.com/api/projects/status/chcaikhiapb4mmn2?svg=true)](https://ci.appveyor.com/project/gluck/gradle-opencover-plugin) [![Build Status](https://travis-ci.org/Ullink/gradle-opencover-plugin.svg?branch=master)](https://travis-ci.org/Ullink/gradle-opencover-plugin) [![GitHub license](https://img.shields.io/github/license/Ullink/gradle-opencover-plugin.svg)](http://www.apache.org/licenses/LICENSE-2.0)
=======================

A gradle plugin for getting test coverage using OpenCover

# opencover plugin

A base plugin 'com.ullink.opencover' is provided. It will sets up a task named 'opencover' that when called will execute
the OpenCover.exe file of the associated OpenCover version. That task may be configured:

    opencover {
        // optional - defaults to '4.6.166'
        openCoverVersion
        // optional - defaults to OPENCOVER_HOME env variable if set or to a downloaded opencover home corresponding to
        // the specified openCoverVersion
        openCoverHome
        // mandatory - specifies the test runner executable path (ie 'nunit-console.exe')
        targetExec
        // mandatory - specifies the test runner arguments (associated 'nunit-console.exe' parameters)
        targetExecArgs
        // mandatory - assemblies to obtain test coverage for
        targetAssemblies
        // optional - defaults to TRUE. OpenCover will return the return code of the test runner executable.
        returnTargetCode
        // optional - defaults to FALSE. Determines the behavior of the task if OpenCover's return code is abnormal
        ignoreFailures
        // optional - defaults to user. Specifies opencover's profile register mode (user, path32, path64, null). More details in https://github.com/OpenCover/opencover/wiki/Usage
        registerMode
    }

#opencover-nunit plugin

An NUnit ready plugin is also provided: 'com.ullink.opencover-nunit'. It relies on the gradle-nunit-plugin 'nunit' task to
configure the 'opencover' task. Using it, provided the default values suit you, the only setup you'll need is

    opencover {
        targetAssemblies = ...
    }

# License

All these plugins are licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) with no warranty (expressed or implied) for any purpose.


text:
package com.almasb.java.framework.demo;

import java.io.IOException;

import com.almasb.common.net.ClientPacketParser;
import com.almasb.common.net.DataPacket;
import com.almasb.common.net.UDPServer;

/**
 * @author Almas Baimagambetov
 * @version 1.0
 *
 */
public class SayMacDemo {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        final Runtime rt = Runtime.getRuntime();

        @SuppressWarnings("unused")
        UDPServer server = new UDPServer(55555, new ClientPacketParser() {

            @Override
            public void parseClientPacket(DataPacket packet) {

                try {
                    rt.exec("say " + packet.stringData);
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
    }

}


text:
module Cellect
  module Server
    module Adapters
      module PanoptesAssociation
        class Workflow < ActiveRecord::Base
          has_many :subject_sets_workflows
          has_many :subject_sets, through: :subject_sets_workflows
        end

        class SubjectSetsWorkflow < ActiveRecord::Base
          belongs_to :workflow
          belongs_to :subject_set
        end

        class SubjectSet < ActiveRecord::Base
          has_many :subject_sets_workflows
          has_many :workflows, through: :subject_sets_workflows
          has_many :set_member_subjects
          has_many :subjects, through: :set_member_subjects
        end

        class SetMemberSubject < ActiveRecord::Base
          belongs_to :subject_set
          belongs_to :subject
          has_many :workflows, through: :subject_set
        end

        class UserSeenSubject < ActiveRecord::Base
        end

        class SubjectWorkflowCount < ActiveRecord::Base
          belongs_to :subject
          belongs_to :workflow

          def self.sanitized_workflow_join(workflow_id)
            sanitize_sql_for_conditions(
              ['subject_workflow_counts.workflow_id = ?', workflow_id]
            )
          end
        end
      end

      class Panoptes < Default
        def status
          { connected: ActiveRecord::Base.connected? }
        end

        def workflow_list(*names)
          with_connection do
            workflow_data = PanoptesAssociation::Workflow
              .select(:id, :prioritized, :pairwise, :grouped)
              .where(id: names)

            [].tap do |rows|
              workflow_data.find_each do |w|
                rows << {
                  'id' => w.id,
                  'name' => "#{w.id}",
                  'prioritized' => w.prioritized,
                  'pairwise' => w.pairwise,
                  'grouped' => w.grouped
                }
              end
            end
          end
        end

        def load_data_for(workflow_id)
          with_connection do
            subject_data_scope = PanoptesAssociation::SetMemberSubject
              .joins(:workflows)
              .where(workflows: {id: workflow_id})
              .joins(
                "LEFT OUTER JOIN subject_workflow_counts " \
                "ON subject_workflow_counts.subject_id = set_member_subjects.subject_id " \
                "AND #{PanoptesAssociation::SubjectWorkflowCount.sanitized_workflow_join(workflow_id)}"
              )
              .where('subject_workflow_counts.retired_at IS NULL')
              .select(:id, :subject_id, :priority, :subject_set_id)

            subject_data_scope.find_each do |s|
              row = {
                'id' => s.subject_id,
                'priority' => 1 / (s.priority || 1).to_f,
                'group_id' => s.subject_set_id
              }
              yield row
            end
          end
        end

        def load_user(workflow_name, user_id)
          with_connection do
            subject_ids = PanoptesAssociation::UserSeenSubject
              .where(workflow_id: workflow_name, user_id: user_id)
              .pluck(:subject_ids)
            subject_ids.flatten!
          end
        end

        def with_connection(&block)
          ActiveRecord::Base.connection_pool.with_connection &block
        end
      end
    end
  end
end


text:
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_COPYS.S01_CopyIntoItems.MSCOPYS_S01_TC10_CopyIntoItems_malformedIRI /testcontainer:..\..\MS-COPYS\TestSuite\bin\Debug\MS-COPYS_TestSuite.dll /runconfig:..\..\MS-COPYS\MS-COPYS.testsettings /unique
pause


text:
import React, { Component } from 'react';
import centerLogo from 'images/icons/Medal-Icon.svg';
import { Link } from 'react-router-dom';
import SocialMedia from 'shared/components/socialMedia/socialMedia';
import styles from './footer.css';

class Footer extends Component {
  render() {
    return (

              contact@operationcode.org

            <SocialMedia />

              <Link to="about">About Us</Link>
              <Link to="programs">Our Programs</Link>
              <Link to="involved">Our Partners</Link>

              <Link to="involved">Get Involved</Link>
              <Link to="blog">Blog</Link>
              <Link to="contact">Contact</Link>

          Please note that this website is managed by Operation Code.
          The content of this website is solely the responsibility of
          Operation Code.

          Copyright 2017 Operation Code

    );
  }
}

export default Footer;


text:
/**
 * Checks if the input is a function
 * @param  {*} v
 * @return {Boolean}
 */
module.exports = function (v) {
    return typeof v === 'function';
};


text:
import unittest, sys, time
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i, h2o_common, h2o_print, h2o_glm, h2o_jobs as h2j, h2o_gbm

print "Assumes you ran ../../cloud.py in this directory"
print "Using h2o-nodes.json. Also the sandbox dir"

print "Uses 0xcust.. data. Cloud must be built as 0xcust.. and run with access to 0xdata /mnt automounts"
print "Assume there are links in /home/0xcust.. to the nas bucket used"
print "i.e. /home/0xcust... should have results of 'ln -s /mnt/0xcustomer-datasets"
print "The path resolver in python tests will find it in the home dir of the username being used"
print "to run h2o..i.e from the config json which builds the cloud and passes that info to the test"
print "via the cloned cloud mechanism (h2o-nodes.json)"

DO_PREDICT_CM = False
class releaseTest(h2o_common.ReleaseCommon, unittest.TestCase):

    def test_c10_rel_gbm(self):
        print "not necessarily run as user=0xcust..., can't use a  schema='put' here"
        print "Want to be able to run python as jenkins"
        print "I guess for big 0xcust files, we don't need schema='put'"
        print "For files that we want to put (for testing put), we can get non-private files"

        # Parse Test***********************************************************
        importFolderPath = '/mnt/0xcustomer-datasets/c3'
        testFilename = 'classification1Test.txt'
        testPathname = importFolderPath + "/" + testFilename

        start = time.time()
        parseTestResult = h2i.import_parse(path=testPathname, schema='local', timeoutSecs=500, doSummary=True)
        print "Parse of", parseTestResult['destination_key'], "took", time.time() - start, "seconds"

        # Parse Train***********************************************************
        importFolderPath = '/mnt/0xcustomer-datasets/c3'
        trainFilename = 'classification1Train.txt'
        trainPathname = importFolderPath + "/" + trainFilename

        start = time.time()
        parseTrainResult = h2i.import_parse(path=trainPathname, schema='local',
            timeoutSecs=500, doSummary=True)
        print "Parse of", parseTrainResult['destination_key'], "took", time.time() - start, "seconds"

        start = time.time()
        inspect = h2o_cmd.runInspect(None, parseTrainResult['destination_key'], timeoutSecs=500)
        print "Inspect:", parseTrainResult['destination_key'], "took", time.time() - start, "seconds"
        h2o_cmd.infoFromInspect(inspect, trainPathname)
        # num_rows = inspect['num_rows']
        # num_cols = inspect['num_cols']
        # do summary of the parsed dataset last, since we know it fails on this dataset
        summaryResult = h2o_cmd.runSummary(key=parseTrainResult['destination_key'])
        h2o_cmd.infoFromSummary(summaryResult, noPrint=False)

        # GBM Train***********************************************************
        x = [6,7,8,10,12,31,32,33,34,35,36,37,40,41,42,43,44,45,46,47,49,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70]
        # response = 0
        # doesn't work if index is used?
        response = 'outcome'

        # x = range(inspect['num_cols'])
        # del x[response]
        ntrees = 10
        # fails with 40
        params = {
            'learn_rate': .2,
            'nbins': 1024,
            'ntrees': ntrees,
            'max_depth': 20,
            'min_rows': 2,
            'response': response,
            'cols': x,
            # 'ignored_cols_by_name': None,
        }
        print "Using these parameters for GBM: ", params
        kwargs = params.copy()
        modelKey = 'GBMModelKey'

        timeoutSecs = 900

        trainStart = time.time()
        gbmTrainResult = h2o_cmd.runGBM(parseResult=parseTrainResult,
            timeoutSecs=timeoutSecs, destination_key=modelKey, **kwargs)
        trainElapsed = time.time() - trainStart
        print "GBM training completed in", trainElapsed, "seconds. On dataset: ", trainFilename

        gbmTrainView = h2o_cmd.runGBMView(model_key=modelKey)
        # errrs from end of list? is that the last tree?
        errsLast = gbmTrainView['gbm_model']['errs'][-1]
        print "GBM 'errsLast'", errsLast

        # get the last cm
        cm = gbmTrainView['gbm_model']['cms'][-1]['_arr']
        pctWrongTrain = h2o_gbm.pp_cm_summary(cm);
        print "Last line of this cm might be NAs, not CM"
        print "\nTrain\n==========\n"
        print h2o_gbm.pp_cm(cm)

        # GBM test****************************************
        predictKey = 'Predict.hex'
        h2o_cmd.runInspect(key=parseTestResult['destination_key'])
        start = time.time()
        gbmTestResult = h2o_cmd.runPredict(
            data_key=parseTestResult['destination_key'],
            model_key=modelKey,
            destination_key=predictKey,
            timeoutSecs=timeoutSecs)
        elapsed = time.time() - start
        print "GBM predict completed in", elapsed, "seconds. On dataset: ", testFilename

        if DO_PREDICT_CM:
            gbmPredictCMResult =h2o.nodes[0].predict_confusion_matrix(
                actual=parseTestResult['destination_key'],
                vactual='predict',
                predict=predictKey,
                vpredict='predict', # choices are 7 (now) and 'predict'
                )

            # errrs from end of list? is that the last tree?
            # all we get is cm
            cm = gbmPredictCMResult['cm']

            # These will move into the h2o_gbm.py
            pctWrong = h2o_gbm.pp_cm_summary(cm);
            print "Last line of this cm is really NAs, not CM"
            print "\nTest\n==========\n"
            print h2o_gbm.pp_cm(cm)

if __name__ == '__main__':
    h2o.unit_main()


text:
<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
        <!-- Window attributes for kiosk full-screen -->
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
     </style>

</resources>


text:
"""
Visualize generic LPU demo output.

Notes
-----
Generate demo output by running

python generic_demo.py
"""

import numpy as np
import matplotlib as mpl
mpl.use('agg')

import neurokernel.LPU.utils.visualizer as vis
import networkx as nx

nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False,
                                       'true':True, 'True':True}

# Select IDs of projection neurons:
G = nx.read_gexf('./data/generic_lpu.gexf.gz')
neu_proj = sorted([int(k) for k, n in G.node.items() if n['name'][:4] == 'proj'])

print neu_proj

V = vis.visualizer()
V.add_LPU('./data/generic_input.h5', LPU='Sensory')
V.add_plot({'type':'waveform', 'ids': [[0]]}, 'input_Sensory')

V.add_LPU('generic_output_gpot.h5',
          './data/generic_lpu.gexf.gz', 'Generic LPU')

V.add_plot({'type':'waveform', 'ids': {0:[0]}},'Generic LPU','Output')
V.add_plot({'type':'waveform', 'ids': {0:[20]}},'Generic LPU','Output')
V.add_plot({'type':'waveform', 'ids': {0:[40]}},'Generic LPU','Output')
V.add_plot({'type':'waveform', 'ids': {0:[60]}},'Generic LPU','Output')
V.add_plot({'type':'waveform', 'ids': {0:[80]}},'Generic LPU','Output')
V.add_plot({'type':'waveform', 'ids': {0:[90]}},'Generic LPU','Output')

#how often it updates
V._update_interval = 50

#rows and colums to plot in terms of size
V.rows = 7
V.cols = 1

#self explantory
V.fontsize = 10
#V.out_filename = 'simple_output.avi'
#V.codec = 'libtheora'

#time step
V.dt = 0.0001

#Changes the sizes on the axis
V.xlim = [0, 1.0]
V.ylim = [-70.0, 10.0]

#figure size
V.figsize = (16, 9)

V.title = "Simple LPU Testing RK4 Models"

#runs the visualizer
V.run('simple_output_network.png', 120)


text:
using AquaWorld.Web.Models;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AquaWorld.Tests.ViewModels
{
    [TestFixture]
    public class RegisterViewModelShould
    {
        [Test]
        public void SetCorrectlyAllPropertiesWhenInitialized()
        {
            //Arrange
            var registerViewModel = new RegisterViewModel();
            string username = "John";
            string password = "Agent007";
            string email = "john@gmail.com";
            string address = "Bulgaria, Sofia";

            //Act
            registerViewModel.UserName = username;
            registerViewModel.Email = email;
            registerViewModel.Address = address;
            registerViewModel.Password = password;
            registerViewModel.ConfirmPassword = password;

            //Assert
            Assert.AreEqual(registerViewModel.UserName, username);
            Assert.AreEqual(registerViewModel.Email, email);
            Assert.AreEqual(registerViewModel.Address, address);
            Assert.AreEqual(registerViewModel.ConfirmPassword, password);
            Assert.AreEqual(registerViewModel.Password, password);
        }
    }
}


text:
<?php
/* @var $this Salary_scaleController */
/* @var $model Salary_scale */

$this->breadcrumbs=array(
	'Salary Scales'=>array('index'),
	$model->ID=>array('view','id'=>$model->ID),
	'Update',
);

$this->menu=array(
	array('label'=>'List Salary_scale', 'url'=>array('index')),
	array('label'=>'Create Salary_scale', 'url'=>array('create')),
	array('label'=>'View Salary_scale', 'url'=>array('view', 'id'=>$model->ID)),
	array('label'=>'Manage Salary_scale', 'url'=>array('admin')),
);
?>

Update Salary_scale <?php echo $model->ID; ?>

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>


text:
package com.vladsch.md.nav.language;

import com.vladsch.flexmark.util.format.options.CodeFenceMarker;
import com.vladsch.plugin.util.ui.ComboBoxAdaptable;
import com.vladsch.plugin.util.ui.ComboBoxAdapter;
import com.vladsch.plugin.util.ui.ComboBoxAdapterImpl;
import org.jetbrains.annotations.NotNull;

public enum CodeFenceMarkerType implements ComboBoxAdaptable<CodeFenceMarkerType> {
    ANY(0, CodeStyleBundle.message("code-fence.marker-type.any"), CodeFenceMarker.ANY),
    BACK_TICK(1, CodeStyleBundle.message("code-fence.marker-type.back-tick"), CodeFenceMarker.BACK_TICK),
    TILDE(2, CodeStyleBundle.message("code-fence.marker-type.tilde"), CodeFenceMarker.TILDE);

    public final @NotNull String displayName;
    public final int intValue;
    public final CodeFenceMarker flexMarkEnum;

    CodeFenceMarkerType(int intValue, @NotNull String displayName, @NotNull CodeFenceMarker flexMarkEnum) {
        this.intValue = intValue;
        this.displayName = displayName;
        this.flexMarkEnum = flexMarkEnum;
    }

    public static Static<CodeFenceMarkerType> ADAPTER = new Static<>(new ComboBoxAdapterImpl<>(ANY));

    @NotNull
    @Override
    public ComboBoxAdapter<CodeFenceMarkerType> getAdapter() {
        return ADAPTER;
    }

    public char getMarkerChar() {
        if (this == TILDE) {
            return '~';
        } else {
            return '`';
        }
    }

    @Override
    public int getIntValue() { return intValue; }

    @NotNull
    public String getDisplayName() { return displayName; }

    @NotNull
    public CodeFenceMarkerType[] getValues() { return values(); }
}


text:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace FarseerPhysics.Samples.ScreenSystem
{
    /// <summary>
    /// The background screen sits behind all the other menu screens.
    /// It draws a background image that remains fixed in place regardless
    /// of whatever transitions the screens on top of it may be doing.
    /// </summary>
    public class BackgroundScreen : GameScreen
    {
        private const float LogoScreenHeightRatio = 0.25f;
        private const float LogoScreenBorderRatio = 0.0375f;
        private const float LogoWidthHeightRatio = 1.4f;

        private Texture2D _backgroundTexture;
        private Rectangle _logoDestination;
        private Texture2D _logoTexture;
        private Rectangle _viewport;

        /// <summary>
        /// Constructor.
        /// </summary>
        public BackgroundScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }

        public override void LoadContent()
        {
            _logoTexture = ScreenManager.Content.Load<Texture2D>("Common/logo");
            _backgroundTexture = ScreenManager.Content.Load<Texture2D>("Common/gradient");

            Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
            Vector2 logoSize = new Vector2();
            logoSize.Y = viewport.Height * LogoScreenHeightRatio;
            logoSize.X = logoSize.Y * LogoWidthHeightRatio;

            float border = viewport.Height * LogoScreenBorderRatio;
            Vector2 logoPosition = new Vector2(viewport.Width - border - logoSize.X, viewport.Height - border - logoSize.Y);
            _logoDestination = new Rectangle((int)logoPosition.X, (int)logoPosition.Y, (int)logoSize.X, (int)logoSize.Y);
            _viewport = viewport.Bounds;
        }

        /// <summary>
        /// Updates the background screen. Unlike most screens, this should not
        /// transition off even if it has been covered by another screen: it is
        /// supposed to be covered, after all! This overload forces the
        /// coveredByOtherScreen parameter to false in order to stop the base
        /// Update method wanting to transition off.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, false);
        }

        /// <summary>
        /// Draws the background screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            ScreenManager.SpriteBatch.Begin();
            ScreenManager.SpriteBatch.Draw(_backgroundTexture, _viewport, Color.White);
            ScreenManager.SpriteBatch.Draw(_logoTexture, _logoDestination, Color.White * 0.6f);
            ScreenManager.SpriteBatch.End();
        }
    }
}