text:
package org.keycloak.testsuite.broker;

import org.keycloak.broker.saml.SAMLIdentityProviderConfig;
import org.keycloak.crypto.Algorithm;
import org.keycloak.dom.saml.v2.protocol.AuthnRequestType;
import org.keycloak.models.IdentityProviderSyncMode;
import org.keycloak.protocol.saml.SamlConfigAttributes;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request;
import org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLAssertionQNames;
import org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLProtocolQNames;
import org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder;

import org.keycloak.testsuite.saml.AbstractSamlTest;
import org.keycloak.testsuite.updaters.ClientAttributeUpdater;
import org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater;
import org.keycloak.testsuite.updaters.RealmAttributeUpdater;
import org.keycloak.testsuite.util.KeyUtils;
import org.keycloak.testsuite.util.SamlClient;
import org.keycloak.testsuite.util.SamlClient.Binding;
import org.keycloak.testsuite.util.SamlClientBuilder;
import org.keycloak.testsuite.util.saml.SamlDocumentStepBuilder.Saml2DocumentTransformer;
import java.io.Closeable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import java.util.Map.Entry;
import java.util.Set;
import javax.ws.rs.core.Response.Status;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.namespace.QName;
import org.apache.http.HttpResponse;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.keycloak.testsuite.broker.BrokerTestConstants.*;
import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot;
import static org.keycloak.testsuite.util.Matchers.bodyHC;
import static org.keycloak.testsuite.util.Matchers.isSamlResponse;
import static org.keycloak.testsuite.broker.BrokerTestTools.getProviderRoot;

public class KcSamlSignedBrokerTest extends AbstractBrokerTest {

    private static final String PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAs46ICYPRIkmr8diECmyT59cChTWIEiXYBY3T6OLlZrF8ofVCzbEeoUOmhrtHijxxuKSoqLWP4nNOt3rINtQNBQIDAQABAkBL2nyxuFQTLhhLdPJjDPd2y6gu6ixvrjkSL5ZEHgZXWRHzhTzBT0eRxg/5rJA2NDRMBzTTegaEGkWUt7lF5wDJAiEA5pC+h9NEgqDJSw42I52BOml3II35Z6NlNwl6OMfnD1sCIQDHXUiOIJy4ZcSgv5WGue1KbdNVOT2gop1XzfuyWgtjHwIhAOCjLb9QC3PqC7Tgx8azcnDiyHojWVesTrTsuvQPcAP5AiAkX5OeQrr1NbQTNAEe7IsrmjAFi4T/6stUOsOiPaV4NwIhAJIeyh4foIXIVQ+M4To2koaDFRssxKI9/O72vnZSJ+uA";
    private static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALOOiAmD0SJJq/HYhApsk+fXAoU1iBIl2AWN0+ji5WaxfKH1Qs2xHqFDpoa7R4o8cbikqKi1j+JzTrd6yDbUDQUCAwEAAQ==";

    public void withSignedEncryptedAssertions(Runnable testBody, boolean signedDocument, boolean signedAssertion, boolean encryptedAssertion) throws Exception {
        String providerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.providerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
        Assert.assertThat(providerCert, Matchers.notNullValue());

        String consumerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
        Assert.assertThat(consumerCert, Matchers.notNullValue());

        try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
            .setAttribute(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, Boolean.toString(signedAssertion || signedDocument))
            .setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, Boolean.toString(signedAssertion))
            .setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_ENCRYPTED, Boolean.toString(encryptedAssertion))
            .setAttribute(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "false")
            .setAttribute(SAMLIdentityProviderConfig.ENCRYPTION_PUBLIC_KEY, PUBLIC_KEY)
            .setAttribute(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, providerCert)
            .update();
          Closeable clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm())
            .setAttribute(SamlConfigAttributes.SAML_ENCRYPT, Boolean.toString(encryptedAssertion))
            .setAttribute(SamlConfigAttributes.SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE, consumerCert)
            .setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, Boolean.toString(signedDocument))
            .setAttribute(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, Boolean.toString(signedAssertion))
            .setAttribute(SamlConfigAttributes.SAML_ENCRYPTION_PRIVATE_KEY_ATTRIBUTE, PRIVATE_KEY)
            .setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")    // Do not require client signature
            .update())
        {
            testBody.run();
        }
    }

    @Override
    protected BrokerConfiguration getBrokerConfiguration() {
        return new KcSamlSignedBrokerConfiguration();
    }

    @Test
    public void testWithExpiredBrokerCertificate() throws Exception {
        try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
            .setAttribute(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, Boolean.toString(true))
            .setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, Boolean.toString(true))
            .setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_ENCRYPTED, Boolean.toString(false))
            .setAttribute(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "true")
            .setAttribute(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_CERTIFICATE)
            .update();
          Closeable clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm())
            .setAttribute(SamlConfigAttributes.SAML_ENCRYPT, Boolean.toString(false))
            .setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true")
            .setAttribute(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, Boolean.toString(true))
            .setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
            .update();
          Closeable realmUpdater = new RealmAttributeUpdater(adminClient.realm(bc.providerRealmName()))
            .setPublicKey(AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_PUBLIC_KEY)
            .setPrivateKey(AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_PRIVATE_KEY)
            .update())
        {
            AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);

            Document doc = SAML2Request.convert(loginRep);
            new SamlClientBuilder()
              .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build()   // Request to consumer IdP
              .login().idp(bc.getIDPAlias()).build()

              .assertResponse(org.keycloak.testsuite.util.Matchers.statusCodeIsHC(Status.BAD_REQUEST));
        }

    }

    @Test
    public void testSignedEncryptedAssertions() throws Exception {
        withSignedEncryptedAssertions(this::testAssertionSignatureRespected, false, true, true);
    }

    @Test
    public void testSignedAssertion() throws Exception {
        withSignedEncryptedAssertions(this::testAssertionSignatureRespected, false, true, false);
    }

    private void testAssertionSignatureRespected() {
        // Login should pass because assertion is signed.
        loginUser();

        // Logout should fail because logout response is not signed.
        final String redirectUri = getAccountUrl(getProviderRoot(), bc.providerRealmName());
        final String logoutUri = oauth.realm(bc.providerRealmName()).getLogoutUrl().redirectUri(redirectUri).build();
        driver.navigate().to(logoutUri);

        errorPage.assertCurrent();
    }

    private Document extractNamespacesToTopLevelElement(Document original) {
        HashMap<String, String> namespaces = new HashMap<>();
        enumerateAndRemoveNamespaces(original.getDocumentElement(), namespaces);

        log.infof("Namespaces: %s", namespaces);
        log.infof("Document: %s", DocumentUtil.asString(original));

        Element rootNode = original.getDocumentElement();
        for (Entry<String, String> me : namespaces.entrySet()) {
            rootNode.setAttribute(me.getKey(), me.getValue());
        }

        log.infof("Updated document: %s", DocumentUtil.asString(original));

        return original;
    }

    private void enumerateAndRemoveNamespaces(Element documentElement, HashMap<String, String> namespaces) {
        final NamedNodeMap attrs = documentElement.getAttributes();
        if (attrs != null) {
            final Set<String> found = new HashSet<>();

            for (int i = attrs.getLength() - 1; i >= 0; i--) {
                Node item = attrs.item(i);
                String nodeName = item.getNodeName();
                if (nodeName != null && nodeName.startsWith("xmlns:")) {
                    namespaces.put(nodeName, item.getNodeValue());
                    found.add(nodeName);
                }
            }

            found.forEach(documentElement::removeAttribute);
        }

        NodeList childNodes = documentElement.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i ++) {
            Node childNode = childNodes.item(i);
            if (childNode instanceof Element) {
                enumerateAndRemoveNamespaces((Element) childNode, namespaces);
            }
        }
    }

    // KEYCLOAK-5581
    @Test
    public void loginUserAllNamespacesInTopElement() {
        AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);

        Document doc;
        try {
            doc = extractNamespacesToTopLevelElement(SAML2Request.convert(loginRep));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        SAMLDocumentHolder samlResponse = new SamlClientBuilder()
          .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build()   // Request to consumer IdP
          .login().idp(bc.getIDPAlias()).build()

          .processSamlResponse(Binding.POST)    // AuthnRequest to producer IdP
            .targetAttributeSamlRequest()
            .transformDocument(this::extractNamespacesToTopLevelElement)
            .build()

          .login().user(bc.getUserLogin(), bc.getUserPassword()).build()

          .processSamlResponse(Binding.POST)    // Response from producer IdP
            .transformDocument(this::extractNamespacesToTopLevelElement)
            .build()

          // first-broker flow
          .updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build()
          .followOneRedirect()

          .getSamlResponse(Binding.POST);       // Response from consumer IdP

        Assert.assertThat(samlResponse, Matchers.notNullValue());
        Assert.assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    }

    @Test
    public void loginUserAllNamespacesInTopElementSignedEncryptedAssertion() throws Exception {
        withSignedEncryptedAssertions(this::loginUserAllNamespacesInTopElement, false, true, true);
    }

    @Test
    public void loginUserAllNamespacesInTopElementSignedAssertion() throws Exception {
        withSignedEncryptedAssertions(this::loginUserAllNamespacesInTopElement, false, true, false);
    }

    @Test
    public void loginUserAllNamespacesInTopElementEncryptedAssertion() throws Exception {
        withSignedEncryptedAssertions(this::loginUserAllNamespacesInTopElement, false, false, true);
    }

    public class KcSamlSignedBrokerConfiguration extends KcSamlBrokerConfiguration {

        @Override
        public RealmRepresentation createProviderRealm() {
            RealmRepresentation realm = super.createProviderRealm();

            realm.setPublicKey(REALM_PUBLIC_KEY);
            realm.setPrivateKey(REALM_PRIVATE_KEY);

            return realm;
        }

        @Override
        public RealmRepresentation createConsumerRealm() {
            RealmRepresentation realm = super.createConsumerRealm();

            realm.setPublicKey(REALM_PUBLIC_KEY);
            realm.setPrivateKey(REALM_PRIVATE_KEY);

            return realm;
        }

        @Override
        public List<ClientRepresentation> createProviderClients() {
            List<ClientRepresentation> clientRepresentationList = super.createProviderClients();

            String consumerCert = KeyUtils.getActiveSigningKey(adminClient.realm(consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
            Assert.assertThat(consumerCert, Matchers.notNullValue());

            for (ClientRepresentation client : clientRepresentationList) {
                client.setClientAuthenticatorType("client-secret");
                client.setSurrogateAuthRequired(false);

                Map<String, String> attributes = client.getAttributes();
                if (attributes == null) {
                    attributes = new HashMap<>();
                    client.setAttributes(attributes);
                }

                attributes.put(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, "true");
                attributes.put(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true");
                attributes.put(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "true");
                attributes.put(SamlConfigAttributes.SAML_SIGNATURE_ALGORITHM, "RSA_SHA256");
                attributes.put(SamlConfigAttributes.SAML_SIGNING_CERTIFICATE_ATTRIBUTE, consumerCert);
            }

            return clientRepresentationList;
        }

        @Override
        public IdentityProviderRepresentation setUpIdentityProvider(IdentityProviderSyncMode syncMode) {
            IdentityProviderRepresentation result = super.setUpIdentityProvider(syncMode);

            String providerCert = KeyUtils.getActiveSigningKey(adminClient.realm(providerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
            Assert.assertThat(providerCert, Matchers.notNullValue());

            Map<String, String> config = result.getConfig();

            config.put(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, "true");
            config.put(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, "true");
            config.put(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "true");
            config.put(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, providerCert);

            return result;
        }
    }

    @Test
    public void testSignatureTampering_NOsignDoc_NOsignAssert_NOencAssert() throws Exception {
        loginAttackChangeSignature(false, false, false);
    }

    @Test
    public void testSignatureTampering_NOsignDoc_NOsignAssert_encAssert() throws Exception {
        loginAttackChangeSignature(false, false, true);
    }

    @Test
    public void testSignatureTampering_NOsignDoc_signAssert_NOencAssert() throws Exception {
        loginAttackChangeSignature(false, true, false);
    }

    @Test
    public void testSignatureTampering_NOsignDoc_signAssert_encAssert() throws Exception {
        loginAttackChangeSignature(false, true, true);
    }

    @Test
    public void testSignatureTampering_signDoc_NOsignAssert_NOencAssert() throws Exception {
        loginAttackChangeSignature(true, false, false);
    }

    @Test
    public void testSignatureTampering_signDoc_NOsignAssert_encAssert() throws Exception {
        loginAttackChangeSignature(true, false, true);
    }

    @Test
    public void testSignatureTampering_signDoc_signAssert_NOencAssert() throws Exception {
        loginAttackChangeSignature(true, true, false);
    }

    @Test
    public void testSignatureTampering_signDoc_signAssert_encAssert() throws Exception {
        loginAttackChangeSignature(true, true, true);
    }

    private Document removeDocumentSignature(Document orig) {
        return removeSignatureTag(orig, Collections.singleton(SAMLProtocolQNames.RESPONSE.getQName()));
    }

    private Document removeAssertionSignature(Document orig) {
        return removeSignatureTag(orig, Collections.singleton(SAMLAssertionQNames.ASSERTION.getQName()));
    }

    private Document removeDocumentAndAssertionSignature(Document orig) {
        return removeSignatureTag(orig,
          new HashSet<>(Arrays.asList(SAMLProtocolQNames.RESPONSE.getQName(), SAMLAssertionQNames.ASSERTION.getQName()))
        );
    }

    private Document removeSignatureTag(Document orig, final Set<QName> qNames) throws DOMException {
        NodeList sigElements = orig.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        LinkedList<Node> nodesToRemove = new LinkedList<>();
        for (int i = 0; i < sigElements.getLength(); i ++) {
            Node n = sigElements.item(i);
            final Node p = n.getParentNode();
            QName q = new QName(p.getNamespaceURI(), p.getLocalName());
            if (qNames.contains(q)) {
                nodesToRemove.add(n);
            }
        }
        nodesToRemove.forEach(n -> n.getParentNode().removeChild(n));
        return orig;
    }

    private void loginAttackChangeSignature(boolean producerSignDocument, boolean producerSignAssertions, boolean producerEncryptAssertions) throws Exception {
        log.debug("");

        loginAttackChangeSignature("No changes to SAML document", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
          t -> t, true);

        // TODO: producerSignAssertions should be removed once there would be option to force check SAML document signature
        boolean validAfterTamperingWithDocumentSignature = ! producerSignDocument || producerSignAssertions;

        loginAttackChangeSignature("Remove document signature", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
          this::removeDocumentSignature, validAfterTamperingWithDocumentSignature);

        // Tests for assertion signature manipulation follow. Tampering with assertion signature is
        // relevant only if assertion is not encrypted since signature is part of encrypted data,
        // hence skipped in the opposite case.
        if (producerEncryptAssertions) {
            return;
        }

        // When assertion signature is removed, the expected document validation passes only
        // if neither the document was not signed
        // (otherwise document signature is invalidated by removing signature from the assertion)
        // nor the assertion is
        boolean validAfterTamperingWithAssertionSignature = ! producerSignAssertions;

        // When both assertion and document signatures are removed, the document validation passes only
        // if neiter the document nor assertion were signed
        boolean validAfterTamperingWithBothDocumentAndAssertionSignature = ! producerSignDocument && ! producerSignAssertions;

        loginAttackChangeSignature("Remove assertion signature", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
          this::removeAssertionSignature, validAfterTamperingWithAssertionSignature);
        loginAttackChangeSignature("Remove both document and assertion signature", producerSignDocument, producerSignAssertions, producerEncryptAssertions,
          this::removeDocumentAndAssertionSignature, validAfterTamperingWithBothDocumentAndAssertionSignature);
    }

    private void loginAttackChangeSignature(String description,
      boolean producerSignDocument, boolean producerSignAssertions, boolean producerEncryptAssertions,
      Saml2DocumentTransformer tr, boolean shouldSucceed) throws Exception {
        log.infof("producerSignDocument: %s, producerSignAssertions: %s, producerEncryptAssertions: %s", producerSignDocument, producerSignAssertions, producerEncryptAssertions);

        Matcher<HttpResponse> responseFromConsumerMatcher = shouldSucceed
          ?     bodyHC(containsString("Update Account Information"))
          : not(bodyHC(containsString("Update Account Information")));

        AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);
        Document doc = SAML2Request.convert(loginRep);

        withSignedEncryptedAssertions(() -> {
            new SamlClientBuilder()
              .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build()   // Request to consumer IdP

              .login().idp(bc.getIDPAlias()).build()

              .processSamlResponse(Binding.POST).build()    // AuthnRequest to producer IdP

              .login().user(bc.getUserLogin(), bc.getUserPassword()).build()

              .processSamlResponse(Binding.POST)    // Response from producer IdP
                .transformDocument(tr)
                .build()

              // first-broker flow: if valid request, it displays an update profile page on consumer realm
              .execute(currentResponse -> assertThat(description, currentResponse, responseFromConsumerMatcher));
        }, producerSignDocument, producerSignAssertions, producerEncryptAssertions);
    }

    @Test
    public void testSignatureDataWhenWantsRequestsSigned() throws Exception {
        // Verifies that an AuthnRequest contains the KeyInfo/X509Data element when
        // client AuthnRequest signature is requested
        String providerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.providerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
        Assert.assertThat(providerCert, Matchers.notNullValue());

        String consumerCert = KeyUtils.getActiveSigningKey(adminClient.realm(bc.consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256).getCertificate();
        Assert.assertThat(consumerCert, Matchers.notNullValue());

        try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
            .setAttribute(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE, Boolean.toString(true))
            .setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_SIGNED, Boolean.toString(true))
            .setAttribute(SAMLIdentityProviderConfig.WANT_ASSERTIONS_ENCRYPTED, Boolean.toString(false))
            .setAttribute(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED, "true")
            .setAttribute(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY, AbstractSamlTest.SAML_CLIENT_SALES_POST_SIG_EXPIRED_CERTIFICATE)
            .update();
          Closeable clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm())
            .setAttribute(SamlConfigAttributes.SAML_ENCRYPT, Boolean.toString(false))
            .setAttribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true")
            .setAttribute(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, Boolean.toString(true))
            .setAttribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
            .update())
        {
            // Build the login request document
            AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
            Document doc = SAML2Request.convert(loginRep);
            new SamlClientBuilder()
                .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST)
                .build()   // Request to consumer IdP
                .login().idp(bc.getIDPAlias()).build()
                .processSamlResponse(Binding.POST)    // AuthnRequest to producer IdP
                  .targetAttributeSamlRequest()
                  .transformDocument(this::extractNamespacesToTopLevelElement)
                  .transformDocument((document) -> {
                    try
                    {
                        // Find the Signature element
                        Element signatureElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), XMLSignature.XMLNS, "Signature");
                        Assert.assertThat("Signature element not found in request document", signatureElement, Matchers.notNullValue());

                        // Find the KeyInfo element
                        Element keyInfoElement = DocumentUtil.getDirectChildElement(signatureElement, XMLSignature.XMLNS, "KeyInfo");
                        Assert.assertThat("KeyInfo element not found in request Signature element", keyInfoElement, Matchers.notNullValue());

                        // Find the X509Data element
                        Element x509DataElement = DocumentUtil.getDirectChildElement(keyInfoElement, XMLSignature.XMLNS, "X509Data");
                        Assert.assertThat("X509Data element not found in request Signature/KeyInfo element", x509DataElement, Matchers.notNullValue());
                    }
                    catch (Exception ex)
                    {
                        throw new RuntimeException(ex);
                    }
                  })
                  .build()
                .execute();
        }
    }
}


text: <!DOCTYPE html>

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.eventhubs.implementation;

import com.azure.resourcemanager.eventhubs.EventHubsManager;
import com.azure.resourcemanager.eventhubs.fluent.models.AccessKeysInner;
import com.azure.resourcemanager.eventhubs.fluent.models.AuthorizationRuleInner;
import com.azure.resourcemanager.eventhubs.models.AccessRights;
import com.azure.resourcemanager.eventhubs.models.AuthorizationRule;
import com.azure.resourcemanager.eventhubs.models.EventHubAuthorizationKey;
import com.azure.resourcemanager.eventhubs.models.KeyType;
import com.azure.resourcemanager.resources.fluentcore.model.implementation.IndexableRefreshableWrapperImpl;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *  Base implementation for authorization rule.
 * (Internal use only)
 *
 * @param <RuleT> rule fluent model
 * @param <RuleImpl> implementation of rule fluent model
 */
abstract class AuthorizationRuleBaseImpl<RuleT extends AuthorizationRule<RuleT>,
    RuleImpl extends IndexableRefreshableWrapperImpl<RuleT, AuthorizationRuleInner>>
    extends NestedResourceImpl<RuleT, AuthorizationRuleInner, RuleImpl> implements AuthorizationRule<RuleT> {

    protected AuthorizationRuleBaseImpl(String name, AuthorizationRuleInner inner, EventHubsManager manager) {
        super(name, inner, manager);
    }

    @Override
    public Mono<EventHubAuthorizationKey> getKeysAsync() {
        return this.getKeysInnerAsync()
            .map(EventHubAuthorizationKeyImpl::new);
    }

    @Override
    public EventHubAuthorizationKey getKeys() {
        return getKeysAsync().block();
    }

    @Override
    public Mono<EventHubAuthorizationKey> regenerateKeyAsync(KeyType keyType) {
        return this.regenerateKeysInnerAsync(keyType)
            .map(EventHubAuthorizationKeyImpl::new);
    }

    @Override
    public EventHubAuthorizationKey regenerateKey(KeyType keyType) {
        return regenerateKeyAsync(keyType).block();
    }

    @Override
    public List<AccessRights> rights() {
        if (this.innerModel().rights() == null) {
            return Collections.unmodifiableList(new ArrayList<>());
        }
        return Collections.unmodifiableList(this.innerModel().rights());
    }

    @SuppressWarnings("unchecked")
    public RuleImpl withListenAccess() {
        if (this.innerModel().rights() == null) {
            this.innerModel().withRights(new ArrayList<>());
        }
        if (!this.innerModel().rights().contains(AccessRights.LISTEN)) {
            this.innerModel().rights().add(AccessRights.LISTEN);
        }
        return (RuleImpl) this;
    }

    @SuppressWarnings("unchecked")
    public RuleImpl withSendAccess() {
        if (this.innerModel().rights() == null) {
            this.innerModel().withRights(new ArrayList<>());
        }
        if (!this.innerModel().rights().contains(AccessRights.SEND)) {
            this.innerModel().rights().add(AccessRights.SEND);
        }
        return (RuleImpl) this;
    }

    @SuppressWarnings("unchecked")
    public RuleImpl withSendAndListenAccess() {
        withListenAccess();
        withSendAccess();
        return (RuleImpl) this;
    }

    @SuppressWarnings("unchecked")
    public RuleImpl withManageAccess() {
        withListenAccess();
        withSendAccess();
        if (!this.innerModel().rights().contains(AccessRights.MANAGE)) {
            this.innerModel().rights().add(AccessRights.MANAGE);
        }
        return (RuleImpl) this;
    }

    protected abstract Mono<AccessKeysInner> getKeysInnerAsync();
    protected abstract Mono<AccessKeysInner> regenerateKeysInnerAsync(KeyType keyType);
    protected abstract Mono<AuthorizationRuleInner> getInnerAsync();
    public abstract Mono<RuleT> createResourceAsync();
}


text:
@implementation DSLinkedListCell

- (id)init{

    if( (self=[super init]) ) {
        self.next = nil;
        self.data = nil;
    }
    return self;

}

- (id)initWithData:(id)data Next:(DSLinkedListCell *)next{

    if( (self=[super init]) ) {
        self.next = next;
        self.data = data;
    }
    return self;

}

- (BOOL)isEqual:(id)other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    return [self isEqualToLinkedListCell:other];
}

- (BOOL)isEqualToLinkedListCell:(DSLinkedListCell*)other {
    if (self == other)
        return YES;
    return ([self.data isEqual:other.data] && [self.next isEqual:other.next]);
}

+ (id)cell{
    return [[DSLinkedListCell alloc]init];
}

+ (id)cellWithData:(id)data Next:(DSLinkedListCell *)next{
    return [[DSLinkedListCell alloc]initWithData:data Next:next];
}

@end


text:
namespace bfvmm::intel_x64
{

interrupt_window_handler::interrupt_window_handler(
    gsl::not_null<vcpu *> vcpu
) :
    m_vcpu{vcpu}
{
    using namespace vmcs_n;

    vcpu->add_exit_handler_for_reason(
        exit_reason::basic_exit_reason::interrupt_window,
    {&interrupt_window_handler::handle, this}
    );
}

// -----------------------------------------------------------------------------
// Add Handler / Enablers
// -----------------------------------------------------------------------------

void
interrupt_window_handler::queue_external_interrupt(uint64_t vector)
{
    // Note:
    //
    // There are two ways to handle injection. Currently, we inject using an
    // interrupt window. This means that an interrupt is always queued, and it
    // is only injected when the VM has an open window. The downside to this
    // approach is that when this function is called, it is possible that the
    // window is actually open, which means that we needlessly generate an
    // extra VM exit.
    //
    // The other approach is to check to see if the window is open and inject.
    // The issue with this approach is that we always have to check to see if
    // the window is open which is expensive, and then we have to have a lot of
    // extra logic to handle injecting without overwritting existing
    // interrupts, getting interrupts out of order, etc... There are a lot
    // more edge cases. The beauty of our current approach is that our window
    // handler is the only thing that can inject an interrupt, which is
    // mutually exclusive with queueing (as queueing occurs on any VM exit
    // other than our window) which means there are no race conditions, or
    // overwritting, etc... And, we do not have to make several vmreads per
    // injection. Since we leverage vpid, a VM exit that occurs before an entry
    // has a minimum performance hit as the VMM is still in the cache so this
    // approach is both reliable and performant.
    //
    // Also note that our approach also works fine with exceptions. Exceptions
    // do not need to be queued since they cannot be blocked. This means that
    // exceptions can be injected on any VM exit without fear of overwritting
    // an external interrupt as they are only injected on an open window exit
    // which once again, will not attempt to inject an exception at the same
    // time since that code is managed here, and is very small.
    //

    this->enable_exiting();
    m_interrupt_queue.push(vector);
}

void
interrupt_window_handler::inject_exception(uint64_t vector, uint64_t ec)
{
    namespace info_n = vmcs_n::vm_entry_interruption_information;
    using namespace info_n::interruption_type;

    uint64_t info = 0;

    info_n::vector::set(info, vector);
    info_n::interruption_type::set(info, hardware_exception);
    info_n::valid_bit::enable(info);

    switch (vector) {
        case 8:
        case 10:
        case 11:
        case 12:
        case 13:
        case 14:
        case 17:
            info_n::deliver_error_code_bit::enable(info);
            vmcs_n::vm_entry_exception_error_code::set(ec);
            break;

        default:
            break;
    }

    info_n::set(info);
}

void
interrupt_window_handler::inject_external_interrupt(uint64_t vector)
{
    namespace info_n = vmcs_n::vm_entry_interruption_information;
    using namespace info_n::interruption_type;

    uint64_t info = 0;

    info_n::vector::set(info, vector);
    info_n::interruption_type::set(info, external_interrupt);
    info_n::valid_bit::enable(info);

    info_n::set(info);
}

// -----------------------------------------------------------------------------
// Handlers
// -----------------------------------------------------------------------------

bool
interrupt_window_handler::handle(vcpu *vcpu)
{
    bfignored(vcpu);
    this->inject_external_interrupt(m_interrupt_queue.pop());

    if (m_interrupt_queue.empty()) {
        this->disable_exiting();
    }

    return true;
}

// -----------------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------------

void
interrupt_window_handler::enable_exiting()
{
    using namespace vmcs_n;

    if (m_enabled == false) {
        primary_processor_based_vm_execution_controls::interrupt_window_exiting::enable();
        m_enabled = true;
    }
}

void
interrupt_window_handler::disable_exiting()
{
    using namespace vmcs_n;

    if (m_enabled == true) {
        primary_processor_based_vm_execution_controls::interrupt_window_exiting::disable();
        m_enabled = false;
    }
}

}


text:
var utils = require('../utils.js');

var defaultConfig = {
  birthRange: 2,
  deathRange: 2
};

module.exports = function(config, data){

  config = utils.defaults(config, defaultConfig);

  var baseUrl = 'http://www.werelate.org/wiki/Special:Search?sort=score&ns=Person&rows=20&ecp=p';
  var query = '';

  // Simple mappings from the person data object to params
  // These don't need any further processing
  var mappings = [
    ['g', 'givenName'],
    ['s', 'familyName'],
    ['bp', 'birthPlace'],
    ['dp', 'deathPlace'],
    ['fg', 'fatherGivenName'],
    ['fs', 'fatherFamilyName'],
    ['mg', 'motherGivenName'],
    ['ms', 'motherFamilyName'],
    ['sg', 'spouseGivenName'],
    ['ss', 'spouseFamilyName']
  ];
  utils.each(mappings, function(map) {
    if(data[map[1]]) {
      query = utils.addQueryParam(query, map[0], data[map[1]]);
    }
  });

  // Process dates and add the ranges
  if(data.birthDate) {
    query = utils.addQueryParam(query, 'bd', utils.getYear(data.birthDate));
    query = utils.addQueryParam(query, 'br', config.birthRange);
  }
  if(data.deathDate) {
    query = utils.addQueryParam(query, 'dd', utils.getYear(data.deathDate));
    query = utils.addQueryParam(query, 'dr', config.deathRange);
  }

  return baseUrl + query;

};


text:
'use strict';

angular.module('d2l-classes').controller('ViewClassDetailController', ['$scope',
	function($scope) {
		// View class detail controller logic
		// ...
	}
]);


text:
package org.afree.chart.plot.dial;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.afree.graphics.geom.ArcShape;
import org.afree.graphics.geom.Font;
import org.afree.graphics.geom.LineShape;
import org.afree.graphics.geom.RectShape;
import org.afree.graphics.geom.Shape;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Paint.Align;

/**
 * A scale for a {@link DialPlot}.
 *
 * @since JFreeChart 1.0.7
 */
public class StandardDialScale extends AbstractDialLayer implements DialScale,
        Cloneable, /*PublicCloneable,*/ Serializable {

    /** For serialization. */
    static final long serialVersionUID = 3715644629665918516L;

    /** The minimum data value for the scale. */
    private double lowerBound;

    /** The maximum data value for the scale. */
    private double upperBound;

    /**
     * The start angle for the scale display, in degrees (using the same
     * encoding as ArcShape).
     */
    private double startAngle;

    /** The extent of the scale display. */
    private double extent;

    /**
     * The factor (in the range 0.0 to 1.0) that determines the outside limit
     * of the tick marks.
     */
    private double tickRadius;

    /**
     * The increment (in data units) between major tick marks.
     */
    private double majorTickIncrement;

    /**
     * The factor that is subtracted from the tickRadius to determine the
     * inner point of the major ticks.
     */
    private double majorTickLength;

    /**
     * The paint to use for major tick marks.  This field is transient because
     * it requires special handling for serialization.
     */
    private transient Paint majorTickPaint;

    /**
     * The stroke to use for major tick marks.  This field is transient because
     * it requires special handling for serialization.
     */
    private transient Float majorTickStroke;

    /**
     * The number of minor ticks between each major tick.
     */
    private int minorTickCount;

    /**
     * The factor that is subtracted from the tickRadius to determine the
     * inner point of the minor ticks.
     */
    private double minorTickLength;

    /**
     * The paint to use for minor tick marks.  This field is transient because
     * it requires special handling for serialization.
     */
    private transient Paint minorTickPaint;

    /**
     * The stroke to use for minor tick marks.  This field is transient because
     * it requires special handling for serialization.
     */
    private transient Float minorTickStroke;

    /**
     * The tick label offset.
     */
    private double tickLabelOffset;

    /**
     * The tick label font.
     */
    private Font tickLabelFont;

    /**
     * A flag that controls whether or not the tick labels are
     * displayed.
     */
    private boolean tickLabelsVisible;

    /**
     * The number formatter for the tick labels.
     */
    private NumberFormat tickLabelFormatter;

    /**
     * A flag that controls whether or not the first tick label is
     * displayed.
     */
    private boolean firstTickLabelVisible;

    /**
     * The tick label paint.  This field is transient because it requires
     * special handling for serialization.
     */
    private transient Paint tickLabelPaint;

    /**
     * Creates a new instance of DialScale.
     */
    public StandardDialScale() {
        this(0.0, 100.0, 175, -170, 10.0, 4);
    }

    /**
     * Creates a new instance.
     *
     * @param lowerBound  the lower bound of the scale.
     * @param upperBound  the upper bound of the scale.
     * @param startAngle  the start angle (in degrees, using the same
     *     orientation as Java's ArcShape class).
     * @param extent  the extent (in degrees, counter-clockwise).
     * @param majorTickIncrement  the interval between major tick marks
     * @param minorTickCount  the number of minor ticks between major tick
     *          marks.
     */
    public StandardDialScale(double lowerBound, double upperBound,
            double startAngle, double extent, double majorTickIncrement,
            int minorTickCount) {
        this.startAngle = startAngle;
        this.extent = extent;
        this.lowerBound = lowerBound;
        this.upperBound = upperBound;
        this.tickRadius = 0.70;
        this.tickLabelsVisible = true;
        this.tickLabelFormatter = new DecimalFormat("0.0");
        this.firstTickLabelVisible = true;
        //this.tickLabelFont = new Font("Dialog", Font.BOLD, 16);
        this.tickLabelFont = new Font();
        //this.tickLabelPaint = Color.blue;
        this.tickLabelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.tickLabelPaint.setColor(Color.BLUE);
        this.tickLabelOffset = 0.10;
        this.majorTickIncrement = majorTickIncrement;
        this.majorTickLength = 0.04;
        //this.majorTickPaint = Color.black;
        this.majorTickPaint =  new Paint(Paint.ANTI_ALIAS_FLAG);
        this.majorTickPaint.setColor(Color.BLACK);
        this.majorTickStroke = 3.0f;
        this.minorTickCount = minorTickCount;
        this.minorTickLength = 0.02;
        //this.minorTickPaint = Color.black;
        this.minorTickPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.minorTickPaint.setColor(Color.BLACK);
        this.minorTickStroke = 1.0f;
    }

    /**
     * Returns the lower bound for the scale.
     *
     * @return The lower bound for the scale.
     *
     * @see #setLowerBound(double)
     *
     * @since JFreeChart 1.0.8
     */
    public double getLowerBound() {
        return this.lowerBound;
    }

    /**
     * Sets the lower bound for the scale and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param lower  the lower bound.
     *
     * @see #getLowerBound()
     *
     * @since JFreeChart 1.0.8
     */
    public void setLowerBound(double lower) {
        this.lowerBound = lower;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the upper bound for the scale.
     *
     * @return The upper bound for the scale.
     *
     * @see #setUpperBound(double)
     *
     * @since JFreeChart 1.0.8
     */
    public double getUpperBound() {
        return this.upperBound;
    }

    /**
     * Sets the upper bound for the scale and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param upper  the upper bound.
     *
     * @see #getUpperBound()
     *
     * @since JFreeChart 1.0.8
     */
    public void setUpperBound(double upper) {
        this.upperBound = upper;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the start angle for the scale (in degrees using the same
     * orientation as Java's ArcShape class).
     *
     * @return The start angle.
     *
     * @see #setStartAngle(double)
     */
    public double getStartAngle() {
        return this.startAngle;
    }

    /**
     * Sets the start angle for the scale and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param angle  the angle (in degrees).
     *
     * @see #getStartAngle()
     */
    public void setStartAngle(double angle) {
        this.startAngle = angle;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the extent.
     *
     * @return The extent.
     *
     * @see #setExtent(double)
     */
    public double getExtent() {
        return this.extent;
    }

    /**
     * Sets the extent and sends a {@link DialLayerChangeEvent} to all
     * registered listeners.
     *
     * @param extent  the extent.
     *
     * @see #getExtent()
     */
    public void setExtent(double extent) {
        this.extent = extent;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the radius (as a percentage of the maximum space available) of
     * the outer limit of the tick marks.
     *
     * @return The tick radius.
     *
     * @see #setTickRadius(double)
     */
    public double getTickRadius() {
        return this.tickRadius;
    }

    /**
     * Sets the tick radius and sends a {@link DialLayerChangeEvent} to all
     * registered listeners.
     *
     * @param radius  the radius.
     *
     * @see #getTickRadius()
     */
    public void setTickRadius(double radius) {
        if (radius <= 0.0) {
            throw new IllegalArgumentException(
                    "The 'radius' must be positive.");
        }
        this.tickRadius = radius;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the increment (in data units) between major tick labels.
     *
     * @return The increment between major tick labels.
     *
     * @see #setMajorTickIncrement(double)
     */
    public double getMajorTickIncrement() {
        return this.majorTickIncrement;
    }

    /**
     * Sets the increment (in data units) between major tick labels and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param increment  the increment.
     *
     * @see #getMajorTickIncrement()
     */
    public void setMajorTickIncrement(double increment) {
        if (increment <= 0.0) {
            throw new IllegalArgumentException(
                    "The 'increment' must be positive.");
        }
        this.majorTickIncrement = increment;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the length factor for the major tick marks.  The value is
     * subtracted from the tick radius to determine the inner starting point
     * for the tick marks.
     *
     * @return The length factor.
     *
     * @see #setMajorTickLength(double)
     */
    public double getMajorTickLength() {
        return this.majorTickLength;
    }

    /**
     * Sets the length factor for the major tick marks and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param length  the length.
     *
     * @see #getMajorTickLength()
     */
    public void setMajorTickLength(double length) {
        if (length < 0.0) {
            throw new IllegalArgumentException("Negative 'length' argument.");
        }
        this.majorTickLength = length;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the major tick paint.
     *
     * @return The major tick paint (never null).
     *
     * @see #setMajorTickPaint(Paint)
     */
    public Paint getMajorTickPaint() {
        return this.majorTickPaint;
    }

    /**
     * Sets the major tick paint and sends a {@link DialLayerChangeEvent} to
     * all registered listeners.
     *
     * @param paint  the paint (null not permitted).
     *
     * @see #getMajorTickPaint()
     */
    public void setMajorTickPaint(Paint paint) {
        if (paint == null) {
            throw new IllegalArgumentException("Null 'paint' argument.");
        }
        this.majorTickPaint = paint;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the stroke used to draw the major tick marks.
     *
     * @return The stroke (never null).
     *
     * @see #setMajorTickStroke(Float stroke)
     */
    public Float getMajorTickStroke() {
        return this.majorTickStroke;
    }

    /**
     * Sets the stroke used to draw the major tick marks and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param stroke  the stroke (null not permitted).
     *
     * @see #getMajorTickStroke()
     */
    public void setMajorTickStroke(Float stroke) {
        if (stroke == null) {
            throw new IllegalArgumentException("Null 'stroke' argument.");
        }
        this.majorTickStroke = stroke;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the number of minor tick marks between major tick marks.
     *
     * @return The number of minor tick marks between major tick marks.
     *
     * @see #setMinorTickCount(int)
     */
    public int getMinorTickCount() {
        return this.minorTickCount;
    }

    /**
     * Sets the number of minor tick marks between major tick marks and sends
     * a {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param count  the count.
     *
     * @see #getMinorTickCount()
     */
    public void setMinorTickCount(int count) {
        if (count < 0) {
            throw new IllegalArgumentException(
                    "The 'count' cannot be negative.");
        }
        this.minorTickCount = count;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the length factor for the minor tick marks.  The value is
     * subtracted from the tick radius to determine the inner starting point
     * for the tick marks.
     *
     * @return The length factor.
     *
     * @see #setMinorTickLength(double)
     */
    public double getMinorTickLength() {
        return this.minorTickLength;
    }

    /**
     * Sets the length factor for the minor tick marks and sends
     * a {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param length  the length.
     *
     * @see #getMinorTickLength()
     */
    public void setMinorTickLength(double length) {
        if (length < 0.0) {
            throw new IllegalArgumentException("Negative 'length' argument.");
        }
        this.minorTickLength = length;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the paint used to draw the minor tick marks.
     *
     * @return The paint (never null).
     *
     * @see #setMinorTickPaint(Paint)
     */
    public Paint getMinorTickPaint() {
        return this.minorTickPaint;
    }

    /**
     * Sets the paint used to draw the minor tick marks and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param paint  the paint (null not permitted).
     *
     * @see #getMinorTickPaint()
     */
    public void setMinorTickPaint(Paint paint) {
        if (paint == null) {
            throw new IllegalArgumentException("Null 'paint' argument.");
        }
        this.minorTickPaint = paint;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the stroke used to draw the minor tick marks.
     *
     * @return The paint (never null).
     *
     * @see #setMinorTickStroke(Float stroke)
     *
     * @since JFreeChart 1.0.8
     */
    public Float getMinorTickStroke() {
        return this.minorTickStroke;
    }

    /**
     * Sets the stroke used to draw the minor tick marks and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param stroke  the stroke (null not permitted).
     *
     * @see #getMinorTickStroke()
     *
     * @since JFreeChart 1.0.8
     */
    public void setMinorTickStroke(Float stroke) {
        if (stroke == null) {
            throw new IllegalArgumentException("Null 'stroke' argument.");
        }
        this.minorTickStroke = stroke;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the tick label offset.
     *
     * @return The tick label offset.
     *
     * @see #setTickLabelOffset(double)
     */
    public double getTickLabelOffset() {
        return this.tickLabelOffset;
    }

    /**
     * Sets the tick label offset and sends a {@link DialLayerChangeEvent} to
     * all registered listeners.
     *
     * @param offset  the offset.
     *
     * @see #getTickLabelOffset()
     */
    public void setTickLabelOffset(double offset) {
        this.tickLabelOffset = offset;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the font used to draw the tick labels.
     *
     * @return The font (never null).
     *
     * @see #setTickLabelFont(Font)
     */
    public Font getTickLabelFont() {
        return this.tickLabelFont;
    }

    /**
     * Sets the font used to display the tick labels and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param font  the font (null not permitted).
     *
     * @see #getTickLabelFont()
     */
    public void setTickLabelFont(Font font) {
        if (font == null) {
            throw new IllegalArgumentException("Null 'font' argument.");
        }
        this.tickLabelFont = font;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the paint used to draw the tick labels.
     *
     * @return The paint (null not permitted).
     *
     * @see #setTickLabelPaint(Paint)
     */
    public Paint getTickLabelPaint() {
        return this.tickLabelPaint;
    }

    /**
     * Sets the paint used to draw the tick labels and sends a
     * {@link DialLayerChangeEvent} to all registered listeners.
     *
     * @param paint  the paint (null not permitted).
     */
    public void setTickLabelPaint(Paint paint) {
        if (paint == null) {
            throw new IllegalArgumentException("Null 'paint' argument.");
        }
        this.tickLabelPaint = paint;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns true if the tick labels should be displayed,
     * and false otherwise.
     *
     * @return A boolean.
     *
     * @see #setTickLabelsVisible(boolean)
     */
    public boolean getTickLabelsVisible() {
        return this.tickLabelsVisible;
    }

    /**
     * Sets the flag that controls whether or not the tick labels are
     * displayed, and sends a {@link DialLayerChangeEvent} to all registered
     * listeners.
     *
     * @param visible  the new flag value.
     *
     * @see #getTickLabelsVisible()
     */
    public void setTickLabelsVisible(boolean visible) {
        this.tickLabelsVisible = visible;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns the number formatter used to convert the tick label values to
     * strings.
     *
     * @return The formatter (never null).
     *
     * @see #setTickLabelFormatter(NumberFormat)
     */
    public NumberFormat getTickLabelFormatter() {
        return this.tickLabelFormatter;
    }

    /**
     * Sets the number formatter used to convert the tick label values to
     * strings, and sends a {@link DialLayerChangeEvent} to all registered
     * listeners.
     *
     * @param formatter  the formatter (null not permitted).
     *
     * @see #getTickLabelFormatter()
     */
    public void setTickLabelFormatter(NumberFormat formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("Null 'formatter' argument.");
        }
        this.tickLabelFormatter = formatter;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns a flag that controls whether or not the first tick label is
     * visible.
     *
     * @return A boolean.
     *
     * @see #setFirstTickLabelVisible(boolean)
     */
    public boolean getFirstTickLabelVisible() {
        return this.firstTickLabelVisible;
    }

    /**
     * Sets a flag that controls whether or not the first tick label is
     * visible, and sends a {@link DialLayerChangeEvent} to all registered
     * listeners.
     *
     * @param visible  the new flag value.
     *
     * @see #getFirstTickLabelVisible()
     */
    public void setFirstTickLabelVisible(boolean visible) {
        this.firstTickLabelVisible = visible;
        notifyListeners(new DialLayerChangeEvent(this));
    }

    /**
     * Returns true to indicate that this layer should be
     * clipped within the dial window.
     *
     * @return true.
     */
    public boolean isClippedToWindow() {
        return true;
    }

    /**
     * Draws the scale on the dial plot.
     *
     * @param canvas  the graphics target (null not permitted).
     * @param plot  the dial plot (null not permitted).
     * @param frame  the reference frame that is used to construct the
     *     geometry of the plot (null not permitted).
     * @param view  the visible part of the plot (null not
     *     permitted).
     */
    public void draw(Canvas canvas, DialPlot plot, RectShape frame,
            Shape view) {

        RectShape arcRect = DialPlot.RectShapeByRadius(frame,
                this.tickRadius, this.tickRadius);
        RectShape arcRectMajor = DialPlot.RectShapeByRadius(frame,
                this.tickRadius - this.majorTickLength,
                this.tickRadius - this.majorTickLength);
        RectShape arcRectMinor = arcRect;
        if (this.minorTickCount > 0 && this.minorTickLength > 0.0) {
            arcRectMinor = DialPlot.RectShapeByRadius(frame,
                    this.tickRadius - this.minorTickLength,
                    this.tickRadius - this.minorTickLength);
        }
        RectShape arcRectForLabels = DialPlot.RectShapeByRadius(frame,
                this.tickRadius - this.tickLabelOffset,
                this.tickRadius - this.tickLabelOffset);

        boolean firstLabel = true;

        ArcShape arc = new ArcShape();
        LineShape workingLine = new LineShape();
        for (double v = this.lowerBound; v <= this.upperBound;
                v += this.majorTickIncrement) {
            arc.setArc(arcRect, this.startAngle, -(this.startAngle - valueToAngle(v)), true);
            PointF pt0 = arc.getEndPoint();
            arc.setArc(arcRectMajor, this.startAngle, -(this.startAngle - valueToAngle(v)), true);
            PointF pt1 = arc.getEndPoint();
            majorTickPaint.setStrokeWidth(majorTickStroke);
            workingLine.setLine(pt0, pt1);
            workingLine.draw(canvas, majorTickPaint);
            arc.setArc(arcRectForLabels, this.startAngle, -(this.startAngle - valueToAngle(v)), true);
            PointF pt2 = arc.getEndPoint();

            if (this.tickLabelsVisible) {
                if (!firstLabel || this.firstTickLabelVisible) {
                    tickLabelPaint.setTypeface(tickLabelFont.getTypeFace());
                    tickLabelPaint.setTextSize(tickLabelFont.getSize());
                    tickLabelPaint.setTextAlign(Align.CENTER);
                    canvas.drawText(this.tickLabelFormatter.format(v), pt2.x, pt2.y, tickLabelPaint);
//                    TextUtilities.drawAlignedString(
//                            this.tickLabelFormatter.format(v), canvas,
//                            (float) pt2.x, (float) pt2.y,
//                            TextAnchor.CENTER, tickLabelPaint);
                }
            }
            firstLabel = false;

            // now do the minor tick marks
            if (this.minorTickCount > 0 && this.minorTickLength > 0.0) {
                double minorTickIncrement = this.majorTickIncrement
                        / (this.minorTickCount + 1);
                for (int i = 0; i < this.minorTickCount; i++) {
                    double vv = v + ((i + 1) * minorTickIncrement);
                    if (vv >= this.upperBound) {
                        break;
                    }
                    double angle = valueToAngle(vv);

                    arc.setArc(arcRect, this.startAngle, -(this.startAngle - angle), true);
                    pt0 = arc.getEndPoint();
                    arc.setArc(arcRectMinor, this.startAngle, -(this.startAngle - angle), true);
                    PointF pt3 = arc.getEndPoint();
                    minorTickPaint.setStrokeWidth(minorTickStroke);
                    workingLine.setLine(pt0, pt3);
                    workingLine.draw(canvas, minorTickPaint);
                }
            }
        }
    }

    /**
     * Converts a data value to an angle against this scale.
     *
     * @param value  the data value.
     *
     * @return The angle (in degrees, using the same specification as Java's
     *     ArcShape class).
     *
     * @see #angleToValue(double)
     */
    public double valueToAngle(double value) {
        double range = this.upperBound - this.lowerBound;
        double unit = this.extent / range;
        return this.startAngle + unit * (value - this.lowerBound);
    }

    /**
     * Converts the given angle to a data value, based on this scale.
     *
     * @param angle  the angle.
     *
     * @return The data value.
     *
     * @see #valueToAngle(double)
     */
    public double angleToValue(double angle) {
        return Double.NaN;  // FIXME
    }

    /**
     * Tests this StandardDialScale for equality with an arbitrary
     * object.
     *
     * @param obj  the object (null permitted).
     *
     * @return A boolean.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof StandardDialScale)) {
            return false;
        }
        StandardDialScale that = (StandardDialScale) obj;
        if (this.lowerBound != that.lowerBound) {
            return false;
        }
        if (this.upperBound != that.upperBound) {
            return false;
        }
        if (this.startAngle != that.startAngle) {
            return false;
        }
        if (this.extent != that.extent) {
            return false;
        }
        if (this.tickRadius != that.tickRadius) {
            return false;
        }
        if (this.majorTickIncrement != that.majorTickIncrement) {
            return false;
        }
        if (this.majorTickLength != that.majorTickLength) {
            return false;
        }
//        if (!PaintUtilities.equal(this.majorTickPaint, that.majorTickPaint)) {
//            return false;
//        }
        if (!this.majorTickStroke.equals(that.majorTickStroke)) {
            return false;
        }
        if (this.minorTickCount != that.minorTickCount) {
            return false;
        }
        if (this.minorTickLength != that.minorTickLength) {
            return false;
        }
//        if (!PaintUtilities.equal(this.minorTickPaint, that.minorTickPaint)) {
//            return false;
//        }
        if (!this.minorTickStroke.equals(that.minorTickStroke)) {
            return false;
        }
        if (this.tickLabelsVisible != that.tickLabelsVisible) {
            return false;
        }
        if (this.tickLabelOffset != that.tickLabelOffset) {
            return false;
        }
        if (!this.tickLabelFont.equals(that.tickLabelFont)) {
            return false;
        }
//        if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) {
//            return false;
//        }
        return super.equals(obj);
    }

    /**
     * Returns a hash code for this instance.
     *
     * @return A hash code.
     */
    public int hashCode() {
        int result = 193;
        // lowerBound
        long temp = Double.doubleToLongBits(this.lowerBound);
        result = 37 * result + (int) (temp ^ (temp >>> 32));
        // upperBound
        temp = Double.doubleToLongBits(this.upperBound);
        result = 37 * result + (int) (temp ^ (temp >>> 32));
        // startAngle
        temp = Double.doubleToLongBits(this.startAngle);
        result = 37 * result + (int) (temp ^ (temp >>> 32));
        // extent
        temp = Double.doubleToLongBits(this.extent);
        result = 37 * result + (int) (temp ^ (temp >>> 32));
        // tickRadius
        temp = Double.doubleToLongBits(this.tickRadius);
        result = 37 * result + (int) (temp ^ (temp >>> 32));
        // majorTickIncrement
        // majorTickLength
        // majorTickPaint
        // majorTickStroke
        // minorTickCount
        // minorTickLength
        // minorTickPaint
        // minorTickStroke
        // tickLabelOffset
        // tickLabelFont
        // tickLabelsVisible
        // tickLabelFormatter
        // firstTickLabelsVisible
        return result;
    }

    /**
     * Returns a clone of this instance.
     *
     * @return A clone.
     *
     * @throws CloneNotSupportedException if this instance is not cloneable.
     */
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

//    /**
//     * Provides serialization support.
//     *
//     * @param stream  the output stream.
//     *
//     * @throws IOException  if there is an I/O error.
//     */
//    private void writeObject(ObjectOutputStream stream) throws IOException {
//        stream.defaultWriteObject();
//        SerialUtilities.writePaint(this.majorTickPaint, stream);
//        SerialUtilities.writeStroke(this.majorTickStroke, stream);
//        SerialUtilities.writePaint(this.minorTickPaint, stream);
//        SerialUtilities.writeStroke(this.minorTickStroke, stream);
//        SerialUtilities.writePaint(this.tickLabelPaint, stream);
//    }
//
//    /**
//     * Provides serialization support.
//     *
//     * @param stream  the input stream.
//     *
//     * @throws IOException  if there is an I/O error.
//     * @throws ClassNotFoundException  if there is a classpath problem.
//     */
//    private void readObject(ObjectInputStream stream)
//            throws IOException, ClassNotFoundException {
//        stream.defaultReadObject();
//        this.majorTickPaint = SerialUtilities.readPaint(stream);
//        this.majorTickStroke = SerialUtilities.readStroke(stream);
//        this.minorTickPaint = SerialUtilities.readPaint(stream);
//        this.minorTickStroke = SerialUtilities.readStroke(stream);
//        this.tickLabelPaint = SerialUtilities.readPaint(stream);
//    }

}


text:
<?xml version="1.0"?>
<Order>
  <orderId>some string</orderId>
  <orderDate>2000-01-23</orderDate>
  <hasOrderDetails>
    <OrderDetails>externally-referenced-instance</OrderDetails>
  </hasOrderDetails>
</Order>


text:
"""
Product tests for SSH authentication for presto-admin commands
"""

import os
import subprocess

from nose.plugins.attrib import attr

from tests.product.base_product_case import BaseProductTestCase, \
    LOCAL_RESOURCES_DIR

class TestAuthentication(BaseProductTestCase):
    def setUp(self):
        super(TestAuthentication, self).setUp()
        self.setup_docker_cluster()

    success_output = (
        'Deploying tpch.properties connector configurations on: slave1 \n'
        'Deploying tpch.properties connector configurations on: master \n'
        'Deploying tpch.properties connector configurations on: slave2 \n'
        'Deploying tpch.properties connector configurations on: slave3 \n'
    )

    interactive_text = (
        '/usr/lib64/python2.6/getpass.py:83: GetPassWarning: Can not control '
        'echo on the terminal.\n'
        'Initial value for env.password: \n'
        'Warning: Password input may be echoed.\n'
        '  passwd = fallback_getpass(prompt, stream)\n'
    )

    sudo_password_prompt = (
        '[master] out: sudo password:\n'
        '[master] out: \n'
        '[slave1] out: sudo password:\n'
        '[slave1] out: \n'
        '[slave2] out: sudo password:\n'
        '[slave2] out: \n'
        '[slave3] out: sudo password:\n'
        '[slave3] out: \n'
    )

    @attr('smoketest')
    def test_incorrect_hostname(self):
        self.install_presto_admin(self.docker_cluster)
        topology = {'coordinator': 'dummy_master',
                    'workers': ['slave1', 'slave2', 'slave3']}
        self.upload_topology(topology=topology)
        command_output = self.run_prestoadmin('--extended-help',
                                              raise_error=False)
        self.assertEqual('u\'dummy_master\' is not a valid ip address or host '
                         'name.  More detailed information can be found in '
                         '/var/log/prestoadmin/presto-admin.log\n',
                         command_output)

    def parallel_password_failure_message(self, with_sudo_prompt=True):
        with open(os.path.join(LOCAL_RESOURCES_DIR,
                               'parallel_password_failure.txt')) as f:
            parallel_password_failure = f.read()
        if with_sudo_prompt:
            parallel_password_failure += (
                '[%(slave3)s] out: sudo password:\n'
                '[%(slave3)s] out: Sorry, try again.\n'
                '[%(slave2)s] out: sudo password:\n'
                '[%(slave2)s] out: Sorry, try again.\n'
                '[%(slave1)s] out: sudo password:\n'
                '[%(slave1)s] out: Sorry, try again.\n'
                '[%(master)s] out: sudo password:\n'
                '[%(master)s] out: Sorry, try again.\n')
        parallel_password_failure = parallel_password_failure % {
            'master': self.docker_cluster.internal_master,
            'slave1': self.docker_cluster.internal_slaves[0],
            'slave2': self.docker_cluster.internal_slaves[1],
            'slave3': self.docker_cluster.internal_slaves[2]}
        return parallel_password_failure

    def non_root_sudo_warning_message(self):
        with open(os.path.join(LOCAL_RESOURCES_DIR,
                               'non_root_sudo_warning_text.txt')) as f:
            non_root_sudo_warning = f.read()
        return non_root_sudo_warning

    @attr('smoketest')
    def test_passwordless_ssh_authentication(self):
        self.install_presto_admin(self.docker_cluster)
        self.upload_topology()
        self.setup_for_connector_add()

        # Passwordless SSH as root, but specify -I
        # We need to do it as a script because docker_py doesn't support
        # redirecting stdin.
        command_output = self.run_prestoadmin_script(
            'echo "password" | ./presto-admin connector add -I')

        self.assertEqualIgnoringOrder(
            self.success_output + self.interactive_text, command_output)

        # Passwordless SSH as root, but specify -p
        command_output = self.run_prestoadmin('connector add --password '
                                              'password')
        self.assertEqualIgnoringOrder(self.success_output, command_output)

        # Passwordless SSH as app-admin, specify -I
        non_root_sudo_warning = self.non_root_sudo_warning_message()

        command_output = self.run_prestoadmin_script(
            'echo "password" | ./presto-admin connector add -I -u app-admin')
        self.assertEqualIgnoringOrder(
            self.success_output + self.interactive_text +
            non_root_sudo_warning, command_output)

        # Passwordless SSH as app-admin, but specify -p
        command_output = self.run_prestoadmin('connector add --password '
                                              'password -u app-admin')
        self.assertEqualIgnoringOrder(
            self.success_output + self.sudo_password_prompt, command_output)

        # Passwordless SSH as app-admin, but specify wrong password with -I
        parallel_password_failure = self.parallel_password_failure_message()
        command_output = self.run_prestoadmin_script(
            'echo "asdf" | ./presto-admin connector add -I -u app-admin')
        self.assertEqualIgnoringOrder(parallel_password_failure +
                                      self.interactive_text, command_output)

        # Passwordless SSH as app-admin, but specify wrong password with -p
        command_output = self.run_prestoadmin(
            'connector add --password asdf -u app-admin')
        self.assertEqualIgnoringOrder(parallel_password_failure,
                                      command_output)

        # Passwordless SSH as root, in serial mode
        command_output = self.run_prestoadmin_script(
            './presto-admin connector add --serial')
        self.assertEqualIgnoringOrder(
            self.success_output, command_output)

    @attr('smoketest')
    def test_no_passwordless_ssh_authentication(self):
        self.install_presto_admin(self.docker_cluster)
        self.upload_topology()
        self.setup_for_connector_add()

        # This is needed because the test for
        # No passwordless SSH, -I correct -u app-admin,
        # was giving Device not a stream error in jenkins
        self.run_prestoadmin_script(
            'echo "password" | ./presto-admin connector add -I')

        for host in self.docker_cluster.all_hosts():
            self.docker_cluster.exec_cmd_on_container(host,
                                                      'rm /root/.ssh/id_rsa')

        # No passwordless SSH, no -I or -p
        parallel_password_failure = self.parallel_password_failure_message(
            with_sudo_prompt=False)
        command_output = self.run_prestoadmin('connector add')
        self.assertEqualIgnoringOrder(parallel_password_failure,
                                      command_output)

        # No passwordless SSH, -p incorrect -u root
        command_output = self.run_prestoadmin(
            'connector add --password password')
        self.assertEqualIgnoringOrder(parallel_password_failure,
                                      command_output)

        # No passwordless SSH, -I correct -u app-admin
        non_root_sudo_warning = self.non_root_sudo_warning_message()
        command_output = self.run_prestoadmin_script(
            'echo "password" | ./presto-admin connector add -I -u app-admin')
        self.assertEqualIgnoringOrder(
            self.success_output + self.interactive_text +
            non_root_sudo_warning, command_output)

        # No passwordless SSH, -p correct -u app-admin
        command_output = self.run_prestoadmin('connector add -p password '
                                              '-u app-admin')
        self.assertEqualIgnoringOrder(
            self.success_output + self.sudo_password_prompt, command_output)

        # No passwordless SSH, specify keyfile with -i
        self.docker_cluster.exec_cmd_on_container(
            self.docker_cluster.master,
            'cp /home/app-admin/.ssh/id_rsa /root/.ssh/id_rsa.bak')
        self.docker_cluster.exec_cmd_on_container(
            self.docker_cluster.master, 'chmod 600 /root/.ssh/id_rsa.bak')
        command_output = self.run_prestoadmin(
            'connector add -i /root/.ssh/id_rsa.bak')
        self.assertEqualIgnoringOrder(self.success_output, command_output)

    @attr('smoketest')
    def test_prestoadmin_no_sudo_popen(self):
        self.install_presto_admin(self.docker_cluster)
        self.upload_topology()
        self.setup_for_connector_add()

        # We use Popen because docker-py loses the first 8 characters of TTY
        # output.
        args = ['docker', 'exec', '-t', self.docker_cluster.master, 'sudo',
                '-u', 'app-admin', '/opt/prestoadmin/presto-admin',
                'topology show']
        proc = subprocess.Popen(args, stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        self.assertEqualIgnoringOrder(
            'Please run presto-admin with sudo.\n'
            '[Errno 13] Permission denied: \'/var/log/prestoadmin/'
            'presto-admin.log\'', proc.stdout.read())

    def setup_for_connector_add(self):
        connector_script = 'mkdir -p /etc/opt/prestoadmin/connectors\n' \
                           'echo \'connector.name=tpch\' ' \
                           '>> /etc/opt/prestoadmin/connectors/' \
                           'tpch.properties\n'
        self.run_prestoadmin_script(connector_script)


text:
import {
  clickable,
  collection,
  is,
  isVisible,
  text
} from 'ember-cli-page-object';

import cardItem from './card-item';

export default {
  scope: '.donation-container',

  cardFormIsVisible: isVisible('.ember-stripe-card'),
  donationButtonIsVisible: isVisible('button.donate'),

  clickCancel: clickable('div.cancel-add-card a'),
  clickSubmit: clickable('button'),

  donationAmountText: text('.donation-container__amount'),
  paymentInformationText: text('.donation-container__information'),

  cards: collection('.card-item', cardItem),

  submitButtonIsVisible: isVisible('button'),
  submitButtonText: text('button'),
  submitDisabled: is(':disabled', 'button')
};


text:
package com.business.data;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 * Created by zakaria on 18/07/2016.
 */
public abstract class DAO {

    /**
     * Constante representant le nom d'unité de persistence à utiliser (déclarée dans le fichier persistence.xml)
     **/
    private static final String _PERSISTENCE_UNIT = "MarsaMaroc";

    /**
     * Instance unique de type EntityManager
     **/
    private static EntityManager _EM = null;

    /**
     * Cette méthode permet d'initialiser et récupérer l'instance unique de type EntityManager.
     * @return   instance EntityManager
     * @see EntityManager
     */
    public synchronized static EntityManager getEntityManager(){
        if(_EM!=null) return _EM;
        _EM = Persistence.createEntityManagerFactory(_PERSISTENCE_UNIT).createEntityManager();
        return _EM;
    }
}


text:
package org.elasticsearch.http;

import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Scope;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;

import java.util.List;

import static java.util.Collections.emptyList;
import static org.elasticsearch.common.settings.Setting.listSetting;

public final class HttpTransportSettings {

    public static final Setting<Boolean> SETTING_CORS_ENABLED = Setting.boolSetting("http.cors.enabled", false, false, Scope.CLUSTER);
    public static final Setting<String> SETTING_CORS_ALLOW_ORIGIN = new Setting<String>("http.cors.allow-origin", "", (value) -> value, false, Scope.CLUSTER);
    public static final Setting<Integer> SETTING_CORS_MAX_AGE = Setting.intSetting("http.cors.max-age", 1728000, false, Scope.CLUSTER);
    public static final Setting<String> SETTING_CORS_ALLOW_METHODS = new Setting<String>("http.cors.allow-methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE", (value) -> value, false, Scope.CLUSTER);
    public static final Setting<String> SETTING_CORS_ALLOW_HEADERS = new Setting<String>("http.cors.allow-headers", "X-Requested-With, Content-Type, Content-Length", (value) -> value, false, Scope.CLUSTER);
    public static final Setting<Boolean> SETTING_CORS_ALLOW_CREDENTIALS = Setting.boolSetting("http.cors.allow-credentials", false, false, Scope.CLUSTER);
    public static final Setting<Boolean> SETTING_PIPELINING = Setting.boolSetting("http.pipelining", true, false, Scope.CLUSTER);
    public static final Setting<Integer> SETTING_PIPELINING_MAX_EVENTS = Setting.intSetting("http.pipelining.max_events", 10000, false, Scope.CLUSTER);
    public static final Setting<Boolean> SETTING_HTTP_COMPRESSION = Setting.boolSetting("http.compression", false, false, Scope.CLUSTER);
    public static final Setting<Integer> SETTING_HTTP_COMPRESSION_LEVEL = Setting.intSetting("http.compression_level", 6, false, Scope.CLUSTER);
    public static final Setting<List<String>> SETTING_HTTP_HOST = listSetting("http.host", emptyList(), s -> s, false, Scope.CLUSTER);
    public static final Setting<List<String>> SETTING_HTTP_PUBLISH_HOST = listSetting("http.publish_host", SETTING_HTTP_HOST, s -> s, false, Scope.CLUSTER);
    public static final Setting<List<String>> SETTING_HTTP_BIND_HOST = listSetting("http.bind_host", SETTING_HTTP_HOST, s -> s, false, Scope.CLUSTER);

    public static final Setting<PortsRange> SETTING_HTTP_PORT = new Setting<PortsRange>("http.port", "9200-9300", PortsRange::new, false, Scope.CLUSTER);
    public static final Setting<Integer> SETTING_HTTP_PUBLISH_PORT = Setting.intSetting("http.publish_port", 0, 0, false, Scope.CLUSTER);
    public static final Setting<Boolean> SETTING_HTTP_DETAILED_ERRORS_ENABLED = Setting.boolSetting("http.detailed_errors.enabled", true, false, Scope.CLUSTER);
    public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_CONTENT_LENGTH = Setting.byteSizeSetting("http.max_content_length", new ByteSizeValue(100, ByteSizeUnit.MB), false, Scope.CLUSTER) ;
    public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_CHUNK_SIZE = Setting.byteSizeSetting("http.max_chunk_size", new ByteSizeValue(8, ByteSizeUnit.KB), false, Scope.CLUSTER) ;
    public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_HEADER_SIZE = Setting.byteSizeSetting("http.max_header_size", new ByteSizeValue(8, ByteSizeUnit.KB), false, Scope.CLUSTER) ;
    public static final Setting<ByteSizeValue> SETTING_HTTP_MAX_INITIAL_LINE_LENGTH = Setting.byteSizeSetting("http.max_initial_line_length", new ByteSizeValue(4, ByteSizeUnit.KB), false, Scope.CLUSTER) ;
    // don't reset cookies by default, since I don't think we really need to
    // note, parsing cookies was fixed in netty 3.5.1 regarding stack allocation, but still, currently, we don't need cookies
    public static final Setting<Boolean> SETTING_HTTP_RESET_COOKIES = Setting.boolSetting("http.reset_cookies", false, false, Scope.CLUSTER);

    private HttpTransportSettings() {
    }
}


text:
package io.github.binaryfoo.decoders;

import io.github.binaryfoo.tlv.ISOUtil;
import io.github.binaryfoo.tlv.Tag;
import org.junit.Test;

import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class DOLParserTest {

  @Test
  public void testParse() {
    List<DOLParser.DOLElement> elements = new DOLParser().parse(ISOUtil.hex2byte("9F66049F02069F03069F1A0295055F2A029A039C019F3704"));
    assertThat(elements.size(), is(9));
    assertThat(elements.get(0), is(new DOLParser.DOLElement(Tag.fromHex("9F66"), 4)));
    assertThat(elements.get(8), is(new DOLParser.DOLElement(Tag.fromHex("9F37"), 4)));
  }
}


text:
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
A sample Github project that reproduces the problem is ideal. Alternatively, please provide a failing unit test that triggers the bug.

**Expected behavior**
A clear and concise description of what you expected to happen.

**Additional context**
Add any other context about the problem here.


text:
/*
 *  jQuery Boilerplate - v3.3.4
 *  A jump-start for jQuery plugins development.
 *  http://jqueryboilerplate.com
 *
 *  Made by Zeno Rocha
 *  Under MIT License
 */
!function(a){function b(b,e){this.element=b,this.settings=a.extend({},d,e),this._defaults=d,this._name=c,this.init()}var c="defaultPluginName",d={propertyName:"value"};a.extend(b.prototype,{init:function(){console.log("xD")},yourOtherFunction:function(){}}),a.fn[c]=function(d){return this.each(function(){a.data(this,"plugin_"+c)||a.data(this,"plugin_"+c,new b(this,d))}),this}}(jQuery,window,document);


text:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../../anaconda_lib'))

from .qa_handler import QAHandler
from .jedi_handler import JediHandler
from .autoformat_handler import AutoFormatHandler
from .python_lint_handler import PythonLintHandler

ANACONDA_HANDLERS = {
    'qa': QAHandler,
    'jedi': JediHandler,
    'autoformat': AutoFormatHandler,
    'python_linter': PythonLintHandler
}

__all__ = [
    'QAHandler', 'JediHandler', 'AutoFormatHandler', 'PythonLintHandler',
    'ANACONDA_HANDLERS'
]


text:
CF Tools
========

A library for collaborative filtering and similarity-based
recommendations.


text:
package model;

import java.awt.Image;
import java.awt.Point;

import javax.swing.ImageIcon;

import control.Control;

/**
 *
 * 'þÐÅÏ¢
 *
 * @author MOVELIGHTS
 *
 */
public class EffectModel extends Tick implements Port {

	Point loction = new Point(0,0);

	/**
	 * ÏÔʾͼƬԴ
	 */
	private Image[] img = null;
	/**
	 *
	 * »ðÑÛЧ¹û¿ªÊ¼
	 *
	 */
	private Image[] imgStart1 = {
			 new ImageIcon("images/effect/start1/0.png").getImage(),
			 new ImageIcon("images/effect/start1/1.png").getImage(),
			 new ImageIcon("images/effect/start1/2.png").getImage(),
			 new ImageIcon("images/effect/start1/3.png").getImage(),
			 new ImageIcon("images/effect/start1/4.png").getImage(),
			 new ImageIcon("images/effect/start1/5.png").getImage(),
			 new ImageIcon("images/effect/start1/6.png").getImage(),
			 new ImageIcon("images/effect/start1/7.png").getImage(),
			 new ImageIcon("images/effect/start1/8.png").getImage(),
			 new ImageIcon("images/effect/start1/9.png").getImage(),
			 new ImageIcon("images/effect/start1/10.png").getImage(),
			 new ImageIcon("images/effect/start1/11.png").getImage(),
			 new ImageIcon("images/effect/start1/12.png").getImage(),
			 new ImageIcon("images/effect/start1/13.png").getImage(),
			 new ImageIcon("images/effect/start1/14.png").getImage()
	};

	/**
	 *
	 * WINЧ¹û
	 *
	 */
	private Image[] win = {
			 new ImageIcon("images/effect/win/0.png").getImage(),
			 new ImageIcon("images/effect/win/1.png").getImage(),
			 new ImageIcon("images/effect/win/2.png").getImage(),
			 new ImageIcon("images/effect/win/3.png").getImage(),
			 new ImageIcon("images/effect/win/4.png").getImage(),
			 new ImageIcon("images/effect/win/5.png").getImage(),
			 new ImageIcon("images/effect/win/6.png").getImage(),
			 new ImageIcon("images/effect/win/7.png").getImage(),
			 new ImageIcon("images/effect/win/8.png").getImage(),
			 new ImageIcon("images/effect/win/9.png").getImage(),
			 new ImageIcon("images/effect/win/10.png").getImage(),
			 new ImageIcon("images/effect/win/11.png").getImage(),
			 new ImageIcon("images/effect/win/12.png").getImage(),
			 new ImageIcon("images/effect/win/13.png").getImage()
	};
	/**
	 *
	 * Ô²»¬Ð§¹û¿ªÊ¼
	 *
	 */
	private Image[] imgStart2 = {
			 new ImageIcon("images/effect/start2/0.png").getImage(),
			 new ImageIcon("images/effect/start2/1.png").getImage(),
			 new ImageIcon("images/effect/start2/2.png").getImage(),
			 new ImageIcon("images/effect/start2/3.png").getImage(),
			 new ImageIcon("images/effect/start2/4.png").getImage(),
			 new ImageIcon("images/effect/start2/5.png").getImage(),
			 new ImageIcon("images/effect/start2/6.png").getImage(),
			 new ImageIcon("images/effect/start2/7.png").getImage(),
			 new ImageIcon("images/effect/start2/8.png").getImage(),
			 new ImageIcon("images/effect/start2/9.png").getImage(),
			 new ImageIcon("images/effect/start2/10.png").getImage()
	};
	/**
	 *
	 * ÓÎÏ·½áÊøЧ¹û¿ªÊ¼
	 *
	 */
	private Image[] timeover = {
			 new ImageIcon("images/effect/timeover/0.png").getImage(),
			 new ImageIcon("images/effect/timeover/1.png").getImage(),
			 new ImageIcon("images/effect/timeover/2.png").getImage(),
			 new ImageIcon("images/effect/timeover/3.png").getImage(),
			 new ImageIcon("images/effect/timeover/4.png").getImage(),
			 new ImageIcon("images/effect/timeover/5.png").getImage(),
			 new ImageIcon("images/effect/timeover/6.png").getImage(),
			 new ImageIcon("images/effect/timeover/7.png").getImage(),
			 new ImageIcon("images/effect/timeover/8.png").getImage(),
			 new ImageIcon("images/effect/timeover/9.png").getImage(),
			 new ImageIcon("images/effect/timeover/10.png").getImage(),
			 new ImageIcon("images/effect/timeover/11.png").getImage(),
			 new ImageIcon("images/effect/timeover/12.png").getImage(),
			 new ImageIcon("images/effect/timeover/13.png").getImage(),
			 new ImageIcon("images/effect/timeover/14.png").getImage(),
			 new ImageIcon("images/effect/timeover/15.png").getImage(),
			 new ImageIcon("images/effect/timeover/16.png").getImage()

	};

	/**
	 *
	 * ÓÎÏ·½áÊøЧ¹û¿ªÊ¼
	 *
	 */
	private Image[] timeover2 = {
			 new ImageIcon("images/effect/timeover2/0.png").getImage(),
			 new ImageIcon("images/effect/timeover2/1.png").getImage(),
			 new ImageIcon("images/effect/timeover2/2.png").getImage(),
			 new ImageIcon("images/effect/timeover2/3.png").getImage(),
			 new ImageIcon("images/effect/timeover2/4.png").getImage(),
			 new ImageIcon("images/effect/timeover2/5.png").getImage(),
			 new ImageIcon("images/effect/timeover2/6.png").getImage(),
			 new ImageIcon("images/effect/timeover2/7.png").getImage(),
			 new ImageIcon("images/effect/timeover2/8.png").getImage(),
			 new ImageIcon("images/effect/timeover2/9.png").getImage(),
			 new ImageIcon("images/effect/timeover2/10.png").getImage(),
			 new ImageIcon("images/effect/timeover2/11.png").getImage(),
			 new ImageIcon("images/effect/timeover2/12.png").getImage(),
			 new ImageIcon("images/effect/timeover2/13.png").getImage()
	};
	/**
	 *
	 * ÓÎÏ·½áÊøЧ¹û¿ªÊ¼
	 *
	 */
	private Image[] win_ = {
			 new ImageIcon("images/effect/win_/0.png").getImage(),
			 new ImageIcon("images/effect/win_/1.png").getImage(),
			 new ImageIcon("images/effect/win_/2.png").getImage(),
			 new ImageIcon("images/effect/win_/3.png").getImage(),
			 new ImageIcon("images/effect/win_/4.png").getImage(),
			 new ImageIcon("images/effect/win_/5.png").getImage(),
			 new ImageIcon("images/effect/win_/6.png").getImage(),
			 new ImageIcon("images/effect/win_/7.png").getImage(),
			 new ImageIcon("images/effect/win_/8.png").getImage(),
			 new ImageIcon("images/effect/win_/9.png").getImage(),
			 new ImageIcon("images/effect/win_/10.png").getImage(),
			 new ImageIcon("images/effect/win_/11.png").getImage(),
			 new ImageIcon("images/effect/win_/12.png").getImage(),
			 new ImageIcon("images/effect/win_/13.png").getImage()
	};
	/**
	 *
	 * ÓÎÏ·½áÊøЧ¹û¿ªÊ¼
	 *
	 */
	private Image[] lose_ = {
			new ImageIcon("images/effect/lose_/0.png").getImage(),
			 new ImageIcon("images/effect/lose_/1.png").getImage(),
			 new ImageIcon("images/effect/lose_/2.png").getImage(),
			 new ImageIcon("images/effect/lose_/3.png").getImage(),
			 new ImageIcon("images/effect/lose_/4.png").getImage(),
			 new ImageIcon("images/effect/lose_/5.png").getImage(),
			 new ImageIcon("images/effect/lose_/6.png").getImage(),
			 new ImageIcon("images/effect/lose_/7.png").getImage(),
			 new ImageIcon("images/effect/lose_/8.png").getImage(),
			 new ImageIcon("images/effect/lose_/9.png").getImage(),
			 new ImageIcon("images/effect/lose_/10.png").getImage(),
			 new ImageIcon("images/effect/lose_/11.png").getImage(),
			 new ImageIcon("images/effect/lose_/12.png").getImage()
	};

	/**
	 * ÿÕÅͼƬÏÔʾ¼ä¸ô £¨/Ö¡Êý£©
	 */
	private int imageShowGap = 3;

	/**
	 *
	 * ÏÔʾͼƬ
	 *
	 */
	public void showImg(String effectName) {
		if (effectName.equals("start")){
			this.img = imgStart2;
		} else if (effectName.equals("win")) {
			this.img = win;
		} else if (effectName.equals("timeover")) {
			this.img = timeover;
		} else if (effectName.equals("timeover2")) {
			this.img = timeover2;
		} else if (effectName.equals("win_")) {
			this.img = win_;
		} else if (effectName.equals("lose_")) {
			this.img = lose_;
		}
		this.setStartTick(this.nowTick);
		this.setNextTick(this.nowTick + (img.length + 1) *(Control.rate / imageShowGap) - 1 );
	}

	public void showImg(String effectName,Point loction) {
		this.loction = loction;
		showImg(effectName);
	}
	public Image[] getImg() {
		return img;
	}

	public int getImageShowGap() {
		return imageShowGap;
	}

	@Override
	public void updata(long tick) {
		this.nowTick = tick;
	}

	@Override
	public void startGameInit() {
	}
}


text:
'use strict';

var helper = require('../../helpers/test.helper.js');

module.exports = function () {
    var get = function () {
        browser.get(helper.rootUrl + '/dashboard');
    };

    return {
        get: get
    };
};


text:
<?php
class tables_subject_comment {

  function getTitle(&$record){
		return $record->val('sc_person_name');
	}

	function titleColumn(){
		return 'sc_person_name';
	}

  function getPermissions(&$record){
    $auth =& Dataface_AuthenticationTool::getInstance();
    $user =& $auth->getLoggedInUser();
    if ( !isset($user) ) return Dataface_PermissionsTool::getRolePermissions('NO ACCESS');
    $role = $user->val('use_role');
    if ($role == 'TEACHER') {
      $perms = Dataface_PermissionsTool::getRolePermissions('READ ONLY');
      if (isset($record)) {
        if (my_static_funcs::UserIsClassTeacher($user,null,$record->val('sc_subject_id'))) {
          $perms = Dataface_PermissionsTool::getRolePermissions('EDIT');
        }
      } else {
        // hack: allow edit for all, otherwise class teachers can't create new comments via the relation in table subject
        $perms['edit'] = 1;
      }
      return $perms;
    } elseif ($role == 'MATRON') {
      return Dataface_PermissionsTool::getRolePermissions('NO ACCESS');
    }
    return Dataface_PermissionsTool::getRolePermissions($role);
  }
}

?>


text:
set system parameters 'return_null_on_function_errors=yes';

create table t1 (s1 varchar(20), sn1 nchar varying(20));

insert into t1 values ('2.1236',n'3.1234');
select trunc(s1,sn1) from t1;
select trunc(sn1,s1) from t1;

truncate table t1;

insert into t1 values ('asd',n'asd');
select trunc(s1,1) from t1;
select trunc(2.23,sn1) from t1;

drop table t1;

select trunc('1.123',1);

select trunc('123','1');

select trunc(n'123','1.1');

select trunc('asd',1);

select trunc(1.523,n'1');

-- 2HV
prepare st from 'select trunc(?,?)'
execute st using '2.1234e0',3;

prepare st from 'select trunc(?,?)'
execute st using '1.123','2';

prepare st from 'select trunc(?,?)'
execute st using 'asd',2;

-- 1HV
prepare st from 'select trunc(?,1)'
execute st using '2001-10-11';

prepare st from 'select trunc(?,1)'
execute st using '1.1234';

prepare st from 'select trunc(1.123,?)'
execute st using '2001-10-11';

prepare st from 'select trunc(1.123,?)'
execute st using '1';

set system parameters 'return_null_on_function_errors=no';commit;
--+ holdcas off;


text:
class TheaterList;

struct TheaterDef
{
    char *m_name;
    char *m_description;
    char *m_terrain;
    char *m_campaign;
    char *m_bitmap;
    char *m_artdir;
    char *m_uisounddir;
    char *m_moviedir;
    char *m_objectdir;
    char *m_3ddatadir;
    char *m_misctexdir;
    int m_mintacan;
    char *m_sounddir;
    // RV - Biker
    char *m_cockpitdir;
    char *m_zipsdir;
    char *m_tacrefdir;
    char *m_splashdir;

    TheaterDef *m_next; // link
};

class TheaterList
{
    TheaterDef *m_first;
    int m_count;
public:
    TheaterDef * FindTheaterByName(const char *name);
    TheaterDef * GetCurrentTheater();
    void SetCurrentTheater(TheaterDef *td);
    bool SetNewTheater(TheaterDef *td);
    bool ChooseTheaterByName(const char *name);
    TheaterList() : m_count(0), m_first(0) {};
    ~TheaterList();
    void AddTheater(TheaterDef *ntheater);
    void DoSoundSetup();

    TheaterDef *GetTheater(int n);
    int Count()
    {
        return m_count;
    };
private:
    void SetPathName(char *dest, char *src, char *reldir);
};

extern TheaterList g_theaters;
#endif


text:
import TestResolverApplicationTestCase from './test-resolver-application';
import Application from '@ember/application';
import { Router } from '@ember/-internals/routing';
import { assign } from '@ember/polyfills';

import { runTask, runLoopSettled } from '../run';

export default class ApplicationTestCase extends TestResolverApplicationTestCase {
  constructor() {
    super(...arguments);

    let { applicationOptions } = this;
    this.application = runTask(this.createApplication.bind(this, applicationOptions));

    this.resolver = this.application.__registry__.resolver;

    if (this.resolver) {
      this.resolver.add('router:main', Router.extend(this.routerOptions));
    }
  }

  createApplication(myOptions = {}, MyApplication = Application) {
    return MyApplication.create(myOptions);
  }

  get applicationOptions() {
    return assign(super.applicationOptions, {
      autoboot: false,
    });
  }

  get appRouter() {
    return this.applicationInstance.lookup('router:main');
  }

  async transitionTo() {
    await this.appRouter.transitionTo(...arguments);

    await runLoopSettled();
  }
}