text:
package certificates

import (
	"context"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/util/retry"

	cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
	cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
	"github.com/jetstack/cert-manager/pkg/util"
	"github.com/jetstack/cert-manager/pkg/util/pki"
	"github.com/jetstack/cert-manager/test/e2e/framework"
	"github.com/jetstack/cert-manager/test/e2e/framework/helper/featureset"
	"github.com/jetstack/cert-manager/test/e2e/framework/helper/validation"
	"github.com/jetstack/cert-manager/test/e2e/framework/helper/validation/certificates"
	e2eutil "github.com/jetstack/cert-manager/test/e2e/util"
)

// Defines simple conformance tests that can be run against any issuer type.
// If Complete has not been called on this Suite before Define, it will be
// automatically called.
func (s *Suite) Define() {
	Describe("with issuer type "+s.Name, func() {
		ctx := context.Background()
		f := framework.NewDefaultFramework("certificates")

		sharedIPAddress := "127.0.0.1"

		// Wrap this in a BeforeEach else flags will not have been parsed and
		// f.Config will not be populated at the time that this code is run.
		BeforeEach(func() {
			if s.completed {
				return
			}

			s.complete(f)

			if s.UseIngressIPAddress {
				sharedIPAddress = f.Config.Addons.ACMEServer.IngressIP
			}
		})

		By("Running test suite with the following unsupported features: " + s.UnsupportedFeatures.String())

		s.it(f, "should issue a basic, defaulted certificate for a single distinct DNS Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					IssuerRef:  issuerRef,
					DNSNames:   []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.OnlySAN)

		s.it(f, "should issue an ECDSA, defaulted certificate for a single distinct DNS Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					PrivateKey: &cmapi.CertificatePrivateKey{
						Algorithm: cmapi.ECDSAKeyAlgorithm,
					},
					DNSNames:  []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					IssuerRef: issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.ECDSAFeature, featureset.OnlySAN)

		s.it(f, "should issue an Ed25519, defaulted certificate for a single distinct DNS Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					PrivateKey: &cmapi.CertificatePrivateKey{
						Algorithm: cmapi.Ed25519KeyAlgorithm,
					},
					DNSNames:  []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					IssuerRef: issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.OnlySAN, featureset.Ed25519FeatureSet)

		s.it(f, "should issue a basic, defaulted certificate for a single Common Name", func(issuerRef cmmeta.ObjectReference) {
			// Some issuers use the CN to define the cert's "ID"
			// if one cert manages to be in an error state in the issuer it might throw an error
			// this makes the CN more unique
			cn := "test-common-name-" + util.RandStringRunes(10)
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					IssuerRef:  issuerRef,
					CommonName: cn,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.CommonNameFeature)

		s.it(f, "should issue an ECDSA, defaulted certificate for a single Common Name", func(issuerRef cmmeta.ObjectReference) {
			// Some issuers use the CN to define the cert's "ID"
			// if one cert manages to be in an error state in the issuer it might throw an error
			// this makes the CN more unique
			cn := "test-common-name-" + util.RandStringRunes(10)
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					PrivateKey: &cmapi.CertificatePrivateKey{
						Algorithm: cmapi.ECDSAKeyAlgorithm,
					},
					CommonName: cn,
					IssuerRef:  issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.ECDSAFeature, featureset.CommonNameFeature)

		s.it(f, "should issue an Ed25519, defaulted certificate for a single Common Name", func(issuerRef cmmeta.ObjectReference) {
			// Some issuers use the CN to define the cert's "ID"
			// if one cert manages to be in an error state in the issuer it might throw an error
			// this makes the CN more unique
			cn := "test-common-name-" + util.RandStringRunes(10)
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					PrivateKey: &cmapi.CertificatePrivateKey{
						Algorithm: cmapi.Ed25519KeyAlgorithm,
					},
					CommonName: cn,
					IssuerRef:  issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.Ed25519FeatureSet, featureset.CommonNameFeature)

		s.it(f, "should issue a certificate that defines an IP Address", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName:  "testcert-tls",
					IPAddresses: []string{sharedIPAddress},
					IssuerRef:   issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.IPAddressFeature)

		s.it(f, "should issue a certificate that defines a DNS Name and IP Address", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName:  "testcert-tls",
					IPAddresses: []string{sharedIPAddress},
					DNSNames:    []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					IssuerRef:   issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.OnlySAN, featureset.IPAddressFeature)

		s.it(f, "should issue a certificate that defines a Common Name and IP Address", func(issuerRef cmmeta.ObjectReference) {
			// Some issuers use the CN to define the cert's "ID"
			// if one cert manages to be in an error state in the issuer it might throw an error
			// this makes the CN more unique
			cn := "test-common-name-" + util.RandStringRunes(10)
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName:  "testcert-tls",
					CommonName:  cn,
					IPAddresses: []string{sharedIPAddress},
					IssuerRef:   issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.CommonNameFeature, featureset.IPAddressFeature)

		s.it(f, "should issue a certificate that defines an Email Address", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName:     "testcert-tls",
					EmailAddresses: []string{"alice@example.com"},
					IssuerRef:      issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.EmailSANsFeature, featureset.OnlySAN)

		s.it(f, "should issue a certificate that defines a Common Name and URI SAN", func(issuerRef cmmeta.ObjectReference) {
			// Some issuers use the CN to define the cert's "ID"
			// if one cert manages to be in an error state in the issuer it might throw an error
			// this makes the CN more unique
			cn := "test-common-name-" + util.RandStringRunes(10)
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					CommonName: cn,
					URIs:       []string{"spiffe://cluster.local/ns/sandbox/sa/foo"},
					IssuerRef:  issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.URISANsFeature, featureset.CommonNameFeature)

		s.it(f, "should issue a certificate that defines a 2 distinct DNS Names with one copied to the Common Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					CommonName: e2eutil.RandomSubdomain(s.DomainSuffix),
					IssuerRef:  issuerRef,
				},
			}
			testCertificate.Spec.DNSNames = []string{
				testCertificate.Spec.CommonName, e2eutil.RandomSubdomain(s.DomainSuffix),
			}

			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.CommonNameFeature)

		s.it(f, "should issue a certificate that defines a distinct DNS Name and another distinct Common Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					CommonName: e2eutil.RandomSubdomain(s.DomainSuffix),
					IssuerRef:  issuerRef,
					DNSNames:   []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
				},
			}

			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.CommonNameFeature)

		s.it(f, "should issue a certificate that defines a DNS Name and sets a duration", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					IssuerRef:  issuerRef,
					DNSNames:   []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					Duration: &metav1.Duration{
						Duration: time.Hour * 896,
					},
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())

			// We set a weird time here as the duration with should never be used as
			// a default by an issuer. This lets us test issuers are using our given
			// duration.
			// We set a 30 second buffer time here since Vault issues certificates
			// with an extra 30 seconds on its duration.
			f.CertificateDurationValid(testCertificate, time.Hour*896, 30*time.Second)
		}, featureset.DurationFeature, featureset.OnlySAN)

		s.it(f, "should issue a certificate that defines a wildcard DNS Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					IssuerRef:  issuerRef,
					DNSNames:   []string{"*." + e2eutil.RandomSubdomain(s.DomainSuffix)},
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.WildcardsFeature, featureset.OnlySAN)

		s.it(f, "should issue a certificate that includes only a URISANs name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					URIs: []string{
						"spiffe://cluster.local/ns/sandbox/sa/foo",
					},
					IssuerRef: issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.URISANsFeature, featureset.OnlySAN)

		s.it(f, "should issue a certificate that includes arbitrary key usages", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					DNSNames:   []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					IssuerRef:  issuerRef,
					Usages: []cmapi.KeyUsage{
						cmapi.UsageSigning,
						cmapi.UsageDataEncipherment,
						cmapi.UsageServerAuth,
						cmapi.UsageClientAuth,
					},
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")

			validations := []certificates.ValidationFunc{
				certificates.ExpectKeyUsageExtKeyUsageClientAuth,
				certificates.ExpectKeyUsageExtKeyUsageServerAuth,
				certificates.ExpectKeyUsageUsageDigitalSignature,
				certificates.ExpectKeyUsageUsageDataEncipherment,
			}
			validations = append(validations, validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)

			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.KeyUsagesFeature, featureset.OnlySAN)

		s.it(f, "should issue another certificate with the same private key if the existing certificate and CertificateRequest are deleted", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					DNSNames:   []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					IssuerRef:  issuerRef,
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())

			By("Deleting existing certificate data in Secret")
			sec, err := f.KubeClientSet.CoreV1().Secrets(f.Namespace.Name).
				Get(context.TODO(), testCertificate.Spec.SecretName, metav1.GetOptions{})
			Expect(err).NotTo(HaveOccurred(), "failed to get secret containing signed certificate key pair data")

			sec = sec.DeepCopy()
			crtPEM1 := sec.Data[corev1.TLSCertKey]
			crt1, err := pki.DecodeX509CertificateBytes(crtPEM1)
			Expect(err).NotTo(HaveOccurred(), "failed to get decode first signed certificate data")

			sec.Data[corev1.TLSCertKey] = []byte{}

			_, err = f.KubeClientSet.CoreV1().Secrets(f.Namespace.Name).Update(context.TODO(), sec, metav1.UpdateOptions{})
			Expect(err).NotTo(HaveOccurred(), "failed to update secret by deleting the signed certificate data")

			By("Waiting for the Certificate to re-issue a certificate")
			sec, err = f.Helper().WaitForSecretCertificateData(f.Namespace.Name, sec.Name, time.Minute*5)
			Expect(err).NotTo(HaveOccurred(), "failed to wait for secret to have a valid 2nd certificate")

			crtPEM2 := sec.Data[corev1.TLSCertKey]
			crt2, err := pki.DecodeX509CertificateBytes(crtPEM2)
			Expect(err).NotTo(HaveOccurred(), "failed to get decode second signed certificate data")

			By("Ensuing both certificates are signed by same private key")
			match, err := pki.PublicKeysEqual(crt1.PublicKey, crt2.PublicKey)
			Expect(err).NotTo(HaveOccurred(), "failed to check public keys of both signed certificates")

			if !match {
				Fail("Both signed certificates not signed by same private key")
			}
		}, featureset.ReusePrivateKeyFeature, featureset.OnlySAN)

		s.it(f, "should issue a certificate for a single distinct DNS Name defined by an ingress with annotations", func(issuerRef cmmeta.ObjectReference) {
			ingClient := f.KubeClientSet.NetworkingV1beta1().Ingresses(f.Namespace.Name)

			name := "testcert-ingress"
			secretName := "testcert-ingress-tls"

			By("Creating an Ingress with the issuer name annotation set")
			ingress, err := ingClient.Create(context.TODO(), e2eutil.NewIngress(name, secretName, map[string]string{
				"cert-manager.io/issuer":       issuerRef.Name,
				"cert-manager.io/issuer-kind":  issuerRef.Kind,
				"cert-manager.io/issuer-group": issuerRef.Group,
			}, e2eutil.RandomSubdomain(s.DomainSuffix)), metav1.CreateOptions{})
			Expect(err).NotTo(HaveOccurred())

			certName := ingress.Spec.TLS[0].SecretName

			By("Waiting for the Certificate to exist...")
			Expect(e2eutil.WaitForCertificateToExist(
				f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name), certName, time.Minute,
			)).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, certName, time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, certName, validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.OnlySAN)

		s.it(f, "should issue a certificate defined by an ingress with certificate field annotations", func(issuerRef cmmeta.ObjectReference) {
			ingClient := f.KubeClientSet.NetworkingV1beta1().Ingresses(f.Namespace.Name)

			name := "testcert-ingress"
			secretName := "testcert-ingress-tls"
			domain := e2eutil.RandomSubdomain(s.DomainSuffix)
			duration := time.Hour * 999
			renewBefore := time.Hour * 111

			By("Creating an Ingress with annotations for issuerRef and other Certificate fields")
			ingress, err := ingClient.Create(context.TODO(), e2eutil.NewIngress(name, secretName, map[string]string{
				"cert-manager.io/issuer":       issuerRef.Name,
				"cert-manager.io/issuer-kind":  issuerRef.Kind,
				"cert-manager.io/issuer-group": issuerRef.Group,
				"cert-manager.io/common-name":  domain,
				"cert-manager.io/duration":     duration.String(),
				"cert-manager.io/renew-before": renewBefore.String(),
			}, domain), metav1.CreateOptions{})
			Expect(err).NotTo(HaveOccurred())

			certName := ingress.Spec.TLS[0].SecretName

			By("Waiting for the Certificate to exist...")
			Expect(e2eutil.WaitForCertificateToExist(
				f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name), certName, time.Minute,
			)).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, certName, time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			// Verify that the ingres-shim has translated all the supplied
			// annotations into equivalent Certificate field values
			By("Validating the created Certificate")
			err = f.Helper().ValidateCertificate(
				f.Namespace.Name, certName,
				func(certificate *cmapi.Certificate, _ *corev1.Secret) error {
					Expect(certificate.Spec.DNSNames).To(ConsistOf(domain))
					Expect(certificate.Spec.CommonName).To(Equal(domain))
					Expect(certificate.Spec.Duration.Duration).To(Equal(duration))
					Expect(certificate.Spec.RenewBefore.Duration).To(Equal(renewBefore))
					return nil
				},
			)
			Expect(err).NotTo(HaveOccurred())

			// Verify that the issuer has preserved all the Certificate values
			// in the signed certificate
			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, certName, validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		})

		s.it(f, "Creating a Gateway with annotations for issuerRef and other Certificate fields", func(issuerRef cmmeta.ObjectReference) {
			name := "testcert-gateway"
			secretName := "testcert-gateway-tls"
			domain := e2eutil.RandomSubdomain(s.DomainSuffix)
			duration := time.Hour * 999
			renewBefore := time.Hour * 111

			By("Creating a Gateway with annotations for issuerRef and other Certificate fields")
			gw, route := e2eutil.NewGateway(name, f.Namespace.Name, secretName, map[string]string{
				"cert-manager.io/issuer":       issuerRef.Name,
				"cert-manager.io/issuer-kind":  issuerRef.Kind,
				"cert-manager.io/issuer-group": issuerRef.Group,
				"cert-manager.io/common-name":  domain,
				"cert-manager.io/duration":     duration.String(),
				"cert-manager.io/renew-before": renewBefore.String(),
			}, domain)

			gw, err := f.GWClientSet.NetworkingV1alpha1().Gateways(f.Namespace.Name).Create(context.TODO(), gw, metav1.CreateOptions{})
			Expect(err).NotTo(HaveOccurred())
			_, err = f.GWClientSet.NetworkingV1alpha1().HTTPRoutes(f.Namespace.Name).Create(context.TODO(), route, metav1.CreateOptions{})
			Expect(err).NotTo(HaveOccurred())

			// XXX(Mael): the CertificateRef seems to contain the Gateway name
			// "testcert-gateway" instead of the secretName
			// "testcert-gateway-tls".
			certName := gw.Spec.Listeners[0].TLS.CertificateRef.Name

			By("Waiting for the Certificate to exist...")
			Expect(e2eutil.WaitForCertificateToExist(
				f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name), certName, time.Minute,
			)).NotTo(HaveOccurred())

			// Verify that the ingres-shim has translated all the supplied
			// annotations into equivalent Certificate field values
			By("Validating the created Certificate")
			cert, err := f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name).Get(context.TODO(), certName, metav1.GetOptions{})
			Expect(err).NotTo(HaveOccurred())

			Expect(cert.Spec.DNSNames).To(ConsistOf(domain))
			Expect(cert.Spec.CommonName).To(Equal(domain))
			Expect(cert.Spec.Duration.Duration).To(Equal(duration))
			Expect(cert.Spec.RenewBefore.Duration).To(Equal(renewBefore))
		})

		s.it(f, "should issue a certificate that defines a long domain", func(issuerRef cmmeta.ObjectReference) {
			// the maximum length of a single segment of the domain being requested
			const maxLengthOfDomainSegment = 63

			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					DNSNames:   []string{e2eutil.RandomSubdomainLength(s.DomainSuffix, maxLengthOfDomainSegment)},
					IssuerRef:  issuerRef,
				},
			}
			validations := validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)

			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Sanity-check the issued Certificate")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.OnlySAN)

		s.it(f, "should allow updating an existing certificate with a new DNS Name", func(issuerRef cmmeta.ObjectReference) {
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					DNSNames:   []string{e2eutil.RandomSubdomain(s.DomainSuffix)},
					IssuerRef:  issuerRef,
				},
			}
			validations := validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)

			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate to be ready")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Sanity-check the issued Certificate")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...)
			Expect(err).NotTo(HaveOccurred())

			By("Getting the latest version of the Certificate")
			cert, err := f.Helper().CMClient.CertmanagerV1().Certificates(f.Namespace.Name).Get(context.TODO(), "testcert", metav1.GetOptions{})
			Expect(err).NotTo(HaveOccurred())

			By("Updating the Certificate after having added an additional dnsName")
			newDNSName := e2eutil.RandomSubdomain(s.DomainSuffix)
			err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
				err := f.CRClient.Get(context.Background(), types.NamespacedName{Namespace: f.Namespace.Name, Name: "testcert"}, cert)
				if err != nil {
					return err
				}

				cert.Spec.DNSNames = append(cert.Spec.DNSNames, newDNSName)

				return f.CRClient.Update(context.TODO(), cert)
			})
			Expect(err).NotTo(HaveOccurred())

			By("Waiting for the Certificate Ready condition to be updated")
			_, err = f.Helper().WaitForCertificateReadyUpdate(cert, time.Minute*5)
			Expect(err).NotTo(HaveOccurred())

			By("Sanity-check the issued Certificate")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.OnlySAN)

		s.it(f, "should issue a certificate that defines a wildcard DNS Name and its apex DNS Name", func(issuerRef cmmeta.ObjectReference) {
			dnsDomain := e2eutil.RandomSubdomain(s.DomainSuffix)
			testCertificate := &cmapi.Certificate{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "testcert",
					Namespace: f.Namespace.Name,
				},
				Spec: cmapi.CertificateSpec{
					SecretName: "testcert-tls",
					IssuerRef:  issuerRef,
					DNSNames:   []string{"*." + dnsDomain, dnsDomain},
				},
			}
			By("Creating a Certificate")
			err := f.CRClient.Create(ctx, testCertificate)
			Expect(err).NotTo(HaveOccurred())

			// use a longer timeout for this, as it requires performing 2 dns validations in serial
			By("Waiting for the Certificate to be issued...")
			_, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*10)
			Expect(err).NotTo(HaveOccurred())

			By("Validating the issued Certificate...")
			err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...)
			Expect(err).NotTo(HaveOccurred())
		}, featureset.WildcardsFeature, featureset.OnlySAN)
	})
}


text:
+++
title = "Search Results"
description = "Home page for Docker's documentation"
keywords = ["Docker, documentation, manual, guide, reference, api"]
type = "search"
+++

redpajama_set_name: RedPajamaGithub


text:
package com.magnoliales.annotatedapp.column;

import info.magnolia.ui.workbench.column.definition.ColumnDefinition;
import info.magnolia.ui.workbench.column.definition.PropertyColumnDefinition;

public class PropertyColumnBuilder extends AbstractColumnBuilder<PropertyColumnBuilder> {

    @Override
    public ColumnDefinition definition() {
        PropertyColumnDefinition columnDefinition = new PropertyColumnDefinition();
        columnDefinition.setName(getName());
        columnDefinition.setPropertyName(getPropertyName());
        columnDefinition.setWidth(getWidth(0));
        columnDefinition.setSortable(isSortable());
        columnDefinition.setExpandRatio(getExpandRatio());
        columnDefinition.setEditable(isEditable());
        return columnDefinition;
    }
}


text:
/**
 * Created with IntelliJ IDEA.
 * User: pat
 * Date: 12-05-10
 * Time: 1:52 PM
 * To change this template use File | Settings | File Templates.
 */
define(['underscore', 'backbone', 'lib/simple-json-schema'], function (_, Backbone, SimpleJsonSchema) {

  var BackboneSchemaModel = Backbone.Model.extend({
    schema: false,
    validate: function(attributes, options){

      if (!options){options = {};}
      _.defaults(options, {
        partialValidation: true
      });

      var report = SimpleJsonSchema.validate(attributes, this.schema, options.partialValidation);

      if (!report.isValid){
        return report;
      }
    }
  });

  return BackboneSchemaModel;
});


text:
package org.sakaiproject.poll.tool.validators;

import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.poll.model.Option;
import org.sakaiproject.poll.util.PollUtils;
import org.sakaiproject.util.FormattedText;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class OptionValidator implements Validator {

	/** Logger for this class and subclasses */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	public String submissionStatus;

	public boolean supports(Class clazz) {
		// TODO Auto-generated method stub
		return clazz.equals(Option.class);
	}

	public void validate(Object obj, Errors errors) {

		Option option = (Option) obj;

		// SAK-14725 : BugFix
		String stripText = null;

		if(null != option.getOptionText()) {
			stripText = FormattedText.convertFormattedTextToPlaintext(option.getOptionText()).trim();
		}

		logger.debug("validating Option with id:" + option.getOptionId());
		if (option.getStatus()!=null && (option.getStatus().equals("cancel") || option.getStatus().equals("delete")))
			return;

		if (option.getOptionText() == null || option.getOptionText().trim().length()==0 ||
				stripText == null || stripText.length()==0) {
			logger.debug("OptionText is empty!");
			errors.reject("option_empty","option empty");
			return;
		}

		//if where here option is not null or empty but could be something like "  "
		String text = option.getOptionText();

		text = PollUtils.cleanupHtmlPtags(text);
		text = text.replace(" ", "");
		text = StringEscapeUtils.unescapeHtml(text).trim();
		logger.debug("text to validate is: " + text);
		if (text.trim().length()==0) {
			logger.debug("OptionText is empty! (after excaping html)");
			errors.reject("option_empty","option empty");
			return;
		}

	}

}


text:
import 'babel-polyfill'
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery/src/core';
import semanticUI from 'semantic-ui/dist/semantic';
import semanticUIcss from 'semantic-ui/dist/semantic.min.css';
// Using hashHistory as BrowserHistory appears to be buggy with some version of react-router
import createBrowserHistory from 'history/lib/createHashHistory';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import makeRoutes from './routes';
import Root from './containers/Root';
import configureStore from './redux/configureStore';
import i18n from './config/i18n';

// Configure history for react-router
const browserHistory = useRouterHistory(createBrowserHistory)({
  basename: __BASENAME__,
  queryKey: false
});

// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the key "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState, browserHistory);
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (state) => state.router
});

// Now that we have the Redux store, we can create our routes. We provide
// the store to the route definitions so that routes have access to it for
// hooks such as `onEnter`.
const routes = makeRoutes(store);

i18n.init();

// Now that redux and react-router have been configured, we can render the
// React application to the DOM!
ReactDOM.render(
  <Root history={history} routes={routes} store={store} />,
  document.getElementById('root')
);


text:
import os
import unittest

class MainTestCase(unittest.TestCase):

    def setUp(self):
        os.environ["TWILIO_ACCOUNT_SID"] = "TEST"
        os.environ["TWILIO_AUTH_TOKEN"] = "TEST"
        import main
        self.app = main.app.test_client()

    def test_hello(self):
        resp = self.app.post('/', data=dict(CallSid='TEST', From='+85298765432'))
        self.assertIn('<Record', resp.data)
        self.assertEqual(resp.status_code, 200)

if __name__ == '__main__':
    unittest.main()


text:
using System.Collections.Generic;
using System.Threading;

using Microsoft.Graph;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

namespace Microsoft.OneDrive.Sdk
{
    /// <summary>
    /// The type ShareRequest.
    /// </summary>
    public partial class ShareRequest : BaseRequest, IShareRequest
    {
        /// <summary>
        /// Constructs a new ShareRequest.
        /// </summary>
        /// <param name="requestUrl">The URL for the built request.</param>
        /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
        /// <param name="options">Query and header option name value pairs for the request.</param>
        public ShareRequest(
            string requestUrl,
            IBaseClient client,
            IEnumerable<Option> options)
            : base(requestUrl, client, options)
        {
            //this.SdkVersionHeaderPrefix = "onedrive";
        }

        /// <summary>
        /// Creates the specified Share using PUT.
        /// </summary>
        /// <param name="shareToCreate">The Share to create.</param>
        /// <returns>The created Share.</returns>
        public System.Threading.Tasks.Task<Share> CreateAsync(Share shareToCreate)
        {
            return this.CreateAsync(shareToCreate, CancellationToken.None);
        }

        /// <summary>
        /// Creates the specified Share using PUT.
        /// </summary>
        /// <param name="shareToCreate">The Share to create.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The created Share.</returns>
        public async System.Threading.Tasks.Task<Share> CreateAsync(Share shareToCreate, CancellationToken cancellationToken)
        {
            this.ContentType = "application/json";
            this.Method = "PUT";
            var newEntity = await this.SendAsync<Share>(shareToCreate, cancellationToken).ConfigureAwait(false);
            this.InitializeCollectionProperties(newEntity);
            return newEntity;
        }

        /// <summary>
        /// Deletes the specified Share.
        /// </summary>
        /// <returns>The task to await.</returns>
        public System.Threading.Tasks.Task DeleteAsync()
        {
            return this.DeleteAsync(CancellationToken.None);
        }

        /// <summary>
        /// Deletes the specified Share.
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The task to await.</returns>
        public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
        {
            this.Method = "DELETE";
            await this.SendAsync<Share>(null, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets the specified Share.
        /// </summary>
        /// <returns>The Share.</returns>
        public System.Threading.Tasks.Task<Share> GetAsync()
        {
            return this.GetAsync(CancellationToken.None);
        }

        /// <summary>
        /// Gets the specified Share.
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The Share.</returns>
        public async System.Threading.Tasks.Task<Share> GetAsync(CancellationToken cancellationToken)
        {
            this.Method = "GET";
            var retrievedEntity = await this.SendAsync<Share>(null, cancellationToken).ConfigureAwait(false);
            this.InitializeCollectionProperties(retrievedEntity);
            return retrievedEntity;
        }

        /// <summary>
        /// Updates the specified Share using PATCH.
        /// </summary>
        /// <param name="shareToUpdate">The Share to update.</param>
        /// <returns>The updated Share.</returns>
        public System.Threading.Tasks.Task<Share> UpdateAsync(Share shareToUpdate)
        {
            return this.UpdateAsync(shareToUpdate, CancellationToken.None);
        }

        /// <summary>
        /// Updates the specified Share using PATCH.
        /// </summary>
        /// <param name="shareToUpdate">The Share to update.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The updated Share.</returns>
        public async System.Threading.Tasks.Task<Share> UpdateAsync(Share shareToUpdate, CancellationToken cancellationToken)
        {
            this.ContentType = "application/json";
            this.Method = "PATCH";
            var updatedEntity = await this.SendAsync<Share>(shareToUpdate, cancellationToken).ConfigureAwait(false);
            this.InitializeCollectionProperties(updatedEntity);
            return updatedEntity;
        }

        /// <summary>
        /// Adds the specified expand value to the request.
        /// </summary>
        /// <param name="value">The expand value.</param>
        /// <returns>The request object to send.</returns>
        public IShareRequest Expand(string value)
        {
            this.QueryOptions.Add(new QueryOption("$expand", value));
            return this;
        }

        /// <summary>
        /// Adds the specified select value to the request.
        /// </summary>
        /// <param name="value">The select value.</param>
        /// <returns>The request object to send.</returns>
        public IShareRequest Select(string value)
        {
            this.QueryOptions.Add(new QueryOption("$select", value));
            return this;
        }

        /// <summary>
        /// Initializes any collection properties after deserialization, like next requests for paging.
        /// </summary>
        /// <param name="shareToInitialize">The <see cref="Share"/> with the collection properties to initialize.</param>
        private void InitializeCollectionProperties(Share shareToInitialize)
        {

            if (shareToInitialize != null && shareToInitialize.AdditionalData != null)
            {

                if (shareToInitialize.Items != null && shareToInitialize.Items.CurrentPage != null)
                {
                    shareToInitialize.Items.AdditionalData = shareToInitialize.AdditionalData;

                    object nextPageLink;
                    shareToInitialize.AdditionalData.TryGetValue("items@odata.nextLink", out nextPageLink);
                    var nextPageLinkString = nextPageLink as string;

                    if (!string.IsNullOrEmpty(nextPageLinkString))
                    {
                        shareToInitialize.Items.InitializeNextPageRequest(
                            this.Client,
                            nextPageLinkString);
                    }
                }

            }

        }
    }
}


text:
var myBookStores=angular.module("my.Books",[]);
myBookStores.service('Book',['$rootScope',function($rootScope) {
	var service={   //该函数中的一个变量
			//有一个数组books
			books:[
	       {title:"一千零一夜",type:"儿童文学"},
	       {title:"java语言程序设计基础篇",type:"计算机编程"}
	       ],
		//有一个addbook方法
	       addBook:function(book){
	    	   service.books.push(book);
	    	   $rootScope.$broadcast('books.update');
	       }
	};
	return service;
}
]);

myBookStores.controller("book.list",['$scope','Book',function(scope,Book)
{
	scope.$on('books.update',function(event){

		scope.books=Book.books;
		scope.$apply();
		});
		scope.books=Book.books;

}]);

myBookStores.directive("addBookButton",['Book',function(Book){
	return{
		restrict:"A",
	link:function(scope,element,attrs){
		element.bind("click",function(){

		Book.addBook({title:"你若安好,便是晴天",type:"现代文学"});
		});
	}
	};
}]);


text:
// This file has been prepared for Doxygen automatic documentation generation.

#ifndef IEEE802_15_4_CONF_H
#define IEEE802_15_4_CONF_H

/*================================= INCLUDES         =========================*/
#include <stdint.h>
#include <stdbool.h>

#include "vrt_timer.h"

//! \addtogroup grIEEE802_15_4
//! @{
/*================================= MACROS           =========================*/
/*! \brief Defines the maximum number of Network Descriptors that will be returned
 *         from a NMLE_NETWORK_DISCOVERY.confirm.
 *
 *  \note This number should be kept the same as that used for the MLME_SCAN.confirm.
 */
#define IEEE802_15_4_MAX_NMBR_OF_PANDESC (4)

/*! \brief Defines the number of packets that can be held by the IEEE 802.15.4 MAC
 *         simultaneously. The number must be different from 0.
 */
#define IEEE_802_15_4_POOL_SIZE (3)

#define IEEE802_15_4_SYMBOL_TO_TICKS(symbols) (VRT_TIME_TICK_PER_SYMBOL * ((uint32_t)symbols))
/*================================= TYEPDEFS         =========================*/
/*================================= GLOBAL VARIABLES =========================*/
/*================================= LOCAL VARIABLES  =========================*/
/*================================= PROTOTYPES       =========================*/
//! @}
#endif
/*EOF*/


text:
package org.apache.taverna.workflow.edits;

import org.apache.taverna.scufl2.api.core.Processor;
import org.apache.taverna.scufl2.api.port.InputProcessorPort;

public class RemoveProcessorInputPortEdit extends RemoveChildEdit<Processor> {
	public RemoveProcessorInputPortEdit(Processor processor,
			InputProcessorPort port) {
		super(processor, port);
	}
}


text:
@interface MyMainTabBarController ()

@end

@implementation MyMainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js Test Suite        **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2013, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */
package org.scalajs.testsuite.jsinterop

import scala.scalajs.js
import js.JSConverters._
import org.scalajs.jasminetest.JasmineTest

import js.annotation.JSExport

object DynamicTest extends JasmineTest {

  describe("scala.scalajs.js.Dynamic") {

    it("should workaround Scala 2.10 issue with implicit conversion for dynamic fields named x - #8") {
      class Point(val x: Int, val y: Int)

      def jsonToPoint(json: js.Dynamic): Point = {
        new Point(json.x.toString.toInt, json.y.toString.toInt)
      }

      val json = js.eval("var dynamicTestPoint = { x: 1, y: 2 }; dynamicTestPoint;")
      val point = jsonToPoint(json.asInstanceOf[js.Dynamic])

      expect(point.x).toEqual(1)
      expect(point.y).toEqual(2)
    }

    it("should allow to call functions with arguments named x") {
      class A {
        def a: Int = 1
      }

      class B extends A {
        @JSExport
        def x(par: Int): Int = a + par // make sure `this` is bound correctly in JS
      }

      val b = (new B).asInstanceOf[js.Dynamic]

      expect(b.x(10)).toEqual(11)
    }

    it("should allow instanciating JS classes dynamically - #10") {
      val DynamicTestClass = js.eval("""
          var DynamicTestClass = function(x) {
            this.x = x;
          };
          DynamicTestClass;
          """).asInstanceOf[js.Dynamic]
      val obj = js.Dynamic.newInstance(DynamicTestClass)("Scala.js")
      expect(obj.x).toEqual("Scala.js")
    }

    it("should allow instantiating JS classes dynamically with varargs - #708") {
      val DynamicTestClassVarArgs = js.eval("""
          var DynamicTestClassVarArgs = function() {
            this.count = arguments.length;
            for (var i = 0; i < arguments.length; i++)
              this['elem'+i] = arguments[i];
          };
          DynamicTestClassVarArgs;
          """).asInstanceOf[js.Dynamic]

      val obj1 = js.Dynamic.newInstance(DynamicTestClassVarArgs)("Scala.js")
      expect(obj1.count).toEqual(1)
      expect(obj1.elem0).toEqual("Scala.js")

      val obj2 = js.Dynamic.newInstance(DynamicTestClassVarArgs)(
          "Scala.js", 42, true)
      expect(obj2.count).toEqual(3)
      expect(obj2.elem0).toEqual("Scala.js")
      expect(obj2.elem1).toEqual(42)
      expect(obj2.elem2).toEqual(true)

      def obj3Args: Seq[js.Any] = Seq("Scala.js", 42, true)
      val obj3 = js.Dynamic.newInstance(DynamicTestClassVarArgs)(obj3Args: _*)
      expect(obj3.count).toEqual(3)
      expect(obj3.elem0).toEqual("Scala.js")
      expect(obj3.elem1).toEqual(42)
      expect(obj3.elem2).toEqual(true)

      // Check backward binary compatibility with the 0.6.{0,1,2} codegen output
      val obj4 = scala.scalajs.runtime.newJSObjectWithVarargs(
          DynamicTestClassVarArgs, obj3Args.toJSArray).asInstanceOf[js.Dynamic]
      expect(obj4.count).toEqual(3)
      expect(obj4.elem0).toEqual("Scala.js")
      expect(obj4.elem1).toEqual(42)
      expect(obj4.elem2).toEqual(true)
    }

    it("should provide an object literal construction") {
      import js.Dynamic.{ literal => obj }
      val x = obj(foo = 3, bar = "foobar")
      expect(x.foo).toEqual(3)
      expect(x.bar).toEqual("foobar")
      expect(x.unknown).toBeUndefined()

      val y = obj(
          inner = obj(name = "inner obj"),
          fun = { () => 42 }
      )
      expect(y.inner.name).toEqual("inner obj")
      expect(y.fun()).toEqual(42)

      expect(obj().anything).toBeUndefined()
    }

    it("object literal in statement position - #1627") {
      // Just make sure it does not cause a SyntaxError
      js.Dynamic.literal(foo = "bar")
      // and also test the case without param (different code path in Printers)
      js.Dynamic.literal()
    }

    it("should provide object literal construction with dynamic naming") {
      import js.Dynamic.{ literal => obj }
      val x = obj("foo" -> 3, "bar" -> "foobar")
      expect(x.foo).toEqual(3)
      expect(x.bar).toEqual("foobar")
      expect(x.unknown).toBeUndefined()

      val tup1 = ("hello1", 3: js.Any)
      val tup2 = ("hello2", 10: js.Any)

      val y = obj(tup1, tup2)
      expect(y.hello1).toEqual(3)
      expect(y.hello2).toEqual(10)

      var count = 0
      val z = obj({ count += 1; ("foo", "bar")})
      expect(z.foo).toEqual("bar")
      expect(count).toEqual(1)
    }

    it("should allow to create an empty object with the literal syntax") {
      import js.Dynamic.{ literal => obj }
      val x = obj()
      expect(x.isInstanceOf[js.Object]).toBeTruthy()
    }

    it("should properly encode object literal property names") {
      import js.Dynamic.{ literal => obj }

      val obj0 = obj("3-" -> 42)
      expect(obj0.`3-`).toEqual(42)

      val obj0Dict = obj0.asInstanceOf[js.Dictionary[js.Any]]
      expect(obj0Dict("3-")).toEqual(42)

      val checkEvilProperties = js.eval("""
        function dynamicLiteralNameEncoding_checkEvilProperties(x) {
          return x['.o[3√!|-pr()per7:3$];'] === ' such eval ';
        }
        dynamicLiteralNameEncoding_checkEvilProperties
      """).asInstanceOf[js.Function1[js.Any, Boolean]]
      val obj1 = obj(
          ".o[3√!|-pr()per7:3$];" -> " such eval ").asInstanceOf[js.Dictionary[js.Any]]
      expect(obj1(".o[3√!|-pr()per7:3$];")).toEqual(" such eval ")
      expect(checkEvilProperties(obj1)).toEqual(true)

      val checkQuotesProperty = js.eval("""
        function dynamicLiteralNameEncoding_quote(x) {
          return x["'" + '"'] === 7357;
        }
        dynamicLiteralNameEncoding_quote
      """).asInstanceOf[js.Function1[js.Any, Boolean]]

      val quote = '"'

      Seq(
        obj("'" + quote -> 7357),
        obj(s"'$quote" -> 7357),
        obj("'\"" -> 7357),
        obj("'" + quote -> 7357)
      ).foreach { o =>
        val dict = o.asInstanceOf[js.Dictionary[js.Any]]
        expect(dict("'\"")).toEqual(7357)
        expect(dict("'" + quote)).toEqual(7357)
        expect(dict(s"'$quote")).toEqual(7357)
        expect(checkQuotesProperty(o)).toEqual(true)
      }
    }

    it("should accept : _* arguments for literal construction - #1743") {
      import js.Dynamic.literal

      val fields = Seq[(String, js.Any)]("foo" -> 42, "bar" -> "foobar")

      /* Note: we cannot write
       * literal(fields: _*)
       * because scalac does not like it. But we still have to support the
       * expanded notation.
       */

      val x = literal.applyDynamic("apply")(fields: _*)
      expect(x.foo).toEqual(42)
      expect(x.bar).toEqual("foobar")

      val y = literal.applyDynamicNamed("apply")(fields: _*)
      expect(y.foo).toEqual(42)
      expect(y.bar).toEqual("foobar")
    }

    it("should allow object literals to have duplicate keys - #1595") {
      import js.Dynamic.{literal => obj}

      // Basic functionality
      val a = obj(foo = 4, bar = 5, foo = 6)
      expect(a.foo).toEqual(6) // last wins
      expect(a.bar).toEqual(5)

      // Side-effects of overwritten properties are kept
      var counter = 0
      val b = obj(foo = { counter += 1; "foo" }, bar = "bar", foo = "foobar")
      expect(counter).toEqual(1)
      expect(b.foo).toEqual("foobar")
      expect(b.bar).toEqual("bar")

      // In a position where unnesting is required - #1628
      @noinline
      def test(x: js.Dynamic): Unit = {
        expect(x.foo).toEqual(6) // last wins
        expect(x.bar).toEqual(5)
      }
      test(obj(foo = 4, bar = 5, foo = 6))
    }

    it("should return subclasses of js.Object in literal construction - #783") {
      import js.Dynamic.{ literal => obj }

      val a: js.Object = obj(theValue = 1)
      expect(a.hasOwnProperty("theValue")).toBeTruthy
      expect(a.hasOwnProperty("noValue")).toBeFalsy

      val b: js.Object = obj("theValue" -> 2)
      expect(b.hasOwnProperty("theValue")).toBeTruthy
      expect(b.hasOwnProperty("noValue")).toBeFalsy

    }
  }
}


text:
The base/ folder holds what we might call the boilerplate stuff for your project. In there, you might find the reset (or Normalize.css, or whatever), probably some stuff dealing with typography, and, depending on the project, maybe some other files.
    `_reset.scss` or `_normalize.scss`
    `_typography.scss`

## Helpers
The helpers/ folder (sometimes called utils/) gathers all Sass tools and helpers we'll use across the project. Got a function? A mixin? Put it in there.
    `_variables.scss`
    `_mixins.scss`
    `_functions.scss`

## Layout
The layout/ directory (sometimes called partials/) usually contains a number of files, each of them setting some styles for the main sections of the layout (header, footer, and so on). It also contains the `_grid` file which is the grid system used to build the layout.
    `_grid.scss`
    `_header.scss`
    `_footer.scss`
    `_sidebar.scss`
    `_forms.scss`

## Components
For smaller components, there is the components/ folder (frequently called modules/). While layout/ is kind of macro (defining the global wireframe), components/ is more micro. It can contain all kinds of specific modules like a slider, a loader, a widget, or anything along those lines. There are usually a lot of files in components/ since your site is should be mostly composed of tiny modules.
    `_media.scss`
    `_carousel.scss`
    `_thumbnails.scss`

## Pages
If you have page-specific styles, I think it's cool to put them in a pages/ folder and in a file named after the page. For example, it's not uncommon to have very specific styles for the home page, so you'd have a `_home.scss` file in pages/ dealing with this.
    `_home.scss`
    `_contact.scss`

## Vendors
And last but not least, you will probably have a vendors/ folder containing all the CSS files from external libraries and frameworks – Bootstrap, jQueryUI, FancyCarouselSliderjQueryPowered, and so on. Putting those aside in the same folder is a good way to tell "Hey, this is not from me, not my code, not my responsibility".
    Example:
    bootstrap.scss
    jquery-ui.scss
    select2.scss


text:
module RAutomation
  module Adapter
    module MsUia
      class KeystrokeConverter
        class << self
          def convert(str)
            special_characters = ""

            str.split(/([{}])/).inject([]) do |converted_keys, str|
              if str == "}"
                converted_keys << convert_special_characters(special_characters << str)
                special_characters = ""
              elsif str == "{" || !special_characters.empty?
                special_characters << str
              else
                converted_keys += convert_characters(str)
              end
              converted_keys
            end.flatten
          end

          private

          def convert_special_characters chars
            case chars.downcase
              when "{tab}"
                Constants::VK_TAB
              when "{backspace}"
                Constants::VK_BACK
              when "{enter}"
                Constants::VK_RETURN
              when "{left}"
                Constants::VK_LEFT
              when "{right}"
                Constants::VK_RIGHT
              when "{down}"
                Constants::VK_DOWN
              when "{up}"
                Constants::VK_UP
              when "{home}"
                Constants::VK_HOME
              when "{end}"
                Constants::VK_END
              when "{delete}"
                Constants::VK_DELETE
              when "{pgdown}"
                Constants::VK_NEXT
              when "{pgup}"
                Constants::VK_PRIOR
              else
                # unsupported special tag, ignore the tag itself, but convert the
                # characters inside the tag
                convert_characters(chars.gsub(/[{}]/, ""))
            end
          end

          private

          def convert_characters(element)
            element.split(//).inject([]) do |chars, char|
              char_code = char.upcase.unpack("c")[0]
              case char
                when "!"
                  chars += in_upcase(49)
                when "@"
                  chars += in_upcase(50)
                when "\#"
                  chars += in_upcase(51)
                when "$"
                  chars += in_upcase(52)
                when "%"
                  chars += in_upcase(53)
                when "^"
                  chars += in_upcase(54)
                when "&"
                  chars += in_upcase(55)
                when "*"
                  chars += in_upcase(56)
                when "("
                  chars += in_upcase(57)
                when ")"
                  chars += in_upcase(48)
                when "\""
                  chars += in_upcase(0xDE)
                when "'"
                  chars << 0xDE
                when "/"
                  chars << 0xBF
                when "-"
                  chars << 0xBD
                when ","
                  chars << 0xBC
                when "'"
                  chars << 0xDE
                when "&"
                  chars += in_upcase(0x37)
                when "_"
                  chars += in_upcase(0xBD)
                when "<"
                  chars += in_upcase(0xBC)
                when ">"
                  chars += in_upcase(0xBE)
                else
                  if char =~ /[A-Z]/
                    chars += in_upcase(char_code)
                  else
                    chars << char_code
                  end
              end
            end
          end

          def in_upcase(char_code)
            [Constants::VK_LSHIFT, char_code]
          end
        end
      end
    end
  end
end


text:
#include <sbml/xml/LibXMLTranscode.h>
#include <sbml/xml/LibXMLNamespaces.h>

/** @cond doxygenIgnored */

using namespace std;

/** @endcond */

LIBSBML_CPP_NAMESPACE_BEGIN

/** @cond doxygenLibsbmlInternal */

/**
 * Creates a new list of XML namespaces declarations from a "raw" LibXML
 * prefix/URI pairs.
 */
LibXMLNamespaces::LibXMLNamespaces (  const xmlChar**     namespaces
                                    , const unsigned int& size )
{
  mNamespaces.reserve(size);

  for (unsigned int n = 0; n < size; ++n)
  {
    const string prefix = LibXMLTranscode( namespaces[2 * n]     );
    const string uri    = LibXMLTranscode( namespaces[2 * n + 1], true );

    add(uri, prefix);
  }
}

/**
 * Destroys this list of XML namespace declarations.
 */
LibXMLNamespaces::~LibXMLNamespaces ()
{
}

/** @endcond */

LIBSBML_CPP_NAMESPACE_END


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenodesmia agardhiana var. albopruinosa Arnold

### Remarks
null


text:
package org.apache.jena.fuseki;

import org.apache.jena.atlas.web.AcceptList;
import org.apache.jena.atlas.web.MediaType;
import static org.apache.jena.riot.WebContent.*;

public class DEF
{
    public static final MediaType acceptRDFXML        = MediaType.create(contentTypeRDFXML);
    public static final MediaType acceptNQuads        = MediaType.create(contentTypeNQuads);
    public static final MediaType acceptRSXML         = MediaType.create(contentTypeResultsXML);
    public static final MediaType acceptJSON          = MediaType.create(contentTypeJSON);
    public static final MediaType acceptTurtle        = MediaType.create(contentTypeTurtle);

    public static final AcceptList jsonOffer          = AcceptList.create(contentTypeJSON);

    public static final AcceptList constructOffer     = AcceptList.create(contentTypeTurtle,
                                                                          contentTypeTurtleAlt1,
                                                                          contentTypeNTriples,
                                                                          contentTypeNTriplesAlt,
                                                                          contentTypeRDFXML,
                                                                          contentTypeTriX,
                                                                          contentTypeTriXxml,
                                                                          contentTypeJSONLD,
                                                                          contentTypeRDFJSON,
                                                                          contentTypeRDFThrift,

                                                                          contentTypeTriG,
                                                                          contentTypeTriGAlt1,
                                                                          contentTypeNQuads,
                                                                          contentTypeNQuadsAlt1
                                                                          );

    public static final AcceptList rdfOffer           = AcceptList.create(contentTypeTurtle,
                                                                          contentTypeTurtleAlt1,
                                                                          contentTypeNTriples,
                                                                          contentTypeNTriplesAlt,
                                                                          contentTypeRDFXML,
                                                                          contentTypeTriX,
                                                                          contentTypeTriXxml,
                                                                          contentTypeJSONLD,
                                                                          contentTypeRDFJSON,
                                                                          contentTypeRDFThrift
                                                                          );

    public static final AcceptList quadsOffer         = AcceptList.create(contentTypeTriG,
                                                                          contentTypeTriGAlt1,
                                                                          contentTypeJSONLD,
                                                                          contentTypeNQuads,
                                                                          contentTypeNQuadsAlt1,
                                                                          contentTypeTriX,
                                                                          contentTypeTriXxml
                                                                          );

    // Offer for SELECT
    // This include application/xml and application/json.
    public static final AcceptList rsOfferTable       = AcceptList.create(contentTypeResultsJSON,
                                                                          contentTypeJSON,
                                                                          contentTypeTextCSV,
                                                                          contentTypeTextTSV,
                                                                          contentTypeResultsXML,
                                                                          contentTypeXML,
                                                                          contentTypeResultsThrift,
                                                                          contentTypeTextPlain
                                                                          );

    // Offer for ASK
    // This includes application/xml and application/json and excludes application/sparql-results+thrift
    public static final AcceptList rsOfferBoolean      = AcceptList.create(contentTypeResultsJSON,
                                                                           contentTypeJSON,
                                                                           contentTypeTextCSV,
                                                                           contentTypeTextTSV,
                                                                           contentTypeResultsXML,
                                                                           contentTypeXML,
                                                                           contentTypeTextPlain
                                                                           );
}


text:
var __result1, __result2;
function scb() { __result1 = 1;}
function ecb(e) { __result2 = e.name; }
var statuscb = {
   onsuccess: function() {
     tizen.networkbearerselection.releaseRouteToHost("CELLULAR", "www.google.com", scb, ecb);
   },
   ondisconnected: function() {  }
 };
 tizen.networkbearerselection.requestRouteToHost("CELLULAR", "www.google.com", statuscb, ecb);

var __expect1 = 1;
var __expect2 = "UnknownError";


text:
#ifndef __TRIMMEDARRAYPROCESSOR2_H
#define __TRIMMEDARRAYPROCESSOR2_H

/**
 * \file
 * \internal
 */

#include "LETypes.h"
#include "MorphTables.h"
#include "SubtableProcessor2.h"
#include "NonContextualGlyphSubst.h"
#include "NonContextualGlyphSubstProc2.h"

U_NAMESPACE_BEGIN

class LEGlyphStorage;

class TrimmedArrayProcessor2 : public NonContextualGlyphSubstitutionProcessor2
{
public:
    virtual void process(LEGlyphStorage &glyphStorage, LEErrorCode &success);

    TrimmedArrayProcessor2(const LEReferenceTo<MorphSubtableHeader2> &morphSubtableHeader, LEErrorCode &success);

    virtual ~TrimmedArrayProcessor2();

    /**
     * ICU "poor man's RTTI", returns a UClassID for the actual class.
     *
     * @stable ICU 2.8
     */
    virtual UClassID getDynamicClassID() const;

    /**
     * ICU "poor man's RTTI", returns a UClassID for this class.
     *
     * @stable ICU 2.8
     */
    static UClassID getStaticClassID();

private:
    TrimmedArrayProcessor2();

protected:
    TTGlyphID firstGlyph;
    TTGlyphID lastGlyph;
    LEReferenceTo<TrimmedArrayLookupTable> trimmedArrayLookupTable;
    LEReferenceToArrayOf<LookupValue> valueArray;
};

U_NAMESPACE_END
#endif


text:
<?php

namespace RDV\Bundle\MigrationBundle\Tests\Unit\Fixture\TestPackage\Test1Bundle\Migrations\Schema\v1_0;

use Doctrine\DBAL\Schema\Schema;
use RDV\Bundle\MigrationBundle\Migration\Migration;
use RDV\Bundle\MigrationBundle\Migration\QueryBag;

class Test1BundleMigration10 implements Migration
{
    /**
     * @inheritdoc
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $queries->addQuery('CREATE TABLE TEST (id INT AUTO_INCREMENT NOT NULL)');
    }
}


text:
package com.jrestless.core.security;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public class AnonSecurityContextTest {
	@Test
	public void getUserPrincipal_ShouldAlwaysBeNull() {
		assertNull(new AnonSecurityContext().getUserPrincipal());
	}

	@Test
	public void isUserInRole_ShouldNeverBeInRole() {
		assertFalse(new AnonSecurityContext().isUserInRole(null));
		assertFalse(new AnonSecurityContext().isUserInRole(""));
		assertFalse(new AnonSecurityContext().isUserInRole("user"));
		assertFalse(new AnonSecurityContext().isUserInRole("admin"));
	}

	@Test
	public void getAuthenticationScheme_ShouldAlwaysBeNull() {
		assertNull(new AnonSecurityContext().getAuthenticationScheme());
		assertNull(new AnonSecurityContext(false).getAuthenticationScheme());
		assertNull(new AnonSecurityContext(true).getAuthenticationScheme());
	}

	@Test
	public void isSecure_SecureConstructorArgGiven_ShouldBeSecure() {
		assertTrue(new AnonSecurityContext(true).isSecure());
	}

	@Test
	public void isSecure_InsecureConstructorArgGiven_ShouldBeInSecure() {
		assertFalse(new AnonSecurityContext(false).isSecure());
	}

	@Test
	public void isSecure_NoSecurityConstructorArgGiven_ShouldBeSecure() {
		assertTrue(new AnonSecurityContext().isSecure());
	}
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace AlarmClock
{
    interface ILocalize
    {
        CultureInfo GetCurrentCultureInfo();
        void SetLocale(CultureInfo ci);
    }
}


text:
using System.Text;
using TryCSharp.Common;

namespace TryCSharp.Samples.Basic
{
    /// <summary>
    ///     バイト配列についてのサンプルです。
    /// </summary>
    [Sample]
    public class ByteArraySamples07 : IExecutable
    {
        public void Execute()
        {
            //
            // バイト列を文字列へ.
            //
            var s = "gsf_zero1";
            var buf = Encoding.ASCII.GetBytes(s);

            Output.WriteLine(Encoding.ASCII.GetString(buf));
        }
    }
}


text:
package com.facebook.buck.test;

import com.facebook.buck.util.Ansi;
import com.facebook.buck.util.TimeFormat;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

import javax.annotation.concurrent.Immutable;

@Immutable
public class TestCaseSummary {

  private final String testCaseName;
  private final ImmutableList<TestResultSummary> testResults;
  private final boolean isSuccess;
  private final int failureCount;
  private final long totalTime;

  public TestCaseSummary(String testCaseName, List<TestResultSummary> testResults) {
    this.testCaseName = Preconditions.checkNotNull(testCaseName);
    this.testResults = ImmutableList.copyOf(testResults);

    boolean isSuccess = true;
    int failureCount = 0;
    long totalTime = 0L;
    for (TestResultSummary result : testResults) {
      totalTime += result.getTime();
      if (!result.isSuccess()) {
        isSuccess = false;
        ++failureCount;
      }
    }
    this.isSuccess = isSuccess;
    this.failureCount = failureCount;
    this.totalTime = totalTime;
  }

  public boolean isSuccess() {
    return isSuccess;
  }

  public String getTestCaseName() {
    return testCaseName;
  }

  /** @return the total time to run all of the tests in this test case, in milliseconds */
  public long getTotalTime() {
    return totalTime;
  }

  /** @return a one-line, printable summary */
  public String getOneLineSummary(Ansi ansi) {
    String status = ansi.asHighlightedStatusText(isSuccess(), isSuccess() ? "PASS" : "FAIL");
    return String.format("%s %s %2d Passed  %2d Failed   %s",
        status,
        TimeFormat.formatForConsole(totalTime, ansi),
        testResults.size() - failureCount,
        failureCount,
        testCaseName);
  }

  public ImmutableList<TestResultSummary> getTestResults() {
    return testResults;
  }

  public int getFailureCount() {
    return failureCount;
  }

  @Override
  public String toString() {
    return String.format("%s %s",
        isSuccess() ? "PASS" : "FAIL",
        testCaseName);
  }
}