text:
package com.opengamma.masterdb.exchange;

import static com.google.common.collect.Lists.newArrayList;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.threeten.bp.temporal.ChronoUnit.HOURS;
import static org.threeten.bp.temporal.ChronoUnit.MINUTES;
import static org.threeten.bp.temporal.ChronoUnit.SECONDS;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.threeten.bp.Clock;
import org.threeten.bp.Instant;
import org.threeten.bp.ZoneOffset;

import com.opengamma.DataNotFoundException;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.exchange.ExchangeDocument;
import com.opengamma.master.exchange.ExchangeHistoryRequest;
import com.opengamma.master.exchange.ExchangeHistoryResult;
import com.opengamma.master.exchange.ExchangeSearchRequest;
import com.opengamma.master.exchange.ExchangeSearchResult;
import com.opengamma.master.exchange.ManageableExchange;
import com.opengamma.util.test.DbTest;
import com.opengamma.util.test.TestGroup;

/**
 * Tests ModifyExchangeDbExchangeMasterWorker.
 */
@Test(groups = TestGroup.UNIT_DB)
public class ModifyExchangeDbExchangeMasterWorkerReplaceVersionTest extends AbstractDbExchangeMasterWorkerTest {
  // superclass sets up dummy database

  private static final Logger LOGGER = LoggerFactory.getLogger(ModifyExchangeDbExchangeMasterWorkerReplaceVersionTest.class);
  private static final ExternalIdBundle BUNDLE = ExternalIdBundle.of("A", "B");
  private static final ExternalIdBundle REGION = ExternalIdBundle.of("C", "D");

  @Factory(dataProvider = "databases", dataProviderClass = DbTest.class)
  public ModifyExchangeDbExchangeMasterWorkerReplaceVersionTest(final String databaseType, final String databaseVersion) {
    super(databaseType, databaseVersion, false);
    LOGGER.info("running testcases for {}", databaseType);
  }

  //-------------------------------------------------------------------------

  @Test
  public void test_ReplaceVersion_of_some_middle_version() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));
      final ExchangeDocument latestDoc = _exgMaster.get(baseOid, VersionCorrection.LATEST);
      final Instant latestFrom = latestDoc.getVersionFromInstant();

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 0; i <= 10; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "test" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(latestFrom.plus(i, MINUTES));
        replacement.add(doc);
      }

      _exgMaster.replaceVersion(latestDoc.getUniqueId(), replacement);

      final ExchangeSearchRequest searchRequest = new ExchangeSearchRequest();
      searchRequest.addExternalIds(bundle.getExternalIds());
      searchRequest.setVersionCorrection(VersionCorrection.LATEST);
      final ExchangeSearchResult result = _exgMaster.search(searchRequest);
      final List<ManageableExchange> exchanges = result.getExchanges();

      assertEquals(1, exchanges.size());
      final ManageableExchange ex = exchanges.get(0);
      assertEquals("test10", ex.getName());

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_ReplaceVersion_of_some_middle_version_timeBoundsNotExact() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));
      final ExchangeDocument latestDoc = _exgMaster.get(baseOid, VersionCorrection.LATEST);
      final Instant latestFrom = latestDoc.getVersionFromInstant();

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 1; i <= 10; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "test" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(latestFrom.plus(i, MINUTES));
        replacement.add(doc);
      }

      _exgMaster.replaceVersion(latestDoc.getUniqueId(), replacement);

      final ExchangeSearchRequest searchRequest = new ExchangeSearchRequest();
      searchRequest.addExternalIds(bundle.getExternalIds());
      searchRequest.setVersionCorrection(VersionCorrection.LATEST);
      final ExchangeSearchResult result = _exgMaster.search(searchRequest);
      final List<ManageableExchange> exchanges = result.getExchanges();

      assertEquals(1, exchanges.size());
      final ManageableExchange ex = exchanges.get(0);
      assertEquals("test10", ex.getName());

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_ReplaceVersion_which_is_not_current() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));

      final ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsToInstant(null);
      final ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      final List<ExchangeDocument> exchanges = result.getDocuments();

      final ExchangeDocument lastButOneDoc = exchanges.get(exchanges.size() - 1);
      final Instant lastButOneDocVersionFrom = lastButOneDoc.getVersionFromInstant();

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 1; i <= 10; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "test" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(lastButOneDocVersionFrom.plus(i, MINUTES));
        replacement.add(doc);
      }

      _exgMaster.replaceVersion(lastButOneDoc.getUniqueId(), replacement);

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_ReplaceVersion_which_is_not_in_the_time_bounds_of_the_replaced_doc() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));

      final ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsToInstant(null);
      final ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      final List<ExchangeDocument> exchanges = result.getDocuments();

      final ExchangeDocument lastButOneDoc = exchanges.get(exchanges.size() - 3);
      final Instant lastButOneDocVersionFrom = lastButOneDoc.getVersionFromInstant();

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 1; i <= 10; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "test" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(lastButOneDocVersionFrom.plus(i, MINUTES));
        replacement.add(doc);
      }

      _exgMaster.replaceVersion(lastButOneDoc.getUniqueId(), replacement);

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test
  public void test_ReplaceVersions() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));
      final ExchangeDocument latestDoc = _exgMaster.get(baseOid, VersionCorrection.LATEST);
      final Instant latestFrom = latestDoc.getVersionFromInstant();

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 0; i <= 10; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "test" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(latestFrom.plus(i, SECONDS));
        replacement.add(doc);
      }

      _exgMaster.replaceVersions(latestDoc, replacement);

      final ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      final ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      final List<ExchangeDocument> exchanges = result.getDocuments();

      assertEquals(15, exchanges.size());

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test
  public void test_ReplaceVersions2() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));
      final ExchangeDocument latestDoc = _exgMaster.get(baseOid, VersionCorrection.LATEST);
      final Instant latestFrom = latestDoc.getVersionFromInstant();

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 0; i <= 10; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "test" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(latestFrom.plus(i - 3, MINUTES));
        replacement.add(doc);
      }

      _exgMaster.replaceVersions(latestDoc, replacement);

      final ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      final ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      final List<ExchangeDocument> exchanges = result.getDocuments();

      assertEquals(12, exchanges.size());

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  /**
   *
   *       |                        |             |
   *       |                        |             |
   *       |     setup_4            |             |
   *       |                        |             |
   *   +5m |------------------------|             |
   *       |                        |             |
   *       |     setup_3            |             |
   *       |                        |             |
   *   +4m |------------------------|             |
   *       |                        |             |
   *       |     setup_2            |             |
   *       |                        |             |
   *   +3m |------------------------|   |         |
   *       |                        |             |      replace_3
   *       |                        |  <-- +2m30s |----------------------------------->>>
   *       |     setup_1            |             |      replace_2
   *       |                        |  <-- +2m20s |----------------------------------->>>
   *       |                        |             |      replace_1
   *       |                        |  <-- +2m10s |----------------------------------->>>
   *   +2m |------------------------
   *       |
   *       |     setup_0
   *       |
   *   +1m |------------------------ ... --------------------------------------------->>>
   *
   *
   *   NOW =================================================================================
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_ReplaceVersion_notInTimeBounds() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));
      final ExchangeDocument latestDoc = _exgMaster.get(baseOid, VersionCorrection.LATEST);
      assertNotNull(latestDoc);

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 1; i <= 3; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "replace_" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(now.plus(1, MINUTES).plus(i * 10, SECONDS));
        replacement.add(doc);
      }

      final ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      final ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      final List<ExchangeDocument> exchanges = result.getDocuments();

      final ExchangeDocument secondVersionDoc = exchanges.get(exchanges.size() - 2);

      _exgMaster.replaceVersion(secondVersionDoc.getUniqueId(), replacement);

    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  /**
   *
   *       |                        |
   *       |                        |
   *       |     setup_4            |
   *       |                        |
   *   +4m |------------------------|
   *       |                        |
   *       |     setup_3            |
   *       |                        |
   *   +3m |------------------------|
   *       |                        |
   *       |     setup_2            |
   *       |                        |
   *   +2m |------------------------|   |
   *       |                        |  <-- +1m40s |----------------------------------->>>
   *       |                        |             |      replace_3
   *       |                        |  <-- +1m30s |----------------------------------->>>
   *       |     setup_1            |             |      replace_2
   *       |                        |  <-- +1m20s |----------------------------------->>>
   *       |                        |             |      replace_1
   *       |                        |  <-- +1m10s |----------------------------------->>>
   *   +1m |------------------------
   *       |
   *       |     setup_0
   *       |
   *   NOW ===========================================================================>>>
   *
   *
   *
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_ReplaceVersion_inTimeBounds() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));
      final ExchangeDocument latestDoc = _exgMaster.get(baseOid, VersionCorrection.LATEST);
      assertNotNull(latestDoc);

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 1; i <= 3; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "replace_" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(now.plus(1, MINUTES).plus(i * 10, SECONDS));
        replacement.add(doc);
      }
      replacement.get(replacement.size() - 1).setVersionToInstant(now.plus(1, MINUTES).plus(40, SECONDS));

      final ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      final ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      final List<ExchangeDocument> exchanges = result.getDocuments();

      final ExchangeDocument secondVersionDoc = exchanges.get(exchanges.size() - 2);

      _exgMaster.replaceVersion(secondVersionDoc.getUniqueId(), replacement);
    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  /**
   *
   *       |                        |
   *       |                        |
   *       |     setup_4            |
   *       |                        |
   *   +4m |------------------------|
   *       |                        |
   *       |     setup_3            |
   *       |                        |
   *   +3m |------------------------|
   *       |                        |
   *       |     setup_2            |
   *       |                        |
   *   +2m |------------------------|  <-- +2m00s |----------------------------------->>>
   *       |                        |             |      replace_3
   *       |     setup_1            |  <-- +1m40s |----------------------------------->>>
   *       |                        |             |      replace_2
   *       |                        |  <-- +1m20s |----------------------------------->>>
   *       |                        |             |      replace_1
   *   +1m |------------------------   <-- +1m00s |----------------------------------->>>
   *       |
   *       |     setup_0
   *       |
   *   NOW ===========================================================================>>>
   *
   *
   *
   *
   */
  @Test
  public void test_ReplaceVersion_atTimeBounds() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 0; i <= 2; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "replace_" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(now.plus(1, MINUTES).plus(i * 20, SECONDS));
        replacement.add(doc);
      }
      replacement.get(replacement.size() - 1).setVersionToInstant(now.plus(2, MINUTES));

      ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      List<ExchangeDocument> exchanges = result.getDocuments();

      final ExchangeDocument secondVersionDoc = exchanges.get(exchanges.size() - 2);

      _exgMaster.replaceVersion(secondVersionDoc.getUniqueId(), replacement);

      historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      result = _exgMaster.history(historyRequest);
      exchanges = result.getDocuments();

      assertEquals(7, exchanges.size());

      assertEquals(now, exchanges.get(6).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES), exchanges.get(6).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES), exchanges.get(5).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(20, SECONDS), exchanges.get(5).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(20, SECONDS), exchanges.get(4).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(40, SECONDS), exchanges.get(4).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(40, SECONDS), exchanges.get(3).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(60, SECONDS), exchanges.get(3).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(60, SECONDS), exchanges.get(2).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(120, SECONDS), exchanges.get(2).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(120, SECONDS), exchanges.get(1).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(180, SECONDS), exchanges.get(1).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(180, SECONDS), exchanges.get(0).getVersionFromInstant());
      assertEquals(null, exchanges.get(0).getVersionToInstant());
    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  /**
   *
   *       |                                      |                            |
   *       |                                      |                            |
   *       |     setup_4                          |                            |      setup_4
   *       |                                      |                            |
   *   +4m |------------------------              |                            |-------------------
   *       |                                      |                            |
   *       |     setup_3                          |                            |      setup_3
   *       |                                      |                            |
   *   +3m |------------------------              |                            |-------------------
   *       |                                      |                            |
   *       |     setup_2                          |                      =>    |      setup_2
   *       |                                      |                            |
   *   +2m |------------------------   <-- +2m00s |                            |-------------------
   *       |                                      |      replace_2             |      replace_2
   *       |     setup_1               <-- +1m40s |-------------------         |-------------------
   *       |                                      |      replace_1             |      replace_1
   *       |                           <-- +1m20s |-------------------         |-------------------
   *       |                                      |      replace_0             |      replace_0
   *   +1m |------------------------   <-- +1m00s |-------------------         |-------------------
   *       |
   *       |     setup_0                                                              setup_0
   *       |
   *   NOW ======================================================================================>>>
   *
   *
   *
   *
   */
  @Test
  public void test_ReplaceVersion_atTimeBounds2() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 0; i <= 2; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "replace_" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(now.plus(1, MINUTES).plus(i * 20, SECONDS));
        replacement.add(doc);
      }

      ExchangeHistoryRequest historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      ExchangeHistoryResult result = _exgMaster.history(historyRequest);
      List<ExchangeDocument> exchanges = result.getDocuments();

      final ExchangeDocument secondVersionDoc = exchanges.get(exchanges.size() - 2);

      _exgMaster.replaceVersion(secondVersionDoc.getUniqueId(), replacement);

      historyRequest = new ExchangeHistoryRequest();
      historyRequest.setObjectId(baseOid);
      historyRequest.setCorrectionsFromInstant(now.plus(2, HOURS));
      result = _exgMaster.history(historyRequest);
      exchanges = result.getDocuments();

      assertEquals(7, exchanges.size());

      assertEquals(now, exchanges.get(6).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES), exchanges.get(6).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES), exchanges.get(5).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(20, SECONDS), exchanges.get(5).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(20, SECONDS), exchanges.get(4).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(40, SECONDS), exchanges.get(4).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(40, SECONDS), exchanges.get(3).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(60, SECONDS), exchanges.get(3).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(60, SECONDS), exchanges.get(2).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(120, SECONDS), exchanges.get(2).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(120, SECONDS), exchanges.get(1).getVersionFromInstant());
      assertEquals(now.plus(1, MINUTES).plus(180, SECONDS), exchanges.get(1).getVersionToInstant());
      //
      assertEquals(now.plus(1, MINUTES).plus(180, SECONDS), exchanges.get(0).getVersionFromInstant());
      assertEquals(null, exchanges.get(0).getVersionToInstant());
    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_ReplaceVersion_noUid() {
    final Clock origClock = _exgMaster.getClock();
    try {
      final Instant now = Instant.now();

      final ObjectId baseOid = setupTestData(now);
      _exgMaster.setClock(Clock.fixed(now.plus(2, HOURS), ZoneOffset.UTC));

      final ExternalIdBundle bundle = ExternalIdBundle.of("B", "B0");
      final ExternalIdBundle region = ExternalIdBundle.of("R", "R0");
      final List<ExchangeDocument> replacement = newArrayList();
      for (int i = 0; i <= 2; i++) {
        final ManageableExchange ex = new ManageableExchange(bundle, "replace_" + i, region, null);
        final ExchangeDocument doc = new ExchangeDocument(ex);
        doc.setVersionFromInstant(now.plus(1, MINUTES).plus(i * 20, SECONDS));
        replacement.add(doc);
      }

      _exgMaster.replaceVersion(baseOid.atVersion("no such uid"), replacement);
    } finally {
      _exgMaster.setClock(origClock);
    }
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_replaceVersion_nullDocument() {
    _exgMaster.replaceVersion(null);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void test_replaceVersion_noExchangeId() {
    final UniqueId uniqueId = UniqueId.of("DbExg", "101");
    final ManageableExchange exchange = new ManageableExchange(BUNDLE, "Test", REGION, null);
    exchange.setUniqueId(uniqueId);
    final ExchangeDocument doc = new ExchangeDocument(exchange);
    doc.setUniqueId(null);
    _exgMaster.replaceVersion(doc);
  }

  @Test(expectedExceptions = DataNotFoundException.class)
  public void test_replaceVersion_notFound() {
    final UniqueId uniqueId = UniqueId.of("DbExg", "0", "0");
    final ManageableExchange exchange = new ManageableExchange(BUNDLE, "Test", REGION, null);
    exchange.setUniqueId(uniqueId);
    final ExchangeDocument doc = new ExchangeDocument(exchange);
    _exgMaster.replaceVersion(doc);
  }

}


text:
package kieker.monitoring.probe.cxf;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.SoapHeaderInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import kieker.common.record.controlflow.OperationExecutionRecord;
import kieker.monitoring.core.controller.IMonitoringController;
import kieker.monitoring.core.controller.MonitoringController;
import kieker.monitoring.core.registry.ControlFlowRegistry;
import kieker.monitoring.core.registry.SessionRegistry;
import kieker.monitoring.probe.IMonitoringProbe;
import kieker.monitoring.timer.ITimeSource;

/**
 * CXF InInterceptor to get the sessionIdentifier header from an incoming soap message
 * and associate it with the current thread id.
 *
 * Look here how to add it to your server config: http://cwiki.apache.org/CXF20DOC/interceptors.html
 */
/**
 * @author Andre van Hoorn, Dennis Kieselhorst
 *
 * @since 1.0
 */
public class OperationExecutionSOAPResponseInInterceptor extends SoapHeaderInterceptor implements IMonitoringProbe {
	// the CXF logger uses java.util.logging by default, look here how to change it
	// to log4j: http://cwiki.apache.org/CXF20DOC/debugging.html

	/**
	 * This constant contains the signature, which will be used in the monitoring
	 * logs.
	 */
	public static final String SIGNATURE = "public void " + OperationExecutionSOAPResponseInInterceptor.class.getName()
			+ ".handleMessage(org.apache.cxf.message.Message)";

	/** Stores the singleton instance of the session registry. */
	protected static final SessionRegistry SESSION_REGISTRY = SessionRegistry.INSTANCE;
	/** Stores the singleton instance of the control flow registry. */
	protected static final ControlFlowRegistry CF_REGISTRY = ControlFlowRegistry.INSTANCE;
	/** Stores the singleton instance of the SOAP trace registry. */
	protected static final SOAPTraceRegistry SOAP_REGISTRY = SOAPTraceRegistry.getInstance();

	private static final Logger LOGGER = LoggerFactory.getLogger(OperationExecutionSOAPResponseInInterceptor.class);

	/** The monitoring controller of this interceptor. */
	protected final IMonitoringController monitoringController;
	/** The used time source. */
	protected final ITimeSource timeSource;
	/** The name of the VM. */
	protected final String vmName;

	/**
	 * Creates a new instance of this class, using the singleton instance of the
	 * {@link MonitoringController} as controller.
	 */
	public OperationExecutionSOAPResponseInInterceptor() {
		this(MonitoringController.getInstance());
	}

	/**
	 * Creates a new instance of this class, using the given instance of a
	 * {@link MonitoringController} as controller.
	 *
	 * @param monitoringCtrl
	 *            The controller of this interceptor.
	 */
	public OperationExecutionSOAPResponseInInterceptor(final IMonitoringController monitoringCtrl) {
		this.monitoringController = monitoringCtrl;
		this.timeSource = this.monitoringController.getTimeSource();
		this.vmName = this.monitoringController.getHostname();
	}

	@Override
	public void handleMessage(final Message msg) throws Fault {
		if (!this.monitoringController.isMonitoringEnabled()) {
			return;
		}
		if (!this.monitoringController.isProbeActivated(OperationExecutionSOAPResponseInInterceptor.SIGNATURE)) {
			return;
		}
		if (msg instanceof SoapMessage) {
			final boolean isEntryCall = OperationExecutionSOAPResponseInInterceptor.SOAP_REGISTRY
					.recallThreadLocalOutRequestIsEntryCall(); // NOPMD (must be requerst here!)
			final SoapMessage soapMsg = (SoapMessage) msg;

			// 1.) Extract sessionId from SOAP header
			// No need to fetch sessionId from reponse header since it must be
			// the same as before the request.

			// 2.) Extract eoi from SOAP header
			Header hdr = soapMsg.getHeader(SOAPHeaderConstants.EOI_IDENTIFIER_QNAME);
			final String eoiStr = this.getStringContentFromHeader(hdr); // null if hdr==null
			if (eoiStr == null) {
				// No Kieker eoi in header. This may happen for responses from callees w/o
				// Kieker instrumentation.

				OperationExecutionSOAPResponseInInterceptor.LOGGER.info("Found no Kieker eoi in response header. Will unset all threadLocal variables");
				this.unsetKiekerThreadLocalData();
				return;
			}
			int eoi = 0;
			try {
				eoi = Integer.parseInt(eoiStr);
			} catch (final NumberFormatException exc) {
				OperationExecutionSOAPResponseInInterceptor.LOGGER.warn("Invalid EOI", exc);
				this.unsetKiekerThreadLocalData();
				return;
			}

			// 3.) Extract ess from SOAP header
			// No need to fetch ess from reponse header since the stack size
			// is the same as before the request.

			// 4. Extract traceId from SOAP header
			hdr = soapMsg.getHeader(SOAPHeaderConstants.TRACE_IDENTIFIER_QNAME);
			final String traceIdStr = this.getStringContentFromHeader(hdr); // null if hdr==null
			if (traceIdStr == null) {
				// No Kieker trace Id in header. This may happen for responses from callees w/o
				// Kieker instrumentation.

				OperationExecutionSOAPResponseInInterceptor.LOGGER.info("Found no Kieker traceId in response header. Will unset all threadLocal variables");
				this.unsetKiekerThreadLocalData();
				return;
			}
			final long traceId;
			try {
				traceId = Long.parseLong(traceIdStr);
			} catch (final NumberFormatException exc) {
				OperationExecutionSOAPResponseInInterceptor.LOGGER.warn("Invalid trace id", exc);
				this.unsetKiekerThreadLocalData();
				return;
			}

			// Recall my thread-local data stored before the SOAP call
			final long myTraceId = OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.recallThreadLocalTraceId();
			final String mySessionId = OperationExecutionSOAPResponseInInterceptor.SESSION_REGISTRY
					.recallThreadLocalSessionId();
			final int myEoi = OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.recallThreadLocalEOI();
			final int myEss = OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.recallThreadLocalESS();
			final long myTin = OperationExecutionSOAPResponseInInterceptor.SOAP_REGISTRY
					.recallThreadLocalOutRequestTin();
			final long myTout = this.timeSource.getTime();

			if (myTraceId != traceId) {
				OperationExecutionSOAPResponseInInterceptor.LOGGER.warn("Inconsistency between traceId before and after SOAP request:\n{}(before) != {}(after)",
						myTraceId, traceId);
			}

			// Log this execution
			final OperationExecutionRecord rec = new OperationExecutionRecord(
					OperationExecutionSOAPResponseInInterceptor.SIGNATURE, mySessionId, myTraceId, myTin, myTout,
					this.vmName, myEoi, myEss);
			this.monitoringController.newMonitoringRecord(rec);

			// Store received Kieker EOI. ESS remains the same as before the call since we
			// didn't increment the variable!

			OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.storeThreadLocalEOI(eoi);

			if (isEntryCall) { // clean up iff trace's origin was right before the call!
				this.unsetKiekerThreadLocalData();
			}
		}
	}

	private final String getStringContentFromHeader(final Header hdr) {
		if (hdr == null) {
			return null;
		}
		if (hdr.getObject() instanceof Element) {
			final Element e = (Element) hdr.getObject();
			return DOMUtils.getContent(e);
		}
		return null;
	}

	private final void unsetKiekerThreadLocalData() {
		OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.unsetThreadLocalTraceId();
		OperationExecutionSOAPResponseInInterceptor.SESSION_REGISTRY.unsetThreadLocalSessionId();
		OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.unsetThreadLocalEOI();
		OperationExecutionSOAPResponseInInterceptor.CF_REGISTRY.unsetThreadLocalESS();
		OperationExecutionSOAPResponseInInterceptor.SOAP_REGISTRY.unsetThreadLocalOutRequestIsEntryCall();
		OperationExecutionSOAPResponseInInterceptor.SOAP_REGISTRY.unsetThreadLocalOutRequestTin();
	}
}

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/agency.css" rel="stylesheet">
<link rel="stylesheet"href="css/style.css"/>
<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'>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>


text:
// This may look like C code, but it's really -*- C++ -*-

#ifndef COMMENT_VIEW_H_
#define COMMENT_VIEW_H_

#include <Wt/WTemplate>
#include <Wt/Dbo/ptr>

namespace Wt {
  class WTextArea;
}

class BlogSession;
class Comment;

namespace dbo = Wt::Dbo;

class CommentView : public Wt::WTemplate
{
public:
  // For new comment, goes immediately to edit mode
  CommentView(BlogSession& session, long long parentId);

  // Existing comment
  CommentView(BlogSession& session, dbo::ptr<Comment> comment);

  virtual void resolveString(const std::string& varName,
			     const std::vector<Wt::WString>& args,
			     std::ostream& result);

protected:
  virtual void renderTemplate(std::ostream& result);

private:
  BlogSession& session_;
  dbo::ptr<Comment> comment_;
  Wt::WTextArea *editArea_;

  void reply();
  void edit();
  void rm();
  void save();
  void cancel();
  bool isNew() const;

  void renderView();
};

#endif // COMMENT_VIEW_H_


text:
<?php

namespace Core\ImageProcessing\Processor\ColorAnalyzer;
use Imagick;

abstract class Method
{
    abstract public function get(Imagick $image);

    protected function getHistorgram(Imagick $image, $discardUnder = 10)
    {
        $geometry = $image->getImageGeometry();
        $total = $geometry['width'] * $geometry['height'];

        $histogram = [];
        foreach ($image->getImageHistogram() as $pixel) {
            $color = $pixel->getColorAsString();
            $count = $pixel->getColorCount();
            if ($count > 1000) {
                $histogram[$color] = $count;
            }
        }

        return $histogram;
    }

    protected function quantizeImage(Imagick $image, $numberColors)
    {
        return $image->quantizeImage(
            $numberColors,
            Imagick::COLORSPACE_RGB,
            5, false, true
        );
    }
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;

namespace QuantConnect.Tests.Brokerages
{
    public abstract class BrokerageTests
    {
        // ideally this class would be abstract, but I wanted to keep the order test cases here which use the
        // various parameters required from derived types

        private IBrokerage _brokerage;
        private OrderProvider _orderProvider;
        private HoldingsProvider _holdingsProvider;

        /// <summary>
        /// Provides the data required to test each order type in various cases
        /// </summary>
        public virtual TestCaseData[] OrderParameters
        {
            get
            {
                return new []
                {
                    new TestCaseData(new MarketOrderTestParameters(Symbol, SecurityType)).SetName("MarketOrder"),
                    new TestCaseData(new LimitOrderTestParameters(Symbol, SecurityType, HighPrice, LowPrice)).SetName("LimitOrder"),
                    new TestCaseData(new StopMarketOrderTestParameters(Symbol, SecurityType, HighPrice, LowPrice)).SetName("StopMarketOrder"),
                    new TestCaseData(new StopLimitOrderTestParameters(Symbol, SecurityType, HighPrice, LowPrice)).SetName("StopLimitOrder")
                };
            }
        }

        #region Test initialization and cleanup

        [SetUp]
        public void Setup()
        {
            Log.Trace("");
            Log.Trace("");
            Log.Trace("--- SETUP ---");
            Log.Trace("");
            Log.Trace("");
            // we want to regenerate these for each test
            _brokerage = null;
            _orderProvider = null;
            _holdingsProvider = null;
            Thread.Sleep(1000);
            CancelOpenOrders();
            LiquidateHoldings();
            Thread.Sleep(1000);
        }

        [TearDown]
        public void Teardown()
        {
            try
            {
                Log.Trace("");
                Log.Trace("");
                Log.Trace("--- TEARDOWN ---");
                Log.Trace("");
                Log.Trace("");
                Thread.Sleep(1000);
                CancelOpenOrders();
                LiquidateHoldings();
                Thread.Sleep(1000);
            }
            finally
            {
                if (_brokerage != null)
                {
                    DisposeBrokerage(_brokerage);
                }
            }
        }

        public IBrokerage Brokerage
        {
            get
            {
                if (_brokerage == null)
                {
                    _brokerage = InitializeBrokerage();
                }
                return _brokerage;
            }
        }

        private IBrokerage InitializeBrokerage()
        {
            Log.Trace("");
            Log.Trace("- INITIALIZING BROKERAGE -");
            Log.Trace("");

            var brokerage = CreateBrokerage(OrderProvider, HoldingsProvider);
            brokerage.Connect();

            if (!brokerage.IsConnected)
            {
                Assert.Fail("Failed to connect to brokerage");
            }

            Log.Trace("");
            Log.Trace("GET OPEN ORDERS");
            Log.Trace("");
            foreach (var openOrder in brokerage.GetOpenOrders())
            {
                OrderProvider.Add(openOrder);
            }

            Log.Trace("");
            Log.Trace("GET ACCOUNT HOLDINGS");
            Log.Trace("");
            foreach (var accountHolding in brokerage.GetAccountHoldings())
            {
                HoldingsProvider[accountHolding.Symbol] = accountHolding;
            }
            brokerage.OrderStatusChanged += (sender, args) =>
            {
                Log.Trace("");
                Log.Trace("ORDER STATUS CHANGED: " + args);
                Log.Trace("");

                // we need to keep this maintained properly
                if (args.Status == OrderStatus.Filled || args.Status == OrderStatus.PartiallyFilled)
                {
                    Log.Trace("FILL EVENT: " + args.FillQuantity + " units of " + args.Symbol);

                    Holding holding;
                    if (_holdingsProvider.TryGetValue(args.Symbol, out holding))
                    {
                        _holdingsProvider[args.Symbol].Quantity += args.FillQuantity;
                    }
                    else
                    {
                        var accountHoldings = brokerage.GetAccountHoldings().ToDictionary(x => x.Symbol);
                        if (accountHoldings.ContainsKey(args.Symbol))
                        {
                            _holdingsProvider[args.Symbol] = accountHoldings[args.Symbol];
                        }
                        else
                        {
                            _holdingsProvider[args.Symbol] = new Holding {Symbol = args.Symbol};
                        }
                    }

                    Log.Trace("--HOLDINGS: " + _holdingsProvider[args.Symbol]);

                    // update order mapping
                    var order = _orderProvider.GetOrderById(args.OrderId);
                    order.Status = args.Status;
                }
            };
            return brokerage;
        }

        public OrderProvider OrderProvider
        {
            get { return _orderProvider ?? (_orderProvider = new OrderProvider()); }
        }

        public HoldingsProvider HoldingsProvider
        {
            get { return _holdingsProvider ?? (_holdingsProvider = new HoldingsProvider()); }
        }

        /// <summary>
        /// Creates the brokerage under test and connects it
        /// </summary>
        /// <returns>A connected brokerage instance</returns>
        protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, IHoldingsProvider holdingsProvider);

        /// <summary>
        /// Disposes of the brokerage and any external resources started in order to create it
        /// </summary>
        /// <param name="brokerage">The brokerage instance to be disposed of</param>
        protected virtual void DisposeBrokerage(IBrokerage brokerage)
        {
        }

        /// <summary>
        /// This is used to ensure each test starts with a clean, known state.
        /// </summary>
        protected void LiquidateHoldings()
        {
            Log.Trace("");
            Log.Trace("LIQUIDATE HOLDINGS");
            Log.Trace("");

            var holdings = Brokerage.GetAccountHoldings();

            foreach (var holding in holdings)
            {
                if (holding.Quantity == 0) continue;
                Log.Trace("Liquidating: " + holding);
                var order = new MarketOrder(holding.Symbol, (int)-holding.Quantity, DateTime.Now, type: holding.Type);
                _orderProvider.Add(order);
                PlaceOrderWaitForStatus(order, OrderStatus.Filled);
            }
        }

        protected void CancelOpenOrders()
        {
            Log.Trace("");
            Log.Trace("CANCEL OPEN ORDERS");
            Log.Trace("");
            var openOrders = Brokerage.GetOpenOrders();
            foreach (var openOrder in openOrders)
            {
                Log.Trace("Canceling: " + openOrder);
                Brokerage.CancelOrder(openOrder);
            }
        }

        #endregion

        /// <summary>
        /// Gets the symbol to be traded, must be shortable
        /// </summary>
        protected abstract string Symbol { get; }

        /// <summary>
        /// Gets the security type associated with the <see cref="Symbol"/>
        /// </summary>
        protected abstract SecurityType SecurityType { get; }

        /// <summary>
        /// Gets a high price for the specified symbol so a limit sell won't fill
        /// </summary>
        protected abstract decimal HighPrice { get; }

        /// <summary>
        /// Gets a low price for the specified symbol so a limit buy won't fill
        /// </summary>
        protected abstract decimal LowPrice { get; }

        /// <summary>
        /// Gets the current market price of the specified security
        /// </summary>
        protected abstract decimal GetAskPrice(string symbol, SecurityType securityType);

        /// <summary>
        /// Gets the default order quantity
        /// </summary>
        protected virtual int GetDefaultQuantity()
        {
            return 1;
        }

        [Test]
        public void IsConnected()
        {
            Assert.IsTrue(Brokerage.IsConnected);
        }

        [Test, TestCaseSource("OrderParameters")]
        public void LongFromZero(OrderTestParameters parameters)
        {
            Log.Trace("");
            Log.Trace("LONG FROM ZERO");
            Log.Trace("");
            PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
        }

        [Test, TestCaseSource("OrderParameters")]
        public void CloseFromLong(OrderTestParameters parameters)
        {
            Log.Trace("");
            Log.Trace("CLOSE FROM LONG");
            Log.Trace("");
            // first go long
            PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);

            // now close it
            PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
        }

        [Test, TestCaseSource("OrderParameters")]
        public void ShortFromZero(OrderTestParameters parameters)
        {
            Log.Trace("");
            Log.Trace("SHORT FROM ZERO");
            Log.Trace("");
            PlaceOrderWaitForStatus(parameters.CreateShortOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
        }

        [Test, TestCaseSource("OrderParameters")]
        public void CloseFromShort(OrderTestParameters parameters)
        {
            Log.Trace("");
            Log.Trace("CLOSE FROM SHORT");
            Log.Trace("");
            // first go short
            PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(GetDefaultQuantity()), OrderStatus.Filled);

            // now close it
            PlaceOrderWaitForStatus(parameters.CreateLongOrder(GetDefaultQuantity()), parameters.ExpectedStatus);
        }

        [Test, TestCaseSource("OrderParameters")]
        public void ShortFromLong(OrderTestParameters parameters)
        {
            Log.Trace("");
            Log.Trace("SHORT FROM LONG");
            Log.Trace("");
            // first go long
            PlaceOrderWaitForStatus(parameters.CreateLongMarketOrder(GetDefaultQuantity()));

            // now go net short
            var order = PlaceOrderWaitForStatus(parameters.CreateShortOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);

            if (parameters.ModifyUntilFilled)
            {
                ModifyOrderUntilFilled(order, parameters);
            }
        }

        [Test, TestCaseSource("OrderParameters")]
        public void LongFromShort(OrderTestParameters parameters)
        {
            Log.Trace("");
            Log.Trace("LONG FROM SHORT");
            Log.Trace("");
            // first fo short
            PlaceOrderWaitForStatus(parameters.CreateShortMarketOrder(-GetDefaultQuantity()), OrderStatus.Filled);

            // now go long
            var order = PlaceOrderWaitForStatus(parameters.CreateLongOrder(2 * GetDefaultQuantity()), parameters.ExpectedStatus);

            if (parameters.ModifyUntilFilled)
            {
                ModifyOrderUntilFilled(order, parameters);
            }
        }

        [Test]
        public void GetCashBalanceContainsUSD()
        {
            Log.Trace("");
            Log.Trace("GET CASH BALANCE");
            Log.Trace("");
            var balance = Brokerage.GetCashBalance();
            Assert.AreEqual(1, balance.Count(x => x.Symbol == "USD"));
        }

        [Test]
        public void GetAccountHoldings()
        {
            Log.Trace("");
            Log.Trace("GET ACCOUNT HOLDINGS");
            Log.Trace("");
            var before = Brokerage.GetAccountHoldings();

            PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now, type: SecurityType));

            var after = Brokerage.GetAccountHoldings();

            var beforeHoldings = before.FirstOrDefault(x => x.Symbol == Symbol);
            var afterHoldings = after.FirstOrDefault(x => x.Symbol == Symbol);

            var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Quantity;
            var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Quantity;

            Assert.AreEqual(GetDefaultQuantity(), afterQuantity - beforeQuantity);
        }

        /// <summary>
        /// Updates the specified order in the brokerage until it fills or reaches a timeout
        /// </summary>
        /// <param name="order">The order to be modified</param>
        /// <param name="parameters">The order test parameters that define how to modify the order</param>
        /// <param name="secondsTimeout">Maximum amount of time to wait until the order fills</param>
        protected void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
        {
            if (order.Status == OrderStatus.Filled)
            {
                return;
            }

            var filledResetEvent = new ManualResetEvent(false);
            EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
            {
                if (args.Status == OrderStatus.Filled)
                {
                    filledResetEvent.Set();
                }
                if (args.Status == OrderStatus.Canceled || args.Status == OrderStatus.Invalid)
                {
                    Log.Trace("ModifyOrderUntilFilled(): " + order);
                    Assert.Fail("Unexpected order status: " + args.Status);
                }
            };

            Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;

            Log.Trace("");
            Log.Trace("MODIFY UNTIL FILLED: " + order);
            Log.Trace("");
            var stopwatch = Stopwatch.StartNew();
            while (!filledResetEvent.WaitOne(3000) && stopwatch.Elapsed.TotalSeconds < secondsTimeout)
            {
                filledResetEvent.Reset();
                if (order.Status == OrderStatus.PartiallyFilled) continue;

                var marketPrice = GetAskPrice(order.Symbol, order.SecurityType);
                Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): Ask: " + marketPrice);

                var updateOrder = parameters.ModifyOrderToFill(Brokerage, order, marketPrice);
                if (updateOrder)
                {
                    if (order.Status == OrderStatus.Filled) break;

                    Log.Trace("BrokerageTests.ModifyOrderUntilFilled(): " + order);
                    if (!Brokerage.UpdateOrder(order))
                    {
                        Assert.Fail("Brokerage failed to update the order");
                    }
                }
            }

            Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;
        }

        /// <summary>
        /// Places the specified order with the brokerage and wait until we get the <paramref name="expectedStatus"/> back via an OrderStatusChanged event.
        /// This function handles adding the order to the <see cref="IOrderProvider"/> instance as well as incrementing the order ID.
        /// </summary>
        /// <param name="order">The order to be submitted</param>
        /// <param name="expectedStatus">The status to wait for</param>
        /// <param name="secondsTimeout">Maximum amount of time to wait for <paramref name="expectedStatus"/></param>
        /// <returns>The same order that was submitted.</returns>
        protected Order PlaceOrderWaitForStatus(Order order, OrderStatus expectedStatus = OrderStatus.Filled, double secondsTimeout = 10.0, bool allowFailedSubmission = false)
        {
            var requiredStatusEvent = new ManualResetEvent(false);
            var desiredStatusEvent = new ManualResetEvent(false);
            EventHandler<OrderEvent> brokerageOnOrderStatusChanged = (sender, args) =>
            {
                // no matter what, every order should fire at least one of these
                if (args.Status == OrderStatus.Submitted || args.Status == OrderStatus.Invalid)
                {
                    Log.Trace("");
                    Log.Trace("SUBMITTED: " + args);
                    Log.Trace("");
                    requiredStatusEvent.Set();
                }
                // make sure we fire the status we're expecting
                if (args.Status == expectedStatus)
                {
                    Log.Trace("");
                    Log.Trace("EXPECTED: " + args);
                    Log.Trace("");
                    desiredStatusEvent.Set();
                }
            };

            Brokerage.OrderStatusChanged += brokerageOnOrderStatusChanged;

            OrderProvider.Add(order);
            if (!Brokerage.PlaceOrder(order) && !allowFailedSubmission)
            {
                Assert.Fail("Brokerage failed to place the order: " + order);
            }
            requiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "Expected every order to fire a submitted or invalid status event");
            desiredStatusEvent.WaitOneAssertFail((int) (1000*secondsTimeout), "OrderStatus " + expectedStatus + " was not encountered within the timeout.");

            Brokerage.OrderStatusChanged -= brokerageOnOrderStatusChanged;

            return order;
        }
    }
}


text:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
//»þ¹ï¥µ¡¼¥Ó¥¹¤ò¼Â¸½¤¹¤ë¤¿¤á¤Î´Ø¿ô¤ò¤·¤è¤¦¤¹¤ë¤¿¤á¤Ë
#include <time.h>
#define SOCKET_ERROR        -1
#define BUFFER_SIZE         100
#define MESSAGE             "This is the message I'm sending back and forth"
#define QUEUE_SIZE          5

int main(int argc, char* argv[])
{
  //»þ¹ï¥µ¡¼¥Ó¥¹¤Î¤¿¤á¤ÎÀë¸À
  time_t timer;
  struct tm *local;
  //change

  int hSocket,hServerSocket;  /* handle to socket */
  struct hostent* pHostInfo;  /* holds info about a machine */
  struct sockaddr_in Address; /* Internet socket address stuct */
  int nAddressSize=sizeof(struct sockaddr_in);
  char pBuffer[BUFFER_SIZE];
  int nHostPort;

  if(argc < 2) {
	printf("\nUsage: server host-port\n");
	return 0;
  } else {
	nHostPort=atoi(argv[1]);
  }

  printf("\nStarting server");
  printf("\nMaking socket"); /* make a socket */
  hServerSocket=socket(AF_INET,SOCK_STREAM,0);
  if(hServerSocket == SOCKET_ERROR) {
    printf("\nCould not make a socket\n");
    return 0;
  }

  Address.sin_addr.s_addr=INADDR_ANY; /* fill address struct */
  Address.sin_port=htons(nHostPort);
  Address.sin_family=AF_INET;

  printf("\nBinding to port %d",nHostPort);    /* bind to a port */
  if(bind(hServerSocket,(struct sockaddr*)&Address,sizeof(Address)) == SOCKET_ERROR) {
    printf("\nCould not connect to host\n");
    return 0;
  }

  getsockname( hServerSocket, (struct sockaddr *) &Address,(int *)&nAddressSize); /*  get port number */
  printf("opened socket as fd (%d) on port (%d) for stream i/o\n",hServerSocket, ntohs(Address.sin_port));
  printf("Server\n  sin_family = %d\n sin_addr.s_addr = %d\n sin_port = %d\n"
         ,Address.sin_family, Address.sin_addr.s_addr, ntohs(Address.sin_port));

  printf("\nMaking a listen queue of %d elements",QUEUE_SIZE); /* establish listen queue */
  if(listen(hServerSocket,QUEUE_SIZE) == SOCKET_ERROR) {
    printf("\nCould not listen\n");
    return 0;
  }

  for(;;) {
    printf("\nWaiting for a connection\n");  /* get the connected socket */
    hSocket=accept(hServerSocket,(struct sockaddr*)&Address,&nAddressSize);

    printf("\nGot a connection");

    //»þ¹ï¤ò¼èÆÀ¤·¤ÆpBuffer¤Ë¥³¥Ô¡¼¤¹¤ë
    timer = time(NULL);
    local = localtime(&timer);
    strcpy(pBuffer, asctime(local));
    //change

    printf("\nSending Current time to client");

    write(hSocket,pBuffer,strlen(pBuffer)+1); /*write what we received back to the server */
    read(hSocket,pBuffer,BUFFER_SIZE);  /* read from socket into buffer */

    if(strcmp(pBuffer, asctime(local)) == 0)
      printf("\nThe messages match");
    else
      printf("\nSomething was changed in the message");

    printf("\nClosing the socket"); /* close socket */
    if(close(hSocket) == SOCKET_ERROR) {
      printf("\nCould not close socket\n");
      return 0;
    }
  }
}


text:
.. PyLTI documentation master file, created by
   sphinx-quickstart on Mon Nov  3 11:17:08 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to PyLTI's documentation!
=================================

Contents:

.. toctree::
   flask.rst
   pylti_common.rst
   pylti_flask.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Getting Started
==================

Changes
=======

v0.4.1
~~~~~~

- Pin mock to allow ``python setup.py test`` without setuptools upgrade

v0.4.0
~~~~~~

- Support for role lists (Sakai 10+) thanks to `@rickyrem <https://github.com/rickyrem>`_
- Added several files to distribution (including test data) thanks
  to @jtriley and `@layus <https://github.com/layus>`_
- Flask app is no longer required to be passed around as it uses
  ``current_app``
- Decorators no longer require parameters, i.e. ``@lti`` can be used,
  which defaults to allowing any role access
- Coursera support was added via the ``Learner`` role thanks to
  `@caioteixeira <https://github.com/caioteixeira>`_
- Choosing to allow ``any`` role, actually works with any role now.
  It used to require the role to be in a set of known roles thanks
  to `@velochy <https://github.com/velochy>`_
- Proper URL checking for https was fixed thanks to `@velochy <https://github.com/velochy>`_


text:
Praxis::ApiDefinition.define do

  response_template :other_response do |media_type:|
    status 200
    media_type media_type
  end

  response_template :multipart do
    status 200
    media_type 'multipart/form-data'
  end

  response_template :bulk_response do |media_type:, parts: |
    status 200
    media_type 'multipart/form-data'

    parts[:media_type] ||= media_type if parts.kind_of? Hash
    parts(parts)
  end

  trait :authenticated do
    headers do
      header :host
    end
  end

end


text:
package tr.com.serkanozal.mysafe.impl.instrument;

public final class MySafeInstrumenterFactory {

    private MySafeInstrumenterFactory() {

    }

    public static MySafeInstrumenter createMySafeInstrumenter() {
        MySafeInstrumenter[] instrumenters =
                new MySafeInstrumenter[] {
                    new UnsafeInterceptorInstrumenter(),
                    new CustomMemoryManagementInstrumenter()
                };
        return new CompositeMySafeInstrumenter(instrumenters);
    }

}


text:
The `Util.Properties` package and children implements support to read, write and use
property files either in the Java property file format or the Windows INI configuration file.
Each property is assigned a key and a value.  The list of properties are stored in the
`Util.Properties.Manager` tagged record and they are indexed by the key name.  A property
is therefore unique in the list.  Properties can be grouped together in sub-properties so
that a key can represent another list of properties.  To use the packages described here,
use the following GNAT project:

```Ada
with "utilada_base";
```

## File formats
The property file consists of a simple name and value pair separated by the `=` sign.
Thanks to the Windows INI file format, list of properties can be grouped together
in sections by using the `[section-name]` notation.

```Ada
test.count=20
test.repeat=5
[FileTest]
test.count=5
test.repeat=2
```

## Using property files
An instance of the `Util.Properties.Manager` tagged record must be declared and it provides
various operations that can be used.  When created, the property manager is empty.  One way
to fill it is by using the `Load_Properties` procedure to read the property file.  Another
way is by using the `Set` procedure to insert or change a property by giving its name
and its value.

In this example, the property file `test.properties` is loaded and assuming that it contains
the above configuration example, the `Get ("test.count")` will return the string `"20"`.
The property `test.repeat` is then modified to have the value `"23"` and the properties are
then saved in the file.

```Ada
with Util.Properties;
...
   Props : Util.Properties.Manager;
   ...
      Props.Load_Properties (Path => "test.properties");
      Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count");
      Props.Set ("test.repeat", "23");
      Props.Save_Properties (Path => "test.properties");
```

To be able to access a section from the property manager, it is necessary to retrieve it
by using the `Get` function and giving the section name.  For example, to retrieve the
`test.count` property of the `FileTest` section, the following code is used:

```Ada
   FileTest : Util.Properties.Manager := Props.Get ("FileTest");
   ...
      Ada.Text_IO.Put_Line ("[FileTest] Count: "
                            & FileTest.Get ("test.count");
```

When getting or removing a property, the `NO_PROPERTY` exception is raised if the property
name was not found in the map.  To avoid that exception, it is possible to check whether
the name is known by using the `Exists` function.

```Ada
   if Props.Exists ("test.old_count") then
      ... --  Property exist
   end if;
```

## Reading JSON property files
The `Util.Properties.JSON` package provides operations to read a JSON
content and put the result in a property manager.  The JSON content is flattened
into a set of name/value pairs.  The JSON structure is reflected in the name.
Example:

```Ada
{ "id": "1",                                 id         -> 1
  "info": { "name": "search",                info.name  -> search
            "count": "12",                   info.count -> 12
            "data": { "value": "empty" }},   info.data.value  -> empty
  "count": 1                                 count      -> 1
}
```

To get the value of a JSON property, the user can use the flatten name.  For example:

```Ada
 Value : constant String := Props.Get ("info.data.value");
```

The default separator to construct a flatten name is the dot (`.`) but this can be
changed easily when loading the JSON file by specifying the desired separator:

```Ada
 Util.Properties.JSON.Read_JSON (Props, "config.json", "|");
```

Then, the property will be fetch by using:

```Ada
 Value : constant String := Props.Get ("info|data|value");
```

## Property bundles
Property bundles represent several property files that share some overriding rules and
capabilities.  Their introduction comes from Java resource bundles which allow to
localize easily some configuration files or some message.  When loading a property bundle
a locale is defined to specify the target language and locale.  If a specific property
file for that locale exists, it is used first.  Otherwise, the property bundle will use
the default property file.

A rule exists on the name of the specific property locale file: it must start with the
bundle name followed by `_` and the name of the locale.  The default property file must
be the bundle name.  For example, the bundle `dates` is associated with the following
property files:

```Ada
dates.properties           Default values (English locale)
dates_fr.properties        French locale
dates_de.properties        German locale
dates_es.properties        Spain locale
```

Because a bundle can be associated with one or several property files, a specific loader is
used.  The loader instance must be declared and configured to indicate one or several search
directories that contain property files.

```Ada
with Util.Properties.Bundles;
...
   Loader : Util.Properties.Bundles.Loader;
   Bundle : Util.Properties.Bundles.Manager;
   ...
   Util.Properties.Bundles.Initialize (Loader,
                                       "bundles;/usr/share/bundles");
   Util.Properties.Bundles.Load_Bundle (Loader, "dates", "fr", Bundle);
   Ada.Text_IO.Put_Line (Bundle.Get ("util.month1.long");
```

In this example, the `util.month1.long` key is first searched in the `dates_fr` French locale
and if it is not found it is searched in the default locale.

The restriction when using bundles is that they don't allow changing any value and the
`NOT_WRITEABLE` exception is raised when one of the `Set` operation is used.

When a bundle cannot be loaded, the `NO_BUNDLE` exception is raised by the `Load_Bundle`
operation.

## Advance usage of properties
The property manager holds the name and value pairs by using an Ada Bean object.

It is possible to iterate over the properties by using the `Iterate` procedure that
accepts as parameter a `Process` procedure that gets the property name as well as the
property value.  The value itself is passed as an `Util.Beans.Objects.Object` type.


text:
package org.jbehave.examples.scala;

import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.ANSI_CONSOLE;

import java.util.List;

import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.configuration.scala.ScalaContext;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnit4StoryRunner;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.scala.ScalaStepsFactory;
import org.junit.runner.RunWith;

@RunWith(JUnit4StoryRunner.class)
public class ScalaStories extends JUnitStories {

    @Override
    public Configuration configuration() {
        return new MostUsefulConfiguration()
                .useStoryReporterBuilder(new StoryReporterBuilder().withFormats(ANSI_CONSOLE));
    }

    @Override
    public List<String> storyPaths() {
        return new StoryFinder()
                .findPaths(codeLocationFromClass(this.getClass()), "**/*.story", "");
    }

    @Override
    public InjectableStepsFactory stepsFactory() {
        return new ScalaStepsFactory(configuration(), new ScalaContext("ScalaSteps"));
    }

}


text:
package com.reyely.expenses.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations={"classpath:application-context.xml"})
public abstract class AbstractDaoTest extends AbstractTransactionalTestNGSpringContextTests {
	@Autowired
    protected SessionFactory factory;

    /**
     * Gets the current session. Do not use it in methods decorated with @BeforeClass since
     * HibernateTransactionManager binds the session to the proper Session holder AFTER running these methods.
     *
     * @return
     */
    protected Session getSession() {
        return factory.getCurrentSession();
    }

    protected void clearSession() {
        Session session = getSession();
        session.flush();
        session.clear();
    }

    @BeforeClass
    @AfterClass
    public void unboundApplicationContext() {

    }
}


text:
// source:

package nl.esciencecenter.vlet.gui.dialog;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;

import nl.esciencecenter.ptk.data.BooleanHolder;
import nl.esciencecenter.ptk.task.ActionTask;
import nl.esciencecenter.vbrowser.vrs.exceptions.VrsException;
import nl.esciencecenter.vlet.gui.HyperLinkListener;
import nl.esciencecenter.vlet.gui.Messages;
import nl.esciencecenter.vlet.gui.UIGlobal;
import nl.esciencecenter.vlet.gui.UIPlatform;
import nl.esciencecenter.vlet.gui.vbrowser.BrowserController;
import nl.esciencecenter.vlet.gui.vhtml.VHTMLEditorPane;
import nl.esciencecenter.vlet.gui.vhtml.VHyperListener;

/**
 * Simple 'About' dialog.
 */
public class AboutDialog extends javax.swing.JDialog implements ActionListener, WindowListener
{
    private static final long serialVersionUID = -4769345816214794352L;

    private JPanel buttonPanel;

    private VHTMLEditorPane  aboutHTMLPane;
    private JPanel mainPanel;
    private JLabel topLabel;
    private JPanel topPanel;
    private JLabel vleImageLabel;
    private JLabel bottomLabel;
    private JLabel rightLabel;
    private JLabel leftLabel;

    private JButton okButton;

    private HyperLinkListener browserController;

    private JScrollPane scrollPane;

    /**
     * Auto-generated main method to display this JDialog
     */
    public static void main(String[] args)
    {
        AboutDialog.showMe(null);

        //AboutDialog inst = new AboutDialog();
        //inst.setVisible(true);
    }

    public AboutDialog(BrowserController bc)
    {
        super((bc!=null?BrowserController.getMasterFrame():null));
        UIPlatform.getPlatform().getWindowRegistry().register(this);
        this.browserController=bc;
        init();
    }

    public AboutDialog()
    {
        UIPlatform.getPlatform().getWindowRegistry().register(this);
        init();
    }

    private void init()
    {
        initGUI();
        this.addWindowListener(this);
    }

    private void initGUI()
    {

        try
        {
            BorderLayout thisLayout = new BorderLayout();

            this.getContentPane().setLayout(thisLayout);
            this.setResizable(true);
            {
                mainPanel = new JPanel();
                this.getContentPane().add(mainPanel, BorderLayout.CENTER);
                BorderLayout mainPanelLayout = new BorderLayout();
                mainPanel.setLayout(mainPanelLayout);
                mainPanel.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
                //mainPanel.setBounds(10, 12, 354, 315);
                //mainPanel.setPreferredSize(new java.awt.Dimension(368, 302));
                {
                    scrollPane=new JScrollPane();
                    mainPanel.add(scrollPane, BorderLayout.CENTER);

                    {
                        aboutHTMLPane = new VHTMLEditorPane();
                        scrollPane.setViewportView(aboutHTMLPane);
                        aboutHTMLPane.setEditable(false);
                        // null viewer.
                        aboutHTMLPane.addHyperlinkListener(new VHyperListener(
                                null,
                                browserController));

                        aboutHTMLPane.setContentType("text/html"); // HTML text s
                        aboutHTMLPane.setText(Messages.aboutText);
                        aboutHTMLPane.setPreferredSize(new java.awt.Dimension(413, 201));
                        aboutHTMLPane.setEditable(false);
                        aboutHTMLPane.setAutoscrolls(false);

                        aboutHTMLPane.setBorder(BorderFactory
                                .createEtchedBorder(BevelBorder.RAISED));
                        //aboutHTMLPane.setBounds(1, 139, 350, 103);
                    }
                }
                {
                    topPanel = new JPanel();
                    mainPanel.add(topPanel, BorderLayout.NORTH);
                    topPanel.setBackground(new java.awt.Color(255,255,255));
                    topPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
                    {
                        vleImageLabel = new JLabel();
                        topPanel.add(vleImageLabel);
                        vleImageLabel.setIcon(loadIcon("images/nlesc_logo_medium.png"));
                    }
                }
                {
                    buttonPanel = new JPanel();
                    FlowLayout buttonPanelLayout = new FlowLayout();
                    mainPanel.add(buttonPanel, BorderLayout.SOUTH);
                    buttonPanel.setLayout(buttonPanelLayout);
                    buttonPanel.setBorder(BorderFactory.createEtchedBorder(BevelBorder.RAISED));
                    {
                        okButton = new JButton();
                        buttonPanel.add(okButton);
                        okButton.setText("OK");
                        okButton.addActionListener(this);
                    }
                }

            }
            {
                leftLabel = new JLabel();
                this.getContentPane().add(leftLabel, BorderLayout.WEST);
                leftLabel.setPreferredSize(new java.awt.Dimension(10, 405));
            }
            {
                rightLabel = new JLabel();
                this.getContentPane().add(rightLabel, BorderLayout.EAST);
                rightLabel.setPreferredSize(new java.awt.Dimension(10, 405));
            }
            {
                topLabel = new JLabel();
                this.getContentPane().add(topLabel, BorderLayout.NORTH);
                topLabel.setPreferredSize(new java.awt.Dimension(375, 10));
            }
            {
                bottomLabel = new JLabel();
                this.getContentPane().add(bottomLabel, BorderLayout.SOUTH);
                bottomLabel.setPreferredSize(new java.awt.Dimension(375, 10));
            }
            this.setSize(550,550);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private Icon loadIcon(String urlStr)
    {
        URL url = getClass().getClassLoader().getResource(urlStr);
        return new ImageIcon(url);

    }

    public void actionPerformed(ActionEvent e)
    {
        Exit();
    }

    private void Exit()
    {
        this.dispose();
    }

    public void windowOpened(WindowEvent e)
    {
    }

    public void windowClosing(WindowEvent e)
    {
        Exit();
    }

    public void windowClosed(WindowEvent e)
    {
    }

    public void windowIconified(WindowEvent e)
    {
    }

    public void windowDeiconified(WindowEvent e)
    {
    }

    public void windowActivated(WindowEvent e)
    {
    }

    public void windowDeactivated(WindowEvent e)
    {
    }

    public static void showMe(final BrowserController bc)
    {
        if (UIGlobal.isGuiThread()==false)
        {
            Runnable run=new Runnable()
            {
                public void run()
                {
                    showMe(bc);
                }
            };
            UIGlobal.swingInvokeLater(run);
            return;
        }

        AboutDialog dialog=new AboutDialog(bc);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        dialog.scrollDown(bc);

    }
    // cleanup:see super.dispose
    public void dispose()
    {
        super.dispose();
        if (scrollTask!=null)
            scrollTask.signalTerminate();
    }

    ActionTask scrollTask=null;

    private void scrollDown(BrowserController bc)
    {
        // scroll up:

        //this.aboutHTMLPane.scrollToReference("top");

        final JViewport vport = this.scrollPane.getViewport();
        final AboutDialog dialog=this;

        //Rectangle rect=new Rectangle(0,-1000);
        //vport.scrollRectToVisible(rect);

        //Rectangle rect=new Rectangle(0,-1000);
        //vport.scrollRectToVisible(rect);
        // init: scrollup:

        scrollTask=new ActionTask(bc,"scrollTask")
        {
            boolean stop=false;

            @Override
            protected void doTask() throws VrsException
            {
                // must use booleanholder
                final BooleanHolder scrollToTop=new BooleanHolder(true);

                try
                {
                    while(stop==false)
                    {
                        Rectangle rect=vport.getViewRect();
                        //rect.y=i;
                        rect.y=1;

                        //System.out.println("Scrolling to:"+rect.y);
                        final Rectangle frect=rect;
                        Runnable run = new Runnable()
                        {
                            public void run()
                            {
                                if (scrollToTop.value)
                                {
                                    dialog.aboutHTMLPane.scrollToReference("top");
                                    scrollToTop.value=false;
                                }
                                vport.scrollRectToVisible(frect);
                            }
                        };
                        SwingUtilities.invokeLater(run);

                        Thread.sleep(100);
                    }

                }
                catch (InterruptedException e)
                {
                    System.out.println("***Error: Exception:"+e);
                    e.printStackTrace();
                }
            }

            @Override
            public void stopTask()
            {
                stop=true;
            }
        };

        scrollTask.startTask();
    }

}