text:
package com.microsoft.azure.storage;

import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.BlobTestHelper;
import com.microsoft.azure.storage.blob.BlobType;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.microsoft.azure.storage.blob.CloudPageBlob;
import com.microsoft.azure.storage.blob.DeleteSnapshotsOption;
import com.microsoft.azure.storage.queue.CloudQueue;
import com.microsoft.azure.storage.queue.CloudQueueClient;
import com.microsoft.azure.storage.queue.QueueRequestOptions;
import com.microsoft.azure.storage.queue.QueueTestHelper;
import com.microsoft.azure.storage.table.CloudTable;
import com.microsoft.azure.storage.table.CloudTableClient;
import com.microsoft.azure.storage.table.TableRequestOptions;
import com.microsoft.azure.storage.table.TableTestHelper;
import com.microsoft.azure.storage.TestRunners.CloudTests;
import com.microsoft.azure.storage.TestRunners.DevFabricTests;
import com.microsoft.azure.storage.TestRunners.DevStoreTests;
import com.microsoft.azure.storage.TestRunners.SlowTests;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

@Category({ SecondaryTests.class, DevFabricTests.class, DevStoreTests.class, CloudTests.class })
public class SecondaryTests {

    @Test
    public void testLocationModeWithMissingUri() throws URISyntaxException, StorageException {
        CloudBlobClient client = TestHelper.createCloudBlobClient();
        CloudBlobClient primaryOnlyClient = new CloudBlobClient(client.getEndpoint(), client.getCredentials());
        CloudBlobContainer container = primaryOnlyClient.getContainerReference("nonexistingcontainer");

        BlobRequestOptions options = new BlobRequestOptions();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        options.setRetryPolicyFactory(new RetryNoRetry());

        try {
            container.downloadAttributes(null, options, null);
            fail();
        }
        catch (StorageException ex) {
            assertEquals(UnsupportedOperationException.class, ex.getCause().getClass());
        }

        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);

        try {
            container.downloadAttributes(null, options, null);
            fail();
        }
        catch (StorageException ex) {
            assertEquals(UnsupportedOperationException.class, ex.getCause().getClass());
        }

        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);

        try {
            container.downloadAttributes(null, options, null);
            fail();
        }
        catch (StorageException ex) {
            assertEquals(UnsupportedOperationException.class, ex.getCause().getClass());
        }
    }

    @Test
    public void testBlobIfExistsShouldNotHitSecondary() throws StorageException, URISyntaxException {
        CloudBlobContainer container = BlobTestHelper.getRandomContainerReference();

        BlobRequestOptions options = new BlobRequestOptions();

        // CreateIfNotExists
        OperationContext context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        container.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        container.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        container.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            container.createIfNotExists(options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }

        // DeleteIfExists
        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        container.deleteIfExists(null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        container.deleteIfExists(null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        container.deleteIfExists(null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            container.deleteIfExists(null, options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }

        CloudBlockBlob blockBlob = container.getBlockBlobReference("blob1");

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        blockBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        blockBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        blockBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            blockBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }

        CloudPageBlob pageBlob = container.getPageBlobReference("blob2");

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        pageBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        pageBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        pageBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            pageBlob.deleteIfExists(DeleteSnapshotsOption.NONE, null, options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }
    }

    @Test
    public void testQueueIfExistsShouldNotHitSecondary() throws StorageException, URISyntaxException {

        CloudQueueClient client = TestHelper.createCloudQueueClient();

        CloudQueue queue = client.getQueueReference("nonexistantqueue");

        QueueRequestOptions options = new QueueRequestOptions();

        // CreateIfNotExists
        OperationContext context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        queue.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        queue.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        queue.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            queue.createIfNotExists(options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }

        // DeleteIfExists
        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        queue.deleteIfExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        queue.deleteIfExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        queue.deleteIfExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            queue.deleteIfExists(options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }
    }

    @Test
    public void testTableIfExistsShouldNotHitSecondary() throws StorageException, URISyntaxException {
        CloudTableClient client = TestHelper.createCloudTableClient();
        CloudTable table = client.getTableReference("nonexistanttable");

        TableRequestOptions options = new TableRequestOptions();

        // CreateIfNotExists
        OperationContext context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        table.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        table.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        table.createIfNotExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            table.createIfNotExists(options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }

        // DeleteIfExists
        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_ONLY);
        table.deleteIfExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.PRIMARY_THEN_SECONDARY);
        table.deleteIfExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_THEN_PRIMARY);
        table.deleteIfExists(options, context);
        assertEquals(StorageLocation.PRIMARY, context.getRequestResults().get(0).getTargetLocation());

        context = new OperationContext();
        options.setLocationMode(LocationMode.SECONDARY_ONLY);
        try {
            table.deleteIfExists(options, context);
        }
        catch (StorageException ex) {
            assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
        }
    }

    @Test
    @Category(SlowTests.class)
    public void testMultiLocationRetriesBlob() throws URISyntaxException, StorageException {
        List<RetryInfo> retryInfoList = new ArrayList<RetryInfo>();
        List<RetryContext> retryContextList = new ArrayList<RetryContext>();

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));

        // Next location is set to primary and location mode is primary only.
        testContainerDownloadAttributes(LocationMode.PRIMARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));

        // Next location is set to secondary and location mode is secondary only.
        testContainerDownloadAttributes(LocationMode.SECONDARY_ONLY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.SECONDARY_ONLY, StorageLocation.SECONDARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));

        // Next location is set to secondary and location mode is PRIMARY_THEN_SECONDARY.
        testContainerDownloadAttributes(LocationMode.PRIMARY_THEN_SECONDARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.PRIMARY, retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.PRIMARY_THEN_SECONDARY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));

        // Next location is set to primary and location mode is SECONDARY_THEN_PRIMARY.
        testContainerDownloadAttributes(LocationMode.SECONDARY_THEN_PRIMARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.SECONDARY_THEN_PRIMARY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testContainerDownloadAttributes(LocationMode.PRIMARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY,
                6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY,
                1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testContainerDownloadAttributes(LocationMode.SECONDARY_ONLY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.SECONDARY_ONLY, StorageLocation.SECONDARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testContainerDownloadAttributes(LocationMode.PRIMARY_THEN_SECONDARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.PRIMARY, retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.PRIMARY_THEN_SECONDARY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_THEN_PRIMARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testContainerDownloadAttributes(LocationMode.SECONDARY_THEN_PRIMARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testContainerDownloadAttributes(null, LocationMode.SECONDARY_THEN_PRIMARY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
    }

    @Test
    @Category(SlowTests.class)
    public void testMultiLocationRetriesQueue() throws URISyntaxException, StorageException {
        List<RetryInfo> retryInfoList = new ArrayList<RetryInfo>();
        List<RetryContext> retryContextList = new ArrayList<RetryContext>();

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));

        // Next location is set to primary and location mode is primary only.
        testQueueDownloadAttributes(LocationMode.PRIMARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));

        // Next location is set to secondary and location mode is secondary only.
        testQueueDownloadAttributes(LocationMode.SECONDARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.SECONDARY_ONLY, StorageLocation.SECONDARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));

        // Next location is set to secondary and location mode is PRIMARY_THEN_SECONDARY.
        testQueueDownloadAttributes(LocationMode.PRIMARY_THEN_SECONDARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.PRIMARY, retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.PRIMARY_THEN_SECONDARY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));

        // Next location is set to primary and location mode is SECONDARY_THEN_PRIMARY.
        testQueueDownloadAttributes(LocationMode.SECONDARY_THEN_PRIMARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.SECONDARY_THEN_PRIMARY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testQueueDownloadAttributes(LocationMode.PRIMARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY,
                6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY,
                1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testQueueDownloadAttributes(LocationMode.SECONDARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.SECONDARY_ONLY, StorageLocation.SECONDARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testQueueDownloadAttributes(LocationMode.PRIMARY_THEN_SECONDARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.PRIMARY, retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.PRIMARY_THEN_SECONDARY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_THEN_PRIMARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testQueueDownloadAttributes(LocationMode.SECONDARY_THEN_PRIMARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testQueueDownloadAttributes(null, LocationMode.SECONDARY_THEN_PRIMARY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
    }

    @Test
    @Category(SlowTests.class)
    public void testMultiLocationRetriesTable() throws URISyntaxException, StorageException {
        List<RetryInfo> retryInfoList = new ArrayList<RetryInfo>();
        List<RetryContext> retryContextList = new ArrayList<RetryContext>();

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));

        // Next location is set to primary and location mode is primary only.
        testTableDownloadPermissions(LocationMode.PRIMARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));

        // Next location is set to secondary and location mode is secondary only.
        testTableDownloadPermissions(LocationMode.SECONDARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.SECONDARY_ONLY, StorageLocation.SECONDARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));

        // Next location is set to secondary and location mode is PRIMARY_THEN_SECONDARY.
        testTableDownloadPermissions(LocationMode.PRIMARY_THEN_SECONDARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.PRIMARY, retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.PRIMARY_THEN_SECONDARY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));

        // Next location is set to primary and location mode is SECONDARY_THEN_PRIMARY.
        testTableDownloadPermissions(LocationMode.SECONDARY_THEN_PRIMARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.SECONDARY_THEN_PRIMARY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testTableDownloadPermissions(LocationMode.PRIMARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.PRIMARY_ONLY, StorageLocation.PRIMARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY,
                6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY,
                1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testTableDownloadPermissions(LocationMode.SECONDARY_ONLY, LocationMode.PRIMARY_ONLY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.SECONDARY_ONLY, StorageLocation.SECONDARY, retryContextList,
                retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.PRIMARY_THEN_SECONDARY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testTableDownloadPermissions(LocationMode.PRIMARY_THEN_SECONDARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.PRIMARY, retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.PRIMARY_THEN_SECONDARY, StorageLocation.PRIMARY,
                retryContextList, retryInfoList);

        retryContextList.clear();
        retryInfoList.clear();
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 6000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_THEN_PRIMARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
        AddUpdatedLocationModes(retryContextList, retryInfoList);

        // Use AlwaysRetry and retry the request multiple times based on the retry context and retry info lists created above.
        testTableDownloadPermissions(LocationMode.SECONDARY_THEN_PRIMARY, LocationMode.PRIMARY_ONLY,
                StorageLocation.SECONDARY, retryContextList, retryInfoList);
        testTableDownloadPermissions(null, LocationMode.SECONDARY_THEN_PRIMARY, StorageLocation.SECONDARY,
                retryContextList, retryInfoList);
    }

    @Test
    public void testRetryOn304() throws StorageException, IOException, URISyntaxException {
        OperationContext operationContext = new OperationContext();
        operationContext.getRetryingEventHandler().addListener(new StorageEvent<RetryingEvent>() {
            @Override
            public void eventOccurred(RetryingEvent eventArg) {
                fail("Request should not be retried.");
            }
        });

        CloudBlobContainer container = BlobTestHelper.getRandomContainerReference();
        try {
            container.create();
            CloudBlockBlob blockBlobRef = (CloudBlockBlob) BlobTestHelper.uploadNewBlob(container, BlobType.BLOCK_BLOB,
                    "originalBlob", 1024, null);
            AccessCondition accessCondition = AccessCondition.generateIfNoneMatchCondition(blockBlobRef.getProperties().getEtag());
            blockBlobRef.download(new ByteArrayOutputStream(), accessCondition, null, operationContext);

            fail("Download should fail with a 304.");
        } catch (StorageException ex) {
            assertEquals("The condition specified using HTTP conditional header(s) is not met.", ex.getMessage());
        } finally {
            container.deleteIfExists();
        }
    }

    private static void AddUpdatedLocationModes(List<RetryContext> retryContextList, List<RetryInfo> retryInfoList) {
        retryInfoList
                .add(populateRetryInfo(new RetryInfo(), StorageLocation.PRIMARY, LocationMode.SECONDARY_ONLY, 4000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.SECONDARY, LocationMode.SECONDARY_ONLY));
        retryInfoList
                .add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY, LocationMode.PRIMARY_ONLY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_ONLY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.PRIMARY_THEN_SECONDARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.PRIMARY_THEN_SECONDARY));
        retryInfoList.add(populateRetryInfo(new RetryInfo(), StorageLocation.SECONDARY,
                LocationMode.SECONDARY_THEN_PRIMARY, 1000));
        retryContextList.add(new RetryContext(0, null, StorageLocation.PRIMARY, LocationMode.SECONDARY_THEN_PRIMARY));
    }

    private static RetryInfo populateRetryInfo(RetryInfo retryInfo, StorageLocation location,
            LocationMode locationMode, int interval) {
        retryInfo.setTargetLocation(location);
        retryInfo.setUpdatedLocationMode(locationMode);
        retryInfo.setRetryInterval(interval);
        return retryInfo;
    }

    private static void testContainerDownloadAttributes(LocationMode optionsLocationMode,
            LocationMode clientLocationMode, StorageLocation initialLocation, List<RetryContext> retryContextList,
            List<RetryInfo> retryInfoList) throws URISyntaxException, StorageException {
        CloudBlobContainer container = BlobTestHelper.getRandomContainerReference();
        MultiLocationTestHelper helper = new MultiLocationTestHelper(container.getServiceClient().getStorageUri(),
                initialLocation, retryContextList, retryInfoList);

        container.getServiceClient().getDefaultRequestOptions().setLocationMode(clientLocationMode);
        BlobRequestOptions options = new BlobRequestOptions();

        options.setLocationMode(optionsLocationMode);
        options.setRetryPolicyFactory(helper.retryPolicy);

        try {
            container.downloadAttributes(null, options, helper.operationContext);
        }
        catch (StorageException ex) {
            assertEquals(HttpURLConnection.HTTP_NOT_FOUND, ex.getHttpStatusCode());
        }
        finally {
            helper.close();
        }
    }

    private static void testQueueDownloadAttributes(LocationMode optionsLocationMode, LocationMode clientLocationMode,
            StorageLocation initialLocation, List<RetryContext> retryContextList, List<RetryInfo> retryInfoList)
            throws URISyntaxException, StorageException {
        CloudQueueClient client = TestHelper.createCloudQueueClient();
        CloudQueue queue = client.getQueueReference(QueueTestHelper.generateRandomQueueName());

        MultiLocationTestHelper helper = new MultiLocationTestHelper(queue.getServiceClient().getStorageUri(),
                initialLocation, retryContextList, retryInfoList);

        queue.getServiceClient().getDefaultRequestOptions().setLocationMode(clientLocationMode);
        QueueRequestOptions options = new QueueRequestOptions();

        options.setLocationMode(optionsLocationMode);
        options.setRetryPolicyFactory(helper.retryPolicy);

        try {
            queue.downloadAttributes(options, helper.operationContext);
        }
        catch (StorageException ex) {
            assertEquals(HttpURLConnection.HTTP_NOT_FOUND, ex.getHttpStatusCode());
        }
        finally {
            helper.close();
        }
    }

    private static void testTableDownloadPermissions(LocationMode optionsLocationMode, LocationMode clientLocationMode,
            StorageLocation initialLocation, List<RetryContext> retryContextList, List<RetryInfo> retryInfoList)
            throws URISyntaxException, StorageException {
        CloudTableClient client = TestHelper.createCloudTableClient();
        CloudTable table = client.getTableReference(TableTestHelper.generateRandomTableName());

        MultiLocationTestHelper helper = new MultiLocationTestHelper(table.getServiceClient().getStorageUri(),
                initialLocation, retryContextList, retryInfoList);

        table.getServiceClient().getDefaultRequestOptions().setLocationMode(clientLocationMode);
        TableRequestOptions options = new TableRequestOptions();

        options.setLocationMode(optionsLocationMode);
        options.setRetryPolicyFactory(helper.retryPolicy);

        try {
            table.downloadPermissions(options, helper.operationContext);
        }
        catch (StorageException ex) {
            assertEquals(HttpURLConnection.HTTP_NOT_FOUND, ex.getHttpStatusCode());
        }
        finally {
            helper.close();
        }
    }
}


text:
namespace HotelSystem.Web.Areas.Hotels.ViewModels.All
{
    using System.Collections.Generic;
    using System.Linq;

    using AutoMapper;

    using HotelSystem.Data.Models;
    using HotelSystem.Web.Infrastructure.Mapping;

    public class HotelViewModel : IMapFrom<Hotel>, IHaveCustomMappings
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public double Rating { get; set; }

        public IEnumerable<string> Images { get; set; }

        public void CreateMappings(IMapperConfiguration configuration)
        {
            configuration.CreateMap<Hotel, HotelViewModel>()
                .ForMember(m => m.Images, opt => opt.MapFrom(m => m.PhotosSource.Select(p => p.Source)))
                .ForMember(m => m.Rating, opt => opt.MapFrom(m => m.Ratings.Any() ? m.Ratings.Select(r => r.Rate).Average() : 0));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.springtraining.jms;

import javax.jms.JMSException;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringJmsAsynchronousMessageTest {
	public static void main(String[] args) throws JMSException {

		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] {"com/springtraining/jms/spring-config.xml"});

		SpringMessageSender testMessageSender = (SpringMessageSender) context.getBean("testMessageSender");

		testMessageSender.sendMessage("HHHHHHHHHHHHHHHHHHHHHHHHHH");
	}
}


text:
import sys
import re
import os.path
from io import open
from setuptools import find_packages, setup

# Change the PACKAGE_NAME only to change folder and different name
PACKAGE_NAME = "azure-appconfiguration"
PACKAGE_PPRINT_NAME = "App Configuration Data"

# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace("-", "/")
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace("-", ".")

# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, "_version.py"), "r") as fd:
    version = re.search(
        r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE
    ).group(1)

if not version:
    raise RuntimeError("Cannot find version information")

with open("README.md", encoding="utf-8") as f:
    readme = f.read()
with open("CHANGELOG.md", encoding="utf-8") as f:
    changelog = f.read()

exclude_packages = [
    "tests",
    "tests.*",
    "samples",
    # Exclude packages that will be covered by PEP420 or nspkg
    "azure",
]
if sys.version_info < (3, 5, 3):
    exclude_packages.extend(["*.aio", "*.aio.*"])

setup(
    name=PACKAGE_NAME,
    version=version,
    include_package_data=True,
    description="Microsoft {} Library for Python".format(PACKAGE_PPRINT_NAME),
    long_description=readme + "\n\n" + changelog,
    long_description_content_type="text/markdown",
    license="MIT License",
    author="Microsoft Corporation",
    author_email="azpysdkhelp@microsoft.com",
    url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/appconfiguration/azure-appconfiguration",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "License :: OSI Approved :: MIT License",
    ],
    zip_safe=False,
    packages=find_packages(exclude=exclude_packages),
    python_requires=">=3.7",
    install_requires=[
        "azure-core<2.0.0,>=1.24.0",
        "isodate>=0.6.0",
    ],
)


text:
"""A set of helper classes to for use by generated python code."""

import ctypes
import re
import struct

from makani.lib.python.pack2 import metadata

# In order to maintain compatibility with ctypes we need to use some protected
# member of that package.  We disable those lint errors here.
# pylint: disable=protected-access

def _IsCtypeArray(obj):
  # Ctype arrays have a _length_ attr, scalars do not.
  return hasattr(obj, '_length_')

class PackableCType(object):

  def PackInto(self, buff, offset):
    struct.pack_into('>' + self._type_, buff, offset, self.value)

  def UnpackFrom(self, buff, offset):
    self.value = struct.unpack_from('>' + self._type_, buff, offset)[0]

class UInt8(ctypes._SimpleCData, PackableCType):
  _type_ = 'B'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '0x%02x' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class Int8(ctypes._SimpleCData, PackableCType):
  _type_ = 'b'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '%d' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class UInt16(ctypes._SimpleCData, PackableCType):
  _type_ = 'H'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '0x%04x' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class Int16(ctypes._SimpleCData, PackableCType):
  _type_ = 'h'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '%d' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class UInt32(ctypes._SimpleCData, PackableCType):
  _type_ = 'L'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '0x%08x' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class Int32(ctypes._SimpleCData, PackableCType):
  _type_ = 'l'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '%d' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class Float32(ctypes._SimpleCData, PackableCType):
  _type_ = 'f'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '%g' % self.value

  def __setstate__(self, state):
    self.value = float(state)

class Date(ctypes._SimpleCData, PackableCType):
  _type_ = 'L'
  size = struct.calcsize(_type_)

  def __repr__(self):
    return '0x%08x' % self.value

  def __setstate__(self, state):
    if isinstance(state, basestring):
      self.value = int(state, 0)
    else:
      self.value = int(state)

class String(object):
  """Pack2 string field."""

  def __init__(self, size, value):
    self.size = size
    self.value = value

  def __repr__(self):
    return self.value

  def PackInto(self, buff, offset):
    struct.pack_into('%ds' % self.size, buff, offset, self.value)

  def UnpackFrom(self, buff, offset):
    self.value = struct.unpack_from('%ds' % self.size, buff, offset)[0]

  def __setstate__(self, state):
    self.value = state

# Things get pretty gross below.  Most of this comes from maintaining
# compatibility with ctypes.  For more info see _NormalizeType() and
# _ForEachElement().
class Structure(ctypes.Structure):
  """Pack2 structure Python base class."""

  def __init__(self, state=None):
    super(Structure, self).__init__()
    if state:
      self.__setstate__(state)

  def _NormalizeType(self, field):
    # When a field's value is assigned to a ctypes Structure, the field
    # in the python object is replaced by whatever type was in the rvalue
    # or the assignment.  Then, some deep magic in the ctypes library
    # ensures that the correct representation ends up in the in memory
    # representation of the object.  This is great for ctypes, not so great
    # for us.  Here we go through the fields and fix up the types.
    field_name, field_class = field
    field_obj = getattr(self, field_name)

    if field_obj.__class__ == field_class:
      return field_obj

    # Arrays require a bit more massaging when constructing them from native
    # types.
    if _IsCtypeArray(field_class):
      # Arrays of c_char are special in ctypes and are treated as strings.
      if field_class._type_ == ctypes.c_char:
        return String(field_class._length_, field_obj)
      field_obj = field_class(*list(field_obj))
    else:
      field_obj = field_class(field_obj)
    return field_obj

  def _ForEachField(self, func):
    for field in self._fields_:
      field_name, _ = field
      field_obj = self._NormalizeType(field)
      field_obj = func(field_name, field_obj)
      if hasattr(field_obj, 'value'):
        setattr(self, field_name, field_obj.value)
      else:
        setattr(self, field_name, field_obj)

  # More ctypes fun here!  Ctype arrays of the primitive types above
  # (i.e. Uint8) have a bit of a split personality.  While array_obj._type_
  # is the correct type (Uint8,) array_obj[i].__class__ is a native Python
  # type (int.)  This helper lets us work solely in our types.
  def _ForEachElement(self, field_obj, func):
    for i in range(len(field_obj)):
      obj = field_obj[i]
      if obj.__class__ != field_obj._type_:
        obj = field_obj._type_(field_obj[i])
      field_obj[i] = func(i, obj)

  def _AlignElemSize(self, elem):
    if hasattr(elem, 'alignment'):
      return metadata.AlignTo(elem.size, elem.alignment)
    else:
      return elem.size

  def PackInto(self, buff, offset):
    def Work(field_name, field_obj):
      """PackInto Work."""
      field_offset = self._offsets_[field_name]
      if _IsCtypeArray(field_obj):
        def ElementWork(i, elem):
          size = self._AlignElemSize(elem)
          elem.PackInto(buff, offset + field_offset + size * i)
          return elem
        self._ForEachElement(field_obj, ElementWork)
      else:
        field_obj.PackInto(buff, offset + field_offset)
      return field_obj
    self._ForEachField(Work)

  def Pack(self):
    buff = ctypes.create_string_buffer(self.size)
    self.PackInto(buff, 0)
    return buff

  def UnpackFrom(self, buff, offset):
    def Work(field_name, field_obj):
      """UnpackFrom Work."""
      field_offset = self._offsets_[field_name]
      if _IsCtypeArray(field_obj):
        def ElementWork(i, elem):
          size = self._AlignElemSize(elem)
          elem.UnpackFrom(buff, offset + field_offset + size * i)
          return elem
        self._ForEachElement(field_obj, ElementWork)
      else:
        field_obj.UnpackFrom(buff, offset + field_offset)
      return field_obj
    self._ForEachField(Work)

  def Unpack(self, buff):
    self.UnpackFrom(buff, 0)

  def SetField(self, name, value):
    def Work(field_name, field_obj):
      if field_name == name:
        if _IsCtypeArray(field_obj):
          def ElementWork(i, elem):
            elem.__setstate__(value[i])
            return elem
          self._ForEachElement(field_obj, ElementWork)
        else:
          field_obj.__setstate__(value)
      return field_obj
    self._ForEachField(Work)

  def _ObjToDictValue(self, obj):
    if hasattr(obj, 'ToDict'):
      return obj.ToDict()
    elif hasattr(obj, 'value'):
      return obj.value
    elif hasattr(obj, '__repr__'):
      return obj.__repr__()
    else:
      return obj

  def ToDict(self):
    state = {}
    def Work(field_name, field_obj):
      """Convert field to dict value."""
      if _IsCtypeArray(field_obj):
        value = [None] * len(field_obj)
        def ElementWork(i, elem):
          value[i] = self._ObjToDictValue(elem)
          return elem
        self._ForEachElement(field_obj, ElementWork)
        state[field_name] = value
      else:
        state[field_name] = self._ObjToDictValue(field_obj)
      return field_obj
    self._ForEachField(Work)
    return state

  def _FieldYamlValue(self, field_obj, indent):
    if hasattr(field_obj, 'ToYaml'):
      value = field_obj.ToYaml(False, indent + '  ')
    else:
      value = repr(field_obj)

    if isinstance(field_obj, String):
      value = '"' + value + '"'

    return value

  # We do our own YAML output for a couple reasons:
  #   - yaml.YAMLObject is has a metaclass.  This appears incompatible with
  #   ctypes.
  #   - We only want to omit !tags on the toplevel object.
  def ToYaml(self, output_tag=True, indent='  '):
    if output_tag:
      out = ['!' + self.__class__.__name__ + '\n']
    else:
      out = ['\n']

    def Work(field_name, field_obj):
      """Convert a field to YAML."""
      if _IsCtypeArray(field_obj):
        out[0] += '{indent}{field_name}:\n'.format(indent=indent,
                                                   field_name=field_name)
        def ElementWork(i, elem):  # pylint: disable=unused-argument
          value = self._FieldYamlValue(elem, indent + '  ')
          # Structures come with leading and trailing whitespace.  They are
          # not needed in this context
          value = re.sub(r'^[\s\n]*(.*?)[\s\n]*$', r'\1', value,
                         flags=re.DOTALL)
          out[0] += '{indent}  - {value}\n'.format(indent=indent, value=value)
          return elem
        self._ForEachElement(field_obj, ElementWork)
      else:
        value = self._FieldYamlValue(field_obj, indent)
        out[0] += '%s%s:' % (indent, field_name)
        if value.startswith('\n'):
          # Substructures start with a newline and come pre-formatted.
          out[0] += value
        else:
          if value:
            out[0] += ' {}'.format(value)
          out[0] += '\n'
      return field_obj
    self._ForEachField(Work)
    return out[0]

  def CopyFrom(self, orig):
    def Work(field_name, field_obj):
      orig_obj = getattr(orig, field_name)

      if hasattr(field_obj, 'CopyFrom'):
        field_obj.CopyFrom(orig_obj)
      else:
        field_obj = orig_obj

      return field_obj
    self._ForEachField(Work)

  def __reduce__(self):
    return (self.__class__, (self.ToDict(),))

  def __setstate__(self, state):
    field_names = set(state.keys())

    has_template = False
    if 'TEMPLATE' in state:
      self.CopyFrom(state['TEMPLATE'])
      has_template = True
      field_names.remove('TEMPLATE')

    def Work(field_name, field_obj):
      """Set the state of a field."""

      if field_name not in state:
        if has_template:
          return field_obj
        raise KeyError("'%s' not found when setting state for class '%s'"
                       % (field_name, self.__class__.__name__))

      field_names.remove(field_name)

      if _IsCtypeArray(field_obj):
        field_state = state[field_name]
        def ElementWork(i, elem):
          elem.__setstate__(field_state[i])
          return elem

        self._ForEachElement(field_obj, ElementWork)
      else:
        field_obj.__setstate__(state[field_name])
      return field_obj

    self._ForEachField(Work)

    if field_names:
      raise KeyError('Unknown fields %s in state for class %s.'
                     % (list(field_names), self.__class__.__name__))


text:
package git4idea.branch;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.util.containers.ContainerUtil;
import git4idea.GitCommit;
import git4idea.GitExecutionException;
import git4idea.GitLocalBranch;
import git4idea.GitPlatformFacade;
import git4idea.changes.GitChangeUtils;
import git4idea.commands.Git;
import git4idea.history.GitHistoryUtils;
import git4idea.rebase.GitRebaseUtils;
import git4idea.repo.GitRepository;
import git4idea.ui.branch.GitCompareBranchesDialog;
import git4idea.util.GitCommitCompareInfo;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Executes the logic of git branch operations.
 * All operations are run in the current thread.
 * All UI interaction is done via the {@link GitBranchUiHandler} passed to the constructor.
 *
 * @author Kirill Likhodedov
 */
public final class GitBranchWorker {

  private static final Logger LOG = Logger.getInstance(GitBranchWorker.class);

  @NotNull private final Project myProject;
  @NotNull private final GitPlatformFacade myFacade;
  @NotNull private final Git myGit;
  @NotNull private final GitBranchUiHandler myUiHandler;

  public GitBranchWorker(@NotNull Project project, @NotNull GitPlatformFacade facade, @NotNull Git git, @NotNull GitBranchUiHandler uiHandler) {
    myProject = project;
    myFacade = facade;
    myGit = git;
    myUiHandler = uiHandler;
  }

  public void checkoutNewBranch(@NotNull final String name, @NotNull List<GitRepository> repositories) {
    updateInfo(repositories);
    repositories = ContainerUtil.filter(repositories, new Condition<GitRepository>() {
      @Override
      public boolean value(GitRepository repository) {
        GitLocalBranch currentBranch = repository.getCurrentBranch();
        return currentBranch == null || !currentBranch.getName().equals(name);
      }
    });
    if (!repositories.isEmpty()) {
      new GitCheckoutNewBranchOperation(myProject, myFacade, myGit, myUiHandler, repositories, name).execute();
    }
    else {
      LOG.error("Creating new branch the same as current in all repositories: " + name);
    }
  }

  public void createNewTag(@NotNull final String name, @NotNull final String reference, @NotNull final List<GitRepository> repositories) {
    for (GitRepository repository : repositories) {
      myGit.createNewTag(repository, name, null, reference);
      VfsUtil.markDirtyAndRefresh(true, true, false, repository.getGitDir());
    }
  }

  public void checkoutNewBranchStartingFrom(@NotNull String newBranchName, @NotNull String startPoint,
                                            @NotNull List<GitRepository> repositories) {
    updateInfo(repositories);
    new GitCheckoutOperation(myProject, myFacade, myGit, myUiHandler, repositories, startPoint, false, newBranchName).execute();
  }

  public void checkout(@NotNull final String reference, boolean detach, @NotNull List<GitRepository> repositories) {
    updateInfo(repositories);
    new GitCheckoutOperation(myProject, myFacade, myGit, myUiHandler, repositories, reference, detach, null).execute();
  }

  public void deleteBranch(@NotNull final String branchName, @NotNull final List<GitRepository> repositories) {
    updateInfo(repositories);
    new GitDeleteBranchOperation(myProject, myFacade, myGit, myUiHandler, repositories, branchName).execute();
  }

  public void deleteRemoteBranch(@NotNull final String branchName, @NotNull final List<GitRepository> repositories) {
    updateInfo(repositories);
    new GitDeleteRemoteBranchOperation(myProject, myFacade, myGit, myUiHandler, repositories, branchName).execute();
  }

  public void merge(@NotNull final String branchName, @NotNull final GitBrancher.DeleteOnMergeOption deleteOnMerge,
                    @NotNull final List<GitRepository> repositories) {
    updateInfo(repositories);
    Map<GitRepository, String> revisions = new HashMap<GitRepository, String>();
    for (GitRepository repository : repositories) {
      revisions.put(repository, repository.getCurrentRevision());
    }
    new GitMergeOperation(myProject, myFacade, myGit, myUiHandler, repositories, branchName, deleteOnMerge, revisions).execute();
  }

  public void rebase(@NotNull List<GitRepository> repositories, @NotNull String branchName) {
    updateInfo(repositories);
    GitRebaseUtils.rebase(myProject, repositories, new GitRebaseParams(branchName),
                          ProgressManager.getInstance().getProgressIndicator());
  }

  public void compare(@NotNull final String branchName, @NotNull final List<GitRepository> repositories,
                      @NotNull final GitRepository selectedRepository) {
    final GitCommitCompareInfo myCompareInfo = loadCommitsToCompare(repositories, branchName);
    if (myCompareInfo == null) {
      LOG.error("The task to get compare info didn't finish. Repositories: \n" + repositories + "\nbranch name: " + branchName);
      return;
    }
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        displayCompareDialog(branchName, GitBranchUtil.getCurrentBranchOrRev(repositories), myCompareInfo, selectedRepository);
      }
    });
  }

  private GitCommitCompareInfo loadCommitsToCompare(List<GitRepository> repositories, String branchName) {
    GitCommitCompareInfo compareInfo = new GitCommitCompareInfo();
    for (GitRepository repository : repositories) {
      compareInfo.put(repository, loadCommitsToCompare(repository, branchName));
      compareInfo.put(repository, loadTotalDiff(repository, branchName));
    }
    return compareInfo;
  }

  @NotNull
  private static Collection<Change> loadTotalDiff(@NotNull GitRepository repository, @NotNull String branchName) {
    try {
      return GitChangeUtils.getDiff(repository.getProject(), repository.getRoot(), null, branchName, null);
    }
    catch (VcsException e) {
      // we treat it as critical and report an error
      throw new GitExecutionException("Couldn't get [git diff " + branchName + "] on repository [" + repository.getRoot() + "]", e);
    }
  }

  @NotNull
  private Couple<List<GitCommit>> loadCommitsToCompare(@NotNull GitRepository repository, @NotNull final String branchName) {
    final List<GitCommit> headToBranch;
    final List<GitCommit> branchToHead;
    try {
      headToBranch = GitHistoryUtils.history(myProject, repository.getRoot(), ".." + branchName);
      branchToHead = GitHistoryUtils.history(myProject, repository.getRoot(), branchName + "..");
    }
    catch (VcsException e) {
      // we treat it as critical and report an error
      throw new GitExecutionException("Couldn't get [git log .." + branchName + "] on repository [" + repository.getRoot() + "]", e);
    }
    return Couple.of(headToBranch, branchToHead);
  }

  private void displayCompareDialog(@NotNull String branchName, @NotNull String currentBranch, @NotNull GitCommitCompareInfo compareInfo,
                                    @NotNull GitRepository selectedRepository) {
    if (compareInfo.isEmpty()) {
      Messages.showInfoMessage(myProject, String.format("There are no changes between %s and %s",
                                                        currentBranch, branchName), "No Changes Detected");
    }
    else {
      new GitCompareBranchesDialog(myProject, branchName, currentBranch, compareInfo, selectedRepository).show();
    }
  }

  private static void updateInfo(@NotNull Collection<GitRepository> repositories) {
    for (GitRepository repository : repositories) {
      repository.update();
    }
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Website of Ren He - Welcome!</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Ren He

                        Objectives

                        Experience

                        Eduction

                        Contact

Welcome to my website!

It's Nice To Meet You

                learn More About Me

Objectives

I am looking for full-time or part-time positions as following.

Full-stack Developer

Front-end code in one or more languages, e.g.
					     HTML, JavaScript, Java, etc. API / back-end code in one or more languages,
						  e.g. Ruby, Java, Python, etc. Understanding, creating, manipulating, and querying databases.

Software Engineer

 Analyze user needs and software requirements to determine
					         feasibility of design within time and cost constraints.Modify existing software to correct errors, allow it to adapt to new hardware, or to improve its performance.

QA Test Engineer

Review requirements specifications and technical design documents to provide timely and meaningful feedback. Estimate, prioritize, plan, and coordinate testing activities.

Experience

Projects from 2010 to present.

Website Developer

Website Design

Technical Internship

At KLA Tencor

3D-PITA

MRI Project

Text Detection System

Computer Vision Project

QA Engineer Internship

At BOCO Telecom

TurtleBots

Robotic Project

Eduction

Lorem ipsum dolor sit amet consectetur.

2013-2015: Master degree

University at Buffalo, SUNY

Courses: Computer vision and Images processing, Intro to MRI, Detection and Estimation I, MIMO Wireless communication,
											Communication Electronics, and Analysis of Algorithms.

											Grade: 3.91/4.00

2011-2013: Bachelor Degree

Australian National University

Courses: Computer Vision, Robotic, Digital Systems Microprocessors, Systems Engineering Analysis,
													Discrete-Time Signal Processing, Digital Communications,Networked Information Systems.

												Grade: Distinction. Graduated with Second Class Honours Division A.

2009-2011: Bachelor Degree

Beijing Institute of Technology

Courses: Algorithms, Data Structure, Signal and System, Computer Architecture, Engineering mechanics and Web Development.

												Grade: 3.52/4.00.

Higigh

School

Contact Me

Lorem ipsum dolor sit amet consectetur.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © Ren He 2015

Privacy Policy

Terms of Use

Personal Website

Design my own website.

Design my personal own by HTML, CSS and Bootstrap! A personal website include my background, project and education!

                                Want these website template?You can download this template for free! Download it at startbootstrap.com/.

Date: July 2015

Client: Ren He

Category: Website Developer

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Phase Unwarpping project

Technical Intern/Co-op at KLA Tencor

Evaluated performances of different phase unwrapping algorithms in the WIG/Surfscan group. Analyzed most current
existed							 state-of-art phase unwrapping algorithms and involved in developing as well as testing algorithms.

Date: March 2015

Company: KLA Tencor

Category: Algorithm Engineer

							<button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

MRI Project: 3D-PITA

Thesis project at UB

Designed a novel sampling pattern and developed a two steps reconstruction strategy for 3D MRI image reconstruction.
									Implemented a kernel-based method during calibration process to estimate the missing data. The reconstruction quality
									was significantly improved compared with conventional 3D GRAPPA at high reduction factors.

Published at ISMRM 23rd Annual Meeting and Exhibition 2015 www.ismrm.org.

Launages: -C/C++, Java, Python and Matlab.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Computer Vision project: Text Detection System

Thesis project at ANU

Developed a Text Detection system based on Stroke Width Transform and Maximally
										Stable Extremal Regions features with LibSVM and Random Forest Classifiers.
										Texts in natural images could be detected with accuracy of 87%..

Launages: -C, C++, Matlab and OpenCV.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Electrical Engineering, QA Intern -

QA Intern at BOCO Inter-Telecom

Focused on debugging and testing an ETC system which is based on Expressway Information Management Platform.
								Trained a Support Vector Machine model to test data accuracy. The efficiency of testing functions got improved by 200%.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Robotic Project: Turtlebot

Student Project at ANU

Leaded a team with 3 members and implemented the TurtleBot.
									scaping and object seeking. Mainly focused on modules and AI design. Turtlebot could escape a small room and successfully find target objects.

Launages: -C, C++ and OpenCV.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>