text:
package apiserver

import (
	"context"
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"os"
	"path"
	"reflect"
	"sort"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apiserver/pkg/server/dynamiccertificates"
	genericapiserveroptions "k8s.io/apiserver/pkg/server/options"
	client "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
	"k8s.io/client-go/util/cert"
	apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
	aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
	"k8s.io/kubernetes/cmd/kube-apiserver/app"
	kastesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/test/integration/framework"
	wardlev1alpha1 "k8s.io/sample-apiserver/pkg/apis/wardle/v1alpha1"
	wardlev1beta1 "k8s.io/sample-apiserver/pkg/apis/wardle/v1beta1"
	sampleserver "k8s.io/sample-apiserver/pkg/cmd/server"
	wardlev1alpha1client "k8s.io/sample-apiserver/pkg/generated/clientset/versioned/typed/wardle/v1alpha1"
	netutils "k8s.io/utils/net"
)

func TestAggregatedAPIServer(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	t.Cleanup(cancel)

	// makes the kube-apiserver very responsive.  it's normally a minute
	dynamiccertificates.FileRefreshDuration = 1 * time.Second

	stopCh := make(chan struct{})
	defer close(stopCh)

	// we need the wardle port information first to set up the service resolver
	listener, wardlePort, err := genericapiserveroptions.CreateListener("tcp", "127.0.0.1:0", net.ListenConfig{})
	if err != nil {
		t.Fatal(err)
	}
	// endpoints cannot have loopback IPs so we need to override the resolver itself
	t.Cleanup(app.SetServiceResolverForTests(staticURLServiceResolver(fmt.Sprintf("https://127.0.0.1:%d", wardlePort))))

	testServer := kastesting.StartTestServerOrDie(t, &kastesting.TestServerInstanceOptions{EnableCertAuth: true}, nil, framework.SharedEtcd())
	defer testServer.TearDownFn()
	kubeClientConfig := rest.CopyConfig(testServer.ClientConfig)
	// force json because everything speaks it
	kubeClientConfig.ContentType = ""
	kubeClientConfig.AcceptContentTypes = ""
	kubeClient := client.NewForConfigOrDie(kubeClientConfig)
	aggregatorClient := aggregatorclient.NewForConfigOrDie(kubeClientConfig)
	wardleClient := wardlev1alpha1client.NewForConfigOrDie(kubeClientConfig)

	// create the bare minimum resources required to be able to get the API service into an available state
	_, err = kubeClient.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: "kube-wardle",
		},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	_, err = kubeClient.CoreV1().Services("kube-wardle").Create(ctx, &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name: "api",
		},
		Spec: corev1.ServiceSpec{
			ExternalName: "needs-to-be-non-empty",
			Type:         corev1.ServiceTypeExternalName,
		},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatal(err)
	}

	// start the wardle server to prove we can aggregate it
	wardleToKASKubeConfigFile := writeKubeConfigForWardleServerToKASConnection(t, rest.CopyConfig(kubeClientConfig))
	defer os.Remove(wardleToKASKubeConfigFile)
	wardleCertDir, _ := os.MkdirTemp("", "test-integration-wardle-server")
	defer os.RemoveAll(wardleCertDir)
	go func() {
		o := sampleserver.NewWardleServerOptions(os.Stdout, os.Stderr)
		// ensure this is a SAN on the generated cert for service FQDN
		o.AlternateDNS = []string{
			"api.kube-wardle.svc",
		}
		o.RecommendedOptions.SecureServing.Listener = listener
		o.RecommendedOptions.SecureServing.BindAddress = netutils.ParseIPSloppy("127.0.0.1")
		wardleCmd := sampleserver.NewCommandStartWardleServer(o, stopCh)
		wardleCmd.SetArgs([]string{
			"--authentication-kubeconfig", wardleToKASKubeConfigFile,
			"--authorization-kubeconfig", wardleToKASKubeConfigFile,
			"--etcd-servers", framework.GetEtcdURL(),
			"--cert-dir", wardleCertDir,
			"--kubeconfig", wardleToKASKubeConfigFile,
		})
		if err := wardleCmd.Execute(); err != nil {
			t.Error(err)
		}
	}()
	directWardleClientConfig, err := waitForWardleRunning(ctx, t, kubeClientConfig, wardleCertDir, wardlePort)
	if err != nil {
		t.Fatal(err)
	}

	// now we're finally ready to test. These are what's run by default now
	wardleDirectClient := client.NewForConfigOrDie(directWardleClientConfig)
	testAPIGroupList(ctx, t, wardleDirectClient.Discovery().RESTClient())
	testAPIGroup(ctx, t, wardleDirectClient.Discovery().RESTClient())
	testAPIResourceList(ctx, t, wardleDirectClient.Discovery().RESTClient())

	wardleCA, err := os.ReadFile(directWardleClientConfig.CAFile)
	if err != nil {
		t.Fatal(err)
	}
	_, err = aggregatorClient.ApiregistrationV1().APIServices().Create(ctx, &apiregistrationv1.APIService{
		ObjectMeta: metav1.ObjectMeta{Name: "v1alpha1.wardle.example.com"},
		Spec: apiregistrationv1.APIServiceSpec{
			Service: &apiregistrationv1.ServiceReference{
				Namespace: "kube-wardle",
				Name:      "api",
			},
			Group:                "wardle.example.com",
			Version:              "v1alpha1",
			CABundle:             wardleCA,
			GroupPriorityMinimum: 200,
			VersionPriority:      200,
		},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatal(err)
	}

	// wait for the API service to be available
	err = wait.Poll(time.Second, wait.ForeverTestTimeout, func() (done bool, err error) {
		apiService, err := aggregatorClient.ApiregistrationV1().APIServices().Get(ctx, "v1alpha1.wardle.example.com", metav1.GetOptions{})
		if err != nil {
			return false, err
		}
		var available bool
		for _, condition := range apiService.Status.Conditions {
			if condition.Type == apiregistrationv1.Available && condition.Status == apiregistrationv1.ConditionTrue {
				available = true
				break
			}
		}
		if !available {
			t.Log("api service is not available", apiService.Status.Conditions)
			return false, nil
		}

		// make sure discovery is healthy overall
		_, _, err = kubeClient.Discovery().ServerGroupsAndResources()
		if err != nil {
			t.Log("discovery failed", err)
			return false, nil
		}

		// make sure we have the wardle resources in discovery
		apiResources, err := kubeClient.Discovery().ServerResourcesForGroupVersion("wardle.example.com/v1alpha1")
		if err != nil {
			t.Log("wardle discovery failed", err)
			return false, nil
		}
		if len(apiResources.APIResources) != 2 {
			t.Log("wardle discovery has wrong resources", apiResources.APIResources)
			return false, nil
		}
		resources := make([]string, 0, 2)
		for _, resource := range apiResources.APIResources {
			resource := resource
			resources = append(resources, resource.Name)
		}
		sort.Strings(resources)
		if !reflect.DeepEqual([]string{"fischers", "flunders"}, resources) {
			return false, fmt.Errorf("unexpected resources: %v", resources)
		}

		return true, nil
	})
	if err != nil {
		t.Fatal(err)
	}

	// perform simple CRUD operations against the wardle resources
	_, err = wardleClient.Fischers().Create(ctx, &wardlev1alpha1.Fischer{
		ObjectMeta: metav1.ObjectMeta{
			Name: "panda",
		},
	}, metav1.CreateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	fischersList, err := wardleClient.Fischers().List(ctx, metav1.ListOptions{})
	if err != nil {
		t.Fatal(err)
	}
	if len(fischersList.Items) != 1 {
		t.Errorf("expected one fischer: %#v", fischersList.Items)
	}
	if len(fischersList.ResourceVersion) == 0 {
		t.Error("expected non-empty resource version for fischer list")
	}

	_, err = wardleClient.Flunders(metav1.NamespaceSystem).Create(ctx, &wardlev1alpha1.Flunder{
		ObjectMeta: metav1.ObjectMeta{
			Name: "panda",
		},
	}, metav1.CreateOptions{})
	flunderList, err := wardleClient.Flunders(metav1.NamespaceSystem).List(ctx, metav1.ListOptions{})
	if err != nil {
		t.Fatal(err)
	}
	if len(flunderList.Items) != 1 {
		t.Errorf("expected one flunder: %#v", flunderList.Items)
	}
	if len(flunderList.ResourceVersion) == 0 {
		t.Error("expected non-empty resource version for flunder list")
	}

	// Since ClientCAs are provided by "client-ca::kube-system::extension-apiserver-authentication::client-ca-file" controller
	// we need to wait until it picks up the configmap (via a lister) otherwise the response might contain an empty result.
	// The following code waits up to ForeverTestTimeout seconds for ClientCA to show up otherwise it fails
	// maybe in the future this could be wired into the /readyz EP

	// Now we want to verify that the client CA bundles properly reflect the values for the cluster-authentication
	var firstKubeCANames []string
	err = wait.Poll(1*time.Second, wait.ForeverTestTimeout, func() (done bool, err error) {
		firstKubeCANames, err = cert.GetClientCANamesForURL(kubeClientConfig.Host)
		if err != nil {
			return false, err
		}
		return len(firstKubeCANames) != 0, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	t.Log(firstKubeCANames)
	var firstWardleCANames []string
	err = wait.Poll(1*time.Second, wait.ForeverTestTimeout, func() (done bool, err error) {
		firstWardleCANames, err = cert.GetClientCANamesForURL(directWardleClientConfig.Host)
		if err != nil {
			return false, err
		}
		return len(firstWardleCANames) != 0, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	t.Log(firstWardleCANames)
	// Now we want to verify that the client CA bundles properly reflect the values for the cluster-authentication
	if !reflect.DeepEqual(firstKubeCANames, firstWardleCANames) {
		t.Fatal("names don't match")
	}

	// now we update the client-ca nd request-header-client-ca-file and the kas will consume it, update the configmap
	// and then the wardle server will detect and update too.
	if err := os.WriteFile(path.Join(testServer.TmpDir, "client-ca.crt"), differentClientCA, 0644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(path.Join(testServer.TmpDir, "proxy-ca.crt"), differentFrontProxyCA, 0644); err != nil {
		t.Fatal(err)
	}
	// wait for it to be picked up.  there's a test in certreload_test.go that ensure this works
	time.Sleep(4 * time.Second)

	// Now we want to verify that the client CA bundles properly updated to reflect the new values written for the kube-apiserver
	secondKubeCANames, err := cert.GetClientCANamesForURL(kubeClientConfig.Host)
	if err != nil {
		t.Fatal(err)
	}
	t.Log(secondKubeCANames)
	for i := range firstKubeCANames {
		if firstKubeCANames[i] == secondKubeCANames[i] {
			t.Errorf("ca bundles should change")
		}
	}
	secondWardleCANames, err := cert.GetClientCANamesForURL(directWardleClientConfig.Host)
	if err != nil {
		t.Fatal(err)
	}
	t.Log(secondWardleCANames)

	// second wardle should contain all the certs, first and last
	numMatches := 0
	for _, needle := range firstKubeCANames {
		for _, haystack := range secondWardleCANames {
			if needle == haystack {
				numMatches++
				break
			}
		}
	}
	for _, needle := range secondKubeCANames {
		for _, haystack := range secondWardleCANames {
			if needle == haystack {
				numMatches++
				break
			}
		}
	}
	if numMatches != 4 {
		t.Fatal("names don't match")
	}
}

func waitForWardleRunning(ctx context.Context, t *testing.T, wardleToKASKubeConfig *rest.Config, wardleCertDir string, wardlePort int) (*rest.Config, error) {
	directWardleClientConfig := rest.AnonymousClientConfig(rest.CopyConfig(wardleToKASKubeConfig))
	directWardleClientConfig.CAFile = path.Join(wardleCertDir, "apiserver.crt")
	directWardleClientConfig.CAData = nil
	directWardleClientConfig.ServerName = ""
	directWardleClientConfig.BearerToken = wardleToKASKubeConfig.BearerToken
	var wardleClient client.Interface
	lastHealthContent := []byte{}
	var lastHealthErr error
	err := wait.PollImmediate(100*time.Millisecond, 10*time.Second, func() (done bool, err error) {
		if _, err := os.Stat(directWardleClientConfig.CAFile); os.IsNotExist(err) { // wait until the file trust is created
			lastHealthErr = err
			return false, nil
		}
		directWardleClientConfig.Host = fmt.Sprintf("https://127.0.0.1:%d", wardlePort)
		wardleClient, err = client.NewForConfig(directWardleClientConfig)
		if err != nil {
			// this happens because we race the API server start
			t.Log(err)
			return false, nil
		}
		healthStatus := 0
		result := wardleClient.Discovery().RESTClient().Get().AbsPath("/healthz").Do(ctx).StatusCode(&healthStatus)
		lastHealthContent, lastHealthErr = result.Raw()
		if healthStatus != http.StatusOK {
			return false, nil
		}
		return true, nil
	})
	if err != nil {
		t.Log(string(lastHealthContent))
		t.Log(lastHealthErr)
		return nil, err
	}

	return directWardleClientConfig, nil
}

func writeKubeConfigForWardleServerToKASConnection(t *testing.T, kubeClientConfig *rest.Config) string {
	// write a kubeconfig out for starting other API servers with delegated auth.  remember, no in-cluster config
	// the loopback client config uses a loopback cert with different SNI.  We need to use the "real"
	// cert, so we'll hope we aren't hacked during a unit test and instead load it from the server we started.
	wardleToKASKubeClientConfig := rest.CopyConfig(kubeClientConfig)

	servingCerts, _, err := cert.GetServingCertificatesForURL(wardleToKASKubeClientConfig.Host, "")
	if err != nil {
		t.Fatal(err)
	}
	encodedServing, err := cert.EncodeCertificates(servingCerts...)
	if err != nil {
		t.Fatal(err)
	}
	wardleToKASKubeClientConfig.CAData = encodedServing

	for _, v := range servingCerts {
		t.Logf("Client: Server public key is %v\n", dynamiccertificates.GetHumanCertDetail(v))
	}
	certs, err := cert.ParseCertsPEM(wardleToKASKubeClientConfig.CAData)
	if err != nil {
		t.Fatal(err)
	}
	for _, curr := range certs {
		t.Logf("CA bundle %v\n", dynamiccertificates.GetHumanCertDetail(curr))
	}

	adminKubeConfig := createKubeConfig(wardleToKASKubeClientConfig)
	wardleToKASKubeConfigFile, _ := os.CreateTemp("", "")
	if err := clientcmd.WriteToFile(*adminKubeConfig, wardleToKASKubeConfigFile.Name()); err != nil {
		t.Fatal(err)
	}

	return wardleToKASKubeConfigFile.Name()
}

func createKubeConfig(clientCfg *rest.Config) *clientcmdapi.Config {
	clusterNick := "cluster"
	userNick := "user"
	contextNick := "context"

	config := clientcmdapi.NewConfig()

	credentials := clientcmdapi.NewAuthInfo()
	credentials.Token = clientCfg.BearerToken
	credentials.ClientCertificate = clientCfg.TLSClientConfig.CertFile
	if len(credentials.ClientCertificate) == 0 {
		credentials.ClientCertificateData = clientCfg.TLSClientConfig.CertData
	}
	credentials.ClientKey = clientCfg.TLSClientConfig.KeyFile
	if len(credentials.ClientKey) == 0 {
		credentials.ClientKeyData = clientCfg.TLSClientConfig.KeyData
	}
	config.AuthInfos[userNick] = credentials

	cluster := clientcmdapi.NewCluster()
	cluster.Server = clientCfg.Host
	cluster.CertificateAuthority = clientCfg.CAFile
	if len(cluster.CertificateAuthority) == 0 {
		cluster.CertificateAuthorityData = clientCfg.CAData
	}
	cluster.InsecureSkipTLSVerify = clientCfg.Insecure
	config.Clusters[clusterNick] = cluster

	context := clientcmdapi.NewContext()
	context.Cluster = clusterNick
	context.AuthInfo = userNick
	config.Contexts[contextNick] = context
	config.CurrentContext = contextNick

	return config
}

func readResponse(ctx context.Context, client rest.Interface, location string) ([]byte, error) {
	return client.Get().AbsPath(location).DoRaw(ctx)
}

func testAPIGroupList(ctx context.Context, t *testing.T, client rest.Interface) {
	contents, err := readResponse(ctx, client, "/apis")
	if err != nil {
		t.Fatalf("%v", err)
	}
	t.Log(string(contents))
	var apiGroupList metav1.APIGroupList
	err = json.Unmarshal(contents, &apiGroupList)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", "/apis", err)
	}
	assert.Equal(t, 1, len(apiGroupList.Groups))
	assert.Equal(t, wardlev1alpha1.GroupName, apiGroupList.Groups[0].Name)
	assert.Equal(t, 2, len(apiGroupList.Groups[0].Versions))

	v1alpha1 := metav1.GroupVersionForDiscovery{
		GroupVersion: wardlev1alpha1.SchemeGroupVersion.String(),
		Version:      wardlev1alpha1.SchemeGroupVersion.Version,
	}
	v1beta1 := metav1.GroupVersionForDiscovery{
		GroupVersion: wardlev1beta1.SchemeGroupVersion.String(),
		Version:      wardlev1beta1.SchemeGroupVersion.Version,
	}

	assert.Equal(t, v1beta1, apiGroupList.Groups[0].Versions[0])
	assert.Equal(t, v1alpha1, apiGroupList.Groups[0].Versions[1])
	assert.Equal(t, v1beta1, apiGroupList.Groups[0].PreferredVersion)
}

func testAPIGroup(ctx context.Context, t *testing.T, client rest.Interface) {
	contents, err := readResponse(ctx, client, "/apis/wardle.example.com")
	if err != nil {
		t.Fatalf("%v", err)
	}
	t.Log(string(contents))
	var apiGroup metav1.APIGroup
	err = json.Unmarshal(contents, &apiGroup)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", "/apis/wardle.example.com", err)
	}
	assert.Equal(t, wardlev1alpha1.SchemeGroupVersion.Group, apiGroup.Name)
	assert.Equal(t, 2, len(apiGroup.Versions))
	assert.Equal(t, wardlev1alpha1.SchemeGroupVersion.String(), apiGroup.Versions[1].GroupVersion)
	assert.Equal(t, wardlev1alpha1.SchemeGroupVersion.Version, apiGroup.Versions[1].Version)
	assert.Equal(t, apiGroup.PreferredVersion, apiGroup.Versions[0])
}

func testAPIResourceList(ctx context.Context, t *testing.T, client rest.Interface) {
	contents, err := readResponse(ctx, client, "/apis/wardle.example.com/v1alpha1")
	if err != nil {
		t.Fatalf("%v", err)
	}
	t.Log(string(contents))
	var apiResourceList metav1.APIResourceList
	err = json.Unmarshal(contents, &apiResourceList)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", "/apis/wardle.example.com/v1alpha1", err)
	}
	assert.Equal(t, wardlev1alpha1.SchemeGroupVersion.String(), apiResourceList.GroupVersion)
	assert.Equal(t, 2, len(apiResourceList.APIResources))
	assert.Equal(t, "fischers", apiResourceList.APIResources[0].Name)
	assert.False(t, apiResourceList.APIResources[0].Namespaced)
	assert.Equal(t, "flunders", apiResourceList.APIResources[1].Name)
	assert.True(t, apiResourceList.APIResources[1].Namespaced)
}

var (
	// I have no idea what these certs are, they just need to be different
	differentClientCA = []byte(`-----BEGIN CERTIFICATE-----
MIIDQDCCAiigAwIBAgIJANWw74P5KJk2MA0GCSqGSIb3DQEBCwUAMDQxMjAwBgNV
BAMMKWdlbmVyaWNfd2ViaG9va19hZG1pc3Npb25fcGx1Z2luX3Rlc3RzX2NhMCAX
DTE3MTExNjAwMDUzOVoYDzIyOTEwOTAxMDAwNTM5WjAjMSEwHwYDVQQDExh3ZWJo
b29rLXRlc3QuZGVmYXVsdC5zdmMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDXd/nQ89a5H8ifEsigmMd01Ib6NVR3bkJjtkvYnTbdfYEBj7UzqOQtHoLa
dIVmefny5uIHvj93WD8WDVPB3jX2JHrXkDTXd/6o6jIXHcsUfFTVLp6/bZ+Anqe0
r/7hAPkzA2A7APyTWM3ZbEeo1afXogXhOJ1u/wz0DflgcB21gNho4kKTONXO3NHD
XLpspFqSkxfEfKVDJaYAoMnYZJtFNsa2OvsmLnhYF8bjeT3i07lfwrhUZvP+7Gsp
7UgUwc06WuNHjfx1s5e6ySzH0QioMD1rjYneqOvk0pKrMIhuAEWXqq7jlXcDtx1E
j+wnYbVqqVYheHZ8BCJoVAAQGs9/AgMBAAGjZDBiMAkGA1UdEwQCMAAwCwYDVR0P
BAQDAgXgMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATApBgNVHREEIjAg
hwR/AAABghh3ZWJob29rLXRlc3QuZGVmYXVsdC5zdmMwDQYJKoZIhvcNAQELBQAD
ggEBAD/GKSPNyQuAOw/jsYZesb+RMedbkzs18sSwlxAJQMUrrXwlVdHrA8q5WhE6
ABLqU1b8lQ8AWun07R8k5tqTmNvCARrAPRUqls/ryER+3Y9YEcxEaTc3jKNZFLbc
T6YtcnkdhxsiO136wtiuatpYL91RgCmuSpR8+7jEHhuFU01iaASu7ypFrUzrKHTF
bKwiLRQi1cMzVcLErq5CDEKiKhUkoDucyARFszrGt9vNIl/YCcBOkcNvM3c05Hn3
M++C29JwS3Hwbubg6WO3wjFjoEhpCwU6qRYUz3MRp4tHO4kxKXx+oQnUiFnR7vW0
YkNtGc1RUDHwecCTFpJtPb7Yu/E=
-----END CERTIFICATE-----
`)
	differentFrontProxyCA = []byte(`-----BEGIN CERTIFICATE-----
MIIBqDCCAU2gAwIBAgIUfbqeieihh/oERbfvRm38XvS/xHAwCgYIKoZIzj0EAwIw
GjEYMBYGA1UEAxMPSW50ZXJtZWRpYXRlLUNBMCAXDTE2MTAxMTA1MDYwMFoYDzIx
MTYwOTE3MDUwNjAwWjAUMRIwEAYDVQQDEwlNeSBDbGllbnQwWTATBgcqhkjOPQIB
BggqhkjOPQMBBwNCAARv6N4R/sjMR65iMFGNLN1GC/vd7WhDW6J4X/iAjkRLLnNb
KbRG/AtOUZ+7upJ3BWIRKYbOabbQGQe2BbKFiap4o3UwczAOBgNVHQ8BAf8EBAMC
BaAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQU
K/pZOWpNcYai6eHFpmJEeFpeQlEwHwYDVR0jBBgwFoAUX6nQlxjfWnP6aM1meO/Q
a6b3a9kwCgYIKoZIzj0EAwIDSQAwRgIhAIWTKw/sjJITqeuNzJDAKU4xo1zL+xJ5
MnVCuBwfwDXCAiEAw/1TA+CjPq9JC5ek1ifR0FybTURjeQqYkKpve1dveps=
-----END CERTIFICATE-----

`)
)

type staticURLServiceResolver string

func (u staticURLServiceResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error) {
	return url.Parse(string(u))
}


text:
module ExampleHelper
  def example_format(text)
    "#{h(text)}".html_safe!
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.clients.commerce.catalog.admin.couponsets;

import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

/**
 *
 *
 */
public class CouponClient {

	/**
	 *
	 *

	 * MozuClient<List<com.mozu.api.contracts.productadmin.AssignedDiscount>> mozuClient=GetAssignedDiscountsClient( couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * AssignedDiscount assignedDiscount = client.Result();
	 *

	 * @param couponSetCode
	 * @return Mozu.Api.MozuClient <List<com.mozu.api.contracts.productadmin.AssignedDiscount>>
	 * @see com.mozu.api.contracts.productadmin.AssignedDiscount
	 */
	public static MozuClient<List<com.mozu.api.contracts.productadmin.AssignedDiscount>> getAssignedDiscountsClient(String couponSetCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.getAssignedDiscountsUrl(couponSetCode);
		String verb = "GET";
		Class<?> clz = new ArrayList<com.mozu.api.contracts.productadmin.AssignedDiscount>(){}.getClass();
		MozuClient<List<com.mozu.api.contracts.productadmin.AssignedDiscount>> mozuClient = (MozuClient<List<com.mozu.api.contracts.productadmin.AssignedDiscount>>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.Coupon> mozuClient=GetCouponClient( couponSetCode,  couponCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * Coupon coupon = client.Result();
	 *

	 * @param couponCode
	 * @param couponSetCode
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Coupon>
	 * @see com.mozu.api.contracts.productadmin.Coupon
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.Coupon> getCouponClient(String couponSetCode, String couponCode) throws Exception
	{
		return getCouponClient( couponSetCode,  couponCode,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.Coupon> mozuClient=GetCouponClient( couponSetCode,  couponCode,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * Coupon coupon = client.Result();
	 *

	 * @param couponCode
	 * @param couponSetCode
	 * @param responseFields
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.Coupon>
	 * @see com.mozu.api.contracts.productadmin.Coupon
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.Coupon> getCouponClient(String couponSetCode, String couponCode, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.getCouponUrl(couponCode, couponSetCode, responseFields);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.productadmin.Coupon.class;
		MozuClient<com.mozu.api.contracts.productadmin.Coupon> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.Coupon>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.CouponCollection> mozuClient=GetCouponsClient( couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CouponCollection couponCollection = client.Result();
	 *

	 * @param couponSetCode
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.CouponCollection>
	 * @see com.mozu.api.contracts.productadmin.CouponCollection
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.CouponCollection> getCouponsClient(String couponSetCode) throws Exception
	{
		return getCouponsClient( couponSetCode,  null,  null,  null,  null,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.CouponCollection> mozuClient=GetCouponsClient( couponSetCode,  startIndex,  pageSize,  sortBy,  filter,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CouponCollection couponCollection = client.Result();
	 *

	 * @param couponSetCode
	 * @param filter
	 * @param pageSize
	 * @param responseFields
	 * @param sortBy
	 * @param startIndex
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.CouponCollection>
	 * @see com.mozu.api.contracts.productadmin.CouponCollection
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.CouponCollection> getCouponsClient(String couponSetCode, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.getCouponsUrl(couponSetCode, filter, pageSize, responseFields, sortBy, startIndex);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.productadmin.CouponCollection.class;
		MozuClient<com.mozu.api.contracts.productadmin.CouponCollection> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.CouponCollection>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.CouponSet> mozuClient=GetCouponSetClient( couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CouponSet couponSet = client.Result();
	 *

	 * @param couponSetCode
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.CouponSet>
	 * @see com.mozu.api.contracts.productadmin.CouponSet
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.CouponSet> getCouponSetClient(String couponSetCode) throws Exception
	{
		return getCouponSetClient( couponSetCode,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.CouponSet> mozuClient=GetCouponSetClient( couponSetCode,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CouponSet couponSet = client.Result();
	 *

	 * @param couponSetCode
	 * @param responseFields
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.CouponSet>
	 * @see com.mozu.api.contracts.productadmin.CouponSet
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.CouponSet> getCouponSetClient(String couponSetCode, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.getCouponSetUrl(couponSetCode, responseFields);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.productadmin.CouponSet.class;
		MozuClient<com.mozu.api.contracts.productadmin.CouponSet> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.CouponSet>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=AssignDiscountClient( assignedDiscount,  couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param couponSetCode
	 * @param assignedDiscount
	 * @return Mozu.Api.MozuClient
	 * @see com.mozu.api.contracts.productadmin.AssignedDiscount
	 */
	public static MozuClient assignDiscountClient(com.mozu.api.contracts.productadmin.AssignedDiscount assignedDiscount, String couponSetCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.assignDiscountUrl(couponSetCode);
		String verb = "POST";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(assignedDiscount);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=AddCouponsClient( coupons,  couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param couponSetCode
	 * @param coupons
	 * @return Mozu.Api.MozuClient
	 * @see com.mozu.api.contracts.productadmin.Coupon
	 */
	public static MozuClient addCouponsClient(List<com.mozu.api.contracts.productadmin.Coupon> coupons, String couponSetCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.addCouponsUrl(couponSetCode);
		String verb = "POST";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(coupons);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.CouponSet> mozuClient=UpdateCouponSetClient( couponSet,  couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CouponSet couponSet = client.Result();
	 *

	 * @param couponSetCode
	 * @param couponSet
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.CouponSet>
	 * @see com.mozu.api.contracts.productadmin.CouponSet
	 * @see com.mozu.api.contracts.productadmin.CouponSet
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.CouponSet> updateCouponSetClient(com.mozu.api.contracts.productadmin.CouponSet couponSet, String couponSetCode) throws Exception
	{
		return updateCouponSetClient( couponSet,  couponSetCode,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.productadmin.CouponSet> mozuClient=UpdateCouponSetClient( couponSet,  couponSetCode,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CouponSet couponSet = client.Result();
	 *

	 * @param couponSetCode
	 * @param responseFields
	 * @param couponSet
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.CouponSet>
	 * @see com.mozu.api.contracts.productadmin.CouponSet
	 * @see com.mozu.api.contracts.productadmin.CouponSet
	 */
	public static MozuClient<com.mozu.api.contracts.productadmin.CouponSet> updateCouponSetClient(com.mozu.api.contracts.productadmin.CouponSet couponSet, String couponSetCode, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.updateCouponSetUrl(couponSetCode, responseFields);
		String verb = "PUT";
		Class<?> clz = com.mozu.api.contracts.productadmin.CouponSet.class;
		MozuClient<com.mozu.api.contracts.productadmin.CouponSet> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.CouponSet>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(couponSet);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=DeleteCouponSetClient( couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param couponSetCode
	 * @return Mozu.Api.MozuClient
	 */
	public static MozuClient deleteCouponSetClient(String couponSetCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.deleteCouponSetUrl(couponSetCode);
		String verb = "DELETE";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=UnAssignDiscountClient( assignedDiscount,  couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param couponSetCode
	 * @param assignedDiscount
	 * @return Mozu.Api.MozuClient
	 * @see com.mozu.api.contracts.productadmin.AssignedDiscount
	 */
	public static MozuClient unAssignDiscountClient(com.mozu.api.contracts.productadmin.AssignedDiscount assignedDiscount, String couponSetCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.unAssignDiscountUrl(couponSetCode);
		String verb = "DELETE";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(assignedDiscount);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=DeleteCouponsClient( coupons,  couponSetCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param couponSetCode
	 * @param coupons
	 * @return Mozu.Api.MozuClient
	 * @see com.mozu.api.contracts.productadmin.Coupon
	 */
	public static MozuClient deleteCouponsClient(List<com.mozu.api.contracts.productadmin.Coupon> coupons, String couponSetCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.couponsets.CouponUrl.deleteCouponsUrl(couponSetCode);
		String verb = "DELETE";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(coupons);
		return mozuClient;

	}

}


text:
package me.calebjones.spacelaunchnow.common.youtube.models;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;

import com.afollestad.materialdialogs.util.DialogUtils;

import androidx.annotation.AttrRes;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;

public class VideoListItem {

    private final Builder builder;

    private VideoListItem(Builder builder) {
        this.builder = builder;
    }

    public Drawable getIcon() {
        return builder.icon;
    }

    public CharSequence getContent() {
        return builder.content;
    }

    public CharSequence getVideoURL() {
        return builder.videoURL;
    }

    public int getIconPadding() {
        return builder.iconPadding;
    }

    @ColorInt
    public int getBackgroundColor() {
        return builder.backgroundColor;
    }

    public long getId() {
        return builder.id;
    }

    @Nullable
    public Object getTag() {
        return builder.tag;
    }

    public static class Builder {

        private final Context context;
        protected Drawable icon;
        protected CharSequence content;
        protected CharSequence videoURL;
        protected long id;

        int iconPadding;
        int backgroundColor;
        Object tag;

        public Builder(Context context) {
            this.context = context;
            backgroundColor = Color.parseColor("#BCBCBC");
        }

        public Builder icon(Drawable icon) {
            this.icon = icon;
            return this;
        }

        public Builder icon(@DrawableRes int iconRes) {
            return icon(ContextCompat.getDrawable(context, iconRes));
        }

        public Builder iconPadding(@IntRange(from = 0, to = Integer.MAX_VALUE) int padding) {
            this.iconPadding = padding;
            return this;
        }

        public Builder iconPaddingDp(@IntRange(from = 0, to = Integer.MAX_VALUE) int paddingDp) {
            this.iconPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingDp,
                    context.getResources().getDisplayMetrics());
            return this;
        }

        public Builder iconPaddingRes(@DimenRes int paddingRes) {
            return iconPadding(context.getResources().getDimensionPixelSize(paddingRes));
        }

        public Builder content(CharSequence content) {
            this.content = content;
            return this;
        }

        public Builder videoURL(@StringRes int videoURLRes) {
            return videoURL(context.getString(videoURLRes));
        }

        public Builder videoURL(CharSequence videoURL) {
            this.videoURL = videoURL;
            return this;
        }

        public Builder content(@StringRes int contentRes) {
            return content(context.getString(contentRes));
        }

        public Builder backgroundColor(@ColorInt int color) {
            this.backgroundColor = color;
            return this;
        }

        public Builder backgroundColorRes(@ColorRes int colorRes) {
            return backgroundColor(DialogUtils.getColor(context, colorRes));
        }

        public Builder backgroundColorAttr(@AttrRes int colorAttr) {
            return backgroundColor(DialogUtils.resolveColor(context, colorAttr));
        }

        public Builder id(long id) {
            this.id = id;
            return this;
        }

        public Builder tag(@Nullable Object tag) {
            this.tag = tag;
            return this;
        }

        public VideoListItem build() {
            return new VideoListItem(this);
        }
    }

    @Override
    public String toString() {
        if (getContent() != null)
            return getContent().toString();
        else return "(no content)";
    }
}


text:
namespace il2cpp
{
namespace os
{
namespace win
{

// Wait for a release of the given handle in way that can be interrupted by APCs.
WaitStatus WaitForSingleObjectAndAccountForAPCs (HANDLE handle, uint32_t ms, bool interruptible);

}
}
}

#endif // IL2CPP_TARGET_WINDOWS


text:
'use strict';
/*jshint -W097*/
/*global it: false, describe: false, before: false*/
var expect = require('expect'),
    UnderTest = require('../index.js'),
    jptr = require('json-ptr');

describe('env-configurator', function () {
  var underTest;
  it('should validate and reject poorly formed configuration requests', function (done) {
    underTest = new UnderTest();
    underTest.fulfill({}, function (errs) {
      expect(errs).toExist();
      done();
    });
  });

  it('should handle validation without a callback function', function () {
    underTest = new UnderTest();
    underTest.fulfill({});
  });

  describe('when #get is called', function () {
    var underTest;
    before('setup a basic config spec for testing #get', function (done) {
      process.env.TEST3_FOO_BAZ = 'bar';
      underTest = new UnderTest();
      underTest.fulfill({
        "name": "test3",
        "keys": [
          "#/foo/baz"
        ],
        "optional": [
          "#/baz/foo"
        ]
      }, function (errs) {
        expect(errs).toNotExist();
        done();
      });
    });

    it('should throw an error when asked for configuration from a nonexistant context', function () {
      try {
        underTest.get('someNamespace', '#/my/ptr');
        throw new Error("Test failure--should not get here");
      } catch (expected) {
        expect(expected).toExist();
      }
    });

    it('should throw an error when given invalid parameters', function () {
      try {
        underTest.get('someNamespace');
        throw new Error("Test failure--should not get here");
      } catch (expected) {
        expect(expected).toExist();
      }
    });

    it('should make keys from the environment available via the get call', function () {
        expect(underTest.get('test3', '#/foo/baz')).toBe('bar');
    });

    it('should not throw an error on a json ptr referencing an optional key', function () {
      expect(underTest.get('#/test3/baz/foo')).toNotExist();
    });
    it('should not throw an error on a context and json ptr referencing an optional key', function () {
      expect(underTest.get('test3', '#/baz/foo')).toNotExist();
    });
  });

  it('should gracefully handle a valid but empty configuration', function (done) {
    underTest = new UnderTest();
    underTest.fulfill({
      "name": "test"
    }, function (errs) {
      expect(errs).toNotExist();
      done();
    });
  });

  it('should ensure that a config spec for a name cannot be changed after the first call', function (done) {
    process.env.TEST5_FOO_BAZ = 'bar';
    underTest = new UnderTest();

    underTest.fulfill({
      "name": "test5",

    }, function (errs) {
      expect(errs).toNotExist();
      underTest.fulfill({
        "name": "test5",
        "keys": [
          "#/foo/baz"
        ]
      }, function (errs) {
        expect(errs).toNotExist();
        try {
          underTest.get('test5', '#/foo/baz');
        } catch (expected) {
          expect(expected).toExist();
        }
        done();
      });
    });
  });

  it('should renew an existing configuration if renew(name) is called', function (done) {
    process.env.TEST6_BAR = 'baz';
    underTest = new UnderTest();

    underTest.fulfill({
      "name": "test6",
      "keys": [
        "#/bar"
      ]
    }, function (errs) {
      expect(underTest.get('test6', '#/bar')).toBe('baz');
      process.env.TEST6_BAR = 'foo';
      underTest.renew('test6', function (err) {
        expect(err).toNotExist();
        expect(underTest.get('test6', '#/bar')).toBe('foo');
        done();
      });
    });
  });

  it('should renew an existing configuration if renewAll is called', function (done) {
    process.env.TEST7_BAR = 'baz';
    underTest = new UnderTest();

    underTest.fulfill({
      "name": "test7",
      "keys": [
        "#/bar"
      ]
    }, function (errs) {
      expect(underTest.get('test7', '#/bar')).toBe('baz');
      process.env.TEST7_BAR = 'foo';
      underTest.renewAll(function (err) {
        expect(err).toNotExist();
        expect(underTest.get('test7', '#/bar')).toBe('foo');
        done();
      });
    });
  });

  describe('namespacing', function () {
    before('Create initial namespace', function (done) {
      underTest = new UnderTest();
      process.env.TEST8_BAR = 'baz';
      underTest.fulfill({
        "name": "test8",
        "keys": [
          "#/bar"
        ]
      }, function (errs) {
        if (errs) {
          throw new Error('Configurator test setup failed');
        } else {
          done();
        }
      });
    });

    it('should separate different configuration specifications', function (done) {
      underTest = new UnderTest();
      process.env.TEST9_BAR = 'bar';
      underTest.fulfill({
        "name": "test9",
        "keys": [
          "#/bar"
        ]
      }, function (errs) {
        if (errs) {
          throw new Error('Configurator test setup failed');
        } else {
          expect(underTest.get('test8', '#/bar')).toBe('baz');
          expect(underTest.get('test9', '#/bar')).toBe('bar');
          done();
        }
      });
    });
  });

  it('should fulfill config specifications passed as an array', function (done) {
    underTest = new UnderTest();
    process.env.TEST10_BAR = 'bar';
    process.env.TEST11_FOO = 'foo';

    underTest.fulfill([
      { "name": "test10", "keys": ["#/bar"] },
      { "name": "test11", "keys": ["#/foo"] }
    ], function (errs) {
      if (errs) {
        throw new Error('Configurator test setup failed');
      } else {
        expect(underTest.get('test10', '#/bar')).toBe('bar');
        expect(underTest.get('test11', '#/foo')).toBe('foo');
        done();
      }
    });
  });

  it('should make configuration via a json-ptr get call', function (done) {
    process.env.TEST12_FOO_BAZ = 'bar';
    underTest = new UnderTest();
    underTest.fulfill({
      "name": "test12",
      "keys": [
        "#/foo/baz"
      ]
    }, function (errs) {
      expect(errs).toNotExist();
      expect(underTest.get('#/test12/foo/baz')).toBe('bar');
      done();
    });
  });

});


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Object2689449295.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Networking.HostTopologyInternal
struct  HostTopologyInternal_t516387376  : public Il2CppObject
{
public:

public:
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
from builtins import filter
from builtins import range
import itertools
import logging
import re
import sys
import time
from datetime import datetime

from desktop.lib import export_csvxls
from libanalyze import analyze as analyzer, rules
from notebook.conf import ENABLE_QUERY_ANALYSIS

from jobbrowser.apis.base_api import Api

if sys.version_info[0] > 2:
  from django.utils.translation import gettext as _
else:
  from django.utils.translation import ugettext as _

ANALYZER = rules.TopDownAnalysis() # We need to parse some files so save as global
LOG = logging.getLogger(__name__)

try:
  from beeswax.models import Session
  from impala.server import get_api as get_impalad_api, _get_impala_server_url
except Exception as e:
  LOG.exception('Some application are not enabled: %s' % e)

def _get_api(user, cluster=None):
  if cluster and cluster.get('type') == 'altus-dw':
    server_url = 'http://impala-coordinator-%(name)s:25000' % cluster
  else:
    # TODO: multi computes if snippet.get('compute') or snippet['type'] has computes
    application = cluster.get('interface', 'impala')
    session = Session.objects.get_session(user, application=application)
    server_url = _get_impala_server_url(session)
  return get_impalad_api(user=user, url=server_url)

class QueryApi(Api):

  def __init__(self, user, impala_api=None, cluster=None):
    if impala_api:
      self.api = impala_api
    else:
      self.api = _get_api(user, cluster)

  def apps(self, filters):
    kwargs = {}

    jobs = self.api.get_queries(**kwargs)

    filter_list = self._get_filter_list(filters)
    jobs_iter = itertools.chain(jobs['in_flight_queries'], jobs['completed_queries'])
    jobs_iter_filtered = self._n_filter(filter_list, jobs_iter)

    apps = {
      'apps': sorted([{
        'id': job['query_id'],
        'name': job['stmt'].replace('\r\n', ' ')[:60] + ('...' if len(job['stmt']) > 60 else ''),
        'status': job['state'],
        'apiStatus': self._api_status(job['state']),
        'type': job['stmt_type'],
        'user': job['effective_user'],
        'queue': job.get('resource_pool'),
        'progress': job['progress'],
        'isRunning': job['start_time'] > job['end_time'],
        'canWrite': job in jobs['in_flight_queries'],
        'duration': self._time_in_ms_groups(
            re.search(r"\s*(([\d.]*)([a-z]*))(([\d.]*)([a-z]*))?(([\d.]*)([a-z]*))?",
            job['duration'],
            re.MULTILINE
        ).groups()),
        'submitted': job['start_time'],
        # Extra specific
        'rows_fetched': job['rows_fetched'],
        'waiting': job['waiting'],
        'waiting_time': job['waiting_time']
      } for job in jobs_iter_filtered], key=lambda job: job.get('submitted'), reverse=True),
      'total': 0
    }
    apps['total'] = len(apps['apps'])

    return apps

  def _time_in_ms_groups(self, groups):
    time = 0
    for x in range(0, len(groups), 3):
      if groups[x+1]:
        time += self._time_in_ms(groups[x+1], groups[x+2])
    return time

  def _time_in_ms(self, time, period):
    if period == 'ns':
      return float(time) / 1000
    elif period == 'ms':
      return float(time)
    elif period == 's':
      return float(time) * 1000
    elif period == 'm':
      return float(time) * 60000 #1000*60
    elif period == 'h':
      return float(time) * 3600000 #1000*60*60
    elif period == 'd':
      return float(time) * 86400000  # 1000*60*60*24
    else:
      return float(time)

  def app(self, appid):
    apps = self.apps({
      'text': 'id:' + appid
    })

    if not apps.get('apps'):
      return {
        'name': _('Unknown or expired query id %s') % appid
      }
    app = apps.get('apps')[0]
    progress_groups = re.search(r"([\d\.\,]+)%", app.get('progress'))
    app.update({
      'progress': float(progress_groups.group(1)) \
          if progress_groups and progress_groups.group(1) else 100 \
            if self._api_status(app.get('status')) in ['SUCCEEDED', 'FAILED'] else 1,
      'type': 'queries',
      'doc_url': "%s/query_plan?query_id=%s" % (self.api.url, appid),
      'properties': {
        'memory': '',
        'profile': '',
        'plan': '',
        'backends': '',
        'finstances': '',
        'metrics': ''
      }
    })

    return app

  def action(self, appid, action):
    message = {'message': '', 'status': 0}

    if action.get('action') == 'kill':
      for _id in appid:
        result = self.api.kill(_id)
        if result.get('error'):
          message['message'] = result.get('error')
          message['status'] = -1
        elif result.get('contents') and message.get('status') != -1:
          message['message'] = result.get('contents')

    return message;

  def logs(self, appid, app_type, log_name=None, is_embeddable=False):
    return {'logs': ''}

  def profile(self, appid, app_type, app_property, app_filters):
    if app_property == 'memory':
      return self._memory(appid, app_type, app_property, app_filters)
    elif app_property == 'profile':
      return self._query_profile(appid)
    elif app_property == 'download-profile':
      return export_csvxls.make_response([self._query_profile(appid)['profile']], 'txt', 'query-profile_%s' % appid)
    elif app_property == 'backends':
      return self._query_backends(appid)
    elif app_property == 'finstances':
      return self._query_finstances(appid)
    else:
      return self._query(appid)

  def profile_encoded(self, appid):
    return self.api.get_query_profile_encoded(query_id=appid)

  def _memory(self, appid, app_type, app_property, app_filters):
    return self.api.get_query_memory(query_id=appid);

  def _metrics(self, appid):
    query_profile = self.api.get_query_profile_encoded(appid)
    profile = analyzer.analyze(analyzer.parse_data(query_profile))
    ANALYZER.pre_process(profile)
    metrics = analyzer.metrics(profile)

    if ENABLE_QUERY_ANALYSIS.get():
      result = ANALYZER.run(profile)
      if result and result[0]:
        for factor in result[0]['result']:
          if factor['reason'] and factor['result_id'] and metrics['nodes'].get(factor['result_id']):
            metrics['nodes'][factor['result_id']]['health'] = factor['reason']
    return metrics

  def _query(self, appid):
    query = self.api.get_query(query_id=appid)
    query['summary'] = query.get('summary').strip() if query.get('summary') else ''
    query['plan'] = query.get('plan').strip() if query.get('plan') else ''
    try:
      query['metrics'] = self._metrics(appid)
    except Exception as e:
      query['metrics'] = {'nodes': {}}
      LOG.exception('Could not parse profile: %s' % e)

    if query.get('plan_json'):
      def get_exchange_icon(o):
        if re.search(r'broadcast', o['label_detail'], re.IGNORECASE):
          return {'svg': 'hi-broadcast'}
        elif re.search(r'hash', o['label_detail'], re.IGNORECASE):
          return {'svg': 'hi-random'}
        else:
          return {'svg': 'hi-exchange'}
      def get_sigma_icon(o):
        if re.search(r'streaming', o['label_detail'], re.IGNORECASE):
          return {'svg': 'hi-sigma'}
        else:
          return {'svg': 'hi-sigma'}
      mapping = {
        'TOP-N': {'type': 'TOPN', 'icon': {'svg': 'hi-filter'}},
        'SORT': {'type': 'SORT', 'icon': {'svg': 'hi-sort'}},
        'MERGING-EXCHANGE': {'type': 'EXCHANGE', 'icon': {'fn': get_exchange_icon}},
        'EXCHANGE': {'type': 'EXCHANGE', 'icon': {'fn': get_exchange_icon}},
        'SCAN HDFS': {'type': 'SCAN_HDFS', 'icon': {'svg': 'hi-copy'}},
        'SCAN KUDU': {'type': 'SCAN_KUDU', 'icon': {'svg': 'hi-table'}},
        'SCAN HBASE': {'type': 'SCAN_HBASE', 'icon': {'font': 'fa-th-large'}},
        'HASH JOIN': {'type': 'HASH_JOIN', 'icon': {'svg': 'hi-join'}},
        'AGGREGATE': {'type': 'AGGREGATE', 'icon': {'fn': get_sigma_icon}},
        'NESTED LOOP JOIN': {'type': 'LOOP_JOIN', 'icon': {'svg': 'hi-nested-loop'}},
        'SUBPLAN': {'type': 'SUBPLAN', 'icon': {'svg': 'hi-map'}},
        'UNNEST': {'type': 'UNNEST', 'icon': {'svg': 'hi-unnest'}},
        'SINGULAR ROW SRC': {'type': 'SINGULAR', 'icon': {'svg': 'hi-vertical-align'}},
        'ANALYTIC': {'type': 'SINGULAR', 'icon': {'svg': 'hi-timeline'}},
        'UNION': {'type': 'UNION', 'icon': {'svg': 'hi-merge'}}
      }
      def process(node, mapping=mapping):
        node['id'], node['name'] = node['label'].split(':')
        details = mapping.get(node['name'])
        if details:
          icon = details['icon']
          if icon and icon.get('fn'):
            icon = icon['fn'](node)
          node['icon'] = icon

      for node in query['plan_json']['plan_nodes']:
        self._for_each_node(node, process)
    return query

  def _for_each_node(self, node, fn):
    fn(node)
    for child in node['children']:
      self._for_each_node(child, fn)

  def _query_profile(self, appid):
    return self.api.get_query_profile(query_id=appid)

  def _query_backends(self, appid):
    return self.api.get_query_backends(query_id=appid)

  def _query_finstances(self, appid):
    return self.api.get_query_finstances(query_id=appid)

  def _api_status_filter(self, status):
    if status == 'FINISHED':
      return 'COMPLETED'
    elif status == 'EXCEPTION':
      return 'FAILED'
    elif status == 'RUNNING':
      return 'RUNNING'

  def _api_status(self, status):
    if status == 'FINISHED':
      return 'SUCCEEDED'
    elif status == 'EXCEPTION':
      return 'FAILED'
    elif status == 'RUNNING':
      return 'RUNNING'
    else:
      return 'PAUSED'

  def _get_filter_list(self, filters):
    filter_list = []
    if filters.get("text"):
      filter_names = {
        'user': 'effective_user',
        'id': 'query_id',
        'name': 'state',
        'type': 'stmt_type',
        'status': 'status'
      }

      def make_lambda(name, value):
        return lambda app: app[name] == value

      for key, name in list(filter_names.items()):
        text_filter = re.search(r"\s*("+key+")\s*:([^ ]+)", filters.get("text"))
        if text_filter and text_filter.group(1) == key:
          filter_list.append(make_lambda(name, text_filter.group(2).strip()))
    if filters.get("time"):
      time_filter = filters.get("time")
      period_ms = self._time_in_ms(float(time_filter.get("time_value")), time_filter.get("time_unit")[0:1])
      current_ms = time.time() * 1000.0
      filter_list.append(
          lambda app: current_ms - (time.mktime(datetime.strptime(app['start_time'][:26], '%Y-%m-%d %H:%M:%S.%f').timetuple()) * 1000)
            < period_ms
      )
    if filters.get("states"):
      filter_list.append(lambda app: self._api_status_filter(app['state']).lower() in filters.get("states"))

    return filter_list

  def _n_filter(self, filters, tuples):
    for f in filters:
      tuples = list(filter(f, tuples))
    return tuples


text:
<?php
/**
 *  Declare the Project Region Taxonomy
 *  This is the taxonomy used to classify each project by the
 *  continent it resides on.
 */
add_action( 'init', 'project_region_tax', 1 );
function project_region_tax() {
    $labels = array(
        'name'              => _x( 'Regions', 'taxonomy general name' ),
        'singular_name'     => _x( 'Region', 'taxonomy singular name' ),
        'search_items'      => __( 'Search Regions' ),
        'all_items'         => __( 'All Regions' ),
        'parent_item'       => __( 'Parent Region' ),
        'parent_item_colon' => __( 'Parent Region:' ),
        'edit_item'         => __( 'Edit Region' ),
        'update_item'       => __( 'Update Region' ),
        'add_new_item'      => __( 'Add New Region' ),
        'new_item_name'     => __( 'New Region Name' ),
        'menu_name'         => __( 'All Regions' ),
    );
    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'show_in_quick_edit'=> false,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'project-region' ),
    );
    register_taxonomy( 'project_region', array( 'project' ), $args );
}


text:
<?php

/* AbloqovVisioplusBundle:Marque:index.html.twig */
class __TwigTemplate_2802b5c2a944713d0a3963e0c51570e15e3ecafbd119b0223d2207578b95cfc0 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("AbloqovVisioplusBundle::layout.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'styleCSS' => array($this, 'block_styleCSS'),
            'javascript' => array($this, 'block_javascript'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "AbloqovVisioplusBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_styleCSS($context, array $blocks = array())
    {
        // line 4
        echo "    ";
        $this->displayParentBlock("styleCSS", $context, $blocks);
        echo "
    <link rel=\"stylesheet\" type=\"text/css\" href=\"";
        // line 5
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/abloqovvisioplus/css/reset.css"), "html", null, true);
        echo "\" media=\"screen\" />
    <link rel=\"stylesheet\" type=\"text/css\" href=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/abloqovvisioplus/css/text.css"), "html", null, true);
        echo "\" media=\"screen\" />
    <link rel=\"stylesheet\" type=\"text/css\" href=\"";
        // line 7
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/abloqovvisioplus/css/grid.css"), "html", null, true);
        echo "\" media=\"screen\" />
    <link rel=\"stylesheet\" type=\"text/css\" href=\"";
        // line 8
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/abloqovvisioplus/css/layout.css"), "html", null, true);
        echo "\" media=\"screen\" />
    <link rel=\"stylesheet\" type=\"text/css\" href=\"";
        // line 9
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/abloqovvisioplus/css/nav.css"), "html", null, true);
        echo "\" media=\"screen\" />

    <link href=\"";
        // line 12
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/abloqovvisioplus/css/table/demo_page.css"), "html", null, true);
        echo "\" rel=\"stylesheet\" type=\"text/css\" />
";
    }

    // line 15
    public function block_javascript($context, array $blocks = array())
    {
        // line 16
        echo "    ";
        $this->displayParentBlock("javascript", $context, $blocks);
        echo "

";
    }

    // line 43
    public function block_content($context, array $blocks = array())
    {
        // line 44
        echo "

            \t
Statistiques

                        Marques

                            ";
        // line 53
        echo twig_escape_filter($this->env, (isset($context["nbmarques"]) ? $context["nbmarques"] : null), "html", null, true);
        echo "

            \t

GESTION DES MARQUES DE MONTURES

                \t

                            \t

                                \t

                                    \tN°
                                         MARQUES
                                         MONTURES
                                         HOMMES
                                         FEMMES
                                         ENFANTS
                                         MIXTES
                                         ACTIONS

                                        ";
        // line 82
        $context["numero"] = 0;
        // line 83
        echo "                                        ";
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["marques"]) ? $context["marques"] : null));
        foreach ($context['_seq'] as $context["_key"] => $context["marque"]) {
            // line 84
            echo "

                                            ";
            // line 85
            $context["numero"] = ((isset($context["numero"]) ? $context["numero"] : null) + 1);
            // line 86
            echo "                                                ";
            echo twig_escape_filter($this->env, (isset($context["numero"]) ? $context["numero"] : null), "html", null, true);
            echo "
                                                 ";
            // line 87
            echo twig_escape_filter($this->env, $this->getAttribute($context["marque"], "libelle", array()), "html", null, true);
            echo "
                                                 ";
            // line 88
            echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("AbloqovVisioplusBundle:Marque:nbmonture", array("id" => $this->getAttribute($context["marque"], "id", array()))));
            echo "
                                                 ";
            // line 89
            echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("AbloqovVisioplusBundle:Marque:nbmonturehomme", array("id" => $this->getAttribute($context["marque"], "id", array()))));
            echo "
                                                 ";
            // line 90
            echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("AbloqovVisioplusBundle:Marque:nbmonturefemme", array("id" => $this->getAttribute($context["marque"], "id", array()))));
            echo "
                                                 ";
            // line 91
            echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("AbloqovVisioplusBundle:Marque:nbmontureenfant", array("id" => $this->getAttribute($context["marque"], "id", array()))));
            echo "
                                                 ";
            // line 92
            echo $this->env->getExtension('http_kernel')->renderFragment($this->env->getExtension('http_kernel')->controller("AbloqovVisioplusBundle:Marque:nbmonturemixte", array("id" => $this->getAttribute($context["marque"], "id", array()))));
            echo "

                                                    env, $this->env->getExtension('routing')->getPath("marque_edit", array("id" => $this->getAttribute($context["marque"], "id", array()))), "html", null, true);
            echo "\" title=\"Modifier la marque\">
                                                      |
                                                    env, $this->env->getExtension('routing')->getPath("marque_show", array("id" => $this->getAttribute($context["marque"], "id", array()))), "html", null, true);
            echo "\" title=\"Voir les details de la marque\">

                                        ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['marque'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 101
        echo "

                                env->getExtension('routing')->getPath("marque_new");
        echo "\"> Ajouter une marque

                    \t

";
    }

    public function getTemplateName()
    {
        return "AbloqovVisioplusBundle:Marque:index.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  256 => 104,  251 => 101,  240 => 96,  235 => 94,  230 => 92,  226 => 91,  222 => 90,  218 => 89,  214 => 88,  210 => 87,  205 => 86,  203 => 85,  200 => 84,  195 => 83,  193 => 82,  161 => 53,  150 => 44,  147 => 43,  130 => 29,  126 => 28,  121 => 26,  117 => 25,  113 => 24,  109 => 23,  105 => 22,  101 => 21,  97 => 20,  93 => 19,  89 => 18,  83 => 16,  80 => 15,  74 => 12,  70 => 11,  66 => 10,  62 => 9,  58 => 8,  54 => 7,  50 => 6,  46 => 5,  41 => 4,  38 => 3,  11 => 1,);
    }
}


text:
FactoryBot.define do
  factory :dummy_group, class: Dummy::DummyGroup do
  end
end


text:
package org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes;

import java.util.ArrayList;
import java.util.Arrays;

import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.UsbPolicy;
import org.ovirt.engine.core.common.businessentities.network.VnicProfileView;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.VnicInstanceType;

public class NewInstanceTypeModelBehavior extends NonClusterModelBehaviorBase {

    @Override
    public void initialize(SystemTreeItemModel systemTreeSelectedItem) {
        super.initialize(systemTreeSelectedItem);
        updateNumOfSockets();

        initDisplayTypes(DisplayType.qxl, UnitVmModel.GraphicsTypes.SPICE);

        // no way to pick a specific host
        getModel().getIsAutoAssign().setEntity(true);
        getModel().getUsbPolicy().setItems(Arrays.asList(
                UsbPolicy.DISABLED,
                UsbPolicy.ENABLED_NATIVE));

        getModel().getIsSoundcardEnabled().setIsChangeable(true);
        getModel().setSelectedMigrationDowntime(null);
        getModel().getMemoryBalloonDeviceEnabled().setIsAvailable(true);
        initPriority(0);
        getModel().getTotalCPUCores().setEntity("1"); //$NON-NLS-1$

        getModel().getNicsWithLogicalNetworks().getVnicProfiles().setItems(new ArrayList<VnicProfileView>(Arrays.asList(VnicProfileView.EMPTY)));
        getModel().getNicsWithLogicalNetworks().setItems(new ArrayList<VnicInstanceType>());
    }
}


text:
namespace Tiny3D {

}


text:
Abhinav Kulkarni

I am a CS undergrad from PESIT, India. I am an avid Hacker and FOSS enthusiast.


text:
layout: post
title: Brazzers - Julia Ann is one hot nurse
titleinfo: pornvd
desc: Watch Brazzers - Julia Ann is one hot nurse. Pornhub is the ultimate xxx porn and sex site.
---

Brazzers - Julia Ann is one hot nurse

Watch Brazzers - Julia Ann is one hot nurse. Pornhub is the ultimate xxx porn and sex site.


text:
package com.cheng.backend.modules.cms.bean;

import com.cheng.backend.framework.common.BaseEntity;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;

import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * 留言Entity
 *
 * @author fengcheng
 * @version 2016/7/28
 */
@Table(name = "cms_guestbook")
public class Guestbook extends BaseEntity<Guestbook> {

    private static final long serialVersionUID = 1L;
    private String type;    // 留言分类(咨询、建议、投诉、其它)
    private String content; // 留言内容
    private String name;    // 姓名
    private String email;    // 邮箱
    private String phone;    // 电话
    private String workunit;// 单位
    private String ip;        // 留言IP
    private Date createDate;// 留言时间
    private String reUserId;        // 回复人
    private Date reDate;    // 回复时间
    private String reContent;// 回复内容
    private String delFlag;    // 删除标记删除标记(0:正常;1:删除;2:审核)

    @Transient
    private String reUserName;

    public Guestbook() {
    }

    public Guestbook(String id) {
        this();
        this.id = id;
    }

    @Length(min = 1, max = 100)
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Length(min = 1, max = 2000)
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Length(min = 1, max = 100)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Email
    @Length(min = 0, max = 100)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Length(min = 0, max = 100)
    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Length(min = 0, max = 100)
    public String getWorkunit() {
        return workunit;
    }

    public void setWorkunit(String workunit) {
        this.workunit = workunit;
    }

    @Length(min = 1, max = 100)
    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    @NotNull
    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public String getReUserId() {
        return reUserId;
    }

    public void setReUserId(String reUserId) {
        this.reUserId = reUserId;
    }

    public String getReContent() {
        return reContent;
    }

    public void setReContent(String reContent) {
        this.reContent = reContent;
    }

    public Date getReDate() {
        return reDate;
    }

    public void setReDate(Date reDate) {
        this.reDate = reDate;
    }

    @Length(min = 1, max = 1)
    public String getDelFlag() {
        return delFlag;
    }

    public void setDelFlag(String delFlag) {
        this.delFlag = delFlag;
    }

    public String getReUserName() {
        return reUserName;
    }

    public void setReUserName(String reUserName) {
        this.reUserName = reUserName;
    }
}


text:
<?php

/**
 * PHP version 7.3
 *
 * @category ClientFactoryDependentService
 * @package  RetailCrm\TestUtils
 */

namespace RetailCrm\TestUtils;

use Psr\Http\Client\ClientInterface;
use RetailCrm\Api\Interfaces\ClientFactoryInterface;
use Throwable;

/**
 * Class ClientFactoryDependentService
 *
 * @category ClientFactoryDependentService
 * @package  RetailCrm\TestUtils
 */
class ClientFactoryDependentService
{
    /** @var ClientFactoryInterface */
    private $clientFactory;

    /** @var \Psr\Http\Client\ClientInterface|null */
    private $httpClient;

    /**
     * ClientFactoryDependentService constructor.
     *
     * @param \RetailCrm\Api\Interfaces\ClientFactoryInterface $clientFactory
     */
    public function __construct(ClientFactoryInterface $clientFactory)
    {
        $this->clientFactory = $clientFactory;
    }

    /**
     * @param \Psr\Http\Client\ClientInterface|null $httpClient
     *
     * @return ClientFactoryDependentService
     */
    public function setHttpClient(?ClientInterface $httpClient): ClientFactoryDependentService
    {
        $this->httpClient = $httpClient;
        return $this;
    }

    /**
     * Returns true if API is available
     *
     * @param string $apiUrl
     * @param string $apiKey
     *
     * @return bool
     */
    public function isApiAccessible(string $apiUrl, string $apiKey): bool
    {
        try {
            $client = $this->clientFactory->createClient($apiUrl, $apiKey);

            if (null !== $this->httpClient) {
                ReflectionUtils::setProperty(
                    ReflectionUtils::getProperty($client, 'api'),
                    'httpClient',
                    $this->httpClient
                );
            }

            $client->api->apiVersions();

            return true;
        } catch (Throwable $throwable) {
            return false;
        }
    }
}


text:
package yaes.ui.format;

import yaes.ui.text.TextUiHelper;

/**
 * Helps create an indented, headlined toString format
 *
 * @author Ladislau Boloni
 *
 */
public class Formatter {

    protected StringBuffer buffer        = new StringBuffer();
    private int          currentIndent = 0;
    private int          indent        = 4;
    private static String       fmtDouble     = "%.3f";

    /**
     * Adds an object at the current level of indent
     *
     * @param object
     */
    public void add(Object object) {
        String objectString = object.toString();
        String temp = TextUiHelper.indent(currentIndent, objectString);
        buffer.append(temp);
        if (!objectString.endsWith("\n")) {
            buffer.append("\n");
        }
    }

    /**
     * Adds the next object in an indented form
     */
    public void addIndented(Object object) {
        currentIndent = currentIndent + indent;
        add(object);
        currentIndent = currentIndent - indent;
    }

    /**
     * Adds the text shifted, with a margin note inserted at the beginning
     *
     * Fixme: the 4,
     *
     * @param prefix
     * @param text
     */
    public void addWithMarginNote(String prefix, String text) {
        StringBuffer buf = new StringBuffer();
        buf.append(prefix);
        text = TextUiHelper.indent(8, text);
        buf.append(text.substring(prefix.length()));
        add(buf);
    }

    /**
     * De-indents the following text
     */
    public void deindent() {
        currentIndent = currentIndent - indent;
        if (currentIndent < 0) {
            throw new Error("Current indent becomes negative here - deindent without indent!!!");
        }
    }

    /**
     * Formats a double
     *
     * @param d
     * @return
     */
    public static String fmt(double value) {
        return String.format(fmtDouble, value);
    }

    /**
     * Indents the following text
     */
    public void indent() {
        currentIndent = currentIndent + indent;
    }

    public void is(String name, Object object) {
        String value;
        if (object instanceof Double) {
            value = fmt((Double) object);
        } else {
            value = object.toString();
        }
        add(name + " = " + value);
    }

    /**
     * Creates a labeled separator (indented with the current value)
     *
     * @param text
     */
    public void separator(String text) {
        String sep = TextUiHelper.createLabeledSeparator("-" + text);
        add(sep);
    }

    @Override
    public String toString() {
        return buffer.toString();
    }

    public void addNonIndented(Object object) {
        String objectString = object.toString();
        buffer.append(object);
        if (!objectString.endsWith("\n")) {
            buffer.append("\n");
        }
    }

}


text:
{% load i18n comments frontadmin_tags flatblocks markup %}
{% frontadmin request object %}

{{ object.title }}

{{ object.text|textile}}

{% endfrontadmin %}


text:
Scott Wiedemann

04/09/2017

## Compile It
ant

## Run It
java -jar ./target/righttrianglesintegercoordinates.jar N

N is 50 in this case. N=x2=y2

## Thoughts
There are x2*y2 triangles where the right angle is at the origin.  Then there are two mirror images of each of these cases, for a total of 3*x2*y2 triangles.  These are the uninteresting cases.

In the fourteen triangles formed where 0 ≤ x1, y1, x2, y2 ≤ 2, there are only two interesting cases, where the right angle is not on the boundary.  The vertex of the triangle with the right angle, v, will be somewhere within the grid.  One edge of the triangle, Eo, is formed between v and the origin.  The other edge of v, Ep, must therefore be perpendicular to Eo.  Using a simple matrix rotation, the slope of Ep can be calculated from the slope of Eo.  The slope of Ep is -Vy/Vx.  The vertex that forms the third edge of the triangle, v2, is formed with the origin and the points where Ep intersects the vertices of the grid lines.  Stepping by the reduced fraction Vx, -Vy from V will give all of these intersections with one ray of Ep.  Stepping by -Vx, Vy will give the other ray of Ep.  The number of steps can be calculated based on the range of the grid.  See the code for more details.

## Run-time
O(N²*log(N))


text:
"""
WSGI config for Callbox project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Callbox.settings")

application = get_wsgi_application()

from monitor.utils import create_daemons
from Callbox.settings import MONITOR_CHANNELS_CONCISE, MONITOR_QUEUES_SHOW

create_daemons([MONITOR_CHANNELS_CONCISE, MONITOR_QUEUES_SHOW])


text:
#if defined(_WIN32)
  #if defined(__MINGW32__) && !defined(WINVER)
      #define WINVER 0x500
  #endif
  #include <windows.h>
  #include <process.h>

  #define USES_DLLMAIN
      /* DLL uses DllMain() for initialization */

  #if defined (_MSC_VER)
    #include <intrin.h>
  #endif

#elif defined (__CYGWIN__)
  #include <windows.h>
  #include <process.h>

  #define USES_DLLMAIN

#endif

// In C++11 UNUSED(x) is explicitly provided
#if __cplusplus <= 199711L
  #if defined (_MSC_VER)
    #define UNUSED(x) (void) (x);
  #else
    #define UNUSED(x) (void) (sizeof((x), 0))
  #endif
  #if ! defined (nullptr)
    #define nullptr NULL
  #endif
#endif


text:
          // can be just the necessary schema
  class {{tupletypename}} {
    // Invariant: data stored in _fields is always in the representation
    // specified by _scheme.

    public:
    {% for ft in fieldtypes %}
        {{ft}} f{{loop.index - 1}};
    {% endfor %}

    static constexpr int numFields() {
      return {{numfields}};
    }

    // size of all fields in struct removing only end padding
    static size_t fieldsSize() {
        const {{tupletypename}} _t;
        return

        {% if numfields == 0 %}
            0;
        {% elif numfields == 1 %}
            sizeof(_t.f0);
         {% else %}
            ((char*)&_t.f{{numfields-1}}) + sizeof(_t.f{{numfields-1}}) - ((char*)&_t);
         {% endif %}
    }

    // debugging function to get storage sizes
    static void print_representation() {
        const {{tupletypename}} _t;

        {% if numfields == 0 %}
            // noop
        {% elif numfields == 1 %}
        std::cout << _t.fieldsSize() << std::endl;
        {% else %}
        {% for i in range(1, numfields) %}
        std::cout << (((char*)&_t.f{{i}}) - ((char*)&_t.f{{i-1}})) << ",";
        {% endfor %}
        std::cout << (_t.fieldsSize() - (((char*)&_t.f{{numfields-2}}) - ((char*)&_t)));
        std::cout << std::endl;
        {% endif %}

    }

    {{tupletypename}} () {
      // no-op
    }

    //template <typename OT>
    //{{tupletypename}} (const OT& other) {
    //  std::memcpy(this, &other, sizeof({{tupletypename}}));
    //}
    {% if numfields > 0 %}
    {{tupletypename}} ({% for ft in fieldtypes %}
                               const {{ft}}& a{{loop.index-1}}
                               {% if not loop.last %},{% endif %}
                       {% endfor %}
                       ) {
        {% for i in range(numfields) %}
            f{{i}} = a{{i}};
        {% endfor %}
    }

    {# list of types comma separated #}
    {# TODO: uncomment when jinja 2.8 is released with support for set blocks
    {% set types_comma %}
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
    {% endset %}
    #}
    {% endif %}

    {{tupletypename}}(const std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
            >& o) {
        {% for i in range(numfields) %}
            f{{i}} = std::get<{{i}}>(o);
        {% endfor %}
     }

     std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
     > to_tuple() {

        std::tuple<
        {% for ft in fieldtypes %}
        {{ft}}
        {% if not loop.last %},{% endif %}
        {% endfor %}
        > r;
        {% for i in range(numfields) %}
            std::get<{{i}}>(r) = f{{i}};
        {% endfor %}
        return r;
     }

    // shamelessly terrible disambiguation: one solution is named factory methods
    //{{tupletypename}} (std::vector<int64_t> vals, bool ignore1, bool ignore2) {
    //    {% for i in range(numfields) %}
    //        f{{i}} = vals[{{i}}];
    //    {% endfor %}
    //}

    // use the tuple schema to interpret the input stream
    static {{tupletypename}} fromIStream(std::istream& ss, char delim=' ') {
        {{tupletypename}} _ret;

        {% for i in range(numfields) %}
            {% if fieldtypes[i] == string_type_name %}
               {
               std::string _temp;
               std::getline(ss, _temp, delim);
               // beware; truncate= true, so unckecked truncation for stringlen >= MAX_STR_LEN!
               _ret.f{{i}} = to_array<MAX_STR_LEN, std::string, true>(_temp);
               }
            {% else %}
               {
               // use operator>> to parse into proper numeric type
               ss >> _ret.f{{i}};
               //throw away the next delimiter
               std::string _temp;
               std::getline(ss, _temp, delim);
               }
            {% endif %}
        {% endfor %}

        return _ret;
    }

    void toOStream(std::ostream& os) const {
        os.write((char*)this, this->fieldsSize());
    }

    void toOStreamAscii(std::ostream& os) const {
        os
        {% if numfields == 0 %}
           << "" <<
        {% else %}
        {% for i in range(numfields-1) %}
        << f{{i}} << " "
        {% endfor %}
        << f{{numfields-1}} <<
        {% endif %}
        std::endl;
    }

    //template <typename Tuple, typename T>
    //{{tupletypename}} (const Tuple& v0, const T& from) {
    //    constexpr size_t v0_size = std::tuple_size<Tuple>::value;
    //    constexpr int from_size = T::numFields();
    //    static_assert({{tupletypename}}::numFields() == (v0_size + from_size), "constructor only works on same number of total fields");
    //    TupleUtils::assign<0, decltype(_scheme)>(_fields, v0);
    //    std::memcpy(((char*)&_fields)+v0_size*sizeof(int64_t), &(from._fields), from_size*sizeof(int64_t));
    //}

    //template <typename Tuple>
    //{{tupletypename}} (const Tuple& v0) {
    //    static_assert({{tupletypename}}::numFields() == (std::tuple_size<Tuple>::value), "constructor only works on same number of total fields");
    //    TupleUtils::assign<0, decltype(_scheme)>(_fields, v0);
    //}

    std::ostream& dump(std::ostream& o) const {
      o << "Materialized(";

      {% for i in range(numfields) %}
        o << f{{i}} << ",";
      {% endfor %}

      o << ")";
      return o;
    }

    {{additional_code}}
  } {{after_def_code}};

  std::ostream& operator<< (std::ostream& o, const {{tupletypename}}& t) {
    return t.dump(o);
  }