text:
module Azure::Network::Mgmt::V2019_08_01
  module Models
    #
    # A common class for general resource information.
    #
    class VirtualNetworkGatewayConnection < Resource

      include MsRestAzure

      # @return [String] The authorizationKey.
      attr_accessor :authorization_key

      # @return [VirtualNetworkGateway] The reference to virtual network
      # gateway resource.
      attr_accessor :virtual_network_gateway1

      # @return [VirtualNetworkGateway] The reference to virtual network
      # gateway resource.
      attr_accessor :virtual_network_gateway2

      # @return [LocalNetworkGateway] The reference to local network gateway
      # resource.
      attr_accessor :local_network_gateway2

      # @return [VirtualNetworkGatewayConnectionType] Gateway connection type.
      # Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute',
      # 'VPNClient'
      attr_accessor :connection_type

      # @return [VirtualNetworkGatewayConnectionProtocol] Connection protocol
      # used for this connection. Possible values include: 'IKEv2', 'IKEv1'
      attr_accessor :connection_protocol

      # @return [Integer] The routing weight.
      attr_accessor :routing_weight

      # @return [String] The IPSec shared key.
      attr_accessor :shared_key

      # @return [VirtualNetworkGatewayConnectionStatus] Virtual Network Gateway
      # connection status. Possible values include: 'Unknown', 'Connecting',
      # 'Connected', 'NotConnected'
      attr_accessor :connection_status

      # @return [Array<TunnelConnectionHealth>] Collection of all tunnels'
      # connection health status.
      attr_accessor :tunnel_connection_status

      # @return [Integer] The egress bytes transferred in this connection.
      attr_accessor :egress_bytes_transferred

      # @return [Integer] The ingress bytes transferred in this connection.
      attr_accessor :ingress_bytes_transferred

      # @return [SubResource] The reference to peerings resource.
      attr_accessor :peer

      # @return [Boolean] EnableBgp flag.
      attr_accessor :enable_bgp

      # @return [Boolean] Enable policy-based traffic selectors.
      attr_accessor :use_policy_based_traffic_selectors

      # @return [Array<IpsecPolicy>] The IPSec Policies to be considered by
      # this connection.
      attr_accessor :ipsec_policies

      # @return [Array<TrafficSelectorPolicy>] The Traffic Selector Policies to
      # be considered by this connection.
      attr_accessor :traffic_selector_policies

      # @return [String] The resource GUID property of the virtual network
      # gateway connection resource.
      attr_accessor :resource_guid

      # @return [ProvisioningState] The provisioning state of the virtual
      # network gateway connection resource. Possible values include:
      # 'Succeeded', 'Updating', 'Deleting', 'Failed'
      attr_accessor :provisioning_state

      # @return [Boolean] Bypass ExpressRoute Gateway for data forwarding.
      attr_accessor :express_route_gateway_bypass

      # @return [String] A unique read-only string that changes whenever the
      # resource is updated.
      attr_accessor :etag

      #
      # Mapper for VirtualNetworkGatewayConnection class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'VirtualNetworkGatewayConnection',
          type: {
            name: 'Composite',
            class_name: 'VirtualNetworkGatewayConnection',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              location: {
                client_side_validation: true,
                required: false,
                serialized_name: 'location',
                type: {
                  name: 'String'
                }
              },
              tags: {
                client_side_validation: true,
                required: false,
                serialized_name: 'tags',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              authorization_key: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.authorizationKey',
                type: {
                  name: 'String'
                }
              },
              virtual_network_gateway1: {
                client_side_validation: true,
                required: true,
                serialized_name: 'properties.virtualNetworkGateway1',
                type: {
                  name: 'Composite',
                  class_name: 'VirtualNetworkGateway'
                }
              },
              virtual_network_gateway2: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.virtualNetworkGateway2',
                type: {
                  name: 'Composite',
                  class_name: 'VirtualNetworkGateway'
                }
              },
              local_network_gateway2: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.localNetworkGateway2',
                type: {
                  name: 'Composite',
                  class_name: 'LocalNetworkGateway'
                }
              },
              connection_type: {
                client_side_validation: true,
                required: true,
                serialized_name: 'properties.connectionType',
                type: {
                  name: 'String'
                }
              },
              connection_protocol: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.connectionProtocol',
                type: {
                  name: 'String'
                }
              },
              routing_weight: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.routingWeight',
                type: {
                  name: 'Number'
                }
              },
              shared_key: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.sharedKey',
                type: {
                  name: 'String'
                }
              },
              connection_status: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.connectionStatus',
                type: {
                  name: 'String'
                }
              },
              tunnel_connection_status: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.tunnelConnectionStatus',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'TunnelConnectionHealthElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'TunnelConnectionHealth'
                      }
                  }
                }
              },
              egress_bytes_transferred: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.egressBytesTransferred',
                type: {
                  name: 'Number'
                }
              },
              ingress_bytes_transferred: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.ingressBytesTransferred',
                type: {
                  name: 'Number'
                }
              },
              peer: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.peer',
                type: {
                  name: 'Composite',
                  class_name: 'SubResource'
                }
              },
              enable_bgp: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.enableBgp',
                type: {
                  name: 'Boolean'
                }
              },
              use_policy_based_traffic_selectors: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.usePolicyBasedTrafficSelectors',
                type: {
                  name: 'Boolean'
                }
              },
              ipsec_policies: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.ipsecPolicies',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'IpsecPolicyElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'IpsecPolicy'
                      }
                  }
                }
              },
              traffic_selector_policies: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.trafficSelectorPolicies',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'TrafficSelectorPolicyElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'TrafficSelectorPolicy'
                      }
                  }
                }
              },
              resource_guid: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.resourceGuid',
                type: {
                  name: 'String'
                }
              },
              provisioning_state: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.provisioningState',
                type: {
                  name: 'String'
                }
              },
              express_route_gateway_bypass: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.expressRouteGatewayBypass',
                type: {
                  name: 'Boolean'
                }
              },
              etag: {
                client_side_validation: true,
                required: false,
                serialized_name: 'etag',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package grpc

import (
	"context"
	"net"

	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/peer"
	"google.golang.org/protobuf/types/known/timestamppb"
	"inet.af/netaddr"

	"github.com/scionproto/scion/go/cs/config"
	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/common"
	"github.com/scionproto/scion/go/lib/drkey"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/scrypto/cppki"
	"github.com/scionproto/scion/go/lib/serrors"
	cs_drkey "github.com/scionproto/scion/go/pkg/cs/drkey"
	cppb "github.com/scionproto/scion/go/pkg/proto/control_plane"
	dkpb "github.com/scionproto/scion/go/pkg/proto/drkey"
)

// Server keeps track of the drkeys.
type Server struct {
	LocalIA addr.IA
	Engine  cs_drkey.ServiceEngine
	// AllowedSVHostProto is a set of Host,Protocol pairs that represents the allowed
	// protocols hosts can obtain secrets values for.
	AllowedSVHostProto map[config.HostProto]struct{}
}

var _ cppb.DRKeyInterServiceServer = &Server{}
var _ cppb.DRKeyIntraServiceServer = &Server{}

// Lvl1 handle a level 1 request and returns a level 1 response.
func (d *Server) Lvl1(ctx context.Context,
	req *dkpb.Lvl1Request) (*dkpb.Lvl1Response, error) {
	logger := log.FromCtx(ctx)
	peer, ok := peer.FromContext(ctx)
	if !ok {
		return nil, serrors.New("Cannot retrieve peer information from ctx")
	}
	dstIA, err := extractIAFromPeer(peer)
	if err != nil {
		return nil, serrors.WrapStr("retrieving info from certficate", err)
	}

	lvl1Meta, err := getMeta(req.ProtocolId, req.ValTime, d.LocalIA, dstIA)
	if err != nil {
		return nil, serrors.WrapStr("invalid DRKey Lvl1 request", err)
	}

	// validate requested ProtoID is specific
	if !lvl1Meta.ProtoId.IsPredefined() {
		return nil, serrors.New("The requested protocol id is not recognized",
			"protoID", lvl1Meta.ProtoId)
	}

	logger.Debug("[DRKey gRPC server] Received Lvl1 request",
		"lvl1_meta", lvl1Meta, "peer", peer.Addr.String(), "IA from cert", dstIA.String())

	lvl1Key, err := d.Engine.DeriveLvl1(lvl1Meta)
	if err != nil {
		return nil, serrors.WrapStr("deriving level 1 key", err)
	}
	resp, err := drkey.KeyToLvl1Resp(lvl1Key)
	if err != nil {
		return nil, serrors.WrapStr("parsing DRKey Lvl1 to protobuf resp", err)
	}
	return resp, nil
}

func getMeta(protoId dkpb.Protocol, ts *timestamppb.Timestamp, srcIA,
	dstIA addr.IA) (drkey.Lvl1Meta, error) {
	err := ts.CheckValid()
	if err != nil {
		return drkey.Lvl1Meta{}, serrors.WrapStr("invalid valTime from pb req", err)
	}
	return drkey.Lvl1Meta{
		Validity: ts.AsTime(),
		ProtoId:  drkey.Protocol(protoId),
		SrcIA:    srcIA,
		DstIA:    dstIA,
	}, nil
}

func extractIAFromPeer(peer *peer.Peer) (addr.IA, error) {
	if peer.AuthInfo == nil {
		return 0, serrors.New("no auth info", "peer", peer)
	}
	tlsInfo, ok := peer.AuthInfo.(credentials.TLSInfo)
	if !ok {
		return 0, serrors.New("auth info is not of type TLS info",
			"peer", peer, "authType", peer.AuthInfo.AuthType())
	}
	chain := tlsInfo.State.PeerCertificates
	certIA, err := cppki.ExtractIA(chain[0].Subject)
	if err != nil {
		return 0, serrors.WrapStr("extracting IA from peer cert", err)
	}
	return certIA, nil
}

func (d *Server) IntraLvl1(ctx context.Context,
	req *dkpb.IntraLvl1Request) (*dkpb.IntraLvl1Response, error) {
	peer, ok := peer.FromContext(ctx)
	if !ok {
		return nil, serrors.New("Cannot retrieve peer information from ctx")
	}

	if d.LocalIA != addr.IA(req.SrcIa) && d.LocalIA != addr.IA(req.DstIa) {
		return nil, serrors.New("Local IA is not part of the request")
	}

	meta, err := getMeta(req.ProtocolId, req.ValTime, addr.IA(req.SrcIa), addr.IA(req.DstIa))
	if err != nil {
		return nil, serrors.WrapStr("parsing AS-AS request", err)
	}
	if err := d.validateAllowedHost(meta.ProtoId, peer.Addr); err != nil {
		return nil, serrors.WrapStr("validating AS-AS request", err)
	}

	lvl1Key, err := d.Engine.GetLvl1Key(ctx, meta)
	if err != nil {
		return nil, serrors.WrapStr("getting AS-AS host key", err)
	}

	resp, err := drkey.KeyToASASResp(lvl1Key)
	if err != nil {
		return nil, serrors.WrapStr("encoding AS-AS to Protobuf response", err)
	}
	return resp, nil
}

func (d *Server) ASHost(ctx context.Context,
	req *dkpb.ASHostRequest) (*dkpb.ASHostResponse, error) {
	logger := log.FromCtx(ctx)
	peer, ok := peer.FromContext(ctx)
	if !ok {
		return nil, serrors.New("Cannot retrieve peer information from ctx")
	}

	meta, err := drkey.RequestToASHostMeta(req)
	if err != nil {
		return nil, serrors.WrapStr("parsing DRKey AS-Host request", err)
	}
	if err := validateASHostReq(meta, d.LocalIA, peer.Addr); err != nil {
		return nil, serrors.WrapStr("validating AS-Host request", err)
	}

	logger.Debug(" [DRKey gRPC server] Received AS-Host request",
		"protocol", meta.ProtoId,
		"SrcIA", meta.SrcIA, "DstIA", meta.DstIA)

	asHostKey, err := d.Engine.DeriveASHost(ctx, meta)
	if err != nil {
		return nil, serrors.WrapStr("deriving AS-Host request", err)
	}

	resp, err := drkey.KeyToASHostResp(asHostKey)
	if err != nil {
		return nil, serrors.WrapStr("parsing AS-Host request", err)
	}
	return resp, nil
}

// validateASHostReq returns and error if the requesting host is different from the
// requested dst host. The source AS infraestructure nodes are not supposed to contact
// the local CS but to derive this key from the SV instead.
func validateASHostReq(meta drkey.ASHostMeta, localIA addr.IA, peerAddr net.Addr) error {
	hostAddr, err := hostAddrFromPeer(peerAddr)
	if err != nil {
		return err
	}

	if !meta.DstIA.Equal(localIA) {
		return serrors.New("invalid request, req.dstIA != localIA",
			"req.dstIA", meta.DstIA, "localIA", localIA)
	}
	dstHost := addr.HostFromIPStr(meta.DstHost)
	if !hostAddr.Equal(dstHost) {
		return serrors.New("invalid request, dst_host != remote host",
			"dst_host", dstHost, "remote_host", hostAddr)
	}
	return nil
}

func (d *Server) HostAS(ctx context.Context,
	req *dkpb.HostASRequest) (*dkpb.HostASResponse, error) {
	logger := log.FromCtx(ctx)
	peer, ok := peer.FromContext(ctx)
	if !ok {
		return nil, serrors.New("Cannot retrieve peer information from ctx")
	}

	meta, err := drkey.RequestToHostASMeta(req)
	if err != nil {
		return nil, serrors.WrapStr("parsing Host-AS request", err)
	}
	if err := validateHostASReq(meta, d.LocalIA, peer.Addr); err != nil {
		return nil, serrors.WrapStr("validating Host-AS request", err)
	}
	logger.Debug(" [DRKey gRPC server] Received Host-AS request",
		"protocol", meta.ProtoId,
		"SrcIA", meta.SrcIA, "DstIA", meta.DstIA)
	key, err := d.Engine.DeriveHostAS(ctx, meta)
	if err != nil {
		return nil, serrors.WrapStr("deriving Host-AS request", err)
	}

	resp, err := drkey.KeyToHostASResp(key)
	if err != nil {
		return nil, serrors.WrapStr("parsing Host-AS request", err)
	}
	return resp, nil
}

// validateASHostReq returns and error if the requesting host is different from the
// requested src host. The dst AS infraestructure nodes are not supposed to contact
// the local CS but to derive this key from the SV instead.
func validateHostASReq(meta drkey.HostASMeta, localIA addr.IA, peerAddr net.Addr) error {
	hostAddr, err := hostAddrFromPeer(peerAddr)
	if err != nil {
		return err
	}

	if !meta.SrcIA.Equal(localIA) {
		return serrors.New("invalid request, req.SrcIA != localIA",
			"req.SrcIA", meta.SrcIA, "localIA", localIA)
	}
	srcHost := addr.HostFromIPStr(meta.SrcHost)
	if !hostAddr.Equal(srcHost) {
		return serrors.New("invalid request, src_host != remote host",
			"src_host", srcHost, "remote_host", hostAddr)
	}
	return nil
}

func (d *Server) HostHost(ctx context.Context,
	req *dkpb.HostHostRequest) (*dkpb.HostHostResponse, error) {
	logger := log.FromCtx(ctx)
	peer, ok := peer.FromContext(ctx)
	if !ok {
		return nil, serrors.New("Cannot retrieve peer information from ctx")
	}

	meta, err := drkey.RequestToHostHostMeta(req)
	if err != nil {
		return nil, serrors.WrapStr("parsing Host-Host request", err)
	}
	if err := validateHostHostReq(meta, d.LocalIA, peer.Addr); err != nil {
		return nil, serrors.WrapStr("validating Host-Host request", err)
	}

	logger.Debug(" [DRKey gRPC server] Received Host-Host request",
		"protocol", meta.ProtoId,
		"SrcIA", meta.SrcIA, "DstIA", meta.DstIA)

	key, err := d.Engine.DeriveHostHost(ctx, meta)
	if err != nil {
		return nil, serrors.WrapStr("deriving Host-Host request", err)
	}

	resp, err := drkey.KeyToHostHostResp(key)
	if err != nil {
		return nil, serrors.WrapStr("parsing Host-Host request", err)
	}
	return resp, nil
}

// validateHostHostReq returns and error if the requesting host is different from the
// requested src host or the dst host.
func validateHostHostReq(meta drkey.HostHostMeta, localIA addr.IA, peerAddr net.Addr) error {
	hostAddr, err := hostAddrFromPeer(peerAddr)
	if err != nil {
		return err
	}
	srcHost := addr.HostFromIPStr(meta.SrcHost)
	dstHost := addr.HostFromIPStr(meta.DstHost)

	isSrc := meta.SrcIA.Equal(localIA) && hostAddr.Equal(srcHost)
	isDst := meta.DstIA.Equal(localIA) && hostAddr.Equal(dstHost)
	if !(isSrc || isDst) {
		return serrors.New(
			"invalid request",
			"local_isd_as", localIA,
			"src_isd_as", meta.SrcIA,
			"dst_isd_as", meta.DstIA,
			"src_host", srcHost,
			"dst_host", dstHost,
			"remote_host", hostAddr,
		)
	}
	return nil
}

func hostAddrFromPeer(peerAddr net.Addr) (addr.HostAddr, error) {
	tcpAddr, ok := peerAddr.(*net.TCPAddr)
	if !ok {
		return nil, serrors.New("invalid peer address type, expected *net.TCPAddr",
			"peer", peerAddr, "type", common.TypeOf(peerAddr))
	}
	return addr.HostFromIP(tcpAddr.IP), nil
}

// SV handles a SV request and returns a SV response.
func (d *Server) SV(ctx context.Context,
	req *dkpb.SVRequest) (*dkpb.SVResponse, error) {
	peer, ok := peer.FromContext(ctx)
	if !ok {
		return nil, serrors.New("Cannot retrieve peer information from ctx")
	}

	meta, err := drkey.SVRequestToMeta(req)
	if err != nil {
		return nil, serrors.WrapStr("parsing Host-Host request", err)
	}
	if err := d.validateAllowedHost(meta.ProtoId, peer.Addr); err != nil {
		return nil, serrors.WrapStr("validating SV request", err)
	}
	sv, err := d.Engine.GetSecretValue(ctx, meta)
	if err != nil {
		return nil, serrors.WrapStr("getting SV from persistence", err)
	}
	resp, err := drkey.SVtoProtoResp(sv)
	if err != nil {
		return nil, serrors.WrapStr("encoding SV to Protobuf response", err)
	}
	return resp, nil
}

// validateAllowedHost checks that the requester is authorized to receive a SV
func (d *Server) validateAllowedHost(protoId drkey.Protocol, peerAddr net.Addr) error {
	tcpAddr, ok := peerAddr.(*net.TCPAddr)
	if !ok {
		return serrors.New("invalid peer address type, expected *net.TCPAddr",
			"peer", peerAddr, "type", common.TypeOf(peerAddr))
	}
	localAddr, ok := netaddr.FromStdIP(tcpAddr.IP)
	if !ok {
		return serrors.New("unable to parse IP", "addr", tcpAddr.IP.String())
	}
	hostProto := config.HostProto{
		Host:  localAddr,
		Proto: protoId,
	}

	_, foundSet := d.AllowedSVHostProto[hostProto]
	if foundSet {
		log.Debug("Authorized delegated secret",
			"protocol", protoId.String(),
			"requester address", localAddr.String(),
		)
		return nil
	}
	return serrors.New("endhost not allowed for DRKey request",
		"protocol", protoId.String(),
		"requester address", localAddr.String(),
	)
}

redpajama_set_name: RedPajamaGithub


text:
namespace juce
{

ComboBox::ComboBox (const String& name)
    : Component (name),
      noChoicesMessage (TRANS("(no choices)"))
{
    setRepaintsOnMouseActivity (true);
    lookAndFeelChanged();
    currentId.addListener (this);
}

ComboBox::~ComboBox()
{
    currentId.removeListener (this);
    hidePopup();
    label.reset();
}

//==============================================================================
void ComboBox::setEditableText (const bool isEditable)
{
    if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
    {
        label->setEditable (isEditable, isEditable, false);
        labelEditableState = (isEditable ? labelIsEditable : labelIsNotEditable);

        setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
        resized();
    }
}

bool ComboBox::isTextEditable() const noexcept
{
    return label->isEditable();
}

void ComboBox::setJustificationType (Justification justification)
{
    label->setJustificationType (justification);
}

Justification ComboBox::getJustificationType() const noexcept
{
    return label->getJustificationType();
}

void ComboBox::setTooltip (const String& newTooltip)
{
    SettableTooltipClient::setTooltip (newTooltip);
    label->setTooltip (newTooltip);
}

//==============================================================================
void ComboBox::addItem (const String& newItemText, int newItemId)
{
    // you can't add empty strings to the list..
    jassert (newItemText.isNotEmpty());

    // IDs must be non-zero, as zero is used to indicate a lack of selection.
    jassert (newItemId != 0);

    // you shouldn't use duplicate item IDs!
    jassert (getItemForId (newItemId) == nullptr);

    if (newItemText.isNotEmpty() && newItemId != 0)
        currentMenu.addItem (newItemId, newItemText, true, false);
}

void ComboBox::addItemList (const StringArray& itemsToAdd, int firstItemID)
{
    for (auto& i : itemsToAdd)
        currentMenu.addItem (firstItemID++, i);
}

void ComboBox::addSeparator()
{
    currentMenu.addSeparator();
}

void ComboBox::addSectionHeading (const String& headingName)
{
    // you can't add empty strings to the list..
    jassert (headingName.isNotEmpty());

    if (headingName.isNotEmpty())
        currentMenu.addSectionHeader (headingName);
}

void ComboBox::setItemEnabled (int itemId, bool shouldBeEnabled)
{
    if (auto* item = getItemForId (itemId))
        item->isEnabled = shouldBeEnabled;
}

bool ComboBox::isItemEnabled (int itemId) const noexcept
{
    if (auto* item = getItemForId (itemId))
        return item->isEnabled;

    return false;
}

void ComboBox::changeItemText (int itemId, const String& newText)
{
    if (auto* item = getItemForId (itemId))
        item->text = newText;
    else
        jassertfalse;
}

void ComboBox::clear (const NotificationType notification)
{
    currentMenu.clear();

    if (! label->isEditable())
        setSelectedItemIndex (-1, notification);
}

//==============================================================================
PopupMenu::Item* ComboBox::getItemForId (int itemId) const noexcept
{
    if (itemId != 0)
    {
        for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
        {
            auto& item = iterator.getItem();

            if (item.itemID == itemId)
                return &item;
        }
    }

    return nullptr;
}

PopupMenu::Item* ComboBox::getItemForIndex (const int index) const noexcept
{
    int n = 0;

    for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
    {
        auto& item = iterator.getItem();

        if (item.itemID != 0)
            if (n++ == index)
                return &item;
    }

    return nullptr;
}

int ComboBox::getNumItems() const noexcept
{
    int n = 0;

    for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
    {
        auto& item = iterator.getItem();

        if (item.itemID != 0)
            n++;
    }

    return n;
}

String ComboBox::getItemText (const int index) const
{
    if (auto* item = getItemForIndex (index))
        return item->text;

    return {};
}

int ComboBox::getItemId (const int index) const noexcept
{
    if (auto* item = getItemForIndex (index))
        return item->itemID;

    return 0;
}

int ComboBox::indexOfItemId (const int itemId) const noexcept
{
    if (itemId != 0)
    {
        int n = 0;

        for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
        {
            auto& item = iterator.getItem();

            if (item.itemID == itemId)
                return n;

            else if (item.itemID != 0)
                n++;
        }
    }

    return -1;
}

//==============================================================================
int ComboBox::getSelectedItemIndex() const
{
    auto index = indexOfItemId (currentId.getValue());

    if (getText() != getItemText (index))
        index = -1;

    return index;
}

void ComboBox::setSelectedItemIndex (const int index, const NotificationType notification)
{
    setSelectedId (getItemId (index), notification);
}

int ComboBox::getSelectedId() const noexcept
{
    if (auto* item = getItemForId (currentId.getValue()))
        if (getText() == item->text)
            return item->itemID;

    return 0;
}

void ComboBox::setSelectedId (const int newItemId, const NotificationType notification)
{
    auto* item = getItemForId (newItemId);
    auto newItemText = item != nullptr ? item->text : String();

    if (lastCurrentId != newItemId || label->getText() != newItemText)
    {
        label->setText (newItemText, dontSendNotification);
        lastCurrentId = newItemId;
        currentId = newItemId;

        repaint();  // for the benefit of the 'none selected' text

        sendChange (notification);
    }
}

bool ComboBox::selectIfEnabled (const int index)
{
    if (auto* item = getItemForIndex (index))
    {
        if (item->isEnabled)
        {
            setSelectedItemIndex (index);
            return true;
        }
    }

    return false;
}

bool ComboBox::nudgeSelectedItem (int delta)
{
    for (int i = getSelectedItemIndex() + delta; isPositiveAndBelow (i, getNumItems()); i += delta)
        if (selectIfEnabled (i))
            return true;

    return false;
}

void ComboBox::valueChanged (Value&)
{
    if (lastCurrentId != (int) currentId.getValue())
        setSelectedId (currentId.getValue());
}

//==============================================================================
String ComboBox::getText() const
{
    return label->getText();
}

void ComboBox::setText (const String& newText, const NotificationType notification)
{
    for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
    {
        auto& item = iterator.getItem();

        if (item.itemID != 0
            && item.text == newText)
        {
            setSelectedId (item.itemID, notification);
            return;
        }
    }

    lastCurrentId = 0;
    currentId = 0;
    repaint();

    if (label->getText() != newText)
    {
        label->setText (newText, dontSendNotification);
        sendChange (notification);
    }
}

void ComboBox::showEditor()
{
    jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?

    label->showEditor();
}

//==============================================================================
void ComboBox::setTextWhenNothingSelected (const String& newMessage)
{
    if (textWhenNothingSelected != newMessage)
    {
        textWhenNothingSelected = newMessage;
        repaint();
    }
}

String ComboBox::getTextWhenNothingSelected() const
{
    return textWhenNothingSelected;
}

void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
{
    noChoicesMessage = newMessage;
}

String ComboBox::getTextWhenNoChoicesAvailable() const
{
    return noChoicesMessage;
}

//==============================================================================
void ComboBox::paint (Graphics& g)
{
    getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
                                   label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
                                   *this);

    if (textWhenNothingSelected.isNotEmpty() && label->getText().isEmpty() && ! label->isBeingEdited())
        getLookAndFeel().drawComboBoxTextWhenNothingSelected (g, *this, *label);
}

void ComboBox::resized()
{
    if (getHeight() > 0 && getWidth() > 0)
        getLookAndFeel().positionComboBoxText (*this, *label);
}

void ComboBox::enablementChanged()
{
    repaint();
}

void ComboBox::colourChanged()
{
    lookAndFeelChanged();
}

void ComboBox::parentHierarchyChanged()
{
    lookAndFeelChanged();
}

void ComboBox::lookAndFeelChanged()
{
    repaint();

    {
        std::unique_ptr<Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
        jassert (newLabel != nullptr);

        if (label != nullptr)
        {
            newLabel->setEditable (label->isEditable());
            newLabel->setJustificationType (label->getJustificationType());
            newLabel->setTooltip (label->getTooltip());
            newLabel->setText (label->getText(), dontSendNotification);
        }

        std::swap (label, newLabel);
    }

    addAndMakeVisible (label.get());

    EditableState newEditableState = (label->isEditable() ? labelIsEditable : labelIsNotEditable);

    if (newEditableState != labelEditableState)
    {
        labelEditableState = newEditableState;
        setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
    }

    label->onTextChange = [this] { triggerAsyncUpdate(); };
    label->addMouseListener (this, false);

    label->setColour (Label::backgroundColourId, Colours::transparentBlack);
    label->setColour (Label::textColourId, findColour (ComboBox::textColourId));

    label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
    label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
    label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
    label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);

    resized();
}

//==============================================================================
bool ComboBox::keyPressed (const KeyPress& key)
{
    if (key == KeyPress::upKey || key == KeyPress::leftKey)
    {
        nudgeSelectedItem (-1);
        return true;
    }

    if (key == KeyPress::downKey || key == KeyPress::rightKey)
    {
        nudgeSelectedItem (1);
        return true;
    }

    if (key == KeyPress::returnKey)
    {
        showPopupIfNotActive();
        return true;
    }

    return false;
}

bool ComboBox::keyStateChanged (const bool isKeyDown)
{
    // only forward key events that aren't used by this component
    return isKeyDown
            && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
                || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
                || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
                || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
}

//==============================================================================
void ComboBox::focusGained (FocusChangeType)    { repaint(); }
void ComboBox::focusLost (FocusChangeType)      { repaint(); }

//==============================================================================
void ComboBox::showPopupIfNotActive()
{
    if (! menuActive)
    {
        menuActive = true;

        SafePointer<ComboBox> safePointer (this);

        // as this method was triggered by a mouse event, the same mouse event may have
        // exited the modal state of other popups currently on the screen. By calling
        // showPopup asynchronously, we are giving the other popups a chance to properly
        // close themselves
        MessageManager::callAsync ([safePointer]() mutable { if (safePointer != nullptr) safePointer->showPopup(); });

        repaint();
    }
}

void ComboBox::hidePopup()
{
    if (menuActive)
    {
        menuActive = false;
        PopupMenu::dismissAllActiveMenus();
        repaint();
    }
}

static void comboBoxPopupMenuFinishedCallback (int result, ComboBox* combo)
{
    if (combo != nullptr)
    {
        combo->hidePopup();

        if (result != 0)
            combo->setSelectedId (result);
    }
}

void ComboBox::showPopup()
{
    if (! menuActive)
        menuActive = true;

    auto menu = currentMenu;

    if (menu.getNumItems() > 0)
    {
        auto selectedId = getSelectedId();

        for (PopupMenu::MenuItemIterator iterator (menu, true); iterator.next();)
        {
            auto& item = iterator.getItem();

            if (item.itemID != 0)
                item.isTicked = (item.itemID == selectedId);
        }
    }
    else
    {
        menu.addItem (1, noChoicesMessage, false, false);
    }

    auto& lf = getLookAndFeel();

    menu.setLookAndFeel (&lf);
    menu.showMenuAsync (lf.getOptionsForComboBoxPopupMenu (*this, *label),
                        ModalCallbackFunction::forComponent (comboBoxPopupMenuFinishedCallback, this));
}

//==============================================================================
void ComboBox::mouseDown (const MouseEvent& e)
{
    beginDragAutoRepeat (300);

    isButtonDown = isEnabled() && ! e.mods.isPopupMenu();

    if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
        showPopupIfNotActive();
}

void ComboBox::mouseDrag (const MouseEvent& e)
{
    beginDragAutoRepeat (50);

    if (isButtonDown && e.mouseWasDraggedSinceMouseDown())
        showPopupIfNotActive();
}

void ComboBox::mouseUp (const MouseEvent& e2)
{
    if (isButtonDown)
    {
        isButtonDown = false;
        repaint();

        auto e = e2.getEventRelativeTo (this);

        if (reallyContains (e.getPosition(), true)
             && (e2.eventComponent == this || ! label->isEditable()))
        {
            showPopupIfNotActive();
        }
    }
}

void ComboBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
{
    if (! menuActive && scrollWheelEnabled && e.eventComponent == this && wheel.deltaY != 0.0f)
    {
        mouseWheelAccumulator += wheel.deltaY * 5.0f;

        while (mouseWheelAccumulator > 1.0f)
        {
            mouseWheelAccumulator -= 1.0f;
            nudgeSelectedItem (-1);
        }

        while (mouseWheelAccumulator < -1.0f)
        {
            mouseWheelAccumulator += 1.0f;
            nudgeSelectedItem (1);
        }
    }
    else
    {
        Component::mouseWheelMove (e, wheel);
    }
}

void ComboBox::setScrollWheelEnabled (bool enabled) noexcept
{
    scrollWheelEnabled = enabled;
}

//==============================================================================
void ComboBox::addListener    (ComboBox::Listener* l)    { listeners.add (l); }
void ComboBox::removeListener (ComboBox::Listener* l)    { listeners.remove (l); }

void ComboBox::handleAsyncUpdate()
{
    Component::BailOutChecker checker (this);
    listeners.callChecked (checker, [this] (Listener& l) { l.comboBoxChanged (this); });

    if (checker.shouldBailOut())
        return;

    if (onChange != nullptr)
        onChange();
}

void ComboBox::sendChange (const NotificationType notification)
{
    if (notification != dontSendNotification)
        triggerAsyncUpdate();

    if (notification == sendNotificationSync)
        handleUpdateNowIfNeeded();
}

// Old deprecated methods - remove eventually...
void ComboBox::clear (const bool dontSendChange)                                 { clear (dontSendChange ? dontSendNotification : sendNotification); }
void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChange) { setSelectedItemIndex (index, dontSendChange ? dontSendNotification : sendNotification); }
void ComboBox::setSelectedId (const int newItemId, const bool dontSendChange)    { setSelectedId (newItemId, dontSendChange ? dontSendNotification : sendNotification); }
void ComboBox::setText (const String& newText, const bool dontSendChange)        { setText (newText, dontSendChange ? dontSendNotification : sendNotification); }

} // namespace juce


text:
import Link from '../Link';
import React from 'react';
import history from '../../history';

function LinkWrapper(WrappedComponent) {
  return class linkWrapper extends React.Component {
    render() {
      let isActive;
      if (history.location)
        isActive = this.props.to === history.location.pathname;
      else isActive = false;
      return (
        <Link to={this.props.to}>
          <WrappedComponent active={isActive} {...this.props} />
        </Link>
      );
    }
  };
}

export default LinkWrapper;


text:
/*
 * base.js
 * 1. handle base template
 * 2. handle whole front-end templates routing
 *
 * */
'use strict';

// declare app level module which depends on filters, and services, and modify $interpolateProvider to avoid the conflict with jinja2' symbol
var index_page_app = angular.module('index_page_app', [ 'angular-responsive', 'ui.router', 'myGpsDataDirective' ], function($interpolateProvider) {
	$interpolateProvider.startSymbol('[[');
	$interpolateProvider.endSymbol(']]');
});

// global values
index_page_app.value('GLOBAL_VALUES',{
	EMAIL : 'gogistics@gogistics-tw.com'
});

// app-routing configuration
index_page_app.config(function(responsiveHelperProvider, $stateProvider, $urlRouterProvider) {
	// templates dispatcher which redirect visitors to appropriate templates;
	// currently, there are desktop and mobile versions
	var device = 'desktop';
	var responsiveHelper = responsiveHelperProvider.$get();
	if (responsiveHelper.isMobile()) {
		device = 'mobile';
	}
	else if(responsiveHelper.isTablet()){
		device = 'tablet';
	}

	// nested templates and routing
	$stateProvider
	.state('home', {
		templateUrl: '/ng_templates/my_ng_template_base.html',
	})
	.state('index_page', {
		parent: 'home',
		templateUrl: '/ng_templates/' + device + '/index/index.html',
		controller: 'indexPageDispatchCtrl'
	})
	.state('index_1', {
		url: '/index_1',
		parent: 'index_page',
		templateUrl: '/ng_templates/' + device + '/index/index_1.html',
	})
	.state('index_2', {
		url: '/index_2',
		parent: 'index_page',
		templateUrl: '/ng_templates/' + device + '/index/index_2.html',
	});

	$urlRouterProvider.otherwise('/index_1'); // for defualt state routing; for current routing mechanism, it's not necessary

});

/* controllers */
// ng-functions mapper
index_page_app
.controller('indexPageDispatchCtrl', indexPageDispatchController)
.controller('myIndexCtrl', myIndexController);

// functions
// for routing to default content on index page
indexPageDispatchController.$injector = ['$state', '$scope', 'GLOBAL_VALUES'];
function indexPageDispatchController($state, $scope, GLOBAL_VALUES) {
	$scope.email = GLOBAL_VALUES.EMAIL;
	console.log($state.current.name);

	if($state.current.name !== 'index_1'){
	    $state.transitionTo('index_1');
	}
}

// page controllers
myIndexController.$injector = ['$scope', 'GLOBAL_VALUES'];
function myIndexController($scope, GLOBAL_VALUES) {
	$scope.email = GLOBAL_VALUES.EMAIL;

	$scope.select_topic = function(section) {
        $scope.selected = section;
    }

    $scope.is_selected = function(section) {
        return ($scope.selected === section);
    }

    // init selected topic
    $scope.select_topic('index_1');
}


text:
<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\Debug\Debug;

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
// if (isset($_SERVER['HTTP_CLIENT_IP'])
//     || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
//     || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
// ) {
//     header('HTTP/1.0 403 Forbidden');
//     exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
// }

$loader = require_once __DIR__.'/vendor/autoload.php';

AnnotationRegistry::registerLoader(function($class) use ($loader) {
    $loader->loadClass($class);
    return class_exists($class, false);
});
AnnotationRegistry::registerFile(__DIR__.'/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');

$app = require __DIR__.'/src/app.php';
require __DIR__.'/src/controllers.php';

if ($app['debug']) {
    $app->run();
} else{
    Debug::enable();
    $app['http_cache']->run();
}


text:
import time

from pygreat.comms import CommandFailureError

from ..neighbor import GreatFETNeighbor
from ..interfaces.i2c.pca6408a import PCA6048A
from ..interfaces.spi.dac084s085 import DAC084S085
from ..programmers.ecp5 import ECP5SlaveSPI, ECP5MasterSerialDirect

class Foxglove(GreatFETNeighbor):
    """ Class representing a Foxglove FPGA/level-shifting neighbor. """

    # The address of our I2C I/O expander.
    IO_EXPANDER_I2C_ADDRESS = 0x21
    IO_EXPANDER_PIN_NAMES = {
        'P0': 'AUX_VREG_EN',
        'P1':  None,
        'P2': 'DIV_EN',
        'P3': 'DAC_CS',
        'P4': 'COMPARATOR1_RESULT',
        'P5': 'COMPARATOR2_RESULT',
        'P6': 'VCCB_VREG_EN',
        'P7': 'VCCA_VREG_EN',
    }

    # I/O pins that select the FPGA's configuration mode.
    CFG_PINS = ('J1_P27', 'J1_P12', 'J1_P13')

    # Pin that triggers a (re)configuration. Places the FPGA into a state where it will accept programming.
    PROGRAM_PIN = 'J1_P25'

    # The chip select on the Foxglove board's flash chip.
    FLASH_CHIP_SELECT_PIN = 'J1_P24'

    # Store the number of discrete values the DAC can represent. We have an 8-bit DAC.
    DAC_POSSIBLE_SAMPLES = 256

    # Mapping that converts supply/reference rail names to their equivalent DAC voltage.
    VREG_DAC_CHANNELS = {
        'VCCA': 'A',
        'VCCB': 'C',
        'AUX':  'B'
    }

    # Mapping that maps supply/reference rail names to their minimum and maximum voltages.
    VREG_VOLTAGE_RANGES = {
        'VCCA': (1.20, 5.0),
        'VCCB': (1.20, 3.3),
        'AUX':  (1.20, 5.0),
    }

    def __init__(self, board, verbose_function=None, set_up_hardware=True):
        """ Set up a new Foxglove neighbor."""

        self.board = board

        # Attach an object represneting the flash chip to program.
        flash_cs_gpio = board.gpio.get_pin(self.FLASH_CHIP_SELECT_PIN)

        # Create an object that represents the on-board I/O expander.
        self._io_expander = PCA6048A(board.i2c, device_address=self.IO_EXPANDER_I2C_ADDRESS,
                name_mappings=self.IO_EXPANDER_PIN_NAMES)

        # Create our GPIO objects.
        self._cfg_port = board.gpio.get_port(*self.CFG_PINS)
        self._program_pin = board.gpio.get_pin(self.PROGRAM_PIN)
        self._vreg_enables = {
            'VCCA': self._io_expander.get_pin('VCCA_VREG_EN'),
            'VCCB': self._io_expander.get_pin('VCCB_VREG_EN'),
            'AUX':  self._io_expander.get_pin('AUX_VREG_EN')
        }

        # Grab a copy of the board's main SPI bus.
        self._spi_bus = board.spi

        # Create an object representing our SPI flash.
        try:
            self.flash_programmer = ECP5MasterSerialDirect(board, chip_select=flash_cs_gpio,
                    cfg_pins=self._cfg_port, program_pin=self._program_pin, verbose_function=verbose_function)
        except CommandFailureError:
            self.flash_programmer = None

        # Create an object used for directly programming our FPGA.
        self.spi_programmer = ECP5SlaveSPI(board, cfg_pins=self._cfg_port,
                program_pin=self._program_pin, verbose_function=verbose_function)

        # Create an object that represents our DAC.
        self._dac = DAC084S085(self._spi_bus, chip_select=self._io_expander.get_pin('DAC_CS'), reference_voltage=5)

        # If the user has requested we set up the hardware, do so.
        if set_up_hardware:
            self.set_up_hardware()

    def set_up_hardware(self):
        """ Initializes the hardware; bringing the Foxglove board into a post-reset state. """

        # Start with our DAC outputs powered down, and our voltage regulators off.
        self._dac.power_down_outputs()
        self.use_external_vcca()
        self.use_external_vccb()

    def program_flash(self, bitstream, configure_after=False):
        """ Programs the given bitstream data to the target flash chip. The program will be retained across resets. """

        if self.flash_programmer is None:
            raise IOError("This Foxglove board does not appear to have an SPI flash populated.")

        # Program the target flash with the relevant bitstream.
        self.flash_programmer.program(bitstream)

        # If the caller wants us to reconfigure the FPGA as well, trigger reconfiguration.
        if configure_after:
            self._spi_bus.disable_drive()
            self.flash_programmer.trigger_reconfiguration()
            time.sleep(1)
            self._spi_bus.enable_drive()

    def configure_fpga(self, bitstream):
        """ Configures the onboard FPGA with the given program. Program will not be retained on reset. """
        self.spi_programmer.configure(bitstream)

    def _dac_value_for_rail_voltage(self, rail, voltage):
        """ Identifies the DAC input value that will produce the target voltage. """

        # Look up our maximum and minimum voltages, and compute the voltage step per DAC bit.
        v_min, v_max = self.VREG_VOLTAGE_RANGES[rail]
        volts_per_quanta = (v_min-v_max) / self.DAC_POSSIBLE_SAMPLES

        # Sanity check our input voltage.
        if voltage < v_min:
            raise ValueError("Rail {} cannot be set to voltages lower than {}.".format(rail, v_min))
        if voltage > v_max:
            raise ValueError("Rail {} cannot be set to voltages higher than {}.".format(rail, v_max))

        # Providing a sample value of N yields a voltage out such that v_out = (volts_per_quanta * N) + v_max.
        # With some algebra, we get a required sample value of:
        target_sample = round((voltage - v_max) / volts_per_quanta)
        target_sample = (target_sample - 1) if (target_sample == self.DAC_POSSIBLE_SAMPLES) else target_sample
        return target_sample

    def _set_rail_voltage(self, rail, voltage):
        """ Sets the voltage of the provided rail.

        Parameters:
            rail       -- The rail name (A, B, or DAC).
            voltage    -- The voltage to set; or None to disable the relevant rail.
        """

        # If this isn't a valid rail, fail out.
        if rail not in self.VREG_DAC_CHANNELS:
            raise ValueError("{} is not a valid rail name".format(voltage))

        dac_channel = self.VREG_DAC_CHANNELS[rail]
        regulator_enable  = self._vreg_enables[rail]

        # If our voltage is None, disable the rail.
        if voltage is None:
            regulator_enable.low()

        # Otherwise, set the DAC to the value that produces the target voltage.
        else:

            # Compute the DAC value we'll need to apply, and then apply it.
            target_sample_value = self._dac_value_for_rail_voltage(rail, voltage)
            self._dac.set_channel_value(dac_channel, target_sample_value)

            # And ensure that the regulator is on.
            regulator_enable.high()

    def apply_configuration(self, configuration):
        """ Applies a FoxgloveConfiguration object to the attached Foxglove.

        This method generates a set of gateware, and then uploads that gatware
        to the attached Foxglove board. This resets the FPGA, and reconfigures it
        to provide the connections and interfaces described in the target configuration.
        """

        try:
            import nmigen
        except ImportError:
            raise EnvironmentError("Cannot import nMigen, so we can't dynamically generate Gateware.")

        # FIXME: read VCC properties and etc. from the relevant bitstream

        # Convert our configuration to a bitstream, and then configure the FPGA with it.
        bitstream = configuration.to_bitstream()
        self.configure_fpga(bitstream)

    def provide_vcca(self, voltage):
        """ Set VCCA to the provided voltage. """
        self._set_rail_voltage('VCCA', voltage)

    def use_external_vcca(self):
        """ Disable the VCCA regulator. """
        self._set_rail_voltage('VCCA', None)

    def provide_vccb(self, voltage):
        """ Set VCCB to the provided voltage. """
        self._set_rail_voltage('VCCB', voltage)

    def use_external_vccb(self):
        """ Disable the VCCA regulator. """
        self._set_rail_voltage('VCCB', None)

    def set_aux_rail_voltage(self, voltage):
        """ Set VCCA to the provided voltage. """
        self._set_rail_voltage('AUX', voltage)

    def disable_aux_rail(self):
        """ Disable the VCCA regulator. """
        self._set_rail_voltage('AUX', None)

    def provide_clock(self, clk_pin=2):
        """ Provide a clock to the target FPGA. """

        # FIXME: abstract this into a clock generator interface
        CLOCK_SOURCE_60MHZ = 0x0D
        self.board.apis.clock_gen.output_clock(clk_pin, CLOCK_SOURCE_60MHZ)


text:
layout: page
title: Fake timers - Sinon.JS
breadcrumb: fake timers
---

Fake timers are synchronous implementations of `setTimeout` and friends that
Sinon.JS can overwrite the global functions with to allow you to more easily
test code using them.

Fake timers provide a `clock` object to pass time, which can also be used to control `Date` objects created through either `new Date();`
or `Date.now();` (if supported by the browser).

For standalone usage of fake timers it is recommended to use [lolex](https://github.com/sinonjs/lolex) package instead. It provides the same
set of features (Sinon uses it under the hood) and was previously extracted from Sinon.JS.

```javascript
{
    setUp: function () {
        this.clock = sinon.useFakeTimers();
    },

    tearDown: function () {
        this.clock.restore();
    },

    "test should animate element over 500ms" : function(){
        var el = jQuery("<div></div>");
        el.appendTo(document.body);

        el.animate({ height: "200px", width: "200px" });
        this.clock.tick(510);

        assertEquals("200px", el.css("height"));
        assertEquals("200px", el.css("width"));
    }
}
```

## Fake timers API

#### `var clock = sinon.useFakeTimers();`

Causes Sinon to replace the global `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, `setImmediate`, `clearImmediate` and `Date` with a custom implementation which is bound to the returned `clock` object.

Starts the clock at the UNIX epoch (timestamp of 0).

#### `var clock = sinon.useFakeTimers(now);`

As above, but rather than starting the clock with a timestamp of 0, start at the provided timestamp.

*Since `sinon@2.0.0`*

You can also pass in a Date object, and its `getTime()` will be used for the starting timestamp.

#### `var clock = sinon.useFakeTimers([now, ]prop1, prop2, ...);`

Sets the clock start timestamp and names functions to fake. If the first argument is not numeric, it sets the clock to 0 and treats all arguments as names of functions to fake.

Possible functions are `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, `setImmediate`, `clearImmediate` and `Date`.  Any functions not listed continue to use the original version of the function, including the actual time for the timestamp. This can have surprising results and should be done with care.

Note that if no functions are listed, the default behavior is to replace all eligible functions.

#### `clock.tick(ms);`

Tick the clock ahead `ms` milliseconds.

Causes all timers scheduled within the affected time range to be called.

#### `clock.restore();`

Restore the faked methods.

Call in e.g. `tearDown`.


text:
package com.kodroid.pilot.lib.android;

import com.kodroid.pilot.lib.android.uiTypeHandler.StateStackFrameSetRenderer;
import com.kodroid.pilot.lib.statestack.StateStackFrame;
import com.kodroid.pilot.lib.statestack.StateStack;

import java.util.LinkedList;
import java.util.List;

/**
 * This class holds the {@link StateStackFrameSetRenderer} collection that is queried upon {@link StateStack}
 * changes.
 */
public class StateStackRenderer implements StateStack.TopFrameChangedListener
{
    private StateStackFrameSetRenderer[] stateStackFrameSetRenderers;
    private StateStack stateStack;
    private boolean hostActivityStarted;

    //==================================================================//
    // Constructor
    //==================================================================//

    /**
     * @param stateStackFrameSetRenderers UITypeHandlers passed in here have to have corresponding entries for
     *                       *all* StateStackFrame classes that exist in this project.
     */
    public StateStackRenderer(StateStack stateStack, StateStackFrameSetRenderer... stateStackFrameSetRenderers)
    {
        this.stateStack = stateStack;
        this.stateStackFrameSetRenderers = stateStackFrameSetRenderers;
    }

    //==================================================================//
    // Hosting Activity Visibility Events
    //==================================================================//

    public void hostActivityOnStarted()
    {
        hostActivityStarted = true;
        //notify all frames represented by views being drawn to the screen
        for(StateStackFrame frame : getCurrentlyVisibleFrames(stateStack, false))
            frame.frameViewVisible(true);
    }

    public void hostActivityOnStopped()
    {
        hostActivityStarted= false;
        //notify all frames represented by views being drawn to the screen
        for(StateStackFrame frame : getCurrentlyVisibleFrames(stateStack, false))
            frame.frameViewVisible(false);
    }

    //==================================================================//
    // Frame View visibility checking
    //==================================================================//

    /**
     * Will iterate the stack top down, and return a list of frames that are all represented by
     * Views that are currently being drawn to screen (Views behind not full screen opaque view are
     * treated as visible in this context).
     *
     * Top frame index 0
     *
     * @param stateStack
     * @return
     */
    private List<StateStackFrame> getCurrentlyVisibleFrames(StateStack stateStack, boolean ignoreTop)
    {
        List<StateStackFrame> currentlyVisibleFrames = new LinkedList<>();

        int count = 1; //1 is top of stack for below method call
        if(ignoreTop)
            count++; //2 is second from top of stack for below method call
        while(true)
        {
            StateStackFrame frame = stateStack.getVisibleFrameFromTopDown(count);
            if(frame == null) //EOL
                return currentlyVisibleFrames;
            currentlyVisibleFrames.add(frame);
            if(isFrameOpaque(frame))
                return currentlyVisibleFrames;
            count++;
        }
    }

    private boolean isFrameOpaque(StateStackFrame stateStackFrame)
    {
        //find the typeHandler that handles this frame
        for(StateStackFrameSetRenderer stateStackFrameSetRenderer : stateStackFrameSetRenderers)
        {
            if (stateStackFrameSetRenderer.isFrameSupported(stateStackFrame.getClass()))
            {
                return stateStackFrameSetRenderer.isFrameOpaque(stateStackFrame);
            }
        }

        throw new IllegalStateException("No StateStackFrameSetRenderer registered for StateStackFrame of type "+ stateStackFrame.getClass().getName());
    }

    //==================================================================//
    // Frame Rendering
    //==================================================================//

    /**
     * Will render all passed frames, bottom up. Should be used after a config change.
     */
    public void renderAllCurrentlyVisibleFrames(StateStack stateStack)
    {
        List<StateStackFrame> framesToRender = getCurrentlyVisibleFrames(stateStack, false);
        for(int i = framesToRender.size() - 1; i >= 0; i--)
            topVisibleFrameUpdated(framesToRender.get(i), Direction.FORWARD);
    }

    @Override
    public void topVisibleFrameUpdated(StateStackFrame topVisibleFrame, Direction direction)
    {
        StateStackFrameSetRenderer handlingTypeHandler = null;

        //find the typeHandler that handles this frame
        for(StateStackFrameSetRenderer stateStackFrameSetRenderer : stateStackFrameSetRenderers) {
            if (stateStackFrameSetRenderer.isFrameSupported(topVisibleFrame.getClass()))
            {
                stateStackFrameSetRenderer.renderFrame(topVisibleFrame);
                handlingTypeHandler = stateStackFrameSetRenderer;
                break;
            }
        }

        //throw if nothing to handle this frame
        if(handlingTypeHandler == null)
            throw new IllegalStateException("No StateStackFrameSetRenderer registered for StateStackFrame of type "+topVisibleFrame.getClass().getName());

        //clear all other handlers IF the new frame is opaque
        if(handlingTypeHandler.isFrameOpaque(topVisibleFrame))
        {
            for(StateStackFrameSetRenderer stateStackFrameSetRenderer : stateStackFrameSetRenderers) {
                if (stateStackFrameSetRenderer != handlingTypeHandler) {
                    stateStackFrameSetRenderer.clearAllUI();
                }
            }
        }

        //View Frame visibility callbacks
        //first set all old visible frames to invis
        if(direction == Direction.FORWARD)
        {
            if(!hostActivityStarted)
                return; //i.e. don't bother calling false when added

            //get all the vis frame stack ignoring the top frame and call false
            for(StateStackFrame frame : getCurrentlyVisibleFrames(stateStack, true))
                frame.frameViewVisible(false);

            //call started state on top frame
            topVisibleFrame.frameViewVisible(hostActivityStarted);
        }
        else if(direction == Direction.BACK)
        {
            for(StateStackFrame frame : getCurrentlyVisibleFrames(stateStack, false))
                frame.frameViewVisible(true);
        }
    }
}


text:
package main

import (
	"github.com/gorilla/mux"
	"net/http"
	"os/exec"
	"io"
	"fmt"
)

// TODO(bp): Use DBUS endpoints and make this JSON!
func updateHandler(w http.ResponseWriter, r *http.Request) {
	cmd := exec.Command("update_engine_client", "-update", "-omaha_url=http://update.core-os.net")
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		w.WriteHeader(400)
		fmt.Fprint(w, err)
		return
	}
	if err := cmd.Start(); err != nil {
		w.WriteHeader(400)
		fmt.Fprint(w, err)
		return
	}
	io.Copy(w, stdout)
	if err := cmd.Wait(); err != nil {
		w.WriteHeader(400)
		fmt.Fprint(w, err)
		return
	}
	return
}

func setupUpdate(r *mux.Router, o Options) {
	r.HandleFunc("", updateHandler)
	r.HandleFunc("/", updateHandler)

	return
}


text:
<?php

use Scalr\DataType\ScopeInterface;

class Scalr_UI_Controller_Dashboard_Widget_Newuser extends Scalr_UI_Controller_Dashboard_Widget
{
    public function getDefinition()
    {
        return array(
            'type' => 'local'
        );
    }

    public function getContent($params = array())
    {
        $items = [];

        $user = [
            'text' => 'Invite a Colleague',
            'href' => '#/account/users',
            'status' => $this->db->GetOne('SELECT COUNT(*) FROM account_users WHERE account_id = ?', [$this->user->getAccountId()]) > 1,
            'info' =>
                'You can add additional users to your Scalr account via the Users Menu. ' .
                'It\'s also possible to configure different permission sets for each user. ' .
                'You can learn more about users on the Scalr Wiki.'
        ];

        /*$team = [
            'text' => 'Create team',
            'href' => '#/account/teams',
            'status' => !!$this->db->GetOne('SELECT COUNT(*) FROM account_teams WHERE account_id = ?', [$this->user->getAccountId()]),
            'info' => ''
        ];*/

        if ($this->request->getScope() == ScopeInterface::SCOPE_ACCOUNT) {
            $items[] = [
                'title' => 'Setup steps',
                'items' => [[
                    'text' => 'Add cloud credentials',
                    'status' => !!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED),
                    'href' => '#/account/environments/' . $this->user->getDefaultEnvironment()->id . '/clouds',
                    'info' =>
                        'Cloud Credentials are added through the Environments Menu. ' .
                        'For step-by-step instructions, review the Quick Start guide on the Scalr Wiki for your Cloud Platform of choice.'
                ], [
                    'text' => 'Start Managing Cloud Resources',
                    'status' => false, //!!$this->db->GetOne('SELECT COUNT(*) FROM governance WHERE env_id = ?', [$this->getEnvironmentId()]),
                    'href' => '#/dashboard',
                    'info' => "After you've added Cloud Credentials, navigate to your Scalr Environment, and continue following the new user checklist there."
                ]]
            ];

            $items[] = [
                'title' => 'Get your Organization on Scalr',
                'items' => [ $user ]
            ];

        } else {
            $items[] = [
                'title' => 'Setup steps',
                'items' => [[
                    'text' => 'Add cloud credentials',
                    'href' => '#/account/environments/' . $this->getEnvironmentId() . '/clouds',
                    'status' => !!count($this->getEnvironment()->getEnabledPlatforms()),
                    'info' =>
                        'Cloud Credentials are added through the Environments Menu. ' .
                        'For step-by-step instructions, review the Quick Start guide on the Scalr Wiki for your Cloud Platform of choice.'
                ]]
            ];

            $items[] = [
                'title' => 'Get started with Scalr',
                'items' => [[
                    'text' => 'Try the Three Tier App Tutorial Series'
                ], [
                    'text' => 'Create a Role',
                    'href' => '#/roles/create',
                    'status' => !!$this->db->GetOne('SELECT COUNT(*) FROM roles WHERE env_id = ?', [$this->getEnvironmentId()]),
                    'info' =>
                        'Navigate to the Roles Library to create a Role. Roles are Server templates that can be reused ' .
                        'across your infrastructure; you can learn more about Roles on the Scalr Wiki.'
                ], [
                    'text' => 'Create a Farm',
                    'href' => '#/farms/designer',
                    'status' => !!$this->db->GetOne('SELECT COUNT(*) FROM farms WHERE env_id = ?', [$this->getEnvironmentId()]),
                    'info' =>
                        'Open the Farms List to create your first Farm. Farms are a collection of parameterized Roles ' .
                        '(named Farm Roles in this context); you can learn more about Farms on the Scalr Wiki.'
                ], [
                    'text' => 'Create a Script',
                    'href' => '#/scripts?new=true',
                    'status' => !!$this->db->GetOne('SELECT COUNT(*) FROM scripts WHERE account_id = ?', [$this->user->getAccountId()]),
                    'info' =>
                        'Scripts are regular shell (or Python, Perl, Ruby etc.) scripts that you add into Scalr. ' .
                        'Once you\'ve added a Script in Scalr, Scalr can transfer it to managed Servers and execute it there.'
                ], [
                    'text' => 'Create an Orchestration Rule',
                    'status' =>
                        !!$this->db->GetOne('SELECT COUNT(*) FROM account_scripts WHERE account_id = ?', [$this->user->getAccountId()]) ||
                        !!$this->db->GetOne('SELECT COUNT(*) FROM role_scripts rs JOIN roles r ON rs.role_id = r.id WHERE r.env_id = ?', [$this->getEnvironmentId()]) ||
                        !!$this->db->GetOne('SELECT COUNT(*) FROM farm_role_scripts frs JOIN farms f ON frs.farmid = f.id WHERE f.env_id = ?', [$this->getEnvironmentId()])
                    ,
                    'info' =>
                        'Orchestration Rules can be added to any Role you created, and to any Farm Role you add. ' .
                        'They let you define event-based automation (such as e.g. running a specific shell script when ' .
                        'a new instance comes online); you can learn more about Orchestration on the Scalr Wiki.'
                ], [
                    'text' => 'Launch a Farm',
                    'href' => '#/farms',
                    'status' => !!$this->db->GetOne('SELECT COUNT(*) FROM farms WHERE env_id = ? AND dtlaunched IS NOT NULL', [$this->getEnvironmentId()]),
                    'info' =>
                        'Once you\'ve created and configured a Farm, launch it from the Farms List. ' .
                        'Launching a Farm results in Scalr provisioning instances from your cloud accoridng to the Farm Roles you configured. ' .
                        'Once a Farm is launched, certain configuration cannot be changed until the Farm is terminated; ' .
                        'you can learn more about Farm lifecycle management on the Scalr Wiki.'
                ], [
                    'text' => 'Create a Global Variable',
                    'href' => '#/core/variables',
                    'status' =>
                        !!$this->db->GetOne('SELECT COUNT(*) FROM account_variables WHERE account_id = ?', [$this->user->getAccountId()]) ||
                        !!$this->db->GetOne('SELECT COUNT(*) FROM client_environment_variables WHERE env_id = ?', [$this->getEnvironmentId()]) ||
                        !!$this->db->GetOne('SELECT COUNT(*) FROM farm_variables fv JOIN farms f ON fv.farm_id = f.id WHERE f.env_id = ?', [$this->getEnvironmentId()]) ||
                        !!$this->db->GetOne('SELECT COUNT(*) FROM role_variables rv JOIN roles r ON rv.role_id = r.id WHERE r.env_id = ?', [$this->getEnvironmentId()])
                    ,
                    'info' =>
                        'Global Variables let you configure the automation you create using Scalr\'s Orchestration Engine. ' .
                        'Any Global Variable you define will be placed by Scalr in the environment when an Orchestration Rules ' .
                        'executes a script. Global Variables are very flexible, and can be defined in a number of different scopes; ' .
                        'you can learn more about Global Variables on the Scalr Wiki.'
                ]]
            ];

            $items[] = [
                'title' => 'Get your Organization on Scalr',
                'items' => [ $user, [
                    'text' => 'Enforce a Governance Policy',
                    'href' => '#/core/governance',
                    'status' => !!$this->db->GetOne('SELECT COUNT(*) FROM governance WHERE env_id = ?', [$this->getEnvironmentId()]),
                    'info' =>
                        'Governance lets you create and enforce policies that control how users can consume the cloud resources available in this Environment. ' .
                        'Governance Policies include restricting instance types or networks, setting lease periods on infrastructure, and more.'
                ]]
            ];
        }

        return $items;
    }
}


text:
package de.nl.moo.data;

public interface NameHashCodeContainer {

    int getHashCode(String name);

    String getName(int hashCode);

}


text:
var pg = require('pg');
pg.conString = "postgres://postgres:1234@localhost:5432/cooking-genie";

module.exports = pg;


text:
'use strict';

describe('Controller: PropertyDetailCtrl', function () {

  var $mdDialog,
    requestHandler,
    property,
    $rootScope,
    $httpBackend,
    createController,
    Definition,
    scope;

  beforeEach(module('amApp'));

  beforeEach(inject(function ($injector) {
    $httpBackend = $injector.get('$httpBackend');
    $mdDialog = {
      hide: jasmine.createSpy('$mdDialog.close'),
      cancel: jasmine.createSpy('$mdDialog.cancel'),
      result: {
        then: jasmine.createSpy('$mdDialog.result.then')
      }
    };

    Definition = $injector.get('Definition');
    var $controller = $injector.get('$controller');

    $rootScope = $injector.get('$rootScope');
    scope = $rootScope.$new();

    createController = function(definition, property, propertyIndex, createAnother) {
      return $controller('PropertyDetailCtrl', {
        '$scope': scope ,
        '$mdDialog': $mdDialog,
        'definition': definition,
        'property': property,
        'propertyIndex': propertyIndex,
        'createAnother': createAnother
      });
    };
  }));

  it('should attach form fields, property to scope', function () {

    var definitionMock = {
      'id': '12',
      'title': 'mockTitle',
      put: function(){
      }
    };

    var propertyMock = {
      'id': '1',
      'key': 'testkey',
      put: function(){
      }
    };

    createController(definitionMock, propertyMock, null, false);

    expect(scope.formFields.length).toBe(10);
    expect(scope.property).toBe(propertyMock);
    expect(scope.createAnother).toBe(false);
  });

  it('should post property with success', function () {

    var definitionMock = {'id': '12', 'title': 'mockTitle', put: function(){}};
    var propertyMock = {'type' : 'integer', '$ref': ''};

    requestHandler = $httpBackend.when('GET', 'http://localhost:1337/definitions?sort=title+ASC')
      .respond([{'id':2, 'title':'two', 'description': 'test', 'properties' : propertyMock}]);
    $httpBackend.expectGET('http://localhost:1337/definitions?sort=title+ASC');

    requestHandler = $httpBackend.when('POST', 'http://localhost:1337/properties')
      .respond([{id: 2, key: 'testkey'}]);
    $httpBackend.expectPOST('http://localhost:1337/properties');

    createController(definitionMock, propertyMock, false);

    scope.add(propertyMock);
    $httpBackend.flush();

    expect($mdDialog.hide).toHaveBeenCalled();
  });

  it('should check cancel function for dialog', function () {

    var definitionMock = {'id': '12', 'title': 'mockTitle', put: function(){}};
    var propertyMock = {'key' : 'testkey', put: function(){}};

    createController(definitionMock, propertyMock);

    scope.cancel();
    expect($mdDialog.cancel).toHaveBeenCalledWith('cancel');
  });
});


text:
'''
    nfvo_packager.reader
    ~~~~~~~~~~~~~~~~~~~~
    CSAR interface for reading CSAR packages
'''

import logging
import os
from shutil import rmtree
from glob import glob
from tempfile import mkstemp, mkdtemp
import mimetypes
import hashlib
from base64 import b64decode
from pprint import pformat
import zipfile
import yaml
import requests

from nfvo_packager import constants

logging.basicConfig(level=logging.DEBUG)

class CSARReader(object):
    '''
        TOSCA Cloud Service Archive (CSAR) reader. This class
        is a helper for reading, validating, and extracting information
        from CSAR v1.1 ZIP files (locally or remotely).
    '''
    def __init__(self, source, is_external=False, logger=None):
        self.log = logger or logging.getLogger('csar.reader')
        self.log.debug('CSARReader(%s, %s)', source, is_external)
        self.csar = {
            'source': source,
            'external': is_external,
            'local': None,
            'destination': None,
            'metadata': None,
            'artifacts': None
        }
        self._retrieve()
        self._extract()
        self._validate()

    def __del__(self):
        '''
            Deletes temporary files and folders
        '''
        if self.csar.get('local') and \
           self.csar.get('source') and \
           self.csar['local'] != os.path.normpath(self.csar['source']) and \
           os.path.isfile(self.csar['local']):
            self.log.debug('Removing temporary file: %s', self.csar['local'])
            os.remove(self.csar['local'])
        if self.csar.get('destination') and \
           os.path.isdir(self.csar['destination']):
            self.log.debug('Removing temporary directory: %s',
                           self.csar['destination'])
            rmtree(self.csar['destination'])

    @property
    def has_metadata_file(self):
        '''Returns True if a metadata file exists'''
        return os.path.isfile(os.path.join(self.path, constants.META_FILE))

    @property
    def metadata(self):
        '''Returns CSAR metadata'''
        return self.csar.get('metadata', dict())

    @property
    def artifacts(self):
        '''Returns CSAR artifacts'''
        return self.metadata.get('artifacts', dict())

    @property
    def path(self):
        '''Returns the root (extracted) CSAR directory path'''
        return self.csar.get('destination')

    @property
    def author(self):
        '''Returns the CSAR package author'''
        return self.metadata.get(constants.META_CREATED_BY_KEY) or \
            self.metadata.get(constants.META_TMPL_AUTHOR_KEY)

    @property
    def version(self):
        '''Returns the CSAR version'''
        return self.metadata.get(constants.META_CSAR_VERSION_KEY) or \
            self.metadata.get(constants.META_TMPL_VERSION_KEY)

    @property
    def metadata_file_version(self):
        '''Returns the CSAR metadata file version'''
        return self.metadata.get(constants.META_FILE_VERSION_KEY)

    @property
    def template_name(self):
        '''Returns the CSAR template name'''
        return self.metadata.get(constants.META_TMPL_NAME_KEY)

    @property
    def entry_definitions(self):
        '''Returns the Entry-Definitions (relative) path'''
        return self.metadata.get(constants.META_ENTRY_DEFINITIONS_KEY)

    @property
    def entry_definitions_yaml(self):
        '''Returns the TOSCA entry definitions YAML contents'''
        with open(os.path.join(self.path,
                               self.entry_definitions), 'r') as mfile:
            return yaml.load(mfile)
        return dict()

    def _retrieve(self):
        '''
            Fetches a CSAR package (remote or local)
        '''
        if not self.csar['external']:
            self.log.debug('CSAR is local; normalizing path')
            self.csar['local'] = os.path.normpath(self.csar['source'])
            self.log.debug('CSAR local path is: %s', self.csar['local'])
            return
        # Get a temporary file
        self.log.debug('Generating temporary file')
        tmp_hndl, tmp_filename = mkstemp()
        self.log.debug('Temporary file is: %s', tmp_filename)
        # Download the archive
        self.log.debug('Starting remote CSAR download')
        req = requests.get(self.csar['source'], stream=True)
        for chunk in req.iter_content(chunk_size=1024):
            if chunk:
                os.write(tmp_hndl, chunk)
        self.log.debug('Remote CSAR downloaded; closing temporary file')
        os.close(tmp_hndl)
        # Update the CSAR definition
        self.csar['local'] = tmp_filename

    def _extract(self):
        '''
            Extracts a CSAR package
        '''
        if not self.csar['local']:
            raise RuntimeError('Missing CSAR file')
        if not zipfile.is_zipfile(self.csar['local']):
            raise RuntimeError('CSAR file is not in ZIP format')
        # Get a temporary directory to use
        self.log.debug('Generating temporary directory')
        tmp_dirname = mkdtemp()
        self.log.debug('Temporary directory is: %s', tmp_dirname)
        # Extract ZIP file to temporary directory
        self.log.debug('Extracting CSAR contents')
        zfile = zipfile.ZipFile(self.csar['local'])
        zfile.extractall(tmp_dirname)
        self.log.debug('CSAR contents successfully extracted')
        # Update the CSAR definition
        self.csar['destination'] = tmp_dirname

    def _validate(self):
        '''
            Validates a CSAR package
        '''
        csar_root = self.csar.get('destination')
        # Check for a CSAR contents folder
        if not csar_root or not os.path.isdir(csar_root):
            raise RuntimeError('Missing CSAR contents')
        # Validate metadata
        if self.has_metadata_file:
            self._validate_metadata_file()
        else:
            self._validate_metadata_inline()
        # Validate entry definitions
        self._validate_entry_definitions()
        # Validate artifacts
        self._validate_artifacts()

    def _validate_metadata_file(self):
        '''
            Validates CSAR metadata file
        '''
        # Check for metadata
        csar_metafile = os.path.join(self.path, constants.META_FILE)
        self.log.debug('CSAR metadata file: %s', csar_metafile)
        # Check the expected files/folders exist
        if not csar_metafile or not os.path.isfile(csar_metafile):
            raise RuntimeError('Missing CSAR metadata file')
        # Validate metadata YAML
        metadata = dict()
        self.log.debug('Attempting to parse CSAR metadata YAML')
        with open(csar_metafile, 'r') as mfile:
            metadata = yaml.load(mfile)
        self.log.debug('CSAR metadata:\n%s', pformat(metadata))
        # Validate metadata specification
        if constants.META_FILE_VERSION_KEY not in metadata:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_FILE_VERSION_KEY)
        if str(metadata[constants.META_FILE_VERSION_KEY]) != '1.0':
            raise RuntimeError('Metadata "%s" must be 1.0' %
                               constants.META_FILE_VERSION_KEY)
        if constants.META_CSAR_VERSION_KEY not in metadata:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_CSAR_VERSION_KEY)
        if str(metadata[constants.META_CSAR_VERSION_KEY]) != '1.1':
            raise RuntimeError('Metadata "%s" must be 1.1' %
                               constants.META_CSAR_VERSION_KEY)
        if constants.META_CREATED_BY_KEY not in metadata or \
           not metadata[constants.META_CREATED_BY_KEY]:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_CREATED_BY_KEY)
        if constants.META_ENTRY_DEFINITIONS_KEY not in metadata or \
           not metadata[constants.META_ENTRY_DEFINITIONS_KEY]:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_ENTRY_DEFINITIONS_KEY)
        # Update the CSAR definition
        self.csar['metadata'] = metadata

    def _validate_metadata_inline(self):
        '''
            Validates CSAR inline metadata
        '''
        # Get a list of all definition files in the root folder
        root_defs = list()
        self.log.debug('Searching for TOSCA template file with metadata')
        for ext in ['yaml', 'yml']:
            root_defs.extend(glob('%s/*.%s' % (self.path, ext)))
        # Make sure there's only one
        if len(root_defs) is not 1:
            raise RuntimeError(
                'Exactly 1 YAML file must exist in the CSAR root directory')
        # Validate metadata YAML
        def_data = dict()
        self.log.debug('Attempting to parse CSAR metadata YAML')
        with open(root_defs[0], 'r') as def_file:
            def_data = yaml.load(def_file)
        # Validate metadata specification
        metadata = def_data.get('metadata')
        if not metadata:
            raise RuntimeError('Missing metadata section')
        if constants.META_TMPL_VERSION_KEY not in metadata:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_TMPL_VERSION_KEY)
        if str(metadata[constants.META_TMPL_VERSION_KEY]) != '1.1':
            raise RuntimeError('Metadata "%s" must be 1.1' %
                               constants.META_TMPL_VERSION_KEY)
        if constants.META_TMPL_AUTHOR_KEY not in metadata or \
           not metadata[constants.META_TMPL_AUTHOR_KEY]:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_TMPL_AUTHOR_KEY)
        if constants.META_TMPL_NAME_KEY not in metadata or \
           not metadata[constants.META_TMPL_NAME_KEY]:
            raise RuntimeError('Missing metadata "%s"' %
                               constants.META_TMPL_NAME_KEY)
        # Update the CSAR definition
        metadata[constants.META_ENTRY_DEFINITIONS_KEY] = root_defs[0]
        self.csar['metadata'] = metadata

    def _validate_entry_definitions(self):
        '''
            Validates entry definitions
        '''
        self.log.debug('CSAR entry definitions: %s', self.entry_definitions)
        if not self.has_metadata_file:
            self.log.debug('Using inline metadata; skipping...')
            return
        if not os.path.isfile(os.path.join(self.path,
                                           self.entry_definitions)):
            raise RuntimeError('"%s" points to "%s", but the file '
                               'does not exist' % (
                                   constants.META_ENTRY_DEFINITIONS_KEY,
                                   self.entry_definitions))

    def _validate_artifacts(self):
        '''
            Validates artifacts
        '''
        self.log.debug('Searching for user-defined MIME types')
        mtypes = glob(os.path.join(self.path, constants.META_MIMETYPES_GLOB))
        self.log.debug('Loading %s user-defined MIME types', len(mtypes))
        mimetypes.init(mtypes or None)
        self.log.debug('Checking for artifacts')
        if not self.artifacts:
            self.log.debug('No artifacts declared')
            return
        # Iterate through each artifacts
        for name, artifact in self.artifacts.iteritems():
            self._validate_artifact(name, artifact)

    def _validate_artifact(self, name, artifact):
        '''
            Validates a single artifact
        '''
        self.log.debug('Validating artifact: %s', name)
        self.log.debug('Checking if artifact file exists')
        path = os.path.join(self.path, name)
        if not os.path.isfile(path):
            raise RuntimeError('Artifact "%s" delcared, but file does '
                               'not exist' % name)
        # Validate the content-type
        if 'content-type' not in artifact:
            raise RuntimeError('Artifact missing "content-type"')
        self.log.debug('Artifact content-type: %s', artifact['content-type'])
        tstype = artifact['content-type'].split('/')
        if len(tstype) < 2:
            raise RuntimeError('Artifact content-type must comply with the '
                               '"type/subtype" structure')
        if not tstype[-1].startswith('vnd.'):
            self.log.warn('Artifact content-type subtype should start '
                          'with "vnd."')
        # Validate content-type as a known MIME type
        self.log.debug('Checking content-type against known MIME types')
        if len([{x: y} for x, y in mimetypes.types_map.iteritems()
                if y == artifact['content-type']]) < 1:
            self.log.warn('Could not match artifact content-type '
                          'with any known MIME type')
        # Validate the artifact MIME type against the content-type
        self.log.debug('Checking artifact MIME type against content-type')
        mtype = mimetypes.guess_type(path)[0]
        if mtype is None:
            self.log.warn('Could not match artifact to a known MIME type')
        if mtype != artifact['content-type']:
            self.log.warn('Artifact content-type does not match the '
                          'artifacts MIME type')
        # Validate the signature / digest
        if 'signature' in artifact:
            sig = artifact['signature']
            algo = sig.get('algorithm')
            digest = sig.get('digest')
            if not algo:
                raise RuntimeError(
                    'Artifact signature delcared, but no algorithm was found')
            if not digest:
                raise RuntimeError(
                    'Artifact signature delcared, but no digest was found')
            # Decode base64 encoded digest
            self.log.debug('Decoding base64-encoded artifact digest')
            digest = b64decode(digest).strip()
            self.log.debug('Decoded artifact digest: %s', digest)
            # Calculate hash of the actual artifact
            self.log.debug('Calculating %s digest of artifact %s', algo, name)
            adigest = hashlib.new(algo, open(path, 'rb').read()).hexdigest()
            self.log.debug('Calculated artifact digest: %s', adigest)
            # Compare digests
            if digest != adigest:
                raise RuntimeError('Artifact digest mismatch')


text:
from djangobench.utils import run_benchmark
from query_exists.models import Book

def benchmark():
    #Checking for object that exists
    Book.objects.filter(id=1).exists()

    #Checking for object that does not exist
    Book.objects.filter(id=11).exists()

if hasattr(Book.objects, 'exists'):
    run_benchmark(
        benchmark,
        meta = {
            'description': 'A Model.objects.exists() call for both existing and non-existing objects.'
        }
    )
else:
    print "SKIP: Django before 1.2 doesn't have QuerySet.exists()"


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tvVcName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="20dp"
        android:text="@string/Vaccine_Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:drawableLeft="@drawable/vaccine" />

    <TextView
        android:id="@+id/tvVcDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tvVcName"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:text="@string/date"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:drawableLeft="@drawable/date" />

    <TextView
        android:id="@+id/dbIdVc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvVcName"
        android:layout_below="@+id/tvVcName"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="28dp"
        android:visibility="gone" />

</RelativeLayout>


text:
from __future__ import print_function

import os
import percy
from percy import errors
from percy import utils

__all__ = ['Runner']

class Runner(object):

    def __init__(self, loader=None, config=None, client=None):
        self.loader = loader
        self.config = config or percy.Config()
        self.client = client or percy.Client(config=self.config)
        self._current_build = None

        self._is_enabled = os.getenv('PERCY_ENABLE', '1') == '1'

        # Sanity check environment and auth setup. If in CI and Percy is disabled, print an error.
        if self._is_enabled:
            try:
                self.client.config.access_token
            except errors.AuthError:
                if self.client.environment.current_ci:
                    utils.print_error('[percy] Warning: Percy is disabled, no PERCY_TOKEN set.')
                self._is_enabled = False

    def initialize_build(self, **kwargs):
        # Silently pass if Percy is disabled.
        if not self._is_enabled:
            return

        build_resources = []
        build_resources = self.loader.build_resources if self.loader else []
        sha_to_build_resource = {}
        for build_resource in build_resources:
            sha_to_build_resource[build_resource.sha] = build_resource

        self._current_build = self.client.create_build(resources=build_resources, **kwargs)

        missing_resources = self._current_build['data']['relationships']['missing-resources']
        missing_resources = missing_resources.get('data', [])

        for missing_resource in missing_resources:
            sha = missing_resource['id']
            resource = sha_to_build_resource.get(sha)
            # This resource should always exist, but if by chance it doesn't we make it safe here.
            # A nicer error will be raised by the finalize API when the resource is still missing.
            if resource:
                print('Uploading new build resource: {}'.format(resource.resource_url))

                # Optimization: we don't hold all build resources in memory. Instead we store a
                # "local_path" variable that be used to read the file again if it is needed.
                if resource.local_path:
                    with open(resource.local_path, 'rb') as f:
                        content = f.read()
                else:
                    content = resource.content
                self.client.upload_resource(self._current_build['data']['id'], content)

    @property
    def build_id(self):
      if not self._is_enabled:
        return
      if not self._current_build:
        raise errors.UninitializedBuildError('Cannot get current build id before build is initialized')
      return self._current_build['data']['id']

    def snapshot(self, **kwargs):
        # Silently pass if Percy is disabled.
        if not self._is_enabled:
            return
        if not self._current_build:
            raise errors.UninitializedBuildError('Cannot call snapshot before build is initialized')

        root_resource = self.loader.snapshot_resources[0]
        build_id = self._current_build['data']['id']
        snapshot_data = self.client.create_snapshot(build_id, [root_resource], **kwargs)

        missing_resources = snapshot_data['data']['relationships']['missing-resources']
        missing_resources = missing_resources.get('data', [])

        if missing_resources:
            # There can only be one missing resource in this case, the root_resource.
            self.client.upload_resource(build_id, root_resource.content)

        self.client.finalize_snapshot(snapshot_data['data']['id'])

    def finalize_build(self):
        # Silently pass if Percy is disabled.
        if not self._is_enabled:
            return
        if not self._current_build:
            raise errors.UninitializedBuildError(
                'Cannot finalize_build before build is initialized.')
        self.client.finalize_build(self._current_build['data']['id'])
        self._current_build = None


text:
#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS

#include <SDL.h>
#include <SDL_Image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include <windows.h>

#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <malloc.h>
#include <hash_set>
#include <unordered_map>

#pragma comment(lib, "SDL2.lib")
#pragma comment(lib, "SDL2Main.lib")
#pragma comment(lib, "legacy_stdio_definitions.lib")
#pragma comment(lib, "SDL2_image.lib")
#pragma comment(lib, "SDL2_ttf.lib")
#pragma comment(lib, "SDL2_mixer.lib")

#define PIOVER180 0.0174532925f

using namespace std;

const string DEFAULT_CONFIG_FILE = "config.cfg";


text:
Configuring Kapost
----
### Setting up the app
1. In your Kapost account go to Settings > App Center
2. Click on Install more apps
3. Choose CMS then select XML-RPC, select your instance and click install
4. Fill in the form for the new XML-RPC, you need to use a username/password that has "Kapost API Access" permission or an administrator.
5. In the Endpoint field you need to use ``http://mywebsite.com/kapost-service/`` (you can also use https:// of course), for the url field set that to the home page of your site ``http://mywebsite.com/``.

### Creating the content type in Kapost
1. In Kapost go to Settings > Content Types and click the New Type button.
2. In the Field Name field, you need to put ``Page`` by default, if you are using a custom Kapost Object ([see here for instructions](custom-types.md)) you should put the name of your custom type you are using in your code.
3. After filling out the base information for the new type set the primary destination to the App you configured in the process above.

### Defining SEO Fields
Because of how Kapost handles/supports the SEO fields it has built in, this module cannot use or access them. So in order to have Kapost populate SilverStripe's ``MetaDescription`` field as well as have the ``MenuTitle`` be different from ``Title`` for basic pages you need to create two custom fields text fields under Settings > Custom Fields. Set the field name's based on the table bellow.

| Kapost Field Name  | Maps to SilverStripe field |
|--------------------|----------------------------|
| SS_Title           | Title (optional, falls back to Kapost's title field) |
| SS_MetaDescription | MetaDescription            |

### Using Conversion Notes
Sometimes you have content types that need some additional information from the Kapost Author. Maybe this information is as simple as where a page appears in the tree or maybe it's more complex if you have additional functionality. To do this you can add a custom field (Settings > Custom Fields in Kapost) to your content types with a field name of ``SS_KapostConversionNotes``. When this field is handled by the Kapost Bridge it will appear in the conversion dialog as an icon of the Kapost Author's avatar. When that icon is clicked a balloon will open containing the notes from the Kapost Author. This field is by default discarded after the conversion is completed.