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

package config

import (
	"bufio"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"reflect"
	"sort"

	"github.com/cilium/cilium/pkg/bpf"
	"github.com/cilium/cilium/pkg/byteorder"
	"github.com/cilium/cilium/pkg/datapath"
	"github.com/cilium/cilium/pkg/datapath/iptables"
	"github.com/cilium/cilium/pkg/datapath/link"
	datapathOption "github.com/cilium/cilium/pkg/datapath/option"
	"github.com/cilium/cilium/pkg/defaults"
	"github.com/cilium/cilium/pkg/identity"
	"github.com/cilium/cilium/pkg/labels"
	"github.com/cilium/cilium/pkg/maglev"
	"github.com/cilium/cilium/pkg/maps/bwmap"
	"github.com/cilium/cilium/pkg/maps/callsmap"
	"github.com/cilium/cilium/pkg/maps/ctmap"
	"github.com/cilium/cilium/pkg/maps/encrypt"
	"github.com/cilium/cilium/pkg/maps/eppolicymap"
	"github.com/cilium/cilium/pkg/maps/eventsmap"
	"github.com/cilium/cilium/pkg/maps/fragmap"
	ipcachemap "github.com/cilium/cilium/pkg/maps/ipcache"
	"github.com/cilium/cilium/pkg/maps/ipmasq"
	"github.com/cilium/cilium/pkg/maps/lbmap"
	"github.com/cilium/cilium/pkg/maps/lxcmap"
	"github.com/cilium/cilium/pkg/maps/metricsmap"
	"github.com/cilium/cilium/pkg/maps/nat"
	"github.com/cilium/cilium/pkg/maps/neighborsmap"
	"github.com/cilium/cilium/pkg/maps/policymap"
	"github.com/cilium/cilium/pkg/maps/signalmap"
	"github.com/cilium/cilium/pkg/maps/sockmap"
	"github.com/cilium/cilium/pkg/maps/tunnel"
	"github.com/cilium/cilium/pkg/node"
	"github.com/cilium/cilium/pkg/option"

	"github.com/vishvananda/netlink"
)

// HeaderfileWriter is a wrapper type which implements datapath.ConfigWriter.
// It manages writing of configuration of datapath program headerfiles.
type HeaderfileWriter struct{}

func writeIncludes(w io.Writer) (int, error) {
	return fmt.Fprintf(w, "#include \"lib/utils.h\"\n\n")
}

// WriteNodeConfig writes the local node configuration to the specified writer.
func (h *HeaderfileWriter) WriteNodeConfig(w io.Writer, cfg *datapath.LocalNodeConfiguration) error {
	extraMacrosMap := make(map[string]string)
	cDefinesMap := make(map[string]string)

	fw := bufio.NewWriter(w)

	writeIncludes(w)

	routerIP := node.GetIPv6Router()
	hostIP := node.GetIPv6()

	fmt.Fprintf(fw, "/*\n")
	if option.Config.EnableIPv6 {
		fmt.Fprintf(fw, " cilium.v6.external.str %s\n", node.GetIPv6().String())
		fmt.Fprintf(fw, " cilium.v6.internal.str %s\n", node.GetIPv6Router().String())
		fmt.Fprintf(fw, " cilium.v6.nodeport.str %s\n", node.GetNodePortIPv6Addrs())
		fmt.Fprintf(fw, "\n")
	}
	fmt.Fprintf(fw, " cilium.v4.external.str %s\n", node.GetExternalIPv4().String())
	fmt.Fprintf(fw, " cilium.v4.internal.str %s\n", node.GetInternalIPv4().String())
	fmt.Fprintf(fw, " cilium.v4.nodeport.str %s\n", node.GetNodePortIPv4Addrs())
	fmt.Fprintf(fw, "\n")
	if option.Config.EnableIPv6 {
		fw.WriteString(dumpRaw(defaults.RestoreV6Addr, node.GetIPv6Router()))
	}
	fw.WriteString(dumpRaw(defaults.RestoreV4Addr, node.GetInternalIPv4()))
	fmt.Fprintf(fw, " */\n\n")

	cDefinesMap["KERNEL_HZ"] = fmt.Sprintf("%d", option.Config.KernelHz)

	if option.Config.EnableIPv6 {
		extraMacrosMap["ROUTER_IP"] = routerIP.String()
		fw.WriteString(defineIPv6("ROUTER_IP", routerIP))
	}

	if option.Config.EnableIPv4 {
		ipv4GW := node.GetInternalIPv4()
		loopbackIPv4 := node.GetIPv4Loopback()
		ipv4Range := node.GetIPv4AllocRange()
		cDefinesMap["IPV4_GATEWAY"] = fmt.Sprintf("%#x", byteorder.HostSliceToNetwork(ipv4GW, reflect.Uint32).(uint32))
		cDefinesMap["IPV4_LOOPBACK"] = fmt.Sprintf("%#x", byteorder.HostSliceToNetwork(loopbackIPv4, reflect.Uint32).(uint32))
		cDefinesMap["IPV4_MASK"] = fmt.Sprintf("%#x", byteorder.HostSliceToNetwork(ipv4Range.Mask, reflect.Uint32).(uint32))

		if option.Config.EnableIPv4FragmentsTracking {
			cDefinesMap["ENABLE_IPV4_FRAGMENTS"] = "1"
			cDefinesMap["IPV4_FRAG_DATAGRAMS_MAP"] = fragmap.MapName
			cDefinesMap["CILIUM_IPV4_FRAG_MAP_MAX_ENTRIES"] = fmt.Sprintf("%d", option.Config.FragmentsMapEntries)
		}
	}

	if nat46Range := option.Config.NAT46Prefix; nat46Range != nil {
		fw.WriteString(FmtDefineAddress("NAT46_PREFIX", nat46Range.IP))
	}

	if option.Config.EnableIPv6 {
		extraMacrosMap["HOST_IP"] = hostIP.String()
		fw.WriteString(defineIPv6("HOST_IP", hostIP))
	}

	cDefinesMap["HOST_ID"] = fmt.Sprintf("%d", identity.GetReservedID(labels.IDNameHost))
	cDefinesMap["WORLD_ID"] = fmt.Sprintf("%d", identity.GetReservedID(labels.IDNameWorld))
	cDefinesMap["HEALTH_ID"] = fmt.Sprintf("%d", identity.GetReservedID(labels.IDNameHealth))
	cDefinesMap["UNMANAGED_ID"] = fmt.Sprintf("%d", identity.GetReservedID(labels.IDNameUnmanaged))
	cDefinesMap["INIT_ID"] = fmt.Sprintf("%d", identity.GetReservedID(labels.IDNameInit))
	cDefinesMap["REMOTE_NODE_ID"] = fmt.Sprintf("%d", identity.GetReservedID(labels.IDNameRemoteNode))
	cDefinesMap["CILIUM_LB_MAP_MAX_ENTRIES"] = fmt.Sprintf("%d", lbmap.MaxEntries)
	cDefinesMap["TUNNEL_MAP"] = tunnel.MapName
	cDefinesMap["TUNNEL_ENDPOINT_MAP_SIZE"] = fmt.Sprintf("%d", tunnel.MaxEntries)
	cDefinesMap["ENDPOINTS_MAP"] = lxcmap.MapName
	cDefinesMap["ENDPOINTS_MAP_SIZE"] = fmt.Sprintf("%d", lxcmap.MaxEntries)
	cDefinesMap["METRICS_MAP"] = metricsmap.MapName
	cDefinesMap["METRICS_MAP_SIZE"] = fmt.Sprintf("%d", metricsmap.MaxEntries)
	cDefinesMap["POLICY_MAP_SIZE"] = fmt.Sprintf("%d", policymap.MaxEntries)
	cDefinesMap["IPCACHE_MAP"] = ipcachemap.Name
	cDefinesMap["IPCACHE_MAP_SIZE"] = fmt.Sprintf("%d", ipcachemap.MaxEntries)
	cDefinesMap["POLICY_PROG_MAP_SIZE"] = fmt.Sprintf("%d", policymap.PolicyCallMaxEntries)
	cDefinesMap["SOCKOPS_MAP_SIZE"] = fmt.Sprintf("%d", sockmap.MaxEntries)
	cDefinesMap["ENCRYPT_MAP"] = encrypt.MapName
	cDefinesMap["CT_CONNECTION_LIFETIME_TCP"] = fmt.Sprintf("%d", int64(option.Config.CTMapEntriesTimeoutTCP.Seconds()))
	cDefinesMap["CT_CONNECTION_LIFETIME_NONTCP"] = fmt.Sprintf("%d", int64(option.Config.CTMapEntriesTimeoutAny.Seconds()))
	cDefinesMap["CT_SERVICE_LIFETIME_TCP"] = fmt.Sprintf("%d", int64(option.Config.CTMapEntriesTimeoutSVCTCP.Seconds()))
	cDefinesMap["CT_SERVICE_LIFETIME_NONTCP"] = fmt.Sprintf("%d", int64(option.Config.CTMapEntriesTimeoutSVCAny.Seconds()))
	cDefinesMap["CT_SYN_TIMEOUT"] = fmt.Sprintf("%d", int64(option.Config.CTMapEntriesTimeoutSYN.Seconds()))
	cDefinesMap["CT_CLOSE_TIMEOUT"] = fmt.Sprintf("%d", int64(option.Config.CTMapEntriesTimeoutFIN.Seconds()))
	cDefinesMap["CT_REPORT_INTERVAL"] = fmt.Sprintf("%d", int64(option.Config.MonitorAggregationInterval.Seconds()))
	cDefinesMap["CT_REPORT_FLAGS"] = fmt.Sprintf("%#04x", int64(option.Config.MonitorAggregationFlags))

	if option.Config.DatapathMode == datapathOption.DatapathModeIpvlan {
		cDefinesMap["ENABLE_SECCTX_FROM_IPCACHE"] = "1"
		cDefinesMap["ENABLE_EXTRA_HOST_DEV"] = "1"
	}

	if option.Config.PreAllocateMaps {
		cDefinesMap["PREALLOCATE_MAPS"] = "1"
	}

	cDefinesMap["EVENTS_MAP"] = eventsmap.MapName
	cDefinesMap["SIGNAL_MAP"] = signalmap.MapName
	cDefinesMap["POLICY_CALL_MAP"] = policymap.PolicyCallMapName
	cDefinesMap["EP_POLICY_MAP"] = eppolicymap.MapName
	cDefinesMap["LB6_REVERSE_NAT_MAP"] = "cilium_lb6_reverse_nat"
	cDefinesMap["LB6_SERVICES_MAP_V2"] = "cilium_lb6_services_v2"
	cDefinesMap["LB6_BACKEND_MAP"] = "cilium_lb6_backends"
	cDefinesMap["LB6_REVERSE_NAT_SK_MAP"] = lbmap.SockRevNat6MapName
	cDefinesMap["LB6_REVERSE_NAT_SK_MAP_SIZE"] = fmt.Sprintf("%d", lbmap.MaxSockRevNat6MapEntries)
	cDefinesMap["LB4_REVERSE_NAT_MAP"] = "cilium_lb4_reverse_nat"
	cDefinesMap["LB4_SERVICES_MAP_V2"] = "cilium_lb4_services_v2"
	cDefinesMap["LB4_BACKEND_MAP"] = "cilium_lb4_backends"
	cDefinesMap["LB4_REVERSE_NAT_SK_MAP"] = lbmap.SockRevNat4MapName
	cDefinesMap["LB4_REVERSE_NAT_SK_MAP_SIZE"] = fmt.Sprintf("%d", lbmap.MaxSockRevNat4MapEntries)

	if option.Config.EnableSessionAffinity {
		cDefinesMap["ENABLE_SESSION_AFFINITY"] = "1"
		cDefinesMap["LB_AFFINITY_MATCH_MAP"] = lbmap.AffinityMatchMapName
		if option.Config.EnableIPv4 {
			cDefinesMap["LB4_AFFINITY_MAP"] = lbmap.Affinity4MapName
		}
		if option.Config.EnableIPv6 {
			cDefinesMap["LB6_AFFINITY_MAP"] = lbmap.Affinity6MapName
		}
	}

	cDefinesMap["TRACE_PAYLOAD_LEN"] = fmt.Sprintf("%dULL", option.Config.TracePayloadlen)
	cDefinesMap["MTU"] = fmt.Sprintf("%d", cfg.MtuConfig.GetDeviceMTU())

	if option.Config.EnableIPv4 {
		cDefinesMap["ENABLE_IPV4"] = "1"
	}

	if option.Config.EnableIPv6 {
		cDefinesMap["ENABLE_IPV6"] = "1"
	}

	if option.Config.EnableIPSec {
		cDefinesMap["ENABLE_IPSEC"] = "1"
	}

	if option.Config.InstallIptRules || iptables.KernelHasNetfilter() {
		cDefinesMap["NO_REDIRECT"] = "1"
	}

	if option.Config.EnableBPFTProxy {
		cDefinesMap["ENABLE_TPROXY"] = "1"
	}

	if option.Config.EncryptNode {
		cDefinesMap["ENCRYPT_NODE"] = "1"
	}

	if option.Config.DevicePreFilter != "undefined" {
		cDefinesMap["ENABLE_PREFILTER"] = "1"
	}

	if !option.Config.DisableK8sServices {
		cDefinesMap["ENABLE_SERVICES"] = "1"
	}

	if option.Config.EnableHostReachableServices {
		if option.Config.EnableHostServicesTCP {
			cDefinesMap["ENABLE_HOST_SERVICES_TCP"] = "1"
		}
		if option.Config.EnableHostServicesUDP {
			cDefinesMap["ENABLE_HOST_SERVICES_UDP"] = "1"
		}
		if option.Config.EnableHostServicesTCP && option.Config.EnableHostServicesUDP {
			cDefinesMap["ENABLE_HOST_SERVICES_FULL"] = "1"
		}
		if option.Config.EnableHostServicesPeer {
			cDefinesMap["ENABLE_HOST_SERVICES_PEER"] = "1"
		}
	}

	if option.Config.EnableNodePort {
		cDefinesMap["ENABLE_NODEPORT"] = "1"
		cDefinesMap["ENABLE_LOADBALANCER"] = "1"

		if option.Config.EnableIPv4 {
			cDefinesMap["NODEPORT_NEIGH4"] = neighborsmap.Map4Name
			cDefinesMap["NODEPORT_NEIGH4_SIZE"] = fmt.Sprintf("%d", option.Config.NeighMapEntriesGlobal)
		}
		if option.Config.EnableIPv6 {
			cDefinesMap["NODEPORT_NEIGH6"] = neighborsmap.Map6Name
			cDefinesMap["NODEPORT_NEIGH6_SIZE"] = fmt.Sprintf("%d", option.Config.NeighMapEntriesGlobal)
		}
		if option.Config.NodePortMode == option.NodePortModeDSR ||
			option.Config.NodePortMode == option.NodePortModeHybrid {
			cDefinesMap["ENABLE_DSR"] = "1"
			if option.Config.NodePortMode == option.NodePortModeHybrid {
				cDefinesMap["ENABLE_DSR_HYBRID"] = "1"
			}
		}
		if option.Config.NodePortAcceleration != option.NodePortAccelerationDisabled {
			cDefinesMap["ENABLE_NODEPORT_ACCELERATION"] = "1"
		}
		if option.Config.NodePortHairpin {
			cDefinesMap["ENABLE_NODEPORT_HAIRPIN"] = "1"
		}
		if option.Config.EnableExternalIPs {
			cDefinesMap["ENABLE_EXTERNAL_IP"] = "1"
		}
		if option.Config.EnableHostPort {
			cDefinesMap["ENABLE_HOSTPORT"] = "1"
		}

		if option.Config.EnableSVCSourceRangeCheck {
			cDefinesMap["ENABLE_SRC_RANGE_CHECK"] = "1"
			if option.Config.EnableIPv4 {
				cDefinesMap["LB4_SRC_RANGE_MAP"] = lbmap.SourceRange4MapName
				cDefinesMap["LB4_SRC_RANGE_MAP_SIZE"] =
					fmt.Sprintf("%d", lbmap.SourceRange4Map.MapInfo.MaxEntries)
			}
			if option.Config.EnableIPv6 {
				cDefinesMap["LB6_SRC_RANGE_MAP"] = lbmap.SourceRange6MapName
				cDefinesMap["LB6_SRC_RANGE_MAP_SIZE"] =
					fmt.Sprintf("%d", lbmap.SourceRange6Map.MapInfo.MaxEntries)
			}
		}

		cDefinesMap["NODEPORT_PORT_MIN"] = fmt.Sprintf("%d", option.Config.NodePortMin)
		cDefinesMap["NODEPORT_PORT_MAX"] = fmt.Sprintf("%d", option.Config.NodePortMax)
		cDefinesMap["NODEPORT_PORT_MIN_NAT"] = fmt.Sprintf("%d", option.Config.NodePortMax+1)
		cDefinesMap["NODEPORT_PORT_MAX_NAT"] = "65535"
	}
	const (
		selectionRandom = iota + 1
		selectionMaglev
	)
	cDefinesMap["LB_SELECTION_RANDOM"] = fmt.Sprintf("%d", selectionRandom)
	cDefinesMap["LB_SELECTION_MAGLEV"] = fmt.Sprintf("%d", selectionMaglev)
	if option.Config.NodePortAlg == option.NodePortAlgRandom {
		cDefinesMap["LB_SELECTION"] = fmt.Sprintf("%d", selectionRandom)
	} else if option.Config.NodePortAlg == option.NodePortAlgMaglev {
		cDefinesMap["LB_SELECTION"] = fmt.Sprintf("%d", selectionMaglev)
		cDefinesMap["LB_MAGLEV_LUT_SIZE"] = fmt.Sprintf("%d", option.Config.MaglevTableSize)
		if option.Config.EnableIPv6 {
			cDefinesMap["LB6_MAGLEV_MAP_INNER"] = lbmap.MaglevInner6MapName
			cDefinesMap["LB6_MAGLEV_MAP_OUTER"] = lbmap.MaglevOuter6MapName
		}
		if option.Config.EnableIPv4 {
			cDefinesMap["LB4_MAGLEV_MAP_INNER"] = lbmap.MaglevInner4MapName
			cDefinesMap["LB4_MAGLEV_MAP_OUTER"] = lbmap.MaglevOuter4MapName
		}
	}
	cDefinesMap["HASH_INIT4_SEED"] = fmt.Sprintf("%d", maglev.SeedJhash0)
	cDefinesMap["HASH_INIT6_SEED"] = fmt.Sprintf("%d", maglev.SeedJhash1)
	if option.Config.EnableNodePort {
		directRoutingIface := option.Config.DirectRoutingDevice
		directRoutingIfIndex, err := link.GetIfIndex(directRoutingIface)
		if err != nil {
			return err
		}
		cDefinesMap["DIRECT_ROUTING_DEV_IFINDEX"] = fmt.Sprintf("%d", directRoutingIfIndex)

		if option.Config.EnableIPv4 {
			nodePortIPv4Addrs := node.GetNodePortIPv4AddrsWithDevices()
			ipv4 := byteorder.HostSliceToNetwork(nodePortIPv4Addrs[directRoutingIface], reflect.Uint32).(uint32)
			cDefinesMap["IPV4_DIRECT_ROUTING"] = fmt.Sprintf("%d", ipv4)
		}

		if option.Config.EnableIPv6 {
			directRoutingIPv6 := node.GetNodePortIPv6AddrsWithDevices()[directRoutingIface]
			extraMacrosMap["IPV6_DIRECT_ROUTING"] = directRoutingIPv6.String()
			fw.WriteString(FmtDefineAddress("IPV6_DIRECT_ROUTING", directRoutingIPv6))
		}
	} else {
		var directRoutingIPv6 net.IP
		cDefinesMap["DIRECT_ROUTING_DEV_IFINDEX"] = "0"
		if option.Config.EnableIPv4 {
			cDefinesMap["IPV4_DIRECT_ROUTING"] = "0"
		}
		if option.Config.EnableIPv6 {
			extraMacrosMap["IPV6_DIRECT_ROUTING"] = directRoutingIPv6.String()
			fw.WriteString(FmtDefineAddress("IPV6_DIRECT_ROUTING", directRoutingIPv6))
		}
	}

	if option.Config.EnableBandwidthManager {
		cDefinesMap["ENABLE_BANDWIDTH_MANAGER"] = "1"
		cDefinesMap["THROTTLE_MAP"] = bwmap.MapName
		cDefinesMap["THROTTLE_MAP_SIZE"] = fmt.Sprintf("%d", bwmap.MapSize)
	}

	if option.Config.EnableHostFirewall {
		cDefinesMap["ENABLE_HOST_FIREWALL"] = "1"
	}

	if option.Config.EncryptInterface != "" {
		link, err := netlink.LinkByName(option.Config.EncryptInterface)
		if err == nil {
			cDefinesMap["ENCRYPT_IFACE"] = fmt.Sprintf("%d", link.Attrs().Index)

			addr, err := netlink.AddrList(link, netlink.FAMILY_V4)
			if err == nil {
				a := byteorder.HostSliceToNetwork(addr[0].IPNet.IP, reflect.Uint32).(uint32)
				cDefinesMap["IPV4_ENCRYPT_IFACE"] = fmt.Sprintf("%d", a)
			}
		}
	}
	if option.Config.IsPodSubnetsDefined() {
		cDefinesMap["IP_POOLS"] = "1"
	}
	if option.Config.EnableNodePort {
		if option.Config.EnableIPv4 {
			cDefinesMap["SNAT_MAPPING_IPV4"] = nat.MapNameSnat4Global
			cDefinesMap["SNAT_MAPPING_IPV4_SIZE"] = fmt.Sprintf("%d", option.Config.NATMapEntriesGlobal)
		}

		if option.Config.EnableIPv6 {
			cDefinesMap["SNAT_MAPPING_IPV6"] = nat.MapNameSnat6Global
			cDefinesMap["SNAT_MAPPING_IPV6_SIZE"] = fmt.Sprintf("%d", option.Config.NATMapEntriesGlobal)
		}

		if option.Config.EnableBPFMasquerade && option.Config.EnableIPv4 {
			cDefinesMap["ENABLE_MASQUERADE"] = "1"
			cidr := datapath.RemoteSNATDstAddrExclusionCIDR()
			cDefinesMap["IPV4_SNAT_EXCLUSION_DST_CIDR"] =
				fmt.Sprintf("%#x", byteorder.HostSliceToNetwork(cidr.IP, reflect.Uint32).(uint32))
			ones, _ := cidr.Mask.Size()
			cDefinesMap["IPV4_SNAT_EXCLUSION_DST_CIDR_LEN"] = fmt.Sprintf("%d", ones)

			// ip-masq-agent depends on bpf-masq
			if option.Config.EnableIPMasqAgent {
				cDefinesMap["ENABLE_IP_MASQ_AGENT"] = "1"
				cDefinesMap["IP_MASQ_AGENT_IPV4"] = ipmasq.MapName
			}
		}

		ctmap.WriteBPFMacros(fw, nil)
	}

	if option.Config.PolicyAuditMode {
		cDefinesMap["POLICY_AUDIT_MODE"] = "1"
	}

	if option.Config.AllowICMPFragNeeded {
		cDefinesMap["ALLOW_ICMP_FRAG_NEEDED"] = "1"
	}

	if option.Config.ClockSource == option.ClockSourceJiffies {
		cDefinesMap["ENABLE_JIFFIES"] = "1"
	}

	if option.Config.EnableIdentityMark {
		cDefinesMap["ENABLE_IDENTITY_MARK"] = "1"
	}

	// Since golang maps are unordered, we sort the keys in the map
	// to get a consistent writtern format to the writer. This maintains
	// the consistency when we try to calculate hash for a datapath after
	// writing the config.
	keys := []string{}
	for key := range cDefinesMap {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	for _, key := range keys {
		fmt.Fprintf(fw, "#define %s %s\n", key, cDefinesMap[key])
	}

	// Populate cDefinesMap with extraMacrosMap to get all the configuration
	// in the cDefinesMap itself.
	for key, value := range extraMacrosMap {
		cDefinesMap[key] = value
	}

	// Write the JSON encoded config as base64 encoded commented string to
	// the header file.
	jsonBytes, err := json.Marshal(cDefinesMap)
	if err == nil {
		// We don't care if some error occurs while marshaling the map.
		// In such cases we skip embedding the base64 encoded JSON configuration
		// to the writer.
		encodedConfig := base64.StdEncoding.EncodeToString(jsonBytes)
		fmt.Fprintf(fw, "\n// JSON_OUTPUT: %s\n", encodedConfig)
	}

	return fw.Flush()
}

func (h *HeaderfileWriter) writeNetdevConfig(w io.Writer, cfg datapath.DeviceConfiguration) {
	fmt.Fprint(w, cfg.GetOptions().GetFmtList())
	if option.Config.IsFlannelMasterDeviceSet() {
		fmt.Fprint(w, "#define HOST_REDIRECT_TO_INGRESS 1\n")
	}

	// In case the Linux kernel doesn't support LPM map type, pass the set
	// of prefix length for the datapath to lookup the map.
	if !ipcachemap.BackedByLPM() {
		ipcachePrefixes6, ipcachePrefixes4 := cfg.GetCIDRPrefixLengths()

		fmt.Fprint(w, "#define IPCACHE6_PREFIXES ")
		for _, prefix := range ipcachePrefixes6 {
			fmt.Fprintf(w, "%d,", prefix)
		}
		fmt.Fprint(w, "\n")
		fmt.Fprint(w, "#define IPCACHE4_PREFIXES ")
		for _, prefix := range ipcachePrefixes4 {
			fmt.Fprintf(w, "%d,", prefix)
		}
		fmt.Fprint(w, "\n")
	}
}

// WriteNetdevConfig writes the BPF configuration for the endpoint to a writer.
func (h *HeaderfileWriter) WriteNetdevConfig(w io.Writer, cfg datapath.DeviceConfiguration) error {
	fw := bufio.NewWriter(w)
	h.writeNetdevConfig(fw, cfg)
	return fw.Flush()
}

// writeStaticData writes the endpoint-specific static data defines to the
// specified writer. This must be kept in sync with loader.ELFSubstitutions().
func (h *HeaderfileWriter) writeStaticData(fw io.Writer, e datapath.EndpointConfiguration) {
	if e.IsHost() {
		if option.Config.EnableNodePort {
			// Values defined here are for the host datapath attached to the
			// host device and therefore won't be used. We however need to set
			// non-zero values to prevent the compiler from optimizing them
			// out, because we need to substitute them for host datapaths
			// attached to native devices.
			// When substituting symbols in the object file, we will replace
			// these values with zero for the host device and with the actual
			// values for the native devices.
			fmt.Fprint(fw, "/* Fake values, replaced by 0 for host device and by actual values for native devices. */\n")
			fmt.Fprint(fw, defineUint32("NATIVE_DEV_IFINDEX", 1))
			if option.Config.EnableIPv6 {
				placeholderIPv6 := []byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
				fmt.Fprint(fw, defineIPv6("IPV6_NODEPORT", placeholderIPv6))
			}
			if option.Config.EnableIPv4 {
				placeholderIPv4 := []byte{1, 1, 1, 1}
				fmt.Fprint(fw, defineIPv4("IPV4_NODEPORT", placeholderIPv4))
			}
			fmt.Fprint(fw, "\n")
		}

		fmt.Fprint(fw, defineUint32("HOST_EP_ID", uint32(e.GetID())))
	} else {
		// We want to ensure that the template BPF program always has "LXC_IP"
		// defined and present as a symbol in the resulting object file after
		// compilation, regardless of whether IPv6 is disabled. Because the type
		// templateCfg hardcodes a dummy IPv6 address (and adheres to the
		// datapath.EndpointConfiguration interface), we can rely on it always
		// having an IPv6 addr. Endpoints however may not have IPv6 addrs if IPv6
		// is disabled. Hence this check prevents us from omitting the "LXC_IP"
		// symbol from the template BPF program. Without this, the following
		// scenario is possible:
		//   1) Enable IPv6 in cilium
		//   2) Create an endpoint (ensure endpoint has an IPv6 addr)
		//   3) Disable IPv6 and restart cilium
		// This results in a template BPF object without an "LXC_IP" defined,
		// __but__ the endpoint still has "LXC_IP" defined. This causes a later
		// call to loader.ELFSubstitutions() to fail on missing a symbol "LXC_IP".
		if e.IPv6Address() != nil {
			fmt.Fprint(fw, defineIPv6("LXC_IP", e.IPv6Address()))
		}

		fmt.Fprint(fw, defineIPv4("LXC_IPV4", e.IPv4Address()))
		fmt.Fprint(fw, defineUint32("LXC_ID", uint32(e.GetID())))
	}

	fmt.Fprint(fw, defineMAC("NODE_MAC", e.GetNodeMAC()))

	secID := e.GetIdentityLocked().Uint32()
	fmt.Fprint(fw, defineUint32("SECLABEL", secID))
	fmt.Fprint(fw, defineUint32("SECLABEL_NB", byteorder.HostToNetwork(secID).(uint32)))
	fmt.Fprint(fw, defineUint32("POLICY_VERDICT_LOG_FILTER", e.GetPolicyVerdictLogFilter()))

	epID := uint16(e.GetID())
	fmt.Fprintf(fw, "#define POLICY_MAP %s\n", bpf.LocalMapName(policymap.MapName, epID))
	callsMapName := callsmap.MapName
	if e.IsHost() {
		callsMapName = callsmap.HostMapName
	}
	fmt.Fprintf(fw, "#define CALLS_MAP %s\n", bpf.LocalMapName(callsMapName, epID))
}

// WriteEndpointConfig writes the BPF configuration for the endpoint to a writer.
func (h *HeaderfileWriter) WriteEndpointConfig(w io.Writer, e datapath.EndpointConfiguration) error {
	fw := bufio.NewWriter(w)

	writeIncludes(w)
	h.writeStaticData(fw, e)

	return h.writeTemplateConfig(fw, e)
}

func (h *HeaderfileWriter) writeTemplateConfig(fw *bufio.Writer, e datapath.EndpointConfiguration) error {
	if e.RequireEgressProg() {
		fmt.Fprintf(fw, "#define USE_BPF_PROG_FOR_INGRESS_POLICY 1\n")
	}

	if option.Config.ForceLocalPolicyEvalAtSource {
		fmt.Fprintf(fw, "#define FORCE_LOCAL_POLICY_EVAL_AT_SOURCE 1\n")
	}

	if e.RequireRouting() {
		fmt.Fprintf(fw, "#define ENABLE_ROUTING 1\n")
	}

	if e.IsHost() {
		// Only used to differentiate between host endpoint template and other templates.
		fmt.Fprintf(fw, "#define HOST_ENDPOINT 1\n")
		if option.Config.EnableNodePort {
			fmt.Fprintf(fw, "#define DISABLE_LOOPBACK_LB 1\n")
		}
	}

	if !e.HasIpvlanDataPath() {
		if e.RequireARPPassthrough() {
			fmt.Fprint(fw, "#define ENABLE_ARP_PASSTHROUGH 1\n")
		} else {
			fmt.Fprint(fw, "#define ENABLE_ARP_RESPONDER 1\n")
		}

		fmt.Fprint(fw, "#define ENABLE_HOST_REDIRECT 1\n")
		if option.Config.IsFlannelMasterDeviceSet() {
			fmt.Fprint(fw, "#define HOST_REDIRECT_TO_INGRESS 1\n")
		}
	}

	if e.ConntrackLocalLocked() {
		ctmap.WriteBPFMacros(fw, e)
	} else {
		ctmap.WriteBPFMacros(fw, nil)
	}

	// Local delivery metrics should always be set for endpoint programs.
	fmt.Fprint(fw, "#define LOCAL_DELIVERY_METRICS 1\n")

	h.writeNetdevConfig(fw, e)

	return fw.Flush()
}

// WriteTemplateConfig writes the BPF configuration for the template to a writer.
func (h *HeaderfileWriter) WriteTemplateConfig(w io.Writer, e datapath.EndpointConfiguration) error {
	fw := bufio.NewWriter(w)
	return h.writeTemplateConfig(fw, e)
}


text:
package com.finddreams.slidingback.adapter;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.finddreams.slidingback.R;
import com.finddreams.slidingback.bean.RecentChat;
/**
 * @Description:消息显示的adapter
 * @author http://blog.csdn.net/finddreams
 */
public class NewsAdapter extends BaseAdapter {
	protected static final String TAG = "NewsAdapter";
	private Context mContext;
	private List<RecentChat> lists;
	private ListView mListView;
	private HashMap<String, SoftReference<Bitmap>> hashMaps = new HashMap<String, SoftReference<Bitmap>>();

	public NewsAdapter(Context context, List<RecentChat> lists,
			ListView mListView) {
		this.mContext = context;
		this.lists = lists;
		this.mListView = mListView;
	}

	@Override
	public int getCount() {
		if (lists != null) {
			return lists.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		return lists.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Holder holder;
		RecentChat chat = lists.get(position);
		if (convertView == null) {
			convertView = View.inflate(mContext, R.layout.news_item,
					null);
			holder = new Holder();
			holder.iv = (ImageView) convertView.findViewById(R.id.user_picture);
			holder.tv_name = (TextView) convertView
					.findViewById(R.id.user_name);
			holder.tv_feel = (TextView) convertView
					.findViewById(R.id.user_feel);
			holder.tv_time = (TextView) convertView
					.findViewById(R.id.user_time);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		String path = chat.getImgPath();

		holder.tv_name.setText(chat.getUserName());
		holder.tv_feel.setText(chat.getUserFeel());
		holder.tv_time.setText(chat.getUserTime());
		return convertView;
	}

	class Holder {
		ImageView iv;
		TextView tv_name;
		TextView tv_feel;
		TextView tv_time;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Whoisdoma\WhoisParser\Templates;

use Whoisdoma\WhoisParser\Templates\Type\KeyValue;

class Sn extends KeyValue
{

    protected $regexKeys = array(
        'created' => '/^Date de creation$/i',
        'expires' => '/^Date d\'expiration$/i',
        'changed' => '/^Derniere modification$/i',
        'nameserver' => '/^Serveur[0-9]+\s*$/i',
        'status' => '/^Etat$/i',
        'registrar:name' => '/^Registrar$/i',

        // Contacts: Owner
        'contacts:owner:handle' => '/^Cod Registrant$/i',
        'contacts:owner:name' => '/^Nom Registrant$/i',
        'contacts:owner:address' => '/^Adresse Registrant$/i',
        'contacts:owner:city' => '/^Ville Registrant$/i',
        'contacts:owner:country' => '/^Pays Registrant$/i',
        'contacts:owner:phone' => '/^Telephone Registrant$/i',
        'contacts:owner:fax' => '/^Fax Registrant$/i',
        'contacts:owner:email' => '/^Courriel Registrant\.?$/i',

        // Contacts: Admin
        'contacts:admin:handle' => '/^ID Contact Admin/i',
        'contacts:admin:name' => '/^Nom Contact Admin$/i',
        'contacts:admin:phone' => '/^Telephone Contact Admin/i',
        'contacts:admin:fax' => '/^Fax Contact Admin$/i',
        'contacts:admin:email' => '/^Courriel Contact Admin\.?$/i',

        // Contacts: Tech
        'contacts:tech:handle' => '/^ID Contact Tech[0-9]?/i',
        'contacts:tech:name' => '/^Nom Contact Tech[0-9]?/i',
        'contacts:tech:phone' => '/^Telephone Contact Tech[0-9]?/i',
        'contacts:tech:fax' => '/^Fax Contact Tech[0-9]?/i',
        'contacts:tech:email' => '/^Courriel Contact Tech[0-9]?\.?$/i',
    );

    protected $available = array(
        '/^(.+?)\s*NOT FOUND\s*$/i',
    );

    public function reformatData()
    {
        $contactKeys = array(
            'Registrant',
            'Contact Admin',
            'Contact Admin1',
            'Contact Admin2',
            'Contact Admin3',
            'Contact Tech',
            'Contact Tech1',
            'Contact Tech2',
            'Contact Tech3',
        );

        foreach ($contactKeys as $key => $string) {
            if (! (array_key_exists('Nom '. $string, $this->data) && array_key_exists('Prenoms '. $string, $this->data))) {
                continue;
            }

            $firstname = $this->data['Prenoms '. $string];
            $lastname = $this->data['Nom '. $string];
            $this->data['Nom '. $string] = trim($firstname) .' '. trim($lastname);
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. mycol. Fr. 1: 102 (1885)

#### Original name
Peziza leiocarpa Curr., 1864

### Remarks
null


text:
<#
.SYNOPSIS
WPF4PS framework Testing

.DESCRIPTION
Pester tests for WFP4PS libraries

.NOTES
Copyright Keith Garner, All rights reserved.

#>

import-module $PSScriptRoot\WPF4PS -force

Describe "MessageBox" {
    It "Simple MsgBox" {
        Show-MessageBox -Message "Hello World" | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
        "Hello World " | Show-MessageBox | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
    }

    It "MsgBox with title" {
        Show-MessageBox -Message "Hello World" -title "Random Title" | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
    }

    It "MsgBox with icons" {
        Show-MessageBox -Message "Hello World" -title "Random Title" -icons 16 | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
        Show-MessageBox -Message "Hello World" -title "Random Title" -icons 32 | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
        Show-MessageBox -Message "Hello World" -title "Random Title" -icons 48 | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
        Show-MessageBox -Message "Hello World" -title "Random Title" -icons 64 | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
    }

    it "MsgBox with Buttons" {
        Show-MessageBox -Message "Hello World" -buttons 0 | should be ([System.Windows.Forms.DialogResult]::OK).ToString()

        write-host "OK Cancel"
        Show-MessageBox -Message "Hello World" -buttons 1 | should be ([System.Windows.Forms.DialogResult]::OK).ToString()
        Show-MessageBox -Message "Hello World" -buttons 1 | should be ([System.Windows.Forms.DialogResult]::Cancel).ToString()

        write-host "Abort Retry Cancel"
        Show-MessageBox -Message "Hello World" -buttons 2 | should be ([System.Windows.Forms.DialogResult]::Abort).ToString()
        Show-MessageBox -Message "Hello World" -buttons 2 | should be ([System.Windows.Forms.DialogResult]::Retry).ToString()
        Show-MessageBox -Message "Hello World" -buttons 2 | should be ([System.Windows.Forms.DialogResult]::Ignore).ToString()

        write-host "Yes No Cancel"
        Show-MessageBox -Message "Hello World" -buttons 3 | should be ([System.Windows.Forms.DialogResult]::Yes).ToString()
        Show-MessageBox -Message "Hello World" -buttons 3 | should be ([System.Windows.Forms.DialogResult]::No).ToString()
        Show-MessageBox -Message "Hello World" -buttons 3 | should be ([System.Windows.Forms.DialogResult]::Cancel).ToString()

        write-host "Yes No"
        Show-MessageBox -Message "Hello World" -buttons 4 | should be ([System.Windows.Forms.DialogResult]::Yes).ToString()
        Show-MessageBox -Message "Hello World" -buttons 4 | should be ([System.Windows.Forms.DialogResult]::No).ToString()

        write-host "Retry Cancel"
        Show-MessageBox -Message "Hello World" -buttons 5 | should be ([System.Windows.Forms.DialogResult]::Retry).ToString()
        Show-MessageBox -Message "Hello World" -buttons 5 | should be ([System.Windows.Forms.DialogResult]::Cancel).ToString()
    }

}

Describe "SaveFileDialog" {
    It "Simple File Save" {
        write-host "Type 'FOO<Enter>'"
        Select-SaveFileDialog  | should match ".*\\foo"
    }

    It "Empty Case " {
        write-host "Type 'FOO<Enter>'"
        Select-SaveFileDialog -DefaultExt "foo" | should match ".*\\foo.foo"
    }

    It "Complex Case " {
        write-host "Type 'FOO<Enter>'"
        Select-SaveFileDialog -Title "Open Log File" -Filter "Text Files (*.log)|*.log|All Files (*.*)|*.*" | should match ".*\\foo"
    }

}

Describe "OpenFileDialog" {
    It "Simple File Open" {
        write-host "Select Any File"
        Select-OpenFileDialog | should exist
    }

    It "Empty Case " {
        write-host "Press Cancel"
        Select-OpenFileDialog | should be $null
    }

    It "Complex Case " {
        write-host "Select Any File"
        Select-OpenFileDialog -Title "Open Log File" -Filter "Text Files (*.log)|*.log|All Files (*.*)|*.*" | should exist
    }

}


text:
platform: linux 3.0.35 openwrt
device: fatbox g3
language: c
---

Configure FATBOX G3 as a LTE device gateway for Azure IoT
===
---

# Table of Contents

-   [Introduction](#Introduction)
-   [Step 1: Prerequisites](#Prerequisites)
-   [Step 2: Prepare your Device](#PrepareDevice)
-   [Step 3: Test the IoT client](#Test)

# Introduction

**About this document**

This document describes how to configure FATBOX G3 as device gateway for Azure IoT with Azure IoT SDK. This multi-step process includes:
-   Configuring Azure IoT Hub
-   Registering your IoT device
-   Test your device

FATBOX G3

An industrial LTE gateway device to allow secure remote monitoring and management of industrial equipment with Modbus RTU, Modbus TCP, RS-485 or CAN bus using the Azure IoT platform.

# Step 1: Prerequisites

You should have the following items ready before beginning the process:

-   [Setup your IoT hub][lnk-setup-iot-hub]
-   [Provision your device and get its credentials][lnk-manage-iot-hub]
-   FATBOX G3 device
-   Save your device connection string into a text file named connstr.txt. It will be used to setup and configure your FATBOX G3 as a secure device to connect to your IoT Hub.

# Step 2: Prepare your Device

-   Login to your FATBOX G3 using the LAN port.

    We suggest 2 ways to upload your unique Azure IoT Hub device connection string to your FATBOX.

    1)  Using a USB drive (with micro USB connector)
        -   Copy the connstr.txt file into your USB drive /user folder.
	-   Insert USB drive into FATBOX G3's USB port in the rear.
        -   From 'Management', click on 'Download to FATBOX' and check that 'OK' led on FATBOX blinks once.

	    ![](media/download_to_fatbox.png)

    2)  Using SCP or WINSCP over Ethernet connection
        -   Enable SSH on the FATBOX (reboot after 'Update').
	-   Use SCP or WINSCP to transfer the connstr.txt from your computer to the FATBOX /user folder.
-   In the FATBOX G3 'Azure IoT' menu, enable the Azure IoT device client option.

            ![](media/fatbox_enable_device_client.png)

# Step 3: Test the IoT client

## 3.1 Send Device Events to IoT Hub:

-   SSH to the FATBOX (using root and password as setup in your LOGIN).
-   Create or copy a few lines of 'test data' into the /tmp/dataq.txt file.
-   Run the /etc/M2MBOT in the FATBOX.
-	'Test data' will be sent line by line by the IoT client to your Azure IoT Hub
-   See [Manage IoT Hub][lnk-manage-iot-hub] to learn how to observe the messages IoT Hub receives from the application.

## 3.2 Receive messages from IoT Hub

-   See [Manage IoT Hub][lnk-manage-iot-hub] to learn how to send cloud-to-device messages to the application.

[lnk-setup-iot-hub]: ../setup_iothub.md
[lnk-manage-iot-hub]: ../manage_iot_hub.md


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr';
import { CommonModule } from '@angular/common';

import { routes } from './app.routes';
import { AppComponent } from './app.component';
import { FeaturesModule } from './features';
import { SharedModule } from './shared';
import { CoreModule } from './core';

import { CoursesService } from './features/courses/shared/services/courses.service';

import '../styles/styles.scss';
import '../styles/headings.css';

@NgModule({
  bootstrap: [ AppComponent ],
  declarations: [ AppComponent ],
  imports: [
    CommonModule,
    CoreModule,
    SharedModule,
    FeaturesModule,
    BrowserModule,
    routes
  ],
  providers: [ CoursesService ],
})

export class AppModule {

  constructor(public appRef: ApplicationRef) {}

  public hmrOnInit(store) {
    if (!store || !store.state) {
      return;
    }
    // set state
    console.log('HMR store', store);

    // this.AppStore.update(store.state)
    if ('restoreInputValues' in store) {
      store.restoreInputValues();
    }
    // change detection
    this.appRef.tick();
    delete store.state;
    delete store.restoreInputValues;
  }

  public hmrOnDestroy(store) {
    const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement);
    // recreate elements
    store.disposeOldHosts = createNewHosts(cmpLocation);
    // inject your AppStore and grab state then set it on store
    // var appState = this.AppStore.get()
    store.state = {data: 'yolo'};
    // store.state = Object.assign({}, appState)
    // save input values
    store.restoreInputValues  = createInputTransfer();
    // remove styles
    removeNgStyles();
  }

  public hmrAfterDestroy(store) {
    // display new elements
    store.disposeOldHosts();
    delete store.disposeOldHosts;
    // anything you need done the component is removed
  }
}


text:
from conans import ConanFile, CMake, tools

class CppAgentConan(ConanFile):
    name = "mtconnect_cppagent"
    version = "2.0"
    generators = "cmake"
    url = "https://github.com/mtconnect/cppagent.git"
    license = "Apache License 2.0"
    settings = "os", "compiler", "arch", "build_type", "arch_build"
    options = { "run_tests": [True, False], "build_tests": [True, False], "without_python": [True, False],
               "without_ruby": [True, False], "without_ipv6": [True, False], "with_ruby": [True, False],
               "with_python": [True, False] }
    description = "MTConnect reference C++ agent copyright Association for Manufacturing Technology"

    requires = ["boost/1.79.0@#3249d9bd2b863a9489767bf9c8a05b4b",
                "libxml2/2.9.10@#9133e645e934381d3cc4f6a0bf563fbe",
                "date/2.4.1@#178e4ada4fefd011aaa81ab2bca646db",
                "nlohmann_json/3.9.1@#a41bc0deaf7f40e7b97e548359ccf14d",
                "openssl/3.0.5@#40f4488f02b36c1193b68f585131e8ef",
                "mqtt_cpp/13.1.0"]

    build_policy = "missing"
    default_options = {
        "run_tests": True,
        "build_tests": True,
        "without_python": True,
        "without_ruby": False,
        "without_ipv6": False,
        "with_python": False,
        "with_ruby": False,

        "boost:shared": False,
        "boost:without_python": True,
        "boost:without_test": True,

        "libxml2:shared": False,
        "libxml2:include_utils": False,
        "libxml2:http": False,
        "libxml2:ftp": False,
        "libxml2:iconv": False,
        "libxml2:zlib": False,

        "gtest:shared": False,

        "date:use_system_tz_db": True
        }

    def configure(self):
        if not self.options.without_python:
            self.options["boost"].without_python = False

        self.windows_xp = self.settings.os == 'Windows' and self.settings.compiler.toolset and \
                          self.settings.compiler.toolset in ('v141_xp', 'v140_xp')
        if self.settings.os == 'Windows':
            if self.settings.build_type and self.settings.build_type == 'Debug':
                self.settings.compiler.runtime = 'MTd'
            else:
                self.settings.compiler.runtime = 'MT'

            if not self.settings.compiler.version:
                self.settings.compiler.version = '16'

        if "libcxx" in self.settings.compiler.fields and self.settings.compiler.libcxx == "libstdc++":
            raise Exception("This package is only compatible with libstdc++11, add -s compiler.libcxx=libstdc++11")

        self.settings.compiler.cppstd = 17

        if self.windows_xp:
            self.options.build_tests = False

        if not self.options.build_tests:
            self.options.run_tests = False

        if not self.options.without_ruby:
            self.options.with_ruby = True

        if not self.options.without_python:
            self.options.with_python = True

        if self.settings.os == "Macos":
            self.options["boost"].visibility = "hidden"

    def requirements(self):
        if not self.windows_xp:
            self.requires("gtest/1.10.0")
        if self.options.with_ruby:
            self.requires("mruby/3.1.0")

    def build(self):
        cmake = CMake(self)
        cmake.verbose = True
        if not self.options.build_tests:
            cmake.definitions['AGENT_ENABLE_UNITTESTS'] = 'OFF'

        if self.options.without_ipv6:
            cmake.definitions['AGENT_WITHOUT_IPV6'] = 'ON'

        if self.options.with_python:
            cmake.definitions['WITH_PYTHON'] = 'ON'
        else:
            cmake.definitions['WITH_PYTHON'] = 'OFF'

        if self.options.with_ruby:
            cmake.definitions['WITH_RUBY'] = 'ON'
        else:
            cmake.definitions['WITH_RUBY'] = 'OFF'

        if self.windows_xp:
            cmake.definitions['WINVER'] = '0x0501'

        cmake.configure()
        cmake.build()
        if self.options.run_tests:
            cmake.test()

    def imports(self):
        self.copy("*.dll", "bin", "bin")
        self.copy("*.so*", "bin", "lib")
        self.copy("*.dylib", "bin", "lib")


text: <div class='shariff uk-margin' <?= $datastring ?>>


text:
var exec = require('cordova/exec');

module.exports = {
	setCategory : function (categoryString, success, fail) {
		console.log('JS: setting audio session');
		return cordova.exec(success, fail, "CDVAudioSession", "setCategoryAndOptions", [categoryString]);
	},

	setCategoryAndOptions : function (categoryString, optionString, success, fail) {
		console.log('JS: setting audio session');
		return cordova.exec(success, fail, "CDVAudioSession", "setCategoryAndOptions", [categoryString, optionString]);
	}
};


text:
package net.dvt32.junit;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class MyMathTest {

	MyMath myMath = new MyMath();

	@Before
	public void before() {
		System.out.println("Before");
	}

	@After
	public void after() {
		System.out.println("After");
	}

	@BeforeClass
	public static void beforeClass() {
		System.out.println("Before Class");
	}

	@AfterClass
	public static void afterClass() {
		System.out.println("After Class");
	}

	@Test
	public void sum_with3numbers() {
		System.out.println("Test1");
		assertEquals(6, myMath.sum(new int[] { 1,2,3 }));
	}

	@Test
	public void sum_with1number() {
		System.out.println("Test2");
		assertEquals(3, myMath.sum(new int[] { 3 }));
	}

}


text:
package com.vaadin.tests.components.popupview;

import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PopupView;

public class PopupViewLabelResized extends TestBase {

    @Override
    protected String getDescription() {
        return "When clicking on the popup view on the left, its size should not change.";
    }

    @Override
    protected Integer getTicketNumber() {
        return 3483;
    }

    @Override
    protected void setup() {
        GridLayout gl = new GridLayout(3, 1);
        gl.setSizeFull();

        Label expander = new Label();
        gl.addComponent(expander, 1, 0);
        gl.setColumnExpandRatio(1, 1);

        gl.addComponent(
                new PopupView("Click here to popup", new Label("test")), 0, 0);
        gl.addComponent(
                new PopupView("Click here to popup", new Label("test")), 2, 0);

        addComponent(gl);
    }

}


text:
package com.aol.webservice_base.configuration.support;

public class StaticData {
	public static Integer intValue = null;

	public static void setIntValue(int setValue) {
		intValue = setValue;
	}
	public static Integer getIntValue() {
		return intValue;
	}
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Logout extends Public_Controller {

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**************************************************************************************
     * PUBLIC FUNCTIONS
     **************************************************************************************/

    /**
     * Logout
     */
    public function index()
    {
        $this->session->unset_userdata('logged_in');
        $this->session->sess_destroy();
        redirect('login');
    }

}


text:
package io.reist.sandbox.food.model.entity;

import com.google.gson.annotations.SerializedName;
import com.pushtorefresh.storio2.sqlite.annotations.StorIOSQLiteColumn;
import com.pushtorefresh.storio2.sqlite.annotations.StorIOSQLiteType;

import io.reist.sandbox.app.model.User;
import io.reist.sandbox.app.model.local.BaseTable;
import io.reist.sandbox.food.model.local.RestaurantsTable;
import io.reist.sandbox.users.model.local.UserTable;

/**
 * Created by Fedorov-DA on 05.03.2018.
 */

@StorIOSQLiteType(table = RestaurantsTable.NAME)
public class RestaurantEntity {

    @SerializedName("id")
    @StorIOSQLiteColumn(name = RestaurantsTable.Column.ID, key = true)
    public String id;

    @SerializedName("name")
    @StorIOSQLiteColumn(name = RestaurantsTable.Column.NAME)
    public String name;

    @SerializedName("lat")
    @StorIOSQLiteColumn(name = RestaurantsTable.Column.LAT)
    public double lat;

    @SerializedName("lon")
    @StorIOSQLiteColumn(name = RestaurantsTable.Column.LON)
    public double lon;

    @SerializedName("rating")
    @StorIOSQLiteColumn(name = RestaurantsTable.Column.RATING)
    public String rating;

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "{name = \"" + name + "\", id = " + id + "}";
    }

}


text:
angular.module('factory.authenticationFactory', [
    'services.configBabylon'
  ])
  .factory('authenticationFactory', function ($q, $http, configBabylon) {
    var resource = 'Token';
    var service = {
      currentUser: null,

      // Attempt to authenticate a user by the given email and password
      login: function (email, password) {
        var deferred = $q.defer();

        var data = "grant_type=password&username=" + email + "&password=" + password;
        $http.post(configBabylon.BASE_URL.concat('/', resource), data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (result) {
          deferred.resolve(result);
        }).error(function (err /*,status*/) {
          deferred.resolve(err);
        });
        return deferred.promise;
      },

      //social account network
      facebook: {
        init: function () {
          if (!window.cordova) {
            facebookConnectPlugin.browserInit(configBabylon.FACEBOOK_APP_ID);
          }
        },
        login: function () {
          var deferred = $q.defer();
          facebookConnectPlugin.login([configBabylon.FACEBOOK_APP_PERMISSION],
            function (response) {
              deferred.resolve(response);
            },
            function (response) {
              deferred.reject(response);
            });
          return deferred.promise;
        },

        showDialog: function () {
          var deferred = $q.defer();
          facebookConnectPlugin.showDialog({ method: "feed" },
            function (response) {
              deferred.resolve(response);
            },
            function (response) {
              deferred.reject(response);
            });
          return deferred.promise;
        },

        me: function () {
          var deferred = $q.defer();
          facebookConnectPlugin.api("me",
            function (response) {
              deferred.resolve(response);
            },
            function (response) {
              deferred.reject(response);
            });
          return deferred.promise;
        },

        getAccessToken: function () {
          var deferred = $q.defer();
          facebookConnectPlugin.getAccessToken(
            function (response) {
              deferred.resolve(response);
            },
            function (response) {
              deferred.reject(response);
            });
          return deferred.promise;
        },

        getStatus: function () {
          var deferred = $q.defer();
          facebookConnectPlugin.getLoginStatus(
            function (response) {
              deferred.resolve(response);
            },
            function (response) {
              deferred.reject(response);
            });
          return deferred.promise;
        },

        logout: function () {
          var deferred = $q.defer();
          facebookConnectPlugin.logout(
            function (response) {
              deferred.resolve(response);
            },
            function (response) {
              deferred.reject(response);
            });
          return deferred.promise;
        }
      },
      googlePlus : {
        init : function(){

        }
      }
    };
    return service;
  });


text:
using Newtonsoft.Json;

namespace Synology.DownloadStation.Task.Results
{
    /// <summary>
    /// Task tracker result.
    /// </summary>
	internal class TaskTrackerResult : ITaskTrackerResult
	{
        /// <summary>
        /// Gets or sets the URL.
        /// </summary>
        /// <value>The URL.</value>
        [JsonProperty("url")]
		public string Url { get; set; }

        /// <summary>
        /// Gets or sets the status.
        /// </summary>
        /// <value>The status.</value>
        [JsonProperty("status")]
		public string Status { get; set; }

        /// <summary>
        /// Gets or sets the update time.
        /// </summary>
        /// <value>The update time.</value>
		[JsonProperty("update_time")]
		public int UpdateTime { get; set; }

        /// <summary>
        /// Gets or sets the seeds.
        /// </summary>
        /// <value>The seeds.</value>
        [JsonProperty("seeds")]
		public int Seeds { get; set; }

        /// <summary>
        /// Gets or sets the peers.
        /// </summary>
        /// <value>The peers.</value>
        [JsonProperty("peers")]
		public int Peers { get; set; }
	}
}


text:
package org.wso2.siddhi.core.executor.condition.compare.greaterthan;

import org.wso2.siddhi.core.executor.ExpressionExecutor;

/**
 * Executor class for Float-Double Greater Than condition. Condition evaluation logic is implemented within executor.
 */
public class GreaterThanCompareConditionExpressionExecutorFloatDouble extends
        GreaterThanCompareConditionExpressionExecutor {

    public GreaterThanCompareConditionExpressionExecutorFloatDouble(
            ExpressionExecutor leftExpressionExecutor,
            ExpressionExecutor rightExpressionExecutor) {
        super(leftExpressionExecutor, rightExpressionExecutor);
    }

    @Override
    protected Boolean execute(Object left, Object right) {
        return (Float) left > (Double) right;

    }

    @Override
    public ExpressionExecutor cloneExecutor(String key) {
        return new GreaterThanCompareConditionExpressionExecutorFloatDouble(leftExpressionExecutor.cloneExecutor(key)
                , rightExpressionExecutor.cloneExecutor(key));
    }
}


text:
package se.emilsjolander.sprinkles;

/**
 * Contains static methods to initiate queries
 */
public final class Query {

	private Query() {
	}

    /**
     * Start a query for a single instance of type T
     *
     * @param clazz
     *      The class representing the type of the model you want returned
     *
     * @param sql
     *      The raw sql statement that should be executed.
     *
     * @param sqlArgs
     *      The array of arguments to insert instead of ? in the placeholderQuery statement.
     *      Strings are automatically placeholderQuery escaped.
     *
     * @param <T>
     *      The type of the model you want returned
     *
     * @return the query to execute
     */
	public static <T extends QueryResult> OneQuery<T> one(Class<T> clazz, String sql,
			Object... sqlArgs) {
		final OneQuery<T> query = new OneQuery<T>();
		query.resultClass = clazz;
        query.placeholderQuery = sql;
		query.rawQuery = Utils.insertSqlArgs(sql, sqlArgs);
		return query;
	}

    /**
     * Start a query for a single instance of type T
     *
     * @param clazz
     *      The class representing the type of the model you want returned
     *
     * @param sqlResId
     *      The raw sql resource id that should be executed.
     *
     * @param sqlArgs
     *      The array of arguments to insert instead of ? in the placeholderQuery statement.
     *      Strings are automatically placeholderQuery escaped.
     *
     * @param <T>
     *      The type of the model you want returned
     *
     * @return the query to execute
     */
    public static <T extends QueryResult> OneQuery<T> one(Class<T> clazz, int sqlResId,
                                                          Object... sqlArgs) {
        String sql = Utils.readRawText(sqlResId);
        return one(clazz, sql, sqlArgs);
    }

    /**
     * Start a query for a list of instance of type T
     *
     * @param clazz
     *      The class representing the type of the list you want returned
     *
     * @param sql
     *      The raw sql statement that should be executed.
     *
     * @param sqlArgs
     *      The array of arguments to insert instead of ? in the placeholderQuery statement.
     *      Strings are automatically placeholderQuery escaped.
     *
     * @param <T>
     *      The type of the list you want returned
     *
     * @return the query to execute
     */
	public static <T extends QueryResult> ManyQuery<T> many(Class<T> clazz, String sql,
			Object... sqlArgs) {
		final ManyQuery<T> query = new ManyQuery<T>();
		query.resultClass = clazz;
        query.placeholderQuery = sql;
		query.rawQuery = Utils.insertSqlArgs(sql, sqlArgs);
		return query;
	}

    /**
     * Start a query for a list of instance of type T
     *
     * @param clazz
     *      The class representing the type of the list you want returned
     *
     * @param sqlResId
     *      The raw sql resource id that should be executed.
     *
     * @param sqlArgs
     *      The array of arguments to insert instead of ? in the placeholderQuery statement.
     *      Strings are automatically placeholderQuery escaped.
     *
     * @param <T>
     *      The type of the list you want returned
     *
     * @return the query to execute
     */
    public static <T extends QueryResult> ManyQuery<T> many(Class<T> clazz, int sqlResId,
                                                            Object... sqlArgs) {
        String sql = Utils.readRawText(sqlResId);
        return many(clazz, sql, sqlArgs);
    }

    /**
     * Start a query for the entire list of instance of type T
     *
     * @param clazz
     *      The class representing the type of the list you want returned
     *
     * @param <T>
     *      The type of the list you want returned
     *
     * @return the query to execute
     */
    public static <T extends Model> ManyQuery<T> all(Class<T> clazz) {
        return many(clazz, "SELECT * FROM " + Utils.getTableName(clazz));
    }
}


text:
extern "C" {
#include "iceoryx_binding_c/service_description.h"
}

#include "test.hpp"

#include <type_traits>

namespace
{
using namespace ::testing;
using namespace iox;
using namespace iox::capro;

TEST(iox_service_description_test, StringSizesAreCorrect)
{
    constexpr uint64_t ZERO_TERMINATOR_SIZE = 1U;
    ::testing::Test::RecordProperty("TEST_ID", "f32a6d19-9ff7-4913-a1d8-39d46267b114");
    EXPECT_THAT(sizeof(decltype(std::declval<iox_service_description_t>().serviceString)),
                Eq(iox::capro::IdString_t().capacity() + ZERO_TERMINATOR_SIZE));
    EXPECT_THAT(sizeof(decltype(std::declval<iox_service_description_t>().instanceString)),
                Eq(iox::capro::IdString_t().capacity() + ZERO_TERMINATOR_SIZE));
    EXPECT_THAT(sizeof(decltype(std::declval<iox_service_description_t>().eventString)),
                Eq(iox::capro::IdString_t().capacity() + ZERO_TERMINATOR_SIZE));
}

} // namespace


text:
#ifdef WITH_CUDA

#  include "device/device.h"
#  include "device/device_denoising.h"
#  include "device/device_split_kernel.h"

#  include "util/util_map.h"
#  include "util/util_task.h"

#  ifdef WITH_CUDA_DYNLOAD
#    include "cuew.h"
#  else
#    include "util/util_opengl.h"
#    include <cuda.h>
#    include <cudaGL.h>
#  endif

CCL_NAMESPACE_BEGIN

class CUDASplitKernel;

class CUDADevice : public Device {

  friend class CUDASplitKernelFunction;
  friend class CUDASplitKernel;
  friend class CUDAContextScope;

 public:
  DedicatedTaskPool task_pool;
  CUdevice cuDevice;
  CUcontext cuContext;
  CUmodule cuModule, cuFilterModule;
  size_t device_texture_headroom;
  size_t device_working_headroom;
  bool move_texture_to_host;
  size_t map_host_used;
  size_t map_host_limit;
  int can_map_host;
  int pitch_alignment;
  int cuDevId;
  int cuDevArchitecture;
  bool first_error;
  CUDASplitKernel *split_kernel;

  struct CUDAMem {
    CUDAMem() : texobject(0), array(0), use_mapped_host(false)
    {
    }

    CUtexObject texobject;
    CUarray array;

    /* If true, a mapped host memory in shared_pointer is being used. */
    bool use_mapped_host;
  };
  typedef map<device_memory *, CUDAMem> CUDAMemMap;
  CUDAMemMap cuda_mem_map;

  struct PixelMem {
    GLuint cuPBO;
    CUgraphicsResource cuPBOresource;
    GLuint cuTexId;
    int w, h;
  };
  map<device_ptr, PixelMem> pixel_mem_map;

  /* Bindless Textures */
  device_vector<TextureInfo> texture_info;
  bool need_texture_info;

  /* Kernels */
  struct {
    bool loaded;

    CUfunction adaptive_stopping;
    CUfunction adaptive_filter_x;
    CUfunction adaptive_filter_y;
    CUfunction adaptive_scale_samples;
    int adaptive_num_threads_per_block;
  } functions;

  static bool have_precompiled_kernels();

  virtual bool show_samples() const override;

  virtual BVHLayoutMask get_bvh_layout_mask() const override;

  void set_error(const string &error) override;

  CUDADevice(DeviceInfo &info, Stats &stats, Profiler &profiler, bool background_);

  virtual ~CUDADevice();

  bool support_device(const DeviceRequestedFeatures & /*requested_features*/);

  bool check_peer_access(Device *peer_device) override;

  bool use_adaptive_compilation();

  bool use_split_kernel();

  virtual string compile_kernel_get_common_cflags(
      const DeviceRequestedFeatures &requested_features, bool filter = false, bool split = false);

  string compile_kernel(const DeviceRequestedFeatures &requested_features,
                        const char *name,
                        const char *base = "cuda",
                        bool force_ptx = false);

  virtual bool load_kernels(const DeviceRequestedFeatures &requested_features) override;

  void load_functions();

  void reserve_local_memory(const DeviceRequestedFeatures &requested_features);

  void init_host_memory();

  void load_texture_info();

  void move_textures_to_host(size_t size, bool for_texture);

  CUDAMem *generic_alloc(device_memory &mem, size_t pitch_padding = 0);

  void generic_copy_to(device_memory &mem);

  void generic_free(device_memory &mem);

  void mem_alloc(device_memory &mem) override;

  void mem_copy_to(device_memory &mem) override;

  void mem_copy_from(device_memory &mem, int y, int w, int h, int elem) override;

  void mem_zero(device_memory &mem) override;

  void mem_free(device_memory &mem) override;

  device_ptr mem_alloc_sub_ptr(device_memory &mem, int offset, int /*size*/) override;

  virtual void const_copy_to(const char *name, void *host, size_t size) override;

  void global_alloc(device_memory &mem);

  void global_free(device_memory &mem);

  void tex_alloc(device_texture &mem);

  void tex_free(device_texture &mem);

  bool denoising_non_local_means(device_ptr image_ptr,
                                 device_ptr guide_ptr,
                                 device_ptr variance_ptr,
                                 device_ptr out_ptr,
                                 DenoisingTask *task);

  bool denoising_construct_transform(DenoisingTask *task);

  bool denoising_accumulate(device_ptr color_ptr,
                            device_ptr color_variance_ptr,
                            device_ptr scale_ptr,
                            int frame,
                            DenoisingTask *task);

  bool denoising_solve(device_ptr output_ptr, DenoisingTask *task);

  bool denoising_combine_halves(device_ptr a_ptr,
                                device_ptr b_ptr,
                                device_ptr mean_ptr,
                                device_ptr variance_ptr,
                                int r,
                                int4 rect,
                                DenoisingTask *task);

  bool denoising_divide_shadow(device_ptr a_ptr,
                               device_ptr b_ptr,
                               device_ptr sample_variance_ptr,
                               device_ptr sv_variance_ptr,
                               device_ptr buffer_variance_ptr,
                               DenoisingTask *task);

  bool denoising_get_feature(int mean_offset,
                             int variance_offset,
                             device_ptr mean_ptr,
                             device_ptr variance_ptr,
                             float scale,
                             DenoisingTask *task);

  bool denoising_write_feature(int out_offset,
                               device_ptr from_ptr,
                               device_ptr buffer_ptr,
                               DenoisingTask *task);

  bool denoising_detect_outliers(device_ptr image_ptr,
                                 device_ptr variance_ptr,
                                 device_ptr depth_ptr,
                                 device_ptr output_ptr,
                                 DenoisingTask *task);

  void denoise(RenderTile &rtile, DenoisingTask &denoising);

  void adaptive_sampling_filter(uint filter_sample,
                                WorkTile *wtile,
                                CUdeviceptr d_wtile,
                                CUstream stream = 0);
  void adaptive_sampling_post(RenderTile &rtile,
                              WorkTile *wtile,
                              CUdeviceptr d_wtile,
                              CUstream stream = 0);

  void render(DeviceTask &task, RenderTile &rtile, device_vector<WorkTile> &work_tiles);

  void film_convert(DeviceTask &task,
                    device_ptr buffer,
                    device_ptr rgba_byte,
                    device_ptr rgba_half);

  void shader(DeviceTask &task);

  CUdeviceptr map_pixels(device_ptr mem);

  void unmap_pixels(device_ptr mem);

  void pixels_alloc(device_memory &mem);

  void pixels_copy_from(device_memory &mem, int y, int w, int h);

  void pixels_free(device_memory &mem);

  void draw_pixels(device_memory &mem,
                   int y,
                   int w,
                   int h,
                   int width,
                   int height,
                   int dx,
                   int dy,
                   int dw,
                   int dh,
                   bool transparent,
                   const DeviceDrawParams &draw_params) override;

  void thread_run(DeviceTask &task);

  virtual void task_add(DeviceTask &task) override;

  virtual void task_wait() override;

  virtual void task_cancel() override;
};

CCL_NAMESPACE_END

#endif


text:
/* @test
   @bug 4090383
   @summary Ensure that BufferedInputStream's read method will fill the target
            array whenever possible
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;

public class Fill {

    /**
     * A simple InputStream that is always ready but may read fewer than the
     * requested number of bytes
     */
    static class Source extends InputStream {

        int shortFall;
        byte next = 0;

        Source(int shortFall) {
            this.shortFall = shortFall;
        }

        public int read() throws IOException {
            return next++;
        }

        public int read(byte[] buf, int off, int len) throws IOException {
            int n = len - shortFall;
            for (int i = off; i < n; i++)
                buf[i] = next++;
            return n;
        }

        public int available() {
            return Integer.MAX_VALUE;
        }

        public void close() throws IOException {
        }

    }

    /**
     * Test BufferedInputStream with an underlying source that always reads
     * shortFall fewer bytes than requested
     */
    static void go(int shortFall) throws Exception {

        InputStream r = new BufferedInputStream(new Source(shortFall), 10);
        byte[] buf = new byte[8];

        int n1 = r.read(buf);
        int n2 = r.read(buf);
        System.err.println("Shortfall " + shortFall
                           + ": Read " + n1 + ", then " + n2 + " bytes");
        if (n1 != buf.length)
            throw new Exception("First read returned " + n1);
        if (n2 != buf.length)
            throw new Exception("Second read returned " + n2);

    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 8; i++) go(i);
    }

}


text:
package com.sun.xml.ws.encoding.xml;

import com.sun.istack.NotNull;
import com.sun.xml.ws.api.SOAPVersion;
import com.sun.xml.ws.api.WSFeatureList;
import com.sun.xml.ws.api.message.*;
import com.sun.xml.ws.api.model.wsdl.WSDLPort;
import com.sun.xml.ws.api.pipe.Codec;
import com.sun.xml.ws.api.streaming.XMLStreamWriterFactory;
import com.sun.xml.ws.developer.StreamingAttachmentFeature;
import com.sun.xml.ws.encoding.ContentType;
import com.sun.xml.ws.encoding.MimeMultipartParser;
import com.sun.xml.ws.encoding.XMLHTTPBindingCodec;
import com.sun.xml.ws.message.AbstractMessageImpl;
import com.sun.xml.ws.message.EmptyMessageImpl;
import com.sun.xml.ws.message.MimeAttachmentSet;
import com.sun.xml.ws.message.source.PayloadSourceMessage;
import com.sun.xml.ws.util.ByteArrayBuffer;
import com.sun.xml.ws.util.StreamUtils;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;

import jakarta.activation.DataSource;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.soap.SOAPException;
import jakarta.xml.soap.SOAPMessage;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import jakarta.xml.ws.WebServiceException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author Jitendra Kotamraju
 */
public final class XMLMessage {

    private static final int PLAIN_XML_FLAG      = 1;       // 00001
    private static final int MIME_MULTIPART_FLAG = 2;       // 00010
    private static final int FI_ENCODED_FLAG     = 16;      // 10000

    /*
     * Construct a message given a content type and an input stream.
     */
    public static Message create(final String ct, InputStream in, WSFeatureList f) {
        Message data;
        try {
            in = StreamUtils.hasSomeData(in);
            if (in == null) {
                return Messages.createEmpty(SOAPVersion.SOAP_11);
            }

            if (ct != null) {
                final ContentType contentType = new ContentType(ct);
                final int contentTypeId = identifyContentType(contentType);
                if ((contentTypeId & MIME_MULTIPART_FLAG) != 0) {
                    data = new XMLMultiPart(ct, in, f);
                } else if ((contentTypeId & PLAIN_XML_FLAG) != 0) {
                    data = new XmlContent(ct, in, f);
                } else {
                    data = new UnknownContent(ct, in);
                }
            } else {
                // According to HTTP spec 7.2.1, if the media type remain
                // unknown, treat as application/octet-stream
                data = new UnknownContent("application/octet-stream", in);
            }
        } catch(Exception ex) {
            throw new WebServiceException(ex);
        }
        return data;
    }

    public static Message create(Source source) {
        return (source == null) ?
            Messages.createEmpty(SOAPVersion.SOAP_11) :
            Messages.createUsingPayload(source, SOAPVersion.SOAP_11);
    }

    public static Message create(DataSource ds, WSFeatureList f) {
        try {
            return (ds == null) ?
                Messages.createEmpty(SOAPVersion.SOAP_11) :
                create(ds.getContentType(), ds.getInputStream(), f);
        } catch(IOException ioe) {
            throw new WebServiceException(ioe);
        }
    }

    public static Message create(Exception e) {
        return new FaultMessage(SOAPVersion.SOAP_11);
    }

    /*
     * Get the content type ID from the content type.
     */
    private static int getContentId(String ct) {
        try {
            final ContentType contentType = new ContentType(ct);
            return identifyContentType(contentType);
        } catch(Exception ex) {
            throw new WebServiceException(ex);
        }
    }

    /**
     * Return true if the content uses fast infoset.
     */
    public static boolean isFastInfoset(String ct) {
        return (getContentId(ct) & FI_ENCODED_FLAG) != 0;
    }

    /*
     * Verify a contentType.
     *
     * @return
     * MIME_MULTIPART_FLAG | PLAIN_XML_FLAG
     * MIME_MULTIPART_FLAG | FI_ENCODED_FLAG;
     * PLAIN_XML_FLAG
     * FI_ENCODED_FLAG
     *
     */
    public static int identifyContentType(ContentType contentType) {
        String primary = contentType.getPrimaryType();
        String sub = contentType.getSubType();

        if (primary.equalsIgnoreCase("multipart") && sub.equalsIgnoreCase("related")) {
            String type = contentType.getParameter("type");
            if (type != null) {
                if (isXMLType(type)) {
                    return MIME_MULTIPART_FLAG | PLAIN_XML_FLAG;
                } else if (isFastInfosetType(type)) {
                    return MIME_MULTIPART_FLAG | FI_ENCODED_FLAG;
                }
            }
            return 0;
        } else if (isXMLType(primary, sub)) {
            return PLAIN_XML_FLAG;
        } else if (isFastInfosetType(primary, sub)) {
            return FI_ENCODED_FLAG;
        }
        return 0;
    }

    protected static boolean isXMLType(@NotNull String primary, @NotNull String sub) {
        return (primary.equalsIgnoreCase("text") && sub.equalsIgnoreCase("xml"))
                || (primary.equalsIgnoreCase("application") && sub.equalsIgnoreCase("xml"))
                || (primary.equalsIgnoreCase("application") && sub.toLowerCase().endsWith("+xml"));
    }

    protected static boolean isXMLType(String type) {
        String lowerType = type.toLowerCase();
        return lowerType.startsWith("text/xml")
                || lowerType.startsWith("application/xml")
                || (lowerType.startsWith("application/") && (lowerType.contains("+xml")));
    }

    protected static boolean isFastInfosetType(String primary, String sub) {
        return primary.equalsIgnoreCase("application") && sub.equalsIgnoreCase("fastinfoset");
    }

    protected static boolean isFastInfosetType(String type) {
        return type.toLowerCase().startsWith("application/fastinfoset");
    }

    /**
     * Access a {@link Message} as a {@link DataSource}.
     *

     * A {@link Message} implementation will implement this if the
     * messages is to be access as data source.
     *

     * TODO: consider putting as part of the API.
     */
    public interface MessageDataSource {
        /**
         * Check if the data source has been consumed.
         * @return true of the data source has been consumed, otherwise false.
         */
        boolean hasUnconsumedDataSource();

        /**
         * Get the data source.
         * @return the data source.
         */
        DataSource getDataSource();
    }

    /**
     * It's conent-type is some XML type
     *
     */
    private static class XmlContent extends AbstractMessageImpl implements MessageDataSource {
        private final XmlDataSource dataSource;
        private boolean consumed;
        private Message delegate;
        private final HeaderList headerList;
//      private final WSBinding binding;
        private WSFeatureList features;

        public XmlContent(String ct, InputStream in, WSFeatureList f) {
            super(SOAPVersion.SOAP_11);
            dataSource = new XmlDataSource(ct, in);
            this.headerList = new HeaderList(SOAPVersion.SOAP_11);
//            this.binding = binding;
            features = f;
        }

        private Message getMessage() {
            if (delegate == null) {
                InputStream in = dataSource.getInputStream();
                assert in != null;
                delegate = Messages.createUsingPayload(new StreamSource(in), SOAPVersion.SOAP_11);
                consumed = true;
            }
            return delegate;
        }

        @Override
        public boolean hasUnconsumedDataSource() {
            return !dataSource.consumed()&&!consumed;
        }

        @Override
        public DataSource getDataSource() {
            return hasUnconsumedDataSource() ? dataSource :
                XMLMessage.getDataSource(getMessage(), features);
        }

        @Override
        public boolean hasHeaders() {
            return false;
        }

        @Override
        public @NotNull MessageHeaders getHeaders() {
            return headerList;
        }

        @Override
        public String getPayloadLocalPart() {
            return getMessage().getPayloadLocalPart();
        }

        @Override
        public String getPayloadNamespaceURI() {
            return getMessage().getPayloadNamespaceURI();
        }

        @Override
        public boolean hasPayload() {
            return true;
        }

        @Override
        public boolean isFault() {
            return false;
        }

        @Override
        public Source readEnvelopeAsSource() {
            return getMessage().readEnvelopeAsSource();
        }

        @Override
        public Source readPayloadAsSource() {
            return getMessage().readPayloadAsSource();
        }

        @Override
        public SOAPMessage readAsSOAPMessage() throws SOAPException {
            return getMessage().readAsSOAPMessage();
        }

        @Override
        public SOAPMessage readAsSOAPMessage(Packet packet, boolean inbound) throws SOAPException {
            return getMessage().readAsSOAPMessage(packet, inbound);
        }

        @Override
        public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
            return getMessage().readPayloadAsJAXB(unmarshaller);
        }

        @Override
        public XMLStreamReader readPayload() throws XMLStreamException {
            return getMessage().readPayload();
        }

        @Override
        public void writePayloadTo(XMLStreamWriter sw) throws XMLStreamException {
            getMessage().writePayloadTo(sw);
        }

        @Override
        public void writeTo(XMLStreamWriter sw) throws XMLStreamException {
            getMessage().writeTo(sw);
        }

        @Override
        public void writeTo(ContentHandler contentHandler, ErrorHandler errorHandler) throws SAXException {
            getMessage().writeTo(contentHandler, errorHandler);
        }

        @Override
        public Message copy() {
            return getMessage().copy().copyFrom(getMessage());
        }

        @Override
        protected void writePayloadTo(ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment) throws SAXException {
            throw new UnsupportedOperationException();
        }

    }

    /**
     * Data represented as a multi-part MIME message.
     *

     * The root part may be an XML or an FI document. This class
     * parses MIME message lazily.
     */
    public static final class XMLMultiPart extends AbstractMessageImpl implements MessageDataSource {
        private final DataSource dataSource;
        private final StreamingAttachmentFeature feature;
        private Message delegate;
        private HeaderList headerList;// = new HeaderList();
//      private final WSBinding binding;
        private final WSFeatureList features;

        public XMLMultiPart(final String contentType, final InputStream is, WSFeatureList f) {
            super(SOAPVersion.SOAP_11);
            headerList = new HeaderList(SOAPVersion.SOAP_11);
            dataSource = createDataSource(contentType, is);
            this.feature = f.get(StreamingAttachmentFeature.class);
            this.features = f;
        }

        private Message getMessage() {
            if (delegate == null) {
                MimeMultipartParser mpp;
                try {
                    mpp = new MimeMultipartParser(dataSource.getInputStream(),
                            dataSource.getContentType(), feature);
                } catch(IOException ioe) {
                    throw new WebServiceException(ioe);
                }
                InputStream in = mpp.getRootPart().asInputStream();
                assert in != null;
                delegate = new PayloadSourceMessage(headerList, new StreamSource(in), new MimeAttachmentSet(mpp), SOAPVersion.SOAP_11);
            }
            return delegate;
        }

        @Override
        public boolean hasUnconsumedDataSource() {
            return delegate == null;
        }

        @Override
        public DataSource getDataSource() {
            return hasUnconsumedDataSource() ? dataSource :
                XMLMessage.getDataSource(getMessage(), features);
        }

        @Override
        public boolean hasHeaders() {
            return false;
        }

        @Override
        public @NotNull MessageHeaders getHeaders() {
            return headerList;
        }

        @Override
        public String getPayloadLocalPart() {
            return getMessage().getPayloadLocalPart();
        }

        @Override
        public String getPayloadNamespaceURI() {
            return getMessage().getPayloadNamespaceURI();
        }

        @Override
        public boolean hasPayload() {
            return true;
        }

        @Override
        public boolean isFault() {
            return false;
        }

        @Override
        public Source readEnvelopeAsSource() {
            return getMessage().readEnvelopeAsSource();
        }

        @Override
        public Source readPayloadAsSource() {
            return getMessage().readPayloadAsSource();
        }

        @Override
        public SOAPMessage readAsSOAPMessage() throws SOAPException {
            return getMessage().readAsSOAPMessage();
        }

        @Override
        public SOAPMessage readAsSOAPMessage(Packet packet, boolean inbound) throws SOAPException {
            return getMessage().readAsSOAPMessage(packet, inbound);
        }

        @Override
        public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
            return getMessage().readPayloadAsJAXB(unmarshaller);
        }

        @Override
        public XMLStreamReader readPayload() throws XMLStreamException {
            return getMessage().readPayload();
        }

        @Override
        public void writePayloadTo(XMLStreamWriter sw) throws XMLStreamException {
            getMessage().writePayloadTo(sw);
        }

        @Override
        public void writeTo(XMLStreamWriter sw) throws XMLStreamException {
            getMessage().writeTo(sw);
        }

        @Override
        public void writeTo(ContentHandler contentHandler, ErrorHandler errorHandler) throws SAXException {
            getMessage().writeTo(contentHandler, errorHandler);
        }

        @Override
        public Message copy() {
            return getMessage().copy().copyFrom(getMessage());
        }

        @Override
        protected void writePayloadTo(ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment) throws SAXException {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean isOneWay(@NotNull WSDLPort port) {
            return false;
        }

        @Override
        public @NotNull AttachmentSet getAttachments() {
            return getMessage().getAttachments();
        }

    }

    private static class FaultMessage extends EmptyMessageImpl {

        public FaultMessage(SOAPVersion version) {
            super(version);
        }

        @Override
        public boolean isFault() {
            return true;
        }
    }

    /**
     * Don't know about this content. It's conent-type is NOT the XML types
     * we recognize(text/xml, application/xml, multipart/related;text/xml etc).
     *
     * This could be used to represent image/jpeg etc
     */
    public static class UnknownContent extends AbstractMessageImpl implements MessageDataSource {
        private final DataSource ds;
        private final HeaderList headerList;

        public UnknownContent(final String ct, final InputStream in) {
            this(createDataSource(ct,in));
        }

        public UnknownContent(DataSource ds) {
            super(SOAPVersion.SOAP_11);
            this.ds = ds;
            this.headerList = new HeaderList(SOAPVersion.SOAP_11);
        }

        /*
         * Copy constructor.
         */
        private UnknownContent(UnknownContent that) {
            super(that.soapVersion);
            this.ds = that.ds;
            this.headerList = HeaderList.copy(that.headerList);
            this.copyFrom(that);
        }

        @Override
        public boolean hasUnconsumedDataSource() {
            return true;
        }

        @Override
        public DataSource getDataSource() {
            assert ds != null;
            return ds;
        }

        @Override
        protected void writePayloadTo(ContentHandler contentHandler,
                                      ErrorHandler errorHandler, boolean fragment) throws SAXException {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean hasHeaders() {
            return false;
        }

        @Override
        public boolean isFault() {
            return false;
        }

        @Override
        public MessageHeaders getHeaders() {
            return headerList;
        }

        @Override
        public String getPayloadLocalPart() {
            throw new UnsupportedOperationException();
        }

        @Override
        public String getPayloadNamespaceURI() {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean hasPayload() {
            return false;
        }

        @Override
        public Source readPayloadAsSource() {
            return null;
        }

        @Override
        public XMLStreamReader readPayload() throws XMLStreamException {
            throw new WebServiceException("There isn't XML payload. Shouldn't come here.");
        }

        @Override
        public void writePayloadTo(XMLStreamWriter sw) throws XMLStreamException {
            // No XML. Nothing to do
        }

        @Override
        public Message copy() {
            return new UnknownContent(this).copyFrom(this);
        }

    }

    public static DataSource getDataSource(Message msg, WSFeatureList f) {
        if (msg == null)
            return null;
        if (msg instanceof MessageDataSource) {
            return ((MessageDataSource)msg).getDataSource();
        } else {
            AttachmentSet atts = msg.getAttachments();
            if (atts != null && !atts.isEmpty()) {
                final ByteArrayBuffer bos = new ByteArrayBuffer();
                try {
                    Codec codec = new XMLHTTPBindingCodec(f);
                    Packet packet = new Packet(msg);
                    com.sun.xml.ws.api.pipe.ContentType ct = codec.getStaticContentType(packet);
                    codec.encode(packet, bos);
                    return createDataSource(ct.getContentType(), bos.newInputStream());
                } catch(IOException ioe) {
                    throw new WebServiceException(ioe);
                }

            } else {
                final ByteArrayBuffer bos = new ByteArrayBuffer();
                XMLStreamWriter writer = XMLStreamWriterFactory.create(bos);
                try {
                    msg.writePayloadTo(writer);
                    writer.flush();
                } catch (XMLStreamException e) {
                    throw new WebServiceException(e);
                }
                return XMLMessage.createDataSource("text/xml", bos.newInputStream());
            }
        }
    }

    public static DataSource createDataSource(final String contentType, final InputStream is) {
        return new XmlDataSource(contentType, is);
    }

    private static class XmlDataSource implements DataSource {
        private final String contentType;
        private final InputStream is;
        private boolean consumed;

        XmlDataSource(String contentType, final InputStream is) {
            this.contentType = contentType;
            this.is = is;
        }

        public boolean consumed() {
            return consumed;
        }

        @Override
        public InputStream getInputStream() {
            consumed = !consumed;
            return is;
        }

        @Override
        public OutputStream getOutputStream() {
            return null;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public String getName() {
            return "";
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>javax.sound.sampled.spi (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.sound.sampled.spi package">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Package

Next Package

Frames

No Frames

All Classes

Package javax.sound.sampled.spi

Supplies abstract classes for service providers to subclass when
offering new audio devices, sound file readers and writers, or audio format converters.

See: Description

Class Summary

Class
Description

AudioFileReader

Provider for audio file reading services.

AudioFileWriter

Provider for audio file writing services.

FormatConversionProvider

A format conversion provider provides format conversion services
 from one or more input formats to one or more output formats.

MixerProvider

A provider or factory for a particular mixer type.

Package javax.sound.sampled.spi Description

Supplies abstract classes for service providers to subclass when
offering new audio devices, sound file readers and writers, or audio format converters.

Related Documentation

For overviews, tutorials, examples, and guides,
please see:

Sound

Since:

1.3

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Package

Next Package

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
/*
 * Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
 * From ASN.1 module "IEEE1609dot2BaseTypes"
 * 	found in "1609dot2-base-types.asn"
 * 	`asn1c -gen-OER`
 */

#ifndef	_SequenceOfRectangularRegion_H_
#define	_SequenceOfRectangularRegion_H_

#include <asn_application.h>

/* Including external dependencies */
#include <asn_SEQUENCE_OF.h>
#include <constr_SEQUENCE_OF.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Forward declarations */
struct RectangularRegion;

/* SequenceOfRectangularRegion */
typedef struct SequenceOfRectangularRegion {
	A_SEQUENCE_OF(struct RectangularRegion) list;

	/* Context for parsing across buffer boundaries */
	asn_struct_ctx_t _asn_ctx;
} SequenceOfRectangularRegion_t;

/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_SequenceOfRectangularRegion;
extern asn_SET_OF_specifics_t asn_SPC_SequenceOfRectangularRegion_specs_1;
extern asn_TYPE_member_t asn_MBR_SequenceOfRectangularRegion_1[1];

#ifdef __cplusplus
}
#endif

/* Referred external types */
#include "RectangularRegion.h"

#endif	/* _SequenceOfRectangularRegion_H_ */
#include <asn_internal.h>


text:
<?php
	class Messages_Controller extends Base_Controller{

		public $restful=true;

		public function __construct()
		{
			$this->filter('before', 'Sentry_auth');
		}
		public function get_index()
		{
			if(Request::ajax()) {
				return '<span style="display:block;margin-top:170px;text-align:center;font-size:2em;color:#ccc;">
					konuşma seçilmedi daha
				</span>';
			}
			//This gets conversation that user started or we started..
			$conversation = Conversation::with('Author')
			->where('receiver_id','=',Sentry::user()->id)
			->or_where(function($query){
				$query->where('user_id','=',Sentry::user()->id);
			})
			->order_by('date','desc')
			->get();

			$view = View::make('messages.index');

			$view->cons = $conversation;
			$view->ifgetverb = false;
			$view->title = "Mesajlar";
			return $view;
		}
		public function get_conversation($conHash){
			$ajaxRequest = false;
			$thread = false;
			$numbered = false;
			if(Request::ajax()) {
				$ajaxRequest = true;
			}
			$userid = Sentry::user()->id;
			/*There should be some protection about sniffing other messages*/

			/*Let check if this conversation exist*/
			$conThread = Conversation::where('id','=',$conHash)->first();
			if(!$conThread)
			{
				return Redirect::to_action('messages@index');
			}elseif($conThread->user_id != $userid && $conThread->receiver_id != $userid){
				/*now we are looking if this conversation is ours*/
				return Redirect::to_action('messages@index');
			}

			$conversation = Message::with('author')
			->where('conversation_id','=',$conHash)
			->order_by('date','asc')
			->get();
			if(!$ajaxRequest)
			{
				//This gets conversation that user started or we started..
				$conversation2 = Conversation::with('Author')
				->where('receiver_id','=',Sentry::user()->id)
				->or_where(function($query){
					$query->where('user_id','=',Sentry::user()->id);
				})
				->order_by('date','desc')
				->get();

				$view = View::make('messages.index');

				$view->cons = $conversation2;
				$view->ifgetverb = true;
				$view->title = "Mesajlar";
			    $view->conversation = $conversation;
			    $view->coninfo = $conThread;
			    return $view;
			}else{
			    $view = View::make('messages.ajaxrequest');
			    $view->conversation = $conversation;
			    $view->coninfo = $conThread;
			    return $view;
		    }
		}
		public function post_index()
		{
			//grabbing conversation
		}

	}

 ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<rs:sqlResource xmlns:rs="http://restsql.org/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://restsql.org/schema ../../../../../restsql/src/resources/xml/SqlResource.xsd">
	<query>
		select id, time, timestamp, date, datetime
		from datetime
	</query>
	<metadata>
		<database default="sakila" />
		<table name="datetime" role="Parent" />
	</metadata>
</rs:sqlResource>


text: * *news_keywords* field changed from free-entry string to controlled enum