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

package com.azure.messaging.servicebus.administration;

import com.azure.core.exception.ResourceExistsException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.test.TestBase;
import com.azure.messaging.servicebus.TestUtils;
import com.azure.messaging.servicebus.administration.models.AccessRights;
import com.azure.messaging.servicebus.administration.models.CreateQueueOptions;
import com.azure.messaging.servicebus.administration.models.CreateSubscriptionOptions;
import com.azure.messaging.servicebus.administration.models.CreateTopicOptions;
import com.azure.messaging.servicebus.administration.models.EmptyRuleAction;
import com.azure.messaging.servicebus.administration.models.NamespaceType;
import com.azure.messaging.servicebus.administration.models.QueueRuntimeProperties;
import com.azure.messaging.servicebus.administration.models.RuleProperties;
import com.azure.messaging.servicebus.administration.models.SharedAccessAuthorizationRule;
import com.azure.messaging.servicebus.administration.models.SubscriptionRuntimeProperties;
import com.azure.messaging.servicebus.administration.models.TopicProperties;
import com.azure.messaging.servicebus.administration.models.TopicRuntimeProperties;
import com.azure.messaging.servicebus.administration.models.TrueRuleFilter;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import reactor.test.StepVerifier;

import java.time.Clock;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

import static com.azure.messaging.servicebus.TestUtils.assertAuthorizationRules;
import static com.azure.messaging.servicebus.TestUtils.getEntityName;
import static com.azure.messaging.servicebus.TestUtils.getSessionSubscriptionBaseName;
import static com.azure.messaging.servicebus.TestUtils.getSubscriptionBaseName;
import static com.azure.messaging.servicebus.TestUtils.getTopicBaseName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Tests {@link ServiceBusAdministrationAsyncClient}.
 */
@Tag("integration")
class ServiceBusAdministrationAsyncClientIntegrationTest extends TestBase {
    private static final Duration TIMEOUT = Duration.ofSeconds(20);

    @BeforeAll
    static void beforeAll() {
        StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
    }

    @AfterAll
    static void afterAll() {
        StepVerifier.resetDefaultTimeout();
    }

    static Stream<Arguments> createHttpClients() {
        return Stream.of(
            Arguments.of(new NettyAsyncHttpClientBuilder().build())
        );
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void createQueue(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = testResourceNamer.randomName("test", 10);
        final CreateQueueOptions expected = new CreateQueueOptions()
            .setMaxSizeInMegabytes(1024)
            .setMaxDeliveryCount(7)
            .setLockDuration(Duration.ofSeconds(45))
            .setRequiresSession(true)
            .setRequiresDuplicateDetection(true)
            .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2))
            .setUserMetadata("some-metadata-for-testing");

        // Act & Assert
        StepVerifier.create(client.createQueue(queueName, expected))
            .assertNext(actual -> {
                assertEquals(queueName, actual.getName());

                assertEquals(expected.getLockDuration(), actual.getLockDuration());
                assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
                assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes());
                assertEquals(expected.getUserMetadata(), actual.getUserMetadata());

                assertEquals(expected.deadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration());
                assertEquals(expected.enablePartitioning(), actual.enablePartitioning());
                assertEquals(expected.requiresDuplicateDetection(), actual.requiresDuplicateDetection());
                assertEquals(expected.requiresSession(), actual.requiresSession());

                final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual);
                assertEquals(0, runtimeProperties.getTotalMessageCount());
                assertEquals(0, runtimeProperties.getSizeInBytes());
                assertNotNull(runtimeProperties.getCreatedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void createQueueExistingName(HttpClient httpClient) {
        // Arrange
        final String queueName = interceptorManager.isPlaybackMode()
            ? "queue-5"
            : getEntityName(TestUtils.getQueueBaseName(), 5);
        final CreateQueueOptions options = new CreateQueueOptions();
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);

        // Act & Assert
        StepVerifier.create(client.createQueue(queueName, options))
            .expectError(ResourceExistsException.class)
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void createQueueAuthorizationRules(HttpClient httpClient) {
        // Arrange
        final String keyName = "test-rule";
        final List<AccessRights> accessRights = Collections.singletonList(AccessRights.SEND);
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = testResourceNamer.randomName("test", 10);
        final SharedAccessAuthorizationRule rule = interceptorManager.isPlaybackMode()
            ? new SharedAccessAuthorizationRule(keyName, "Uobo65ke57pwWehaL9JzGXAK30MZgErqVyn5E+rHl1c=",
            "B4ENtK9Ze1nVMQ1mGdDsy9TuuQuGC4/K8q7OnPl8mn0=", accessRights)
            : new SharedAccessAuthorizationRule(keyName, accessRights);

        final CreateQueueOptions expected = new CreateQueueOptions()
            .setMaxSizeInMegabytes(1024)
            .setMaxDeliveryCount(7)
            .setLockDuration(Duration.ofSeconds(45))
            .setRequiresSession(true)
            .setRequiresDuplicateDetection(true)
            .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2))
            .setUserMetadata("some-metadata-for-testing");

        expected.getAuthorizationRules().add(rule);

        // Act & Assert
        StepVerifier.create(client.createQueue(queueName, expected))
            .assertNext(actual -> {
                assertEquals(queueName, actual.getName());

                assertEquals(expected.getLockDuration(), actual.getLockDuration());
                assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
                assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes());
                assertEquals(expected.getUserMetadata(), actual.getUserMetadata());

                assertEquals(expected.deadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration());
                assertEquals(expected.enablePartitioning(), actual.enablePartitioning());
                assertEquals(expected.requiresDuplicateDetection(), actual.requiresDuplicateDetection());
                assertEquals(expected.requiresSession(), actual.requiresSession());

                final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(actual);
                assertEquals(0, runtimeProperties.getTotalMessageCount());
                assertEquals(0, runtimeProperties.getSizeInBytes());
                assertNotNull(runtimeProperties.getCreatedAt());

                assertAuthorizationRules(expected.getAuthorizationRules(), actual.getAuthorizationRules());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void createSubscription(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-0"
            : getEntityName(getTopicBaseName(), 0);
        final String subscriptionName = testResourceNamer.randomName("sub", 10);
        final CreateSubscriptionOptions expected = new CreateSubscriptionOptions()
            .setMaxDeliveryCount(7)
            .setLockDuration(Duration.ofSeconds(45))
            .setUserMetadata("some-metadata-for-testing-subscriptions");

        // Act & Assert
        StepVerifier.create(client.createSubscription(topicName, subscriptionName, expected))
            .assertNext(actual -> {
                assertEquals(topicName, actual.getTopicName());
                assertEquals(subscriptionName, actual.getSubscriptionName());

                assertEquals(expected.getLockDuration(), actual.getLockDuration());
                assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
                assertEquals(expected.getUserMetadata(), actual.getUserMetadata());

                assertEquals(expected.deadLetteringOnMessageExpiration(), actual.deadLetteringOnMessageExpiration());
                assertEquals(expected.requiresSession(), actual.requiresSession());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void createSubscriptionExistingName(HttpClient httpClient) {
        // Arrange
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-1"
            : getEntityName(getTopicBaseName(), 1);
        final String subscriptionName = interceptorManager.isPlaybackMode()
            ? "subscription-session"
            : getSessionSubscriptionBaseName();
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);

        // Act & Assert
        StepVerifier.create(client.createSubscription(topicName, subscriptionName))
            .expectError(ResourceExistsException.class)
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void createTopicWithResponse(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = testResourceNamer.randomName("test", 10);
        final CreateTopicOptions expected = new CreateTopicOptions()
            .setMaxSizeInMegabytes(2048L)
            .setRequiresDuplicateDetection(true)
            .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(2))
            .setUserMetadata("some-metadata-for-testing-topic");

        // Act & Assert
        StepVerifier.create(client.createTopicWithResponse(topicName, expected))
            .assertNext(response -> {
                assertEquals(201, response.getStatusCode());

                // Assert values on a topic.
                final TopicProperties actual = response.getValue();

                assertEquals(topicName, actual.getName());

                assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes());
                assertEquals(expected.getUserMetadata(), actual.getUserMetadata());

                assertEquals(expected.enablePartitioning(), actual.enablePartitioning());
                assertEquals(expected.requiresDuplicateDetection(), actual.requiresDuplicateDetection());

                final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(actual);
                assertEquals(0, runtimeProperties.getSubscriptionCount());
                assertEquals(0, runtimeProperties.getSizeInBytes());
                assertNotNull(runtimeProperties.getCreatedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void deleteQueue(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = testResourceNamer.randomName("sub", 10);

        client.createQueue(queueName).block(TIMEOUT);

        // Act & Assert
        StepVerifier.create(client.deleteQueue(queueName))
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void deleteSubscription(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = testResourceNamer.randomName("topic", 10);
        final String subscriptionName = testResourceNamer.randomName("sub", 7);

        client.createTopic(topicName).block(TIMEOUT);
        client.createSubscription(topicName, subscriptionName).block(TIMEOUT);

        // Act & Assert
        StepVerifier.create(client.deleteSubscription(topicName, subscriptionName))
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void deleteTopic(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = testResourceNamer.randomName("topic", 10);

        client.createTopic(topicName).block(TIMEOUT);

        // Act & Assert
        StepVerifier.create(client.deleteTopic(topicName))
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getQueue(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = interceptorManager.isPlaybackMode()
            ? "queue-5"
            : getEntityName(TestUtils.getQueueBaseName(), 5);
        final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC());

        // Act & Assert
        StepVerifier.create(client.getQueue(queueName))
            .assertNext(queueDescription -> {
                assertEquals(queueName, queueDescription.getName());

                assertFalse(queueDescription.enablePartitioning());
                assertFalse(queueDescription.requiresSession());
                assertNotNull(queueDescription.getLockDuration());

                final QueueRuntimeProperties runtimeProperties = new QueueRuntimeProperties(queueDescription);
                assertNotNull(runtimeProperties.getCreatedAt());
                assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt()));
                assertNotNull(runtimeProperties.getAccessedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getNamespace(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String expectedName;
        if (interceptorManager.isPlaybackMode()) {
            expectedName = "ShivangiServiceBus";
        } else {
            final String[] split = TestUtils.getFullyQualifiedDomainName().split("\\.", 2);
            expectedName = split[0];
        }

        // Act & Assert
        StepVerifier.create(client.getNamespaceProperties())
            .assertNext(properties -> {
                assertEquals(NamespaceType.MESSAGING, properties.getNamespaceType());
                assertEquals(expectedName, properties.getName());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getQueueDoesNotExist(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = testResourceNamer.randomName("exist", 10);

        // Act & Assert
        StepVerifier.create(client.getQueue(queueName))
            .expectError(ResourceNotFoundException.class)
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getQueueExists(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = interceptorManager.isPlaybackMode()
            ? "queue-2"
            : getEntityName(TestUtils.getQueueBaseName(), 2);

        // Act & Assert
        StepVerifier.create(client.getQueueExists(queueName))
            .expectNext(true)
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getQueueExistsFalse(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = testResourceNamer.randomName("exist", 10);

        // Act & Assert
        StepVerifier.create(client.getQueueExists(queueName))
            .expectNext(false)
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getQueueRuntimeProperties(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String queueName = interceptorManager.isPlaybackMode()
            ? "queue-2"
            : getEntityName(TestUtils.getQueueBaseName(), 2);
        final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC());

        // Act & Assert
        StepVerifier.create(client.getQueueRuntimeProperties(queueName))
            .assertNext(RuntimeProperties -> {
                assertEquals(queueName, RuntimeProperties.getName());

                assertNotNull(RuntimeProperties.getCreatedAt());
                assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt()));
                assertNotNull(RuntimeProperties.getAccessedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getRule(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);

        // There is a single default rule created.
        final String ruleName = "$Default";
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-13"
            : getEntityName(getTopicBaseName(), 13);
        final String subscriptionName = interceptorManager.isPlaybackMode()
            ? "subscription"
            : getSubscriptionBaseName();

        // Act & Assert
        StepVerifier.create(client.getRuleWithResponse(topicName, subscriptionName, ruleName))
            .assertNext(response -> {
                assertEquals(200, response.getStatusCode());

                final RuleProperties contents = response.getValue();

                assertNotNull(contents);
                assertEquals(ruleName, contents.getName());
                assertNotNull(contents.getFilter());
                assertTrue(contents.getFilter() instanceof TrueRuleFilter);

                assertNotNull(contents.getAction());
                assertTrue(contents.getAction() instanceof EmptyRuleAction);
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getSubscription(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode() ? "topic-1" : getEntityName(getTopicBaseName(), 1);
        final String subscriptionName = interceptorManager.isPlaybackMode()
            ? "subscription-session"
            : getSessionSubscriptionBaseName();
        final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC());

        // Act & Assert
        StepVerifier.create(client.getSubscription(topicName, subscriptionName))
            .assertNext(description -> {
                assertEquals(topicName, description.getTopicName());
                assertEquals(subscriptionName, description.getSubscriptionName());

                assertTrue(description.requiresSession());
                assertNotNull(description.getLockDuration());

                final SubscriptionRuntimeProperties runtimeProperties = new SubscriptionRuntimeProperties(description);
                assertNotNull(runtimeProperties.getCreatedAt());
                assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt()));
                assertNotNull(runtimeProperties.getAccessedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getSubscriptionDoesNotExist(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode() ? "topic-1" : getEntityName(getTopicBaseName(), 1);
        final String subscriptionName = "subscription-session-not-exist";

        // Act & Assert
        StepVerifier.create(client.getSubscription(topicName, subscriptionName))
            .expectError(ResourceNotFoundException.class)
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getSubscriptionExists(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-1"
            : getEntityName(getTopicBaseName(), 1);
        final String subscriptionName = interceptorManager.isPlaybackMode()
            ? "subscription-session"
            : getSessionSubscriptionBaseName();

        // Act & Assert
        StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName))
            .expectNext(true)
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getSubscriptionExistsFalse(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode() ? "topic-1" : getEntityName(getTopicBaseName(), 1);
        final String subscriptionName = "subscription-session-not-exist";

        // Act & Assert
        StepVerifier.create(client.getSubscriptionExists(topicName, subscriptionName))
            .expectNext(false)
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getSubscriptionRuntimeProperties(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode() ? "topic-1" : getEntityName(getTopicBaseName(), 1);
        final String subscriptionName = interceptorManager.isPlaybackMode()
            ? "subscription-session"
            : getSessionSubscriptionBaseName();
        final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC());

        // Act & Assert
        StepVerifier.create(client.getSubscriptionRuntimeProperties(topicName, subscriptionName))
            .assertNext(description -> {
                assertEquals(topicName, description.getTopicName());
                assertEquals(subscriptionName, description.getSubscriptionName());

                assertTrue(description.getTotalMessageCount() >= 0);
                assertEquals(0, description.getActiveMessageCount());
                assertEquals(0, description.getTransferDeadLetterMessageCount());
                assertEquals(0, description.getTransferMessageCount());
                assertTrue(description.getDeadLetterMessageCount() >= 0);

                assertNotNull(description.getCreatedAt());
                assertTrue(nowUtc.isAfter(description.getCreatedAt()));
                assertNotNull(description.getAccessedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getTopic(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-1"
            : getEntityName(getTopicBaseName(), 1);
        final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC());

        // Act & Assert
        StepVerifier.create(client.getTopic(topicName))
            .assertNext(topicDescription -> {
                assertEquals(topicName, topicDescription.getName());

                assertTrue(topicDescription.enableBatchedOperations());
                assertFalse(topicDescription.requiresDuplicateDetection());
                assertNotNull(topicDescription.getDuplicateDetectionHistoryTimeWindow());
                assertNotNull(topicDescription.getDefaultMessageTimeToLive());
                assertFalse(topicDescription.enablePartitioning());

                final TopicRuntimeProperties runtimeProperties = new TopicRuntimeProperties(topicDescription);
                assertNotNull(runtimeProperties.getCreatedAt());
                assertTrue(nowUtc.isAfter(runtimeProperties.getCreatedAt()));
                assertNotNull(runtimeProperties.getAccessedAt());
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getTopicDoesNotExist(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = testResourceNamer.randomName("exists", 10);

        // Act & Assert
        StepVerifier.create(client.getTopic(topicName))
            .consumeErrorWith(error -> {
                assertTrue(error instanceof ResourceNotFoundException);

                final ResourceNotFoundException notFoundError = (ResourceNotFoundException) error;
                final HttpResponse response = notFoundError.getResponse();

                assertNotNull(response);
                assertEquals(200, response.getStatusCode());
                StepVerifier.create(response.getBody())
                    .verifyComplete();
            })
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getTopicExists(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-1"
            : getEntityName(getTopicBaseName(), 1);

        // Act & Assert
        StepVerifier.create(client.getTopicExists(topicName))
            .expectNext(true)
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getTopicExistsFalse(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = testResourceNamer.randomName("exists", 10);

        // Act & Assert
        StepVerifier.create(client.getTopicExists(topicName))
            .expectNext(false)
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void getTopicRuntimeProperties(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-1"
            : getEntityName(getTopicBaseName(), 1);
        final OffsetDateTime nowUtc = OffsetDateTime.now(Clock.systemUTC());

        // Act & Assert
        StepVerifier.create(client.getTopicRuntimeProperties(topicName))
            .assertNext(RuntimeProperties -> {
                assertEquals(topicName, RuntimeProperties.getName());

                if (interceptorManager.isPlaybackMode()) {
                    assertEquals(3, RuntimeProperties.getSubscriptionCount());
                } else {
                    assertTrue(RuntimeProperties.getSubscriptionCount() > 1);
                }

                assertNotNull(RuntimeProperties.getCreatedAt());
                assertTrue(nowUtc.isAfter(RuntimeProperties.getCreatedAt()));
                assertNotNull(RuntimeProperties.getAccessedAt());
                assertTrue(nowUtc.isAfter(RuntimeProperties.getAccessedAt()));
                assertEquals(0, RuntimeProperties.getScheduledMessageCount());

            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void listRules(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);

        // There is a single default rule created.
        final String ruleName = "$Default";
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-13"
            : getEntityName(getTopicBaseName(), 13);
        final String subscriptionName = interceptorManager.isPlaybackMode()
            ? "subscription"
            : getSubscriptionBaseName();

        // Act & Assert
        StepVerifier.create(client.listRules(topicName, subscriptionName))
            .assertNext(response -> {
                assertEquals(ruleName, response.getName());
                assertNotNull(response.getFilter());
                assertTrue(response.getFilter() instanceof TrueRuleFilter);

                assertNotNull(response.getAction());
                assertTrue(response.getAction() instanceof EmptyRuleAction);
            })
            .verifyComplete();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void listQueues(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);

        // Act & Assert
        StepVerifier.create(client.listQueues())
            .assertNext(queueDescription -> {
                assertNotNull(queueDescription.getName());
                assertTrue(queueDescription.enableBatchedOperations());
                assertFalse(queueDescription.requiresDuplicateDetection());
                assertFalse(queueDescription.enablePartitioning());
            })
            .expectNextCount(9)
            .thenCancel()
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void listSubscriptions(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);
        final String topicName = interceptorManager.isPlaybackMode()
            ? "topic-1"
            : getEntityName(getTopicBaseName(), 1);

        // Act & Assert
        StepVerifier.create(client.listSubscriptions(topicName))
            .assertNext(subscription -> {
                assertEquals(topicName, subscription.getTopicName());
                assertNotNull(subscription.getSubscriptionName());
            })
            .expectNextCount(1)
            .thenCancel()
            .verify();
    }

    @ParameterizedTest
    @MethodSource("createHttpClients")
    void listTopics(HttpClient httpClient) {
        // Arrange
        final ServiceBusAdministrationAsyncClient client = createClient(httpClient);

        // Act & Assert
        StepVerifier.create(client.listTopics())
            .assertNext(topics -> {
                assertNotNull(topics.getName());
                assertTrue(topics.enableBatchedOperations());
                assertFalse(topics.enablePartitioning());
            })
            .expectNextCount(2)
            .thenCancel()
            .verify();
    }

    private ServiceBusAdministrationAsyncClient createClient(HttpClient httpClient) {
        final String connectionString = interceptorManager.isPlaybackMode()
            ? "Endpoint=sb://foo.servicebus.windows.net;SharedAccessKeyName=dummyKey;SharedAccessKey=dummyAccessKey"
            : TestUtils.getConnectionString();
        final ServiceBusAdministrationClientBuilder builder = new ServiceBusAdministrationClientBuilder()
            .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
            .connectionString(connectionString);

        if (interceptorManager.isPlaybackMode()) {
            builder.httpClient(interceptorManager.getPlaybackClient());
        } else if (interceptorManager.isLiveMode()) {
            builder.httpClient(httpClient)
                .addPolicy(new RetryPolicy());
        } else {
            builder.httpClient(httpClient)
                .addPolicy(interceptorManager.getRecordPolicy())
                .addPolicy(new RetryPolicy());
        }

        return builder.buildAsyncClient();
    }
}


text:
title: Wednesday 3 October 2018
layout: post
author: arvin.joy
permalink: /wednesday-3-october-2018/
source-id: 1nznY-Q1tGEwOpVrY5uPDUXavFHAErMDKJjPedUHSOX4
published: true
---
Computer science lesson 20                                03.10.18

In today's lesson we were using a website called thimble to create a webpage for our blogs instead of using github. The majority of this lesson was making the layout of my website. I copied the scss code foom my github and put it into my thimble so that I had a similar style form my github site. I created a home page where I put 4 buttons that would eventually lead to my blogs from year 7 to 10 (My current blogs). I spent some of the lesson trying to add my background to the webpage and I finally managed to do it in the end.

redpajama_set_name: RedPajamaGithub


text:
module Panda
  module Associations
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods

      def has_one(relation_name)
        # for example creates : @video ||= VideoScope.new(self)

        define_method relation_name do
          param_id = "#{relation_name}_id"
          if instance_var = instance_variable_get("@#{relation_name}")
            instance_var
          else
            @associations ||= []
            @associations << relation_name
            instance_variable_set("@#{relation_name}",
              Panda::const_get(relation_name.to_s.capitalize).find(send(param_id.to_sym)))
          end
        end
      end

      def has_many(relation_name)
        # for example creates : @encodings ||= EncodingScope.new(self)

        define_method relation_name do
          model_name = "#{relation_name.to_s[0..-2].capitalize}"
          if instance_var = instance_variable_get("@#{relation_name}")
            instance_var
          else
            @associations ||= []
            @associations << relation_name
            instance_variable_set("@#{relation_name}",
              Panda::const_get("#{model_name}Scope").new(self))
          end
        end
      end

      alias :belongs_to :has_one

    end

    private
    def reset_associations
      if @associations
        @associations.each do |a|
          instance_variable_set("@#{a}",nil)
        end
      end
    end

  end
end


text:
{% extends 'base_app.html' %}

{% block title %}{% trans 'Not found' %}{% endblock title %}

{% block content %}

{% trans 'Not found' %}

{% trans 'The requested resource is not found.' %}

{% endblock content %}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Helmisporium molle Berk. & M.A. Curtis

### Remarks
null


text:
from __future__ import print_function
import sys
import os

if sys.version_info > (2, 7, 0):
    import unittest
else:
    import unittest2 as unittest
from mock import *

sys.path.append(os.path.join(os.path.dirname(__file__), '../bin'))
import qds
from qds_sdk.connection import Connection
from qds_sdk.scheduler import *
from test_base import print_command
from test_base import QdsCliTestCase

def list_actions_side_effect(*args, **kwargs):
    if args[1] == "scheduler/123":
        return {'id': '123'}
    else:
        return {"actions": []}

class TestSchedulerCheck(QdsCliTestCase):
    def test_list_actions(self):
        sys.argv = ['qds.py', 'scheduler', 'list-actions', '123']
        print_command()
        Connection._api_call = Mock()
        Connection._api_call.side_effect = list_actions_side_effect
        qds.main()
        Connection._api_call.assert_has_calls(
            [call("GET", "scheduler/123", params=None),
             call("GET", "scheduler/123/actions", params={})])

    def test_list_actions_seq_id(self):
        sys.argv = ['qds.py', 'scheduler', 'list-actions', '123',
                    '--sequence_id', '123']
        print_command()
        Connection._api_call = Mock()
        Connection._api_call.side_effect = list_actions_side_effect
        qds.main()
        Connection._api_call.assert_has_calls(
            [call("GET", "scheduler/123", params=None),
             call("GET", "scheduler/123/actions/123", params={})])

    def test_list_actions_pages(self):
        sys.argv = ['qds.py', 'scheduler', 'list-actions', '123', '--per-page',
                    '2']
        print_command()
        Connection._api_call = Mock()
        Connection._api_call.side_effect = list_actions_side_effect
        qds.main()
        Connection._api_call.assert_has_calls(
            [call("GET", "scheduler/123", params=None),
             call("GET", "scheduler/123/actions", params={'per_page': '2'})])

    def test_list_actions_pages_fields(self):
        sys.argv = ['qds.py', 'scheduler', 'list-actions', '123', '--per-page',
                    '2', '--fields', 'id', 'sequence_id']
        print_command()
        Connection._api_call = Mock()
        Connection._api_call.side_effect = list_actions_side_effect
        qds.main()
        Connection._api_call.assert_has_calls(
            [call("GET", "scheduler/123", params=None),
             call("GET", "scheduler/123/actions", params={'per_page': '2'})])

    def test_view_by_name(self):
        sys.argv = ['qds.py', 'scheduler', 'view_by_name', '123']
        print_command()
        Connection._api_call = Mock(return_value={"schedules": []})
        qds.main()
        Connection._api_call.assert_has_calls(
            [call("GET", "scheduler", params={'name': '123'})])

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


text:
package com.github.jucovschi.model.delta;

public class Operation {
	String type;
	OpData data;
	String client_timestamp;
	String undo_data;

	public String getClient_timestamp() {
		return client_timestamp;
	}
	public OpData getData() {
		return data;
	}
	public String getType() {
		return type;
	}
	public String getUndo_data() {
		return undo_data;
	}
	public void setClient_timestamp(String client_timestamp) {
		this.client_timestamp = client_timestamp;
	}
	public void setData(OpData data) {
		this.data = data;
	}
	public void setType(String type) {
		this.type = type;
	}
	public void setUndo_data(String undo_data) {
		this.undo_data = undo_data;
	}
}


text:
using SharpDX;
using System.Collections.Generic;
using System.Linq;

public class Morpher {
	private readonly List<Morph> morphs;

	public Morpher(List<Morph> morphs) {
		this.morphs = morphs;
	}

	public List<Morph> Morphs => morphs;

	public void Apply(ChannelOutputs channelOutputs, Vector3[] vertices) {
		for (int morphIdx = 0; morphIdx < morphs.Count; ++morphIdx) {
			morphs[morphIdx].Apply(channelOutputs, vertices);
		}
	}

	public PackedLists<VertexDelta> ConvertToVertexDeltas(int vertexCount, bool[] channelsToInclude) {
		List<List<VertexDelta>> vertexDeltas = Enumerable.Range(0, vertexCount)
			.Select(idx => new List<VertexDelta>())
			.ToList();

		int morphCount = Morphs.Count;
		for (int morphIdx = 0; morphIdx < morphCount; ++morphIdx) {
			Morph morph = morphs[morphIdx];

			if (channelsToInclude != null && !channelsToInclude[morph.Channel.Index]) {
				continue;
			}

			foreach (var delta in morph.Deltas) {
				vertexDeltas[delta.VertexIdx].Add(new VertexDelta(morphIdx, delta.PositionOffset));
			}
		}

		return PackedLists<VertexDelta>.Pack(vertexDeltas);
	}

	public List<WeightedHdMorph> LoadActiveHdMorphs(ChannelOutputs channelOutputs) {
		List<WeightedHdMorph> hdMorphs = new List<WeightedHdMorph>();

		foreach (var morph in morphs) {
			float weight = (float) morph.Channel.GetValue(channelOutputs);
			if (weight == 0) {
				continue;
			}

			var hdFile = morph.HdFile;
			if (hdFile == null) {
				continue;
			}

			var hdMorph = HdMorphSerialization.LoadHdMorph(hdFile);

			hdMorphs.Add(new WeightedHdMorph(hdMorph, weight));
		}

		return hdMorphs;
	}
}


text:
require(['require-config'], function () {
  require([
    'controllers/app'
  ], function (app) {
    // FIRE IT UP!
    app.init();
  });
});


text:
I am ZnEncodedStream, an abstract support class for read and write streams on an encoded binary stream.

Part of Zinc HTTP Components


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>Fedora Repository</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/classes/spring/repository.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.fcrepo.http.commons.FedoraContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>jersey-servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>org.fcrepo.http.commons.FedoraApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>ETagFilter</filter-name>
        <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>ETagFilter</filter-name>
        <url-pattern>/static/*</url-pattern>
    </filter-mapping>

    <!--Uncomment section below to enable Basic-Authentication-->
    <!--
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Fedora4</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>DELETE</http-method>
            <http-method>PUT</http-method>
            <http-method>HEAD</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>PATCH</http-method>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>MOVE</http-method>
            <http-method>COPY</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>fedoraUser</role-name>
            <role-name>fedoraAdmin</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>fcrepo</realm-name>
    </login-config>
    -->

</web-app>


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>sprockets.stl.base.FuncGetField</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package sprockets ::
        Package stl ::
        Module base ::
        Class FuncGetField

[hide private]

[frames] | no frames]

Class FuncGetField

source code

 object --+
          |
NamedObject --+
              |
           Func --+
                  |
                 FuncGetField

External function to get the value of a field either of Role or dictionary.

Attributes:
  obj: Object which has the field of |field|. It can be either Role or
      dictionary.
  field: Field name to get the value of.

        Instance Methods
        [hide private]

          __init__(self,
        obj,
        field)

      x.__init__(...) initializes x; see help(type(x)) for signature

            source code

          __str__(self)

      str(x)

            source code

          Run(self)

      Execute the function with |args|.

            source code

Inherited from NamedObject:
      Resolve,
      __eq__,
      __ne__,
      __repr__

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __setattr__,
      __sizeof__,
      __subclasshook__

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        obj,
        field)

(Constructor)

  	source code

x.__init__(...) initializes x; see help(type(x)) for signature

Overrides:
        object.__init__

(inherited documentation)

__str__(self)

(Informal representation operator)

  	source code

str(x)

Overrides:
        object.__str__

(inherited documentation)

Run(self)

  	source code

Execute the function with |args|.

Returns:
  Whether the function succeeded to execute.
Raises:
  RuntimeError: If self.func is None.

Overrides:
        Func.Run

(inherited documentation)

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Mon Feb 27 16:17:07 2017

      http://epydoc.sourceforge.net


text:
package de.fu_berlin.imp.apiua.core.model.data;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import de.fu_berlin.imp.apiua.core.model.data.IBaseDataContainer;
import de.fu_berlin.imp.apiua.core.model.data.impl.FileBaseDataContainer;

public class FileBaseDataContainerTest {

	public static File createTempDirectory() throws IOException {
		final File temp;

		temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

		if (!(temp.delete())) {
			throw new IOException("Could not delete temp file: "
					+ temp.getAbsolutePath());
		}

		if (!(temp.mkdir())) {
			throw new IOException("Could not create temp directory: "
					+ temp.getAbsolutePath());
		}

		return (temp);
	}

	@Test
	public void test() throws URISyntaxException, IOException {
		File dir = createTempDirectory();

		new File(dir, "__dataset.txt").createNewFile();

		IBaseDataContainer baseDataContainer = new FileBaseDataContainer(dir);
		File file = baseDataContainer.getFile("test", "my_name");
		assertFalse(file.exists());

		FileUtils.write(file, "Hello World!", "UTF-8");
		File file2 = baseDataContainer.getFile("test", "my_name");
		assertFalse(file2.exists());
		assertNotSame(file, file2);

		baseDataContainer.putFile("test", "my_name", file);
		File file3 = baseDataContainer.getFile("test", "my_name");
		assertEquals("Hello World!", FileUtils.readFileToString(file3, "UTF-8"));

		baseDataContainer.putFile("test", "my_name", null);
		File file4 = baseDataContainer.getFile("test", "my_name");
		assertFalse(file4.exists());
	}
}


text:
define([
    'dojo/text!ijit/widgets/notify/templates/ChangeRequest.html',

    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/Color',
    'dojo/_base/array',
    'dojo/_base/json',

    'dojo/dom-style',
    'dojo/dom-attr',
    'dojo/dom-class',

    'dojo/on',
    'dojo/query',
    'dojo/string',
    'dojo/aspect',
    'dojo/request',

    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',

    'esri/toolbars/draw',
    'esri/symbols/SimpleMarkerSymbol',
    'esri/graphic'
], function(
    template,

    declare,
    lang,
    Color,
    array,
    dojoJson,

    style,
    domAttr,
    domClass,

    on,
    query,
    dojoString,
    aspect,
    request,

    widgetBase,
    templatedMixin,

    Draw,
    SimpleMarkerSymbol,
    Graphic
) {
    // summary:
    //      Allows a user to markup a map, give a description,
    //      and submit the shape and description for review.
    //      This widget hits the email service.
    //      A separate viewer page will show the markup made.

    return declare([widgetBase, templatedMixin], {
        templateString: template,
        baseClass: 'change-request',
        // a reference to the map
        map: null,
        // the title to display on the widget
        title: 'Report Map Issue',
        // a reference to the graphics layer
        graphicsLayer: null,
        // a reference to the graphic on the map
        _graphic: null,
        // the drawing toolbar
        toolbar: null,
        // the redline symbol
        symbol: null,
        // the base url to the red liner application
        redliner: 'https://chalkdust.ugrc.utah.gov',
        // the id's of the emails to notify
        toIds: null,
        // the email service configuration
        emailServiceConfiguration: 'prod',

        constructor: function() {
            // summary:
            //      first function to fire after page loads
            console.info('agrc.ijit.widgets.notify.ChangeRequest::constructor', arguments, arguments);
        },

        postMixInProperties: function() {
            // summary:
            //      postMixin properties like symbol and graphics layer
            // description:
            //      decide whether to use default graphics layer and symbol
            // tags:
            //      public
            console.info('agrc.ijit.widgets.notify.ChangeRequest::postMixInProperties', arguments);

            // default to use the map's graphics layer if none was passed in
            if (!this.graphicsLayer && !!this.map) {
                this.graphicsLayer = this.map.graphics;

                //if maps already loaded just set this first.
                this.map.on('Load', lang.hitch(this, function() {
                    this.graphicsLayer = this.map.graphics;
                }));
            }

            // create symbol if none was provided in options
            if (!this.symbol && !!this.map) {
                this.symbol = new SimpleMarkerSymbol()
                    .setStyle(SimpleMarkerSymbol.STYLE_CIRCLE)
                    .setColor(new Color([255, 0, 0, 0.5]))
                    .setOutline(null)
                    .setSize('32');
            }

            this.toolbar = new Draw(this.map);
            this.toolbar.setLineSymbol(this.symbol);
        },

        postCreate: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::postCreate', arguments);

            this.formRedline.onsubmit = function() {
                return false;
            };

            var scoped = this;
            this.own(
                on(this.btnSubmit, 'click', lang.hitch(this, 'submitRedline')),
                on(this.btnRedline, 'click', lang.hitch(this, 'onDrawStart')),
                aspect.after(this.toolbar, 'onDrawEnd', lang.hitch(this, 'onDrawEnd'), true),
                aspect.after(this.toolbar, 'activate', function() {
                    domAttr.set(scoped.btnRedline, 'disabled', true);
                }),
                aspect.after(this.toolbar, 'deactivate', function() {
                    domAttr.set(scoped.btnRedline, 'disabled', false);
                })
            );
        },

        onDrawStart: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::onDrawStart', arguments);

            if (this.map && this._graphic) {
                this.graphicsLayer.remove(this._graphic);
            }

            this.toolbar.activate(Draw.POINT);
        },

        onDrawEnd: function(geometry) {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::onDrawEnd', arguments);

            this._graphic = new Graphic(geometry, this.symbol);
            this.graphicsLayer.add(this._graphic);

            this.toolbar.deactivate();
        },

        submitRedline: function() {
            // summary:
            //      submits the change request.
            console.info('agrc.ijit.widgets.notify.ChangeRequest::submitRedline', arguments);

            if (!this._validate()) {
                return false;
            }

            if (this.map && this._graphic) {
                this.graphicsLayer.remove(this._graphic);
            }

            var description = this.txtDescription.value;

            if (this.request) {
                return;
            }

            this.btnSubmit.innerHTML = 'Submitting...';

            this.request = this._invokeWebService({
                description: description
            }).then(
                lang.hitch(this, 'completed'), lang.hitch(this, 'error')
            );

            return false;
        },

        _validate: function() {
            // summary:
            //      validates the widget
            // description:
            //      makes sure everything is the way it needs to be
            // tags:
            //      private
            // returns:
            //      bool
            console.info('agrc.ijit.widgets.notify.ChangeRequest::_validate', arguments);

            var that = this;

            // hide error messages
            query('.help-inline.error', this.domNode).style('display', 'none');
            query('.control-group', this.domNode).removeClass('error');

            return array.every([
                    this.txtDescription
                ],
                function(tb) {
                    return that._isValid(tb);
                });
        },

        _isValid: function(textBox) {
            // summary:
            //      validates that there are values in the textbox
            // textBox: TextBox Element
            console.log('agrc.ijit.widgets.notify.ChangeRequest::_isValid', arguments);

            var valid = dojoString.trim(textBox.value).length > 0;

            if (!valid) {
                query('span', textBox.parentElement).style('display', 'inline');
                domClass.add(textBox.parentElement.parentElement, 'error');
            }

            return valid;
        },

        _invokeWebService: function(args) {
            // summary:
            //      calls the web service
            // description:
            //      sends the request to the service
            // tags:
            //      private
            // returns:
            //     Deferred
            console.info('agrc.ijit.widgets.notify.ChangeRequest::_invokeWebService', arguments);

            var url = 'https://us-central1-ut-dts-agrc-chalkdust-prod.cloudfunctions.net/send-email-service';
            var ids = this.toIds || [2];

            if (this.emailServiceConfiguration !== 'prod') {
                url = 'https://us-central1-ut-dts-agrc-chalkdust-dev.cloudfunctions.net/send-email-service';
            }

            if (ids.length < 1) {
                ids = [2];
            }

            var email = lang.getObject('window.AGRC.user.email', false);

            var options = {
                email: {
                    toIds: ids,
                    fromId: 2
                },
                template: {
                    templateId: 3,
                    templateValues: {
                        description: args.description,
                        application: window.location.href,
                        basemap: this.map.layerIds[0],
                        user: email || 'anonymous'
                    }
                }
            };

            if (this._graphic && this._graphic.geometry) {
                options.template.templateValues.link = this.redliner;
                options.template.templateValues.redline = this._graphic.geometry.toJson();
            }

            return request.post(url, {
                data: dojoJson.toJson(options),
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': null
                }
            });
        },

        completed: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::completed', arguments);

            this._graphic = null;
            this.request = null;
            this.txtDescription.value = '';
            this.btnSubmit.innerHTML = 'Thanks!';
        },

        error: function() {
            // summary:
            //      handles script io error
            // description:
            //      publishes error
            // tags:
            //      private
            // returns:
            //
            console.info('agrc.ijit.widgets.notify.ChangeRequest::error', arguments);

            style.set(this.errorMsg, 'display', 'inline');
            this.request = null;
            domClass.add(this.errorMsg.parentElement.parentElement, 'error');
            this.btnSubmit.innerHTML = 'Whoops.';
        }
    });
});


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

class C {
    List<String> test(boolean b) {
        List<String> result1 = new ArrayList<>();
        List<String> result2 = new ArrayList<>();
        return b ? Collections.unmodifiableList(result1) : result2;
    }
}


text:
module VeryOwn
  class CustomException < StandardError; end
end

class RegularWorker
  include ::Sidekiq::Worker
end

class SingleExceptionWorker
  include ::Sidekiq::Worker
  sidekiq_options expected_failures: { ZeroDivisionError => nil }
end

class MultipleExceptionWorker
  include ::Sidekiq::Worker
  sidekiq_options expected_failures: { NotImplementedError => nil, VeryOwn::CustomException => nil }
end

class CustomizedWorker
  include ::Sidekiq::Worker
  sidekiq_options expected_failures: {
    NotImplementedError      => nil,
    VeryOwn::CustomException => [10, 20, 50],
    ZeroDivisionError        => 5
  }
end


text:
package iso9660_test

/*
 These tests the exported functions
 We want to do full-in tests with files
*/

import (
	"fmt"
	"io"
	"os"
	"path"
	"strings"
	"testing"

	"github.com/diskfs/go-diskfs/filesystem"
	"github.com/diskfs/go-diskfs/filesystem/iso9660"
)

func getOpenMode(mode int) string {
	modes := make([]string, 0)
	if mode&os.O_CREATE == os.O_CREATE {
		modes = append(modes, "CREATE")
	}
	if mode&os.O_APPEND == os.O_APPEND {
		modes = append(modes, "APPEND")
	}
	if mode&os.O_RDWR == os.O_RDWR {
		modes = append(modes, "RDWR")
	} else {
		modes = append(modes, "RDONLY")
	}
	return strings.Join(modes, "|")
}

func getValidIso9660FSWorkspace() (*iso9660.FileSystem, error) {
	// create the filesystem
	f, err := tmpIso9660File()
	if err != nil {
		return nil, fmt.Errorf("Failed to create iso9660 tmpfile: %v", err)
	}
	return iso9660.Create(f, 0, 0, 2048, "")
}
func getValidIso9660FSUserWorkspace() (*iso9660.FileSystem, error) {
	f, err := tmpIso9660File()
	if err != nil {
		return nil, fmt.Errorf("Failed to create iso9660 tmpfile: %v", err)
	}
	dir, err := os.MkdirTemp("", "myIso9660")
	if err != nil {
		return nil, fmt.Errorf("Failed to create iso9660 tmpfile: %v", err)
	}
	return iso9660.Create(f, 0, 0, 2048, dir)
}
func getValidIso9660FSReadOnly() (*iso9660.FileSystem, error) {
	f, err := os.Open(iso9660.ISO9660File)
	if err != nil {
		return nil, fmt.Errorf("Failed to read iso9660 testfile %s: %v", iso9660.ISO9660File, err)
	}
	return iso9660.Read(f, 0, 0, 2048)
}
func getValidRockRidgeFSReadOnly() (*iso9660.FileSystem, error) {
	f, err := os.Open(iso9660.RockRidgeFile)
	if err != nil {
		return nil, fmt.Errorf("Failed to read iso9660 testfile %s: %v", iso9660.RockRidgeFile, err)
	}
	return iso9660.Read(f, 0, 0, 2048)
}

func tmpIso9660File() (*os.File, error) {
	filename := "iso9660_test.iso"
	f, err := os.CreateTemp("", filename)
	if err != nil {
		return nil, fmt.Errorf("Failed to create tempfile %s :%v", filename, err)
	}
	return f, nil
}

func TestISO9660Type(t *testing.T) {
	fs := &iso9660.FileSystem{}
	fstype := fs.Type()
	expected := filesystem.TypeISO9660
	if fstype != expected {
		t.Errorf("Type() returns %v instead of expected %v", fstype, expected)
	}
}

func TestIso9660Mkdir(t *testing.T) {
	t.Run("read-only", func(t *testing.T) {
		fs, err := getValidIso9660FSReadOnly()
		if err != nil {
			t.Fatalf("Failed to get read-only ISO9660 filesystem: %v", err)
		}
		err = fs.Mkdir("/abcdef")
		if err == nil {
			t.Errorf("received no error when trying to mkdir read-only filesystem")
		}
	})
	t.Run("workspace", func(t *testing.T) {
		fs, err := getValidIso9660FSWorkspace()
		if err != nil {
			t.Errorf("Failed to get workspace: %v", err)
		}
		existPath := "/abc"
		tests := []struct {
			fs   *iso9660.FileSystem
			path string
			err  error
		}{
			{fs, "/abcdef", nil},                          // new one
			{fs, existPath, nil},                          // already exists
			{fs, path.Join(existPath, "bar/def/la"), nil}, // already exists
			{fs, "/a/b/c", nil},                           // already exists
		}

		// for fsw, we want to work at least once with a path that exists
		existPathFull := path.Join(fs.Workspace(), existPath)
		err = os.MkdirAll(existPathFull, 0o755)
		if err != nil {
			t.Fatalf("could not create path %s in workspace as %s: %v", existPath, existPathFull, err)
		}
		for _, tt := range tests {
			fs := tt.fs
			ws := fs.Workspace()
			err := fs.Mkdir(tt.path)
			if (err == nil && tt.err != nil) || (err != nil && err == nil) {
				t.Errorf("unexpected error mismatch. Actual: %v, expected: %v", err, tt.err)
			}
			// did the path exist?
			if ws != "" {
				fullPath := path.Join(ws, tt.path)
				if _, err := os.Stat(fullPath); os.IsNotExist(err) {
					t.Errorf("path did not exist after creation base %s, in workspace %s", tt.path, fullPath)
				}
			}
		}
	})
}

func TestIso9660Create(t *testing.T) {
	testFile, testError := os.CreateTemp("", "iso9660_test")
	if testError != nil {
		t.Errorf("Failed to create workspace tmpfile: %v", testError)
	}
	defer os.RemoveAll(testFile.Name())
	testDir, testError := os.MkdirTemp("", "iso9660_test")
	if testError != nil {
		t.Errorf("Failed to create workspace tmpdir: %v", testError)
	}
	defer os.RemoveAll(testDir)

	missingDir, testError := os.MkdirTemp("", "iso9660_test")
	if testError != nil {
		t.Errorf("Failed to create workspace tmpdir: %v", testError)
	}
	os.RemoveAll(missingDir)

	tests := []struct {
		blocksize int64
		filesize  int64
		fs        *iso9660.FileSystem
		err       error
		workdir   string
	}{
		{500, 6000, nil, fmt.Errorf("blocksize for ISO9660 must be"), ""},
		{513, 6000, nil, fmt.Errorf("blocksize for ISO9660 must be"), ""},
		{2048, 2048*iso9660.MaxBlocks + 1, nil, fmt.Errorf("requested size is larger than maximum allowed ISO9660 size"), ""},
		{2048, 32*iso9660.KB + 3*2048 - 1, nil, fmt.Errorf("requested size is smaller than minimum allowed ISO9660 size"), ""},
		{2048, 10000000, nil, fmt.Errorf("provided workspace is not a directory"), testFile.Name()},
		{2048, 10000000, nil, fmt.Errorf("could not stat working directory"), missingDir},
		{2048, 10000000, &iso9660.FileSystem{}, nil, testDir},
		{2048, 10000000, &iso9660.FileSystem{}, nil, ""},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(fmt.Sprintf("blocksize %d filesize %d", tt.blocksize, tt.filesize), func(t *testing.T) {
			// create the filesystem
			f, err := tmpIso9660File()
			if err != nil {
				t.Errorf("Failed to create iso9660 tmpfile: %v", err)
			}
			fs, err := iso9660.Create(f, tt.filesize, 0, tt.blocksize, tt.workdir)
			defer os.Remove(f.Name())
			switch {
			case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
				t.Errorf("Create(%s, %d, %d, %d): mismatched errors, actual %v expected %v", f.Name(), tt.filesize, 0, tt.blocksize, err, tt.err)
			case (fs == nil && tt.fs != nil) || (fs != nil && tt.fs == nil):
				t.Errorf("Create(%s, %d, %d, %d): mismatched fs, actual then expected", f.Name(), tt.filesize, 0, tt.blocksize)
				t.Logf("%v", fs)
				t.Logf("%v", tt.fs)
			}
			// we do not match the filesystems here, only check functional accuracy
		})
	}
}

func TestISO9660Read(t *testing.T) {
	// test cases:
	// - invalid blocksize
	// - invalid file size (too small and too big)
	// - valid file
	tests := []struct {
		blocksize  int64
		filesize   int64
		bytechange int64
		fs         *iso9660.FileSystem
		err        error
	}{
		{500, 6000, -1, nil, fmt.Errorf("blocksize for ISO9660 must be")},
		{513, 6000, -1, nil, fmt.Errorf("blocksize for ISO9660 must be")},
		{512, iso9660.MaxBlocks*2048 + 10000, -1, nil, fmt.Errorf("blocksize for ISO9660 must be")},
		{2048, 10000000, -1, &iso9660.FileSystem{}, nil},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(fmt.Sprintf("blocksize %d filesize %d", tt.blocksize, tt.filesize), func(t *testing.T) {
			// get a temporary working file
			f, err := os.Open(iso9660.ISO9660File)
			if err != nil {
				t.Fatal(err)
			}
			defer f.Close()
			// create the filesystem
			fs, err := iso9660.Read(f, tt.filesize, 0, tt.blocksize)
			switch {
			case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
				t.Errorf("read(%s, %d, %d, %d): mismatched errors, actual %v expected %v", f.Name(), tt.filesize, 0, tt.blocksize, err, tt.err)
			case (fs == nil && tt.fs != nil) || (fs != nil && tt.fs == nil):
				t.Errorf("read(%s, %d, %d, %d): mismatched fs, actual then expected", f.Name(), tt.filesize, 0, tt.blocksize)
				t.Logf("%v", fs)
				t.Logf("%v", tt.fs)
			}
			// we do not match the filesystems here, only check functional accuracy
		})
	}
}

func TestIso9660ReadDir(t *testing.T) {
	type testList struct {
		fs    *iso9660.FileSystem
		path  string
		count int
		first string
		last  string
		err   error
	}
	//nolint:thelper // this is not a helper function
	runTests := func(t *testing.T, tests []testList) {
		for _, tt := range tests {
			fi, err := tt.fs.ReadDir(tt.path)
			switch {
			case (err == nil && tt.err != nil) || (err != nil && tt.err == nil):
				t.Errorf("fs.ReadDir(%s): mismatched errors, actual %v expected %v", tt.path, err, tt.err)
			case len(fi) != tt.count:
				t.Errorf("fs.ReadDir(%s): mismatched directory received %d entries, expected %d", tt.path, len(fi), tt.count)
			case fi != nil && tt.count > 2 && fi[0].Name() != tt.first:
				t.Errorf("fs.ReadDir(%s): mismatched first non-self or parent entry, actual then expected", tt.path)
				t.Logf("%s", fi[0].Name())
				t.Logf("%s", tt.first)
			case fi != nil && tt.count > 0 && fi[len(fi)-1].Name() != tt.last:
				t.Errorf("fs.ReadDir(%s): mismatched last entry, actual then expected", tt.path)
				t.Logf("%s", fi[len(fi)-1].Name())
				t.Logf("%s", tt.last)
			}
		}
	}
	t.Run("read-only 9660", func(t *testing.T) {
		fs, err := getValidIso9660FSReadOnly()
		if err != nil {
			t.Errorf("Failed to get read-only ISO9660 filesystem: %v", err)
		}
		runTests(t, []testList{
			{fs, "/abcdef", 0, "", "", fmt.Errorf("directory does not exist")}, // does not exist
			// root should have 4 entries (since we do not pass back . and ..):
			// .
			// ..
			// /ABC
			// /BAR
			// /FOO
			// /README.MD;1
			{fs, "/", 5, "ABC", "README.MD", nil},                                   // exists
			{fs, "/ABC", 1, "", "LARGEFIL", nil},                                    // exists
			{fs, "/abc", 0, "", "LARGEFIL", fmt.Errorf("directory does not exist")}, // should not find rock ridge name
		},
		)
	})
	t.Run("read-only rock ridge", func(t *testing.T) {
		fs, err := getValidRockRidgeFSReadOnly()
		if err != nil {
			t.Errorf("Failed to get read-only Rock Ridge filesystem: %v", err)
		}
		runTests(t, []testList{
			{fs, "/abcdef", 0, "", "", fmt.Errorf("directory does not exist")}, // does not exist
			// root should have 4 entries (since we do not pass back . and ..):
			{fs, "/", 6, "abc", "README.md", nil},                                   // exists
			{fs, "/ABC", 0, "", "LARGEFIL", fmt.Errorf("directory does not exist")}, // should not find 8.3 name
			{fs, "/abc", 1, "", "largefile", nil},                                   // should find rock ridge name
			{fs, "/deep/a/b/c/d/e/f/g/h/i/j/k", 1, "file", "file", nil},             // should find a deep directory
			{fs, "/G", 0, "", "H", fmt.Errorf("directory does not exist")},          // relocated directory
			{fs, "/g", 0, "", "h", fmt.Errorf("directory does not exist")},          // relocated directory
		},
		)
	})
	t.Run("workspace", func(t *testing.T) {
		fs, err := getValidIso9660FSWorkspace()
		if err != nil {
			t.Errorf("Failed to get workspace: %v", err)
		}
		// make sure existPath exists in the workspace
		ws := fs.Workspace()
		existPath := "/abc"
		existPathWs := path.Join(ws, existPath)
		_ = os.MkdirAll(existPathWs, 0o755)
		// create files
		for i := 0; i < 10; i++ {
			filename := path.Join(existPathWs, fmt.Sprintf("filename_%d", i))
			contents := fmt.Sprintf("abcdefg %d", i)
			_ = os.WriteFile(filename, []byte(contents), 0o600)
		}
		runTests(t, []testList{
			{fs, "/abcdef", 0, "", "", fmt.Errorf("directory does not exist")}, // does not exist
			{fs, existPath, 10, "filename_0", "filename_9", nil},               // exists
		},
		)
	})
}

//nolint:gocyclo // we really do not care about the cyclomatic complexity of a test function. Maybe someday we will improve it.
func TestIso9660OpenFile(t *testing.T) {
	// opening directories and files for reading
	type testStruct struct {
		path     string
		mode     int
		expected string
		err      error
	}

	t.Run("read", func(t *testing.T) {
		//nolint:thelper // this is not a helper function
		runTests := func(t *testing.T, fs *iso9660.FileSystem, tests []testStruct) {
			for _, tt := range tests {
				header := fmt.Sprintf("OpenFile(%s, %s)", tt.path, getOpenMode(tt.mode))
				reader, err := fs.OpenFile(tt.path, tt.mode)
				switch {
				case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
					t.Errorf("%s: mismatched errors, actual: %v , expected: %v", header, err, tt.err)
				case reader == nil && (tt.err == nil || tt.expected != ""):
					t.Errorf("%s: Unexpected nil output", header)
				case reader != nil:
					b, err := io.ReadAll(reader)
					if err != nil {
						t.Errorf("%s: io.ReadAll(reader) unexpected error: %v", header, err)
					}
					if string(b) != tt.expected {
						t.Errorf("%s: mismatched contents, actual then expected", header)
						t.Log(string(b))
						t.Log(tt.expected)
					}
				}
			}
		}
		t.Run("read-only 9660", func(t *testing.T) {
			fs, err := getValidIso9660FSReadOnly()
			if err != nil {
				t.Errorf("Failed to get read-only ISO9660 filesystem: %v", err)
			}
			tests := []testStruct{
				// error opening a directory
				{"/", os.O_RDONLY, "", fmt.Errorf("cannot open directory %s as file", "/")},
				// open non-existent file for read or read write
				{"/abcdefg", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
				// open file for read or read write and check contents
				{"/FOO/FILENA01", os.O_RDONLY, "filename_1\n", nil},
				{"/FOO/FILENA75", os.O_RDONLY, "filename_9\n", nil},
				// rock ridge versions should not exist
				{"/README.md", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/README.md")},
			}
			runTests(t, fs, tests)
		})
		t.Run("read-only rock ridge", func(t *testing.T) {
			fs, err := getValidRockRidgeFSReadOnly()
			if err != nil {
				t.Errorf("Failed to get read-only Rock Ridge filesystem: %v", err)
			}
			tests := []testStruct{
				// error opening a directory
				{"/", os.O_RDONLY, "", fmt.Errorf("cannot open directory %s as file", "/")},
				// open non-existent file for read or read write
				{"/abcdefg", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
				// open file for read or read write and check contents
				{"/foo/filename_1", os.O_RDONLY, "filename_1\n", nil},
				{"/foo/filename_75", os.O_RDONLY, "filename_75\n", nil},
				// only rock ridge versions should exist
				{"/README.MD", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/README.MD")},
				{"/README.md", os.O_RDONLY, "README\n", nil},
			}
			runTests(t, fs, tests)
		})
		t.Run("workspace", func(t *testing.T) {
			fs, err := getValidIso9660FSWorkspace()
			if err != nil {
				t.Errorf("Failed to get workspace: %v", err)
			}
			// make sure our test files exist and have necessary content
			ws := fs.Workspace()
			subdir := "/FOO"
			_ = os.MkdirAll(path.Join(ws, subdir), 0o755)
			for i := 0; i <= 75; i++ {
				filename := fmt.Sprintf("FILENA%02d", i)
				content := fmt.Sprintf("filename_%d\n", i)
				_ = os.WriteFile(path.Join(ws, subdir, filename), []byte(content), 0o600)
			}
			tests := []testStruct{
				// error opening a directory
				{"/", os.O_RDONLY, "", fmt.Errorf("cannot open directory %s as file", "/")},
				// open non-existent file for read or read write
				{"/abcdefg", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
				// open file for read or read write and check contents
				{"/FOO/FILENA01", os.O_RDONLY, "filename_1\n", nil},
				{"/FOO/FILENA75", os.O_RDONLY, "filename_75\n", nil},
			}
			runTests(t, fs, tests)
		})
	})

	// write / create-and-write files and check contents
	// *** Write - writes right after last write or read
	// *** Read - reads right after last write or read
	// ** WriteAt - writes at specific location in file
	// ** ReadAt - reads at specific location in file
	t.Run("Write", func(t *testing.T) {
		t.Run("read-only", func(t *testing.T) {
			flags := []int{
				os.O_CREATE, os.O_APPEND, os.O_WRONLY, os.O_RDWR,
			}
			fs, err := getValidIso9660FSReadOnly()
			if err != nil {
				t.Errorf("Failed to get read-only ISO9660 filesystem: %v", err)
			}
			for _, m := range flags {
				_, err := fs.OpenFile("/NEWFILE", os.O_CREATE)
				if err == nil {
					t.Errorf("Did not return error when opening a file with read flag %v in read-only filesystem", m)
				}
			}
		})
		t.Run("workspace", func(t *testing.T) {
			fsTemp, err := getValidIso9660FSWorkspace()
			if err != nil {
				t.Errorf("Failed to get workspace: %v", err)
			}
			fsUser, err := getValidIso9660FSUserWorkspace()
			if err != nil {
				t.Errorf("Failed to get workspace: %v", err)
			}

			baseContent := "INITIAL DATA GALORE\n"
			editFile := "/EXISTS.TXT"
			tests := []struct {
				path      string
				mode      int
				beginning bool
				contents  string
				expected  string
				err       error
			}{
				//  - open for create file that does not exist (write contents, check that written)
				{"/abcdefg", os.O_RDWR | os.O_CREATE, false, "This is a test", "This is a test", nil},
				//  - open for readwrite file that does exist (write contents, check that overwritten)
				{editFile, os.O_RDWR, true, "This is a very long replacement string", "This is a very long replacement string", nil},
				{editFile, os.O_RDWR, true, "Two", "TwoTIAL DATA GALORE\n", nil},
				{editFile, os.O_RDWR, false, "This is a very long replacement string", "INITIAL DATA GALORE\nThis is a very long replacement string", nil},
				{editFile, os.O_RDWR, false, "Two", "INITIAL DATA GALORE\nTwo", nil},
				//  - open for append file that does exist (write contents, check that appended)
				{editFile, os.O_APPEND, false, "More", "", fmt.Errorf("write ")},
				{editFile, os.O_APPEND | os.O_RDWR, false, "More", "INITIAL DATA GALORE\nMore", nil},
				{editFile, os.O_APPEND, true, "More", "", fmt.Errorf("write ")},
				{editFile, os.O_APPEND | os.O_RDWR, true, "More", "INITIAL DATA GALORE\nMore", nil},
			}
			for i, tt := range tests {
				for _, fs := range []*iso9660.FileSystem{fsTemp, fsUser} {
					filepath := path.Join(fs.Workspace(), tt.path)
					// remove any old file if it exists - ignore errors
					_ = os.Remove(filepath)
					// if the file is supposed to exist, create it and add its contents
					if tt.mode&os.O_CREATE != os.O_CREATE {
						_ = os.WriteFile(filepath, []byte(baseContent), 0o600)
					}
					header := fmt.Sprintf("%d: OpenFile(%s, %s, %t)", i, tt.path, getOpenMode(tt.mode), tt.beginning)
					readWriter, err := fs.OpenFile(tt.path, tt.mode)
					switch {
					case err != nil:
						t.Errorf("%s: unexpected error: %v", header, err)
					case readWriter == nil:
						t.Errorf("%s: Unexpected nil output", header)
					default:
						// read to the end of the file
						var offset int64
						_, err := readWriter.Seek(0, io.SeekEnd)
						if err != nil {
							t.Errorf("%s: Seek end of file gave unexpected error: %v", header, err)
							continue
						}
						if tt.beginning {
							offset, err = readWriter.Seek(0, io.SeekStart)
							if err != nil {
								t.Errorf("%s: Seek(0,io.SeekStart) unexpected error: %v", header, err)
								continue
							}
							if offset != 0 {
								t.Errorf("%s: Seek(0,io.SeekStart) reset to %d instead of %d", header, offset, 0)
								continue
							}
						}
						bWrite := []byte(tt.contents)
						written, writeErr := readWriter.Write(bWrite)
						_, _ = readWriter.Seek(0, io.SeekStart)
						bRead, readErr := io.ReadAll(readWriter)

						switch {
						case readErr != nil:
							t.Errorf("%s: io.ReadAll() unexpected error: %v", header, readErr)
						case (writeErr == nil && tt.err != nil) || (writeErr != nil && tt.err == nil) || (writeErr != nil && tt.err != nil && !strings.HasPrefix(writeErr.Error(), tt.err.Error())):
							t.Errorf("%s: readWriter.Write(b) mismatched errors, actual: %v , expected: %v", header, writeErr, tt.err)
						case written != len(bWrite) && tt.err == nil:
							t.Errorf("%s: readWriter.Write(b) wrote %d bytes instead of expected %d", header, written, len(bWrite))
						case string(bRead) != tt.expected && tt.err == nil:
							t.Errorf("%s: mismatched contents, actual then expected", header)
							t.Log(string(bRead))
							t.Log(tt.expected)
						}
					}
				}
			}
		})
	})
}

func TestIso9660Finalize(t *testing.T) {

}


text:
package org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.strategy.decoration;

import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.HaltedTraverserStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedPath;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedProperty;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceEdge;
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferencePath;
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceProperty;
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceVertex;
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceVertexProperty;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class HaltedTraverserStrategyTest {

    @Before
    public void setup() {
        // necessary as ComputerResult step for testing purposes attaches Attachables
        System.setProperty("is.testing", "false");
    }

    @After
    public void shutdown() {
        System.setProperty("is.testing", "true");
    }

    @Test
    public void shouldReturnDetachedElements() {
        final Graph graph = TinkerFactory.createModern();
        final GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.detached());
        g.V().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
        g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(DetachedVertexProperty.class, vertexProperty.getClass()));
        g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
        g.V().out().outE().forEachRemaining(edge -> assertEquals(DetachedEdge.class, edge.getClass()));
        g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(DetachedProperty.class, property.getClass()));
        g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
        g.V().out().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
        g.V().out().out().path().forEachRemaining(path -> assertEquals(DetachedPath.class, path.getClass()));
        g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
        g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    }

    @Test
    public void shouldReturnReferenceElements() {
        final Graph graph = TinkerFactory.createModern();
        GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.reference());
        g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
        g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
        g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
        g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
        g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
        g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
        g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        // the default should be reference elements
        g = graph.traversal().withComputer();
        g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
        g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
        g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
        g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
        g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
        g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
        g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
        g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="25dp"
    tools:background="@color/colorPrimary"
    android:id="@+id/cl_alc_container">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/civ_alc_avatar"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintDimensionRatio="H, 1:1"
        tools:src="@drawable/ribot_logo" />

    <TextView
        android:id="@+id/tv_alc_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:autoSizeMaxTextSize="18sp"
        android:autoSizeMinTextSize="12sp"
        android:autoSizeTextType="uniform"
        android:gravity="center_horizontal"
        android:maxLines="1"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@+id/civ_alc_avatar"
        app:layout_constraintStart_toStartOf="@+id/civ_alc_avatar"
        app:layout_constraintTop_toBottomOf="@+id/civ_alc_avatar"
        tools:text="Stu Stirling" />

</android.support.constraint.ConstraintLayout>