text:
package androidx.media3.exoplayer.offline;

import static androidx.media3.test.utils.robolectric.RobolectricUtil.createRobolectricConditionVariable;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Arrays.asList;

import android.net.Uri;
import androidx.annotation.GuardedBy;
import androidx.annotation.Nullable;
import androidx.media3.common.C;
import androidx.media3.common.StreamKey;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.ConditionVariable;
import androidx.media3.exoplayer.scheduler.Requirements;
import androidx.media3.test.utils.DownloadBuilder;
import androidx.media3.test.utils.DummyMainThread;
import androidx.media3.test.utils.DummyMainThread.TestRunnable;
import androidx.media3.test.utils.TestUtil;
import androidx.media3.test.utils.robolectric.TestDownloadManagerListener;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.shadows.ShadowLog;

/** Tests {@link DownloadManager}. */
@RunWith(AndroidJUnit4.class)
public class DownloadManagerTest {

  /** Timeout to use when blocking on conditions that we expect to become unblocked. */
  private static final int TIMEOUT_MS = 10_000;
  /** An application provided stop reason. */
  private static final int APP_STOP_REASON = 1;
  /** The minimum number of times a download must be retried before failing. */
  private static final int MIN_RETRY_COUNT = 3;
  /** Test value for the current time. */
  private static final long NOW_MS = 1234;

  private static final String ID1 = "id1";
  private static final String ID2 = "id2";
  private static final String ID3 = "id3";

  @GuardedBy("downloaders")
  private final List<FakeDownloader> downloaders = new ArrayList<>();

  private DownloadManager downloadManager;
  private TestDownloadManagerListener downloadManagerListener;
  private DummyMainThread testThread;

  @Before
  public void setUp() throws Exception {
    ShadowLog.stream = System.out;
    testThread = new DummyMainThread();
    setupDownloadManager(/* maxParallelDownloads= */ 100);
  }

  @After
  public void tearDown() throws Exception {
    releaseDownloadManager();
    testThread.release();
  }

  @Test
  public void downloadRequest_downloads() throws Throwable {
    postDownloadRequest(ID1);
    assertDownloading(ID1);

    FakeDownloader downloader = getDownloaderAt(0);
    downloader.assertId(ID1);
    downloader.assertDownloadStarted();
    downloader.finish();
    assertCompleted(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(1);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void removeRequest_cancelsAndRemovesDownload() throws Throwable {
    postDownloadRequest(ID1);

    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();
    assertDownloading(ID1);

    // The download will be canceled by the remove request.
    postRemoveRequest(ID1);
    downloader0.assertCanceled();
    assertRemoving(ID1);

    // The download will be removed.
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertRemoveStarted();
    downloader1.finish();
    assertRemoved(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(0);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void download_retryUntilMinRetryCount_withoutProgress_thenFails() throws Throwable {
    postDownloadRequest(ID1);

    FakeDownloader downloader = getDownloaderAt(0);
    downloader.assertId(ID1);
    for (int i = 0; i <= MIN_RETRY_COUNT; i++) {
      downloader.assertDownloadStarted();
      downloader.fail();
    }
    assertFailed(ID1);

    downloadManagerListener.blockUntilIdle();
    assertDownloaderCount(1);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void download_retryUntilMinRetryCountMinusOne_thenSucceeds() throws Throwable {
    postDownloadRequest(ID1);

    FakeDownloader downloader = getDownloaderAt(0);
    downloader.assertId(ID1);
    for (int i = 0; i < MIN_RETRY_COUNT; i++) {
      downloader.assertDownloadStarted();
      downloader.fail();
    }
    downloader.assertDownloadStarted();
    downloader.finish();
    assertCompleted(ID1);

    downloadManagerListener.blockUntilIdle();
    assertDownloaderCount(1);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void download_retryMakesProgress_resetsRetryCount() throws Throwable {
    postDownloadRequest(ID1);

    FakeDownloader downloader = getDownloaderAt(0);
    downloader.assertId(ID1);
    for (int i = 0; i <= MIN_RETRY_COUNT; i++) {
      downloader.assertDownloadStarted();
      downloader.incrementBytesDownloaded(); // Make some progress.
      downloader.fail();
    }
    // Since previous attempts all made progress the current error count should be 1. Therefore we
    // should be able to fail (MIN_RETRY_COUNT - 1) more times and then still complete the download
    // successfully.
    for (int i = 0; i < MIN_RETRY_COUNT - 1; i++) {
      downloader.assertDownloadStarted();
      downloader.fail();
    }
    downloader.assertDownloadStarted();
    downloader.finish();
    assertCompleted(ID1);

    downloadManagerListener.blockUntilIdle();
    assertDownloaderCount(1);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void download_retryMakesProgress_resetsRetryCount_thenFails() throws Throwable {
    postDownloadRequest(ID1);

    FakeDownloader downloader = getDownloaderAt(0);
    downloader.assertId(ID1);
    for (int i = 0; i <= MIN_RETRY_COUNT; i++) {
      downloader.assertDownloadStarted();
      downloader.incrementBytesDownloaded(); // Make some progress.
      downloader.fail();
    }
    // Since previous attempts all made progress the current error count should be 1. Therefore we
    // should fail after MIN_RETRY_COUNT more attempts without making any progress.
    for (int i = 0; i < MIN_RETRY_COUNT; i++) {
      downloader.assertDownloadStarted();
      downloader.fail();
    }
    assertFailed(ID1);

    downloadManagerListener.blockUntilIdle();
    assertDownloaderCount(1);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void download_WhenRemovalInProgress_doesNotCancelRemoval() throws Throwable {
    postDownloadRequest(ID1);
    postRemoveRequest(ID1);
    assertRemoving(ID1);

    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertRemoveStarted();

    postDownloadRequest(ID1);
    // The removal should still complete.
    downloader1.finish();

    // The download should then start and complete.
    FakeDownloader downloader2 = getDownloaderAt(2);
    downloader2.assertId(ID1);
    downloader2.assertDownloadStarted();
    downloader2.finish();
    assertCompleted(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(3);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void remove_WhenRemovalInProgress_doesNothing() throws Throwable {
    postDownloadRequest(ID1);
    postRemoveRequest(ID1);
    assertRemoving(ID1);

    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertRemoveStarted();

    postRemoveRequest(ID1);
    // The existing removal should still complete.
    downloader1.finish();
    assertRemoved(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(0);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void removeAllDownloads_removesAllDownloads() throws Throwable {
    // Finish one download.
    postDownloadRequest(ID1);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();
    downloader0.finish();
    assertCompleted(ID1);

    // Start a second download.
    postDownloadRequest(ID2);
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID2);
    downloader1.assertDownloadStarted();

    postRemoveAllRequest();
    // Both downloads should be removed.
    FakeDownloader downloader2 = getDownloaderAt(2);
    downloader2.assertId(ID1);
    downloader2.assertRemoveStarted();
    downloader2.finish();
    assertRemoved(ID1);
    FakeDownloader downloader3 = getDownloaderAt(3);
    downloader3.assertId(ID2);
    downloader3.assertRemoveStarted();
    downloader3.finish();
    assertRemoved(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(4);
    assertDownloadIndexSize(0);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void downloads_withSameIdsAndDifferentStreamKeys_areMerged() throws Throwable {
    StreamKey streamKey1 = new StreamKey(/* groupIndex= */ 0, /* trackIndex= */ 0);
    postDownloadRequest(ID1, streamKey1);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();

    StreamKey streamKey2 = new StreamKey(/* groupIndex= */ 1, /* trackIndex= */ 1);
    postDownloadRequest(ID1, streamKey2);
    // The request for streamKey2 will cause the downloader for streamKey1 to be canceled and
    // replaced with a new downloader for both keys.
    downloader0.assertCanceled();
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertStreamKeys(streamKey1, streamKey2);
    downloader1.assertDownloadStarted();
    downloader1.finish();
    assertCompleted(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void downloads_withDifferentIds_executeInParallel() throws Throwable {
    postDownloadRequest(ID1);
    postDownloadRequest(ID2);

    FakeDownloader downloader0 = getDownloaderAt(0);
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader0.assertId(ID1);
    downloader1.assertId(ID2);
    downloader0.assertDownloadStarted();
    downloader1.assertDownloadStarted();
    downloader0.finish();
    downloader1.finish();
    assertCompleted(ID1);
    assertCompleted(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(2);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void downloads_withDifferentIds_maxDownloadsIsOne_executedSequentially() throws Throwable {
    setupDownloadManager(/* maxParallelDownloads= */ 1);
    postDownloadRequest(ID1);
    postDownloadRequest(ID2);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();

    // The second download should be queued and the first one should be able to complete.
    assertNoDownloaderAt(1);
    assertQueued(ID2);
    downloader0.finish();
    assertCompleted(ID1);

    // The second download can start once the first one has completed.
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID2);
    downloader1.assertDownloadStarted();
    downloader1.finish();
    assertCompleted(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(2);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void downloadAndRemove_withDifferentIds_maxDownloadsIsOne_executeInParallel()
      throws Throwable {
    setupDownloadManager(/* maxParallelDownloads= */ 1);

    // Complete a download so that we can remove it.
    postDownloadRequest(ID1);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();
    downloader0.finish();

    // Request removal of the first download, and downloading of a second download.
    postRemoveRequest(ID1);
    postDownloadRequest(ID2);

    // The removal and download should proceed in parallel.
    FakeDownloader downloader1 = getDownloaderAt(1);
    FakeDownloader downloader2 = getDownloaderAt(2);
    downloader1.assertId(ID1);
    downloader2.assertId(ID2);
    downloader1.assertRemoveStarted();
    downloader2.assertDownloadStarted();
    downloader1.finish();
    downloader2.finish();
    assertRemoved(ID1);
    assertCompleted(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(3);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void downloadAfterRemove_maxDownloadIsOne_isNotStarted() throws Throwable {
    setupDownloadManager(/* maxParallelDownloads= */ 1);
    postDownloadRequest(ID1);
    postDownloadRequest(ID2);
    postRemoveRequest(ID2);
    postDownloadRequest(ID2);

    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();

    // The second download shouldn't have been started, so the second downloader is for removal.
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID2);
    downloader1.assertRemoveStarted();
    downloader1.finish();
    // A downloader to re-download the second download should not be started.
    assertNoDownloaderAt(2);
    // The first download should be able to complete.
    downloader0.finish();
    assertCompleted(ID1);

    // Now the first download has completed, the second download should start.
    FakeDownloader downloader2 = getDownloaderAt(2);
    downloader2.assertId(ID2);
    downloader2.assertDownloadStarted();
    downloader2.finish();
    assertCompleted(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(3);
    assertDownloadIndexSize(2);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void pauseAndResume_pausesAndResumesDownload() throws Throwable {
    postDownloadRequest(ID1);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();

    postPauseDownloads();
    downloader0.assertCanceled();
    assertQueued(ID1);

    postResumeDownloads();
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertDownloadStarted();
    downloader1.finish();
    assertCompleted(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void pause_doesNotCancelRemove() throws Throwable {
    postDownloadRequest(ID1);
    postRemoveRequest(ID1);
    FakeDownloader downloader = getDownloaderAt(1);
    downloader.assertId(ID1);
    downloader.assertRemoveStarted();

    postPauseDownloads();
    downloader.finish();
    assertRemoved(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(0);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void setAndClearStopReason_stopsAndRestartsDownload() throws Throwable {
    postDownloadRequest(ID1);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();

    postSetStopReason(ID1, APP_STOP_REASON);
    downloader0.assertCanceled();
    assertStopped(ID1);

    postSetStopReason(ID1, Download.STOP_REASON_NONE);
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertDownloadStarted();
    downloader1.finish();

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(1);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void setStopReason_doesNotStopOtherDownload() throws Throwable {
    postDownloadRequest(ID1);
    postDownloadRequest(ID2);

    FakeDownloader downloader0 = getDownloaderAt(0);
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader0.assertId(ID1);
    downloader1.assertId(ID2);
    downloader0.assertDownloadStarted();
    downloader1.assertDownloadStarted();

    postSetStopReason(ID1, APP_STOP_REASON);
    downloader0.assertCanceled();
    assertStopped(ID1);

    // The second download should still complete.
    downloader1.finish();
    assertCompleted(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(2);
    assertCurrentDownloadCount(1);
  }

  @Test
  public void remove_removesStoppedDownload() throws Throwable {
    postDownloadRequest(ID1);
    FakeDownloader downloader0 = getDownloaderAt(0);
    downloader0.assertId(ID1);
    downloader0.assertDownloadStarted();

    postSetStopReason(ID1, APP_STOP_REASON);
    downloader0.assertCanceled();
    assertStopped(ID1);

    postRemoveRequest(ID1);
    FakeDownloader downloader1 = getDownloaderAt(1);
    downloader1.assertId(ID1);
    downloader1.assertRemoveStarted();
    downloader1.finish();
    assertRemoved(ID1);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
    assertDownloaderCount(2);
    assertDownloadIndexSize(0);
    assertCurrentDownloadCount(0);
  }

  @Test
  public void getCurrentDownloads_returnsCurrentDownloads() throws Throwable {
    setupDownloadManager(/* maxParallelDownloads= */ 1);
    postDownloadRequest(ID1);
    postDownloadRequest(ID2);
    postDownloadRequest(ID3);
    postRemoveRequest(ID3);

    assertRemoving(ID3); // Blocks until the downloads will be visible.

    List<Download> downloads = postGetCurrentDownloads();
    assertThat(downloads).hasSize(3);
    Download download0 = downloads.get(0);
    assertThat(download0.request.id).isEqualTo(ID1);
    assertThat(download0.state).isEqualTo(Download.STATE_DOWNLOADING);
    Download download1 = downloads.get(1);
    assertThat(download1.request.id).isEqualTo(ID2);
    assertThat(download1.state).isEqualTo(Download.STATE_QUEUED);
    Download download2 = downloads.get(2);
    assertThat(download2.request.id).isEqualTo(ID3);
    assertThat(download2.state).isEqualTo(Download.STATE_REMOVING);
  }

  @Test
  public void addDownload_whilstRemovingWithStopReason_addsStartedDownload() throws Throwable {
    runOnMainThread(
        () -> downloadManager.addDownload(createDownloadRequest(ID1), /* stopReason= */ 1234));

    postRemoveRequest(ID1);
    FakeDownloader downloadRemover = getDownloaderAt(0);
    downloadRemover.assertRemoveStarted();

    // Re-add the download without a stop reason.
    postDownloadRequest(ID1);

    downloadRemover.finish();

    FakeDownloader downloader = getDownloaderAt(1);
    downloader.finish();
    assertCompleted(ID1);

    assertDownloadIndexSize(1);
    // We expect one downloader for the removal, and one for when the download was re-added.
    assertDownloaderCount(2);
    // The download has completed, and so is no longer current.
    assertCurrentDownloadCount(0);

    Download download = postGetDownloadIndex().getDownload(ID1);
    assertThat(download.state).isEqualTo(Download.STATE_COMPLETED);
    assertThat(download.stopReason).isEqualTo(0);
  }

  /** Test for https://github.com/google/ExoPlayer/issues/8419 */
  @Test
  public void addDownloadWithStopReason_whilstRemoving_addsStoppedDownload() throws Throwable {
    postDownloadRequest(ID1);
    getDownloaderAt(0).finish();
    assertCompleted(ID1);

    postRemoveRequest(ID1);
    FakeDownloader downloadRemover = getDownloaderAt(1);
    downloadRemover.assertRemoveStarted();

    // Re-add the download with a stop reason.
    runOnMainThread(
        () -> downloadManager.addDownload(createDownloadRequest(ID1), /* stopReason= */ 1234));

    downloadRemover.finish();
    downloadManagerListener.blockUntilIdle();

    assertDownloadIndexSize(1);
    // We expect one downloader for the initial download, and one for the removal. A downloader
    // should not be created when the download is re-added, since a stop reason is specified.
    assertDownloaderCount(2);
    // The download isn't completed, and is therefore still current.
    assertCurrentDownloadCount(1);

    List<Download> downloads = postGetCurrentDownloads();
    Download download = downloads.get(0);
    assertThat(download.request.id).isEqualTo(ID1);
    assertThat(download.state).isEqualTo(Download.STATE_STOPPED);
    assertThat(download.stopReason).isEqualTo(1234);
  }

  @Test
  public void mergeRequest_removing_becomesRestarting() {
    DownloadRequest downloadRequest = createDownloadRequest(ID1);
    DownloadBuilder downloadBuilder =
        new DownloadBuilder(downloadRequest).setState(Download.STATE_REMOVING);
    Download download = downloadBuilder.build();

    Download mergedDownload =
        DownloadManager.mergeRequest(download, downloadRequest, download.stopReason, NOW_MS);

    Download expectedDownload =
        downloadBuilder.setStartTimeMs(NOW_MS).setState(Download.STATE_RESTARTING).build();
    assertEqualIgnoringUpdateTime(mergedDownload, expectedDownload);
  }

  @Test
  public void mergeRequest_failed_becomesQueued() {
    DownloadRequest downloadRequest = createDownloadRequest(ID1);
    DownloadBuilder downloadBuilder =
        new DownloadBuilder(downloadRequest)
            .setState(Download.STATE_FAILED)
            .setFailureReason(Download.FAILURE_REASON_UNKNOWN);
    Download download = downloadBuilder.build();

    Download mergedDownload =
        DownloadManager.mergeRequest(download, downloadRequest, download.stopReason, NOW_MS);

    Download expectedDownload =
        downloadBuilder
            .setStartTimeMs(NOW_MS)
            .setState(Download.STATE_QUEUED)
            .setFailureReason(Download.FAILURE_REASON_NONE)
            .build();
    assertEqualIgnoringUpdateTime(mergedDownload, expectedDownload);
  }

  @Test
  public void mergeRequest_stopped_staysStopped() {
    DownloadRequest downloadRequest = createDownloadRequest(ID1);
    DownloadBuilder downloadBuilder =
        new DownloadBuilder(downloadRequest)
            .setState(Download.STATE_STOPPED)
            .setStopReason(/* stopReason= */ 1);
    Download download = downloadBuilder.build();

    Download mergedDownload =
        DownloadManager.mergeRequest(download, downloadRequest, download.stopReason, NOW_MS);

    assertEqualIgnoringUpdateTime(mergedDownload, download);
  }

  @Test
  public void mergeRequest_completedWithStopReason_becomesStopped() {
    DownloadRequest downloadRequest = createDownloadRequest(ID1);
    DownloadBuilder downloadBuilder =
        new DownloadBuilder(downloadRequest)
            .setState(Download.STATE_COMPLETED)
            .setStopReason(/* stopReason= */ 1);
    Download download = downloadBuilder.build();

    Download mergedDownload =
        DownloadManager.mergeRequest(download, downloadRequest, download.stopReason, NOW_MS);

    Download expectedDownload =
        downloadBuilder.setStartTimeMs(NOW_MS).setState(Download.STATE_STOPPED).build();
    assertEqualIgnoringUpdateTime(mergedDownload, expectedDownload);
  }

  @Test
  public void removeRequests_runSequentially() throws Throwable {
    // Trigger two remove requests.
    postDownloadRequest(ID1);
    getDownloaderAt(0).finish();
    postDownloadRequest(ID2);
    getDownloaderAt(1).finish();
    postRemoveRequest(ID1);
    postRemoveRequest(ID2);

    // Assert first remove request is executing, second one is queued.
    assertRemoving(ID1);
    assertQueued(ID2);
    FakeDownloader downloader2 = getDownloaderAt(2);
    downloader2.assertId(ID1);
    downloader2.assertRemoveStarted();
    downloader2.finish();
    assertRemoved(ID1);

    // Assert second one is running after first one finished
    assertRemoving(ID2);
    FakeDownloader downloader3 = getDownloaderAt(3);
    downloader3.assertId(ID2);
    downloader3.assertRemoveStarted();
    downloader3.finish();
    assertRemoved(ID2);

    downloadManagerListener.blockUntilIdleAndThrowAnyFailure();
  }

  private void setupDownloadManager(int maxParallelDownloads) throws Exception {
    if (downloadManager != null) {
      releaseDownloadManager();
    }
    try {
      runOnMainThread(
          () -> {
            downloadManager =
                new DownloadManager(
                    ApplicationProvider.getApplicationContext(),
                    new DefaultDownloadIndex(TestUtil.getInMemoryDatabaseProvider()),
                    new FakeDownloaderFactory());
            downloadManager.setMaxParallelDownloads(maxParallelDownloads);
            downloadManager.setMinRetryCount(MIN_RETRY_COUNT);
            downloadManager.setRequirements(new Requirements(0));
            downloadManager.resumeDownloads();
            downloadManagerListener = new TestDownloadManagerListener(downloadManager);
          });
      downloadManagerListener.blockUntilInitialized();
    } catch (Throwable throwable) {
      throw new Exception(throwable);
    }
  }

  private void releaseDownloadManager() throws Exception {
    try {
      runOnMainThread(() -> downloadManager.release());
    } catch (Throwable throwable) {
      throw new Exception(throwable);
    }
  }

  private void postRemoveRequest(String id) {
    runOnMainThread(() -> downloadManager.removeDownload(id));
  }

  private void postRemoveAllRequest() {
    runOnMainThread(() -> downloadManager.removeAllDownloads());
  }

  private void postPauseDownloads() {
    runOnMainThread(() -> downloadManager.pauseDownloads());
  }

  private void postResumeDownloads() {
    runOnMainThread(() -> downloadManager.resumeDownloads());
  }

  private void postSetStopReason(String id, int reason) {
    runOnMainThread(() -> downloadManager.setStopReason(id, reason));
  }

  private void postDownloadRequest(String id, StreamKey... keys) {
    runOnMainThread(() -> downloadManager.addDownload(createDownloadRequest(id, keys)));
  }

  private List<Download> postGetCurrentDownloads() {
    AtomicReference<List<Download>> currentDownloadsReference = new AtomicReference<>();
    runOnMainThread(() -> currentDownloadsReference.set(downloadManager.getCurrentDownloads()));
    return currentDownloadsReference.get();
  }

  private DownloadIndex postGetDownloadIndex() {
    AtomicReference<DownloadIndex> downloadIndexReference = new AtomicReference<>();
    runOnMainThread(() -> downloadIndexReference.set(downloadManager.getDownloadIndex()));
    return downloadIndexReference.get();
  }

  private void runOnMainThread(TestRunnable r) {
    testThread.runTestOnMainThread(r);
  }

  private FakeDownloader getDownloaderAt(int index) throws InterruptedException {
    return Assertions.checkNotNull(getDownloaderInternal(index, TIMEOUT_MS));
  }

  private void assertNoDownloaderAt(int index) throws InterruptedException {
    // We use a timeout shorter than TIMEOUT_MS because timing out is expected in this case.
    assertThat(getDownloaderInternal(index, /* timeoutMs= */ 1_000)).isNull();
  }

  private void assertDownloading(String id) {
    downloadManagerListener.assertState(id, Download.STATE_DOWNLOADING);
  }

  private void assertCompleted(String id) {
    downloadManagerListener.assertState(id, Download.STATE_COMPLETED);
  }

  private void assertRemoving(String id) {
    downloadManagerListener.assertState(id, Download.STATE_REMOVING);
  }

  private void assertFailed(String id) {
    downloadManagerListener.assertState(id, Download.STATE_FAILED);
  }

  private void assertQueued(String id) {
    downloadManagerListener.assertState(id, Download.STATE_QUEUED);
  }

  private void assertStopped(String id) {
    downloadManagerListener.assertState(id, Download.STATE_STOPPED);
  }

  private void assertRemoved(String id) {
    downloadManagerListener.assertRemoved(id);
  }

  private void assertDownloaderCount(int expectedCount) {
    synchronized (downloaders) {
      assertThat(downloaders).hasSize(expectedCount);
    }
  }

  private void assertCurrentDownloadCount(int expectedCount) {
    assertThat(postGetCurrentDownloads()).hasSize(expectedCount);
  }

  private void assertDownloadIndexSize(int expectedSize) throws IOException {
    assertThat(postGetDownloadIndex().getDownloads().getCount()).isEqualTo(expectedSize);
  }

  private static void assertEqualIgnoringUpdateTime(Download download, Download that) {
    assertThat(download.request).isEqualTo(that.request);
    assertThat(download.state).isEqualTo(that.state);
    assertThat(download.startTimeMs).isEqualTo(that.startTimeMs);
    assertThat(download.contentLength).isEqualTo(that.contentLength);
    assertThat(download.failureReason).isEqualTo(that.failureReason);
    assertThat(download.stopReason).isEqualTo(that.stopReason);
    assertThat(download.getPercentDownloaded()).isEqualTo(that.getPercentDownloaded());
    assertThat(download.getBytesDownloaded()).isEqualTo(that.getBytesDownloaded());
  }

  private static DownloadRequest createDownloadRequest(String id, StreamKey... keys) {
    return new DownloadRequest.Builder(id, Uri.parse("http://abc.com/ " + id))
        .setStreamKeys(asList(keys))
        .build();
  }

  // Internal methods.

  @Nullable
  private FakeDownloader getDownloaderInternal(int index, long timeoutMs)
      throws InterruptedException {
    long nowMs = System.currentTimeMillis();
    long endMs = nowMs + timeoutMs;
    synchronized (downloaders) {
      while (downloaders.size() <= index && nowMs < endMs) {
        downloaders.wait(endMs - nowMs);
        nowMs = System.currentTimeMillis();
      }
      return downloaders.size() <= index ? null : downloaders.get(index);
    }
  }

  private final class FakeDownloaderFactory implements DownloaderFactory {

    @Override
    public Downloader createDownloader(DownloadRequest request) {
      FakeDownloader fakeDownloader = new FakeDownloader(request);
      synchronized (downloaders) {
        downloaders.add(fakeDownloader);
        downloaders.notifyAll();
      }
      return fakeDownloader;
    }
  }

  private static final class FakeDownloader implements Downloader {

    private final DownloadRequest request;
    private final ConditionVariable downloadStarted;
    private final ConditionVariable removeStarted;
    private final ConditionVariable finished;
    private final ConditionVariable blocker;
    private final AtomicInteger startCount;
    private final AtomicInteger bytesDownloaded;

    private volatile boolean canceled;
    private volatile boolean enableDownloadIOException;

    private FakeDownloader(DownloadRequest request) {
      this.request = request;
      downloadStarted = createRobolectricConditionVariable();
      removeStarted = createRobolectricConditionVariable();
      finished = createRobolectricConditionVariable();
      blocker = createRobolectricConditionVariable();
      startCount = new AtomicInteger();
      bytesDownloaded = new AtomicInteger();
    }

    @Override
    public void cancel() {
      canceled = true;
      blocker.open();
    }

    @Override
    public void download(ProgressListener listener) throws IOException {
      startCount.incrementAndGet();
      downloadStarted.open();
      try {
        block();
        if (canceled) {
          return;
        }
        int bytesDownloaded = this.bytesDownloaded.get();
        if (listener != null && bytesDownloaded > 0) {
          listener.onProgress(C.LENGTH_UNSET, bytesDownloaded, C.PERCENTAGE_UNSET);
        }
        if (enableDownloadIOException) {
          enableDownloadIOException = false;
          throw new IOException();
        }
      } finally {
        finished.open();
      }
    }

    @Override
    public void remove() {
      startCount.incrementAndGet();
      removeStarted.open();
      try {
        block();
      } finally {
        finished.open();
      }
    }

    /** Finishes the {@link #download} or {@link #remove} without an error. */
    public void finish() throws InterruptedException {
      blocker.open();
      blockUntilFinished();
    }

    /** Fails {@link #download} or {@link #remove} with an error. */
    public void fail() throws InterruptedException {
      enableDownloadIOException = true;
      blocker.open();
      blockUntilFinished();
    }

    /** Increments the number of bytes that the fake downloader has downloaded. */
    public void incrementBytesDownloaded() {
      bytesDownloaded.incrementAndGet();
    }

    public void assertId(String id) {
      assertThat(request.id).isEqualTo(id);
    }

    public void assertStreamKeys(StreamKey... streamKeys) {
      assertThat(request.streamKeys).containsExactlyElementsIn(streamKeys);
    }

    public void assertDownloadStarted() throws InterruptedException {
      assertThat(downloadStarted.block(TIMEOUT_MS)).isTrue();
      downloadStarted.close();
    }

    public void assertRemoveStarted() throws InterruptedException {
      assertThat(removeStarted.block(TIMEOUT_MS)).isTrue();
      removeStarted.close();
    }

    public void assertCanceled() throws InterruptedException {
      blockUntilFinished();
      assertThat(canceled).isTrue();
    }

    // Internal methods.

    private void block() {
      try {
        blocker.block();
      } catch (InterruptedException e) {
        throw new IllegalStateException(e); // Never happens.
      } finally {
        blocker.close();
      }
    }

    private void blockUntilFinished() throws InterruptedException {
      assertThat(finished.block(TIMEOUT_MS)).isTrue();
      finished.close();
    }
  }
}


text:
#
# Modeled heavily after macros for the Log4Cplus project
#

# Get Integrator version macro
# first param - path to include folder, we will rip version from version.h
macro(integrator_get_version _include_PATH vmajor vminor vpatch vsuffix)
  file(STRINGS "${_include_PATH}/version.h" _integrator_VER_STRING_AUX REGEX ".*#define[ ]+INTEGRATOR_VERSION_STR[ ]+")
  # message(${_integrator_VER_STRING_AUX}) debugging message
  string(REGEX MATCHALL "[0-9]+" _integrator_VER_LIST "${_integrator_VER_STRING_AUX}") # version numbers
  list(LENGTH _integrator_VER_LIST _integrator_VER_LIST_LEN)

  # suffix processing
  string(REGEX MATCH "[\"A-Z,a-z\")]*$" _integrator_VER_SUFFIX "${_integrator_VER_STRING_AUX}") # version suffix (string)
  string(LENGTH ${_integrator_VER_SUFFIX} _integrator_SUFFIX_LENGTH)
  if(_integrator_SUFFIX_LENGTH EQUAL 1)
    set(_integrator_VER_SUFFIX " ")
  else()
      string(REPLACE ")" "" _integrator_VER_SUFFIX ${_integrator_VER_SUFFIX}) # trim the suffix
  endif()
  # message(${_integrator_VER_SUFFIX}) # debugging message

# get each version value from the list and return
  set(${vsuffix} ${_integrator_VER_SUFFIX})
  if(_integrator_VER_LIST_LEN EQUAL 3)
    list(GET _integrator_VER_LIST 0 ${vmajor})
    list(GET _integrator_VER_LIST 1 ${vminor})
    list(GET _integrator_VER_LIST 2 ${vpatch})
  endif()
endmacro()

redpajama_set_name: RedPajamaGithub


text:
@interface CoinDouViewController ()<UIGestureRecognizerDelegate>

@property (strong,nonatomic) UIView *wView;
@property (strong,nonatomic) UIView *gView;

@property (strong,nonatomic) UIButton *coinBtn;

@end

@implementation CoinDouViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"币斗收益";
    self.view.backgroundColor = whiteC;

    [self.view addSubview:self.wView];
    [self.view addSubview:self.gView];

    [self initWithFrame];

    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if (self.navigationController.viewControllers.count == 1) {
        return NO;
    }
    else{
        return YES;
    }
}

//白色view
-(UIView *)wView{
    if (!_wView) {
        _wView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2-32)];
        _wView.backgroundColor = whiteC;
    }
    return _wView;
}

//灰色view
-(UIView *)gView{
    if (!_gView) {
        _gView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-32, SCREEN_WIDTH, SCREEN_HEIGHT/2-32)];
        _gView.backgroundColor = grayC;
    }
    return _gView;
}

//布局
-(void)initWithFrame{
    //标题
    UILabel *titleLab = [UILabel labelWithTextColor:orangeC FontSize:23 Sview:self.wView];
    titleLab.text = @"币斗可以赚通币";
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(SCREEN_WIDTH*0.15);
    }];

    //币斗图片
    UIImageView *imgView = [UIImageView new];
    imgView.image = [UIImage imageNamed:@"coinDou"];
    [self.wView addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleLab);
        make.centerY.mas_equalTo(20);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH*0.4, SCREEN_WIDTH*0.4));
    }];

    //存取标题
    UILabel *saveLab = [UILabel labelWithTextColor:MainColor FontSize:MTitleSize Sview:self.gView];
    saveLab.text = @"放心存 ∙ 大量赚 ∙ 随时取";
    [saveLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(topToMargin);
        make.top.mas_equalTo(SCREEN_WIDTH*0.12);
    }];
    UILabel *douLab = [UILabel labelWithTextColor:SecondTitleColor FontSize:subTitleSize Sview:self.gView];
    douLab.text = @"币斗是企聘通提供的服务支持,安全有保证,值得信赖。";
    [douLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(saveLab);
        make.top.equalTo(saveLab.mas_bottom).offset(leftToMargin);
    }];
    UILabel *deLab = [UILabel labelWithTextColor:SecondTitleColor FontSize:subTitleSize Sview:self.gView];
    deLab.text = @"灵活取出,随时到账。";
    [deLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(douLab);
        make.top.equalTo(douLab.mas_bottom).offset(leftToMargin);
    }];

    //赚通币按钮
    self.coinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.coinBtn setTitle:@"我要赚通币" forState:UIControlStateNormal];
    [self.coinBtn setTitleColor:whiteC forState:UIControlStateNormal];
    self.coinBtn.backgroundColor = blueC;
    self.coinBtn.layer.cornerRadius = 3;
    [self.coinBtn addTarget:self action:@selector(coinBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.gView addSubview:self.coinBtn];
    [self.coinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.gView);
        make.top.equalTo(deLab.mas_bottom).offset(SCREEN_WIDTH*0.12);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-30, formBtnHeight));
    }];
}

-(void)coinBtnClick{
    HWLog(@"log");
    CoinDouProfitViewController *vc = [CoinDouProfitViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

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

@end


text:
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pf-@jxtojga)z+4s*uwbgjrq$aep62-thd0q7f&o77xtpka!_m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'guestbook'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

# When 'NODB' is enabled,we skip Database and Cache setup. This is useful
# to test the rest of the Django deployment while boostrapping the application.
if os.getenv('NODB'):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
else:
    # Dockerfile reads the DJANGO_PW from the secret into an environment
    # variable but its not there on kubectl exec. Soon Kubernetes versions
    # will have secrets as environment variables but currently just read it
    # from the volume
    DJANGO_PW = os.getenv('DJANGO_PASSWORD')
    if not DJANGO_PW:
        try:
            f = open('/etc/secrets/djangouserpw')
            DJANGO_PW = f.readline().rstrip()
        except IOError:
            pass
    if not DJANGO_PW:
        raise Exception("No DJANGO_PASSWORD provided.")

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'guestbook',
            'USER': 'django_user',
            'PASSWORD': DJANGO_PW,
            'HOST': os.getenv('POSTGRES_SERVICE_HOST', '127.0.0.1'),
            'PORT': os.getenv('POSTGRES_SERVICE_PORT', 5432)
        }
    }
    CACHES = {
        'default': {
            'BACKEND': 'redis_cache.RedisCache',
            'LOCATION': [
                '%s:%s' % (os.getenv('REDIS_MASTER_SERVICE_HOST', '127.0.0.1'),
                           os.getenv('REDIS_MASTER_SERVICE_PORT', 6379)),
            ],
            'OPTIONS': {
                'DB': 1,
                'PARSER_CLASS': 'redis.connection.HiredisParser',
                'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
                'CONNECTION_POOL_CLASS_KWARGS': {
                    'max_connections': 50,
                    'timeout': 20,
                },
                'MAX_CONNECTIONS': 1000,
                'PICKLE_VERSION': -1,
            },
        },
    }

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
# STATIC_URL = 'https://storage.googleapis.com/delete-me-1156/static/'

STATIC_ROOT = 'static/'


text:
layout: post
date: '2016-08-04'
title: "One Shoulder Pretty Maids 22577 Short Chiffon Bridesmaids Dress"
category: One Shoulder
tags: [One Shoulder]
---
### One Shoulder Pretty Maids 22577 Short Chiffon Bridesmaids Dress
Just **$226.99**
###

Buy it: [https://www.eudances.com/en/one-shoulder/2079-pretty-maids-22577-short-chiffon-bridesmaids-dress.html](https://www.eudances.com/en/one-shoulder/2079-pretty-maids-22577-short-chiffon-bridesmaids-dress.html)


text:
class Division < ApplicationRecord
  include Authority::Abilities

  belongs_to :owner, class_name: 'User'
  alias_attribute :to_s, :name

  audited
end


text:
Loads or reloads a shared library file.

## Synopsis

``` {#sql_command_synopsis}
LOAD '<filename>'
```

## Description

This command loads a shared library file into the Greenplum Database server address space. If the file had been loaded previously, it is first unloaded. This command is primarily useful to unload and reload a shared library file that has been changed since the server first loaded it. To make use of the shared library, function\(s\) in it need to be declared using the `CREATE FUNCTION` command.

The file name is specified in the same way as for shared library names in `CREATE FUNCTION`; in particular, one may rely on a search path and automatic addition of the system's standard shared library file name extension.

Note that in Greenplum Database the shared library file \(`.so` file\) must reside in the same path location on every host in the Greenplum Database array \(masters, segments, and mirrors\).

Only database superusers can load shared library files.

## Parameters

filename
:   The path and file name of a shared library file. This file must exist in the same location on all hosts in your Greenplum Database array.

## Examples

Load a shared library file:

```
LOAD '/usr/local/greenplum-db/lib/myfuncs.so';
```

## Compatibility

`LOAD` is a Greenplum Database extension.

## See Also

[CREATE FUNCTION](CREATE_FUNCTION.html)

**Parent topic:** [SQL Commands](../sql_commands/sql_ref.html)


text:
MATRIXMULSIZE=1500

declare -a benchmarks=( \
"histogram" \
"kmeans" \
"kmeans_nosharing" \
"linear_regression" \
"matrix_multiply" \
"pca" \
"string_match" \
"word_count" \
"word_count_nosharing" \
)

declare -a benchinputs=(\
"input/large.bmp"\                 # histogram
" "\                               # kmeans -- dont need anything
" "\                               # kmeans_nosharing -- dont need anything
"input/key_file_500MB.txt"\        # linear
"$MATRIXMULSIZE"\                  # matrix multiply (requires created files)
"-r 3000 -c 3000"\                 # pca
"input/key_file_500MB.txt"\        # string match
"input/word_100MB.txt"\            # word count
"../word_count/input/word_100MB.txt"\            # take input from word count
)

declare -a threadsarr=(1 2 4 8 12 14)
declare -a typesarr=("native" "ilr" "tx" "haft")

#action="perf stat -e cpu/cpu-cycles/,cpu/cycles-t/,cpu/cycles-ct/"
action="perf stat -e cycles,instructions -e tx-start,tx-commit,tx-abort -e tx-capacity,tx-conflict"

#========================== EXPERIMENT SCRIPT =================================#
echo "===== Results for Phoenix benchmark ====="

# first remake all benches
for bm in "${benchmarks[@]}"; do
  for type in "${typesarr[@]}"; do
    make -C ${bm} ACTION=${type} clean
    make -C ${bm} ACTION=${type}
  done
done

# special case of matrix_multiply: need to create files
cd ./matrix_multiply
./matrix_multiply.native.exe $MATRIXMULSIZE 1 > /dev/null 2>&1
cd ..

# then run all benches
for times in {1..${NUM_RUNS}}; do

for bmidx in "${!benchmarks[@]}"; do
  bm="${benchmarks[$bmidx]}"
  in="${benchinputs[$bmidx]}"

  cd ./${bm}

  # dry run to load files into RAM
  ./${bm}.native.exe ${in} > /dev/null 2>&1

  for threads in "${threadsarr[@]}"; do
    for type in "${typesarr[@]}"; do

      echo "--- Running ${bm} ${threads} ${type} (input: '${in}') ---"
      lastthreadid=$((threads-1))
      ${action} taskset -c 0-${lastthreadid} ./${bm}.${type}.exe ${in}

    done  # type
  done  # threads

  cd ../
done # benchmarks

done # times


text:
sudo apt-get install -y		\
	python-lxml		\
	python-pip		\
	python-ply		\
	libpython-dev

sudo pip install -r requirements.txt

# Export Docker link variables
export DOCKER_PASSWORD='iSoof4Vo'
export DB_PORT_5432_TCP_ADDR='localhost'
export DB_PORT_5432_TCP_PORT='5432'
export XMLDB_PORT_8080_TCP_ADDR='localhost'
export XMLDB_PORT_8080_TCP_PORT='8080'
export SPARQL_PORT_3030_TCP_ADDR='localhost'
export SPARQL_PORT_3030_TCP_PORT='3030'
export RABBITMQ_PORT_5672_TCP_ADDR='localhost'
export RABBITMQ_PORT_5672_TCP_PORT='5672'
export SOLR_PORT_8983_TCP_ADDR='localhost'
export SOLR_PORT_8983_TCP_PORT='8983'
export DJANGO_SETTINGS_MODULE=roche.settings

python manage.py syncdb --noinput
python manage.py compilemessages


text:
package main

import (
	"context"
	"flag"
	"os"
	"path/filepath"

	"github.com/moby/buildkit/client/llb"
	"github.com/moby/buildkit/util/system"
)

type buildOpt struct {
	buildkit       string
	containerd     string
	runc           string
	withContainerd bool
	installPrefix  string
}

func main() {
	var opt buildOpt
	flag.BoolVar(&opt.withContainerd, "with-containerd", true, "enable containerd worker")
	flag.StringVar(&opt.containerd, "containerd", "v1.5.9", "containerd version")
	flag.StringVar(&opt.runc, "runc", "v1.1.0", "runc version")
	flag.StringVar(&opt.buildkit, "buildkit", "master", "buildkit version")
	flag.StringVar(&opt.installPrefix, "prefix", "/usr/local/bin", "path under which binaries should be installed")
	flag.Parse()

	bk := buildkit(opt)
	out := bk
	dt, err := out.Marshal(context.TODO())
	if err != nil {
		panic(err)
	}
	llb.WriteTo(dt, os.Stdout)
}

func goBuildBase() llb.State {
	goAlpine := llb.Image("docker.io/library/golang:1.18-alpine")
	return goAlpine.
		AddEnv("PATH", "/usr/local/go/bin:"+system.DefaultPathEnvUnix).
		AddEnv("GOPATH", "/go").
		Run(llb.Shlex("apk add --no-cache g++ linux-headers libseccomp-dev make")).Root()
}

func goRepo(s llb.State, repo string, src llb.State) func(ro ...llb.RunOption) llb.State {
	dir := "/go/src/" + repo
	return func(ro ...llb.RunOption) llb.State {
		es := s.Dir(dir).Run(ro...)
		es.AddMount(dir, src, llb.Readonly)
		return es.AddMount("/out", llb.Scratch())
	}
}

func runc(version string) llb.State {
	repo := "github.com/opencontainers/runc"
	src := llb.Git(repo, version)
	if version == "local" {
		src = llb.Local("runc-src")
	}
	return goRepo(goBuildBase(), repo, src)(
		llb.Shlex("go build -o /out/runc ./"),
	)
}

func containerd(version string) llb.State {
	repo := "github.com/containerd/containerd"
	src := llb.Git(repo, version, llb.KeepGitDir())
	if version == "local" {
		src = llb.Local("containerd-src")
	}
	return goRepo(
		goBuildBase().
			Run(llb.Shlex("apk add --no-cache btrfs-progs-dev")).Root(),
		repo, src)(
		llb.Shlex("go build -o /out/containerd ./cmd/containerd"),
	)
}

func buildkit(opt buildOpt) llb.State {
	repo := "github.com/moby/buildkit"
	src := llb.Git(repo, opt.buildkit)
	if opt.buildkit == "local" {
		src = llb.Local("buildkit-src")
	}
	run := goRepo(goBuildBase(), repo, src)

	buildkitdOCIWorkerOnly := prefixed(
		run(llb.Shlex("go build -o /out/buildkitd.oci_only -tags no_containerd_worker ./cmd/buildkitd")),
		opt.installPrefix,
	)

	buildkitd := prefixed(run(llb.Shlex("go build -o /out/buildkitd ./cmd/buildkitd")), opt.installPrefix)

	buildctl := prefixed(run(llb.Shlex("go build -o /out/buildctl ./cmd/buildctl")), opt.installPrefix)

	inputs := []llb.State{buildctl, prefixed(runc(opt.runc), opt.installPrefix)}

	if opt.withContainerd {
		inputs = append(inputs, prefixed(containerd(opt.containerd), opt.installPrefix), buildkitd)
	} else {
		inputs = append(inputs, buildkitdOCIWorkerOnly)
	}
	return llb.Merge(inputs)
}

func prefixed(st llb.State, prefix string) llb.State {
	prefix = filepath.Clean(prefix)
	if prefix == "/" {
		return st
	}
	return llb.Scratch().File(llb.Copy(st, "/", prefix, &llb.CopyInfo{CreateDestPath: true}))
}


text:
module QA
  module Page
    module Project
      module SubMenus
        module Common
          extend QA::Page::PageConcern
          include QA::Page::SubMenus::Common

          private

          def sidebar_element
            :project_sidebar
          end
        end
      end
    end
  end
end


text:
package ecs

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// AllocateDedicatedHosts invokes the ecs.AllocateDedicatedHosts API synchronously
func (client *Client) AllocateDedicatedHosts(request *AllocateDedicatedHostsRequest) (response *AllocateDedicatedHostsResponse, err error) {
	response = CreateAllocateDedicatedHostsResponse()
	err = client.DoAction(request, response)
	return
}

// AllocateDedicatedHostsWithChan invokes the ecs.AllocateDedicatedHosts API asynchronously
func (client *Client) AllocateDedicatedHostsWithChan(request *AllocateDedicatedHostsRequest) (<-chan *AllocateDedicatedHostsResponse, <-chan error) {
	responseChan := make(chan *AllocateDedicatedHostsResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.AllocateDedicatedHosts(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// AllocateDedicatedHostsWithCallback invokes the ecs.AllocateDedicatedHosts API asynchronously
func (client *Client) AllocateDedicatedHostsWithCallback(request *AllocateDedicatedHostsRequest, callback func(response *AllocateDedicatedHostsResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *AllocateDedicatedHostsResponse
		var err error
		defer close(result)
		response, err = client.AllocateDedicatedHosts(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// AllocateDedicatedHostsRequest is the request struct for api AllocateDedicatedHosts
type AllocateDedicatedHostsRequest struct {
	*requests.RpcRequest
	ResourceOwnerId                requests.Integer             `position:"Query" name:"ResourceOwnerId"`
	ClientToken                    string                       `position:"Query" name:"ClientToken"`
	Description                    string                       `position:"Query" name:"Description"`
	CpuOverCommitRatio             requests.Float               `position:"Query" name:"CpuOverCommitRatio"`
	ResourceGroupId                string                       `position:"Query" name:"ResourceGroupId"`
	ActionOnMaintenance            string                       `position:"Query" name:"ActionOnMaintenance"`
	DedicatedHostClusterId         string                       `position:"Query" name:"DedicatedHostClusterId"`
	Tag                            *[]AllocateDedicatedHostsTag `position:"Query" name:"Tag"  type:"Repeated"`
	DedicatedHostType              string                       `position:"Query" name:"DedicatedHostType"`
	AutoRenewPeriod                requests.Integer             `position:"Query" name:"AutoRenewPeriod"`
	Period                         requests.Integer             `position:"Query" name:"Period"`
	Quantity                       requests.Integer             `position:"Query" name:"Quantity"`
	DedicatedHostName              string                       `position:"Query" name:"DedicatedHostName"`
	ResourceOwnerAccount           string                       `position:"Query" name:"ResourceOwnerAccount"`
	OwnerAccount                   string                       `position:"Query" name:"OwnerAccount"`
	AutoReleaseTime                string                       `position:"Query" name:"AutoReleaseTime"`
	OwnerId                        requests.Integer             `position:"Query" name:"OwnerId"`
	PeriodUnit                     string                       `position:"Query" name:"PeriodUnit"`
	AutoRenew                      requests.Boolean             `position:"Query" name:"AutoRenew"`
	NetworkAttributesSlbUdpTimeout requests.Integer             `position:"Query" name:"NetworkAttributes.SlbUdpTimeout"`
	ZoneId                         string                       `position:"Query" name:"ZoneId"`
	AutoPlacement                  string                       `position:"Query" name:"AutoPlacement"`
	ChargeType                     string                       `position:"Query" name:"ChargeType"`
	NetworkAttributesUdpTimeout    requests.Integer             `position:"Query" name:"NetworkAttributes.UdpTimeout"`
}

// AllocateDedicatedHostsTag is a repeated param struct in AllocateDedicatedHostsRequest
type AllocateDedicatedHostsTag struct {
	Key   string `name:"Key"`
	Value string `name:"Value"`
}

// AllocateDedicatedHostsResponse is the response struct for api AllocateDedicatedHosts
type AllocateDedicatedHostsResponse struct {
	*responses.BaseResponse
	RequestId           string              `json:"RequestId" xml:"RequestId"`
	DedicatedHostIdSets DedicatedHostIdSets `json:"DedicatedHostIdSets" xml:"DedicatedHostIdSets"`
}

// CreateAllocateDedicatedHostsRequest creates a request to invoke AllocateDedicatedHosts API
func CreateAllocateDedicatedHostsRequest() (request *AllocateDedicatedHostsRequest) {
	request = &AllocateDedicatedHostsRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Ecs", "2014-05-26", "AllocateDedicatedHosts", "ecs", "openAPI")
	request.Method = requests.POST
	return
}

// CreateAllocateDedicatedHostsResponse creates a response to parse from AllocateDedicatedHosts response
func CreateAllocateDedicatedHostsResponse() (response *AllocateDedicatedHostsResponse) {
	response = &AllocateDedicatedHostsResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?php
namespace ContentinumComponents\Action;

abstract class AbstractContentinumAction
{

    /**
     * Worker
     *
     * @var ContentinumComponents\Mapper\Worker $worker
     */
    protected $worker;

    /**
     * AbstractEntity
     *
     * @var ContentinumComponents\Entity\AbstractEntity $entity
     */
    protected $entity;

    /**
     *
     * @return \ContentinumComponents\Mapper\Worker $worker
     */
    public function getWorker()
    {
        return $this->worker;
    }

    /**
     *
     * @param \ContentinumComponents\Mapper\Worker $worker
     */
    public function setWorker($worker)
    {
        $this->worker = $worker;
    }

    /**
     *
     * @return \ContentinumComponents\Entity\AbstractEntity $entity
     */
    public function getEntity()
    {
        return $this->entity;
    }

    /**
     *
     * @param \ContentinumComponents\Entity\AbstractEntity $entity
     */
    public function setEntity($entity)
    {
        $this->entity = $entity;
    }
}


text:
import { TextEditorComponent } from './textEditor';

export {
  TextEditorComponent
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  AVOID_BANK_CONFLICTS
  cudpp_globals.h

Searching...

No Matches


text:
class CreateMigrations < ActiveRecord::Migration
  def change
    create_table :migrations do |t|
      t.string :number
      t.string :owner

      t.timestamps
    end
  end
end


text:
use strict;
use Data::Dumper;
use Bio::KBase::Utilities::ScriptThing;
use Carp;

#
# This is a SAS Component
#

=head1 NAME

get_entity_ObservationalUnit

=head1 SYNOPSIS

get_entity_ObservationalUnit [-c N] [-a] [--fields field-list] < ids > table.with.fields.added

=head1 DESCRIPTION

An ObservationalUnit is an individual plant that 1) is part of an experiment or study, 2) has measured traits, and 3) is assayed for the purpose of determining alleles.

Example:

    get_entity_ObservationalUnit -a < ids > table.with.fields.added

would read in a file of ids and add a column for each field in the entity.

The standard input should be a tab-separated table (i.e., each line
is a tab-separated set of fields).  Normally, the last field in each
line would contain the id. If some other column contains the id,
use

    -c N

where N is the column (from 1) that contains the id.

This is a pipe command. The input is taken from the standard input, and the
output is to the standard output.

=head2 Related entities

The ObservationalUnit entity has the following relationship links:

=over 4

=item DefinedBy TaxonomicGrouping

=item HasTrait Trait

=item IsLocated Locality

=item IsPartOf StudyExperiment

=item IsVariedIn Contig

=item UsesReference Genome

=back

=head1 COMMAND-LINE OPTIONS

Usage: get_entity_ObservationalUnit [arguments] < ids > table.with.fields.added

    -a		    Return all available fields.
    -c num          Select the identifier from column num.
    -i filename     Use filename rather than stdin for input.
    --fields list   Choose a set of fields to return. List is a comma-separated list of strings.
    -a		    Return all available fields.
    --show-fields   List the available fields.

The following fields are available:

=over 4

=item source_name

Name/ID by which the observational unit may be known by the originator and is used in queries.

=item source_name2

Secondary name/ID by which the observational unit may be known and is queried.

=item plant_id

ID of the plant that was tested to produce this observational unit. Observational units with the same plant ID are different assays of a single physical organism.

=back

=head1 AUTHORS

L<The SEED Project|http://www.theseed.org>

=cut

our $usage = <<'END';
Usage: get_entity_ObservationalUnit [arguments] < ids > table.with.fields.added

    -c num          Select the identifier from column num
    -i filename     Use filename rather than stdin for input
    --fields list   Choose a set of fields to return. List is a comma-separated list of strings.
    -a		    Return all available fields.
    --show-fields   List the available fields.

The following fields are available:

    source_name
        Name/ID by which the observational unit may be known by the originator and is used in queries.
    source_name2
        Secondary name/ID by which the observational unit may be known and is queried.
    plant_id
        ID of the plant that was tested to produce this observational unit. Observational units with the same plant ID are different assays of a single physical organism.
END

use Bio::KBase::CDMI::CDMIClient;
use Getopt::Long;

#Default fields

my @all_fields = ( 'source_name', 'source_name2', 'plant_id' );
my %all_fields = map { $_ => 1 } @all_fields;

my $column;
my $a;
my $f;
my $i = "-";
my @fields;
my $help;
my $show_fields;
my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script('c=i'		 => \$column,
								  "all-fields|a" => \$a,
								  "help|h"	 => \$help,
								  "show-fields"	 => \$show_fields,
								  "fields=s"	 => \$f,
								  'i=s'		 => \$i);
if ($help)
{
    print $usage;
    exit 0;
}

if ($show_fields)
{
    print STDERR "Available fields:\n";
    print STDERR "\t$_\n" foreach @all_fields;
    exit 0;
}

if ($a && $f)
{
    print STDERR "Only one of the -a and --fields options may be specified\n";
    exit 1;
}
if ($a)
{
    @fields = @all_fields;
}
elsif ($f) {
    my @err;
    for my $field (split(",", $f))
    {
	if (!$all_fields{$field})
	{
	    push(@err, $field);
	}
	else
	{
	    push(@fields, $field);
	}
    }
    if (@err)
    {
	print STDERR "get_entity_ObservationalUnit: unknown fields @err. Valid fields are: @all_fields\n";
	exit 1;
    }
} else {
    print STDERR $usage;
    exit 1;
}

my $ih;
if ($i eq '-')
{
    $ih = \*STDIN;
}
else
{
    open($ih, "<", $i) or die "Cannot open input file $i: $!\n";
}

while (my @tuples = Bio::KBase::Utilities::ScriptThing::GetBatch($ih, undef, $column)) {
    my @h = map { $_->[0] } @tuples;
    my $h = $geO->get_entity_ObservationalUnit(\@h, \@fields);
    for my $tuple (@tuples) {
        my @values;
        my ($id, $line) = @$tuple;
        my $v = $h->{$id};
	if (! defined($v))
	{
	    #nothing found for this id
	    print STDERR $line,"\n";
     	} else {
	    foreach $_ (@fields) {
		my $val = $v->{$_};
		push (@values, ref($val) eq 'ARRAY' ? join(",", @$val) : $val);
	    }
	    my $tail = join("\t", @values);
	    print "$line\t$tail\n";
        }
    }
}
__DATA__


text:
1. Run `npm install` command
1. Run `./gulp` command
1. Open `build/index.html` file by your browser

## See

### gulp-rev

* [sindresorhus/gulp-rev](https://github.com/sindresorhus/gulp-rev)
* [Expiresヘッダの設定と、gulp-revを利用したフィンガープリントの付与 | Another Sky](http://www.anothersky.pw/2014/07/site_performance_improvement.html)

### gulp-rev-replace

* [jamesknelson/gulp-rev-replace](https://github.com/jamesknelson/gulp-rev-replace)

### rev-del

* [callumacrae/rev-del](https://github.com/callumacrae/rev-del)


text:
import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import {
  Col,
  PaneHeader,
  Row,
} from '@folio/stripes/components';
import { Link } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import {
  getFullName,
} from '../util';

import { refundClaimReturned } from '../../constants';

import css from './Menu.css';

const Menu = (props) => {
  const {
    user,
    showFilters,
    match: { params },
    filters,
    selected,
    accounts
  } = props;

  let balanceOutstanding = 0;
  let balanceSuspended = 0;
  if (params.accountstatus !== 'closed') {
    accounts.forEach((a) => {
      if (a.paymentStatus.name === refundClaimReturned.PAYMENT_STATUS) {
        balanceSuspended += (parseFloat(a.remaining) * 100);
      } else {
        balanceOutstanding += (parseFloat(a.remaining) * 100);
      }
    });
  }
  balanceOutstanding /= 100;
  balanceSuspended /= 100;
  const suspended = parseFloat(balanceSuspended).toFixed(2);
  const outstanding = parseFloat(balanceOutstanding).toFixed(2);

  const showSelected = (selected !== 0 && selected !== parseFloat(0).toFixed(2))
    && outstanding > parseFloat(0).toFixed(2);

  const type = <FormattedMessage id={`ui-users.accounts.${params.accountstatus}`} />;

  const firstMenu = (

      <Row>
        <Col className={css.firstMenuItems}>
          <FormattedMessage id="ui-users.accounts.history.statusLabel" values={{ type }} />
          {' '}
          <Link to={`/users/view/${user.id}`}>
            {`${getFullName(user)} (${_.upperFirst(props.patronGroup.group)})`}
          </Link>
          {(Object.values(filters).length !== 0 && !showFilters)
            ?
            : ''
          }
        </Col>
      </Row>
      <Row>
        <Col className={css.firstMenuItems}>

            <FormattedMessage
              id="ui-users.accounts.outstanding.page"
              values={{ amount: outstanding }}
            />
             |
            <FormattedMessage
              id="ui-users.accounts.suspended.page"
              values={{ amount: suspended }}
            />
            {showSelected &&

               |
              <FormattedMessage
                id="ui-users.accounts.selected.balance"
                values={{ amount: parseFloat(selected).toFixed(2) }}
              />

            }

        </Col>
      </Row>

);

  return (
    <PaneHeader firstMenu={firstMenu} />
  );
};

Menu.propTypes = {
  user: PropTypes.object,
  stripes: PropTypes.shape({
    hasPerm: PropTypes.func,
  }),
  showFilters: PropTypes.bool,
  selected: PropTypes.number,
  filters: PropTypes.object,
  match: PropTypes.object,
  patronGroup: PropTypes.object,
  accounts: PropTypes.arrayOf(PropTypes.object).isRequired,
};

export default Menu;


text:
package com.tja.frame.core.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tja.frame.common.util.Constants;

/**
 * CmsAuthenticationFilter
 *
 * @author liufang
 *
 */
public class CmsAuthenticationFilter extends FormAuthenticationFilter {
	private Logger logger = LoggerFactory
			.getLogger(CmsAuthenticationFilter.class);
	/**
	 * 是否需要验证码
	 */
	public static final String CAPTCHA_REQUIRED_KEY = "shiroCaptchaRequired";
	/**
	 * 验证码错误次数
	 */
	public static final String CAPTCHA_ERROR_COUNT_KEY = "shiroCaptchaErrorCount";
	/**
	 * 验证码名称
	 */
	public static final String CAPTCHA_PARAM = "captcha";
	/**
	 * 返回URL
	 */
	public static final String FALLBACK_URL_PARAM = "fallbackUrl";

	@Override
	protected boolean executeLogin(ServletRequest request,
			ServletResponse response) throws Exception {/*
		AuthenticationToken token = createToken(request, response);
		if (token == null) {
			String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken "
					+ "must be created in order to execute a login attempt.";
			throw new IllegalStateException(msg);
		}
		String username = (String) token.getPrincipal();
		User user = userShiroService.findByUsername(username);
		HttpServletRequest hsr = (HttpServletRequest) request;
		HttpServletResponse hsp = (HttpServletResponse) response;
		if (isCaptchaSessionRequired(hsr, hsp) || user != null
				&& user.isCaptchaRequired()) {
			String captcha = request.getParameter(CAPTCHA_PARAM);
			if (captcha != null) {
				if (!Captchas.isValid(captchaService, hsr, captcha)) {
					return onLoginFailure(token,
							new IncorrectCaptchaException(), request, response);
				}
			} else {
				return onLoginFailure(token, new CaptchaRequiredException(),
						request, response);
			}
		}
		String ip = Servlets.getRemoteAddr(request);
		try {
			Subject subject = getSubject(request, response);
			subject.login(token);
			logService.loginSuccess(ip, user.getId());
			return onLoginSuccess(token, subject, request, response);
		} catch (AuthenticationException e) {
			Object cred = token.getCredentials();
			String password = "";
			if (cred instanceof char[]) {
				password = new String((char[]) cred);
			}
			logService.loginFailure(username + ":" + password, ip);
			return onLoginFailure(token, e, request, response);
		}
	*/
	return true;
	}

	@Override
	public boolean onPreHandle(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		boolean isAllowed = isAccessAllowed(request, response, mappedValue);
		if (isAllowed && isLoginRequest(request, response)) {
			try {
				issueSuccessRedirect(request, response);
			} catch (Exception e) {
				logger.error("", e);
			}
			return false;
		}
		return isAllowed || onAccessDenied(request, response, mappedValue);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		/*ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
		String ip = Servlets.getRemoteAddr(request);
		userShiroService.updateLoginSuccess(shiroUser.id, ip);
		HttpServletRequest hsr = (HttpServletRequest) request;
		HttpServletResponse hsp = (HttpServletResponse) response;
		// 清除需要验证码的session
		removeCaptchaSession(hsr, hsp);*/
		return super.onLoginSuccess(token, subject, request, response);
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		/*String username = (String) token.getPrincipal();
		HttpServletRequest hsr = (HttpServletRequest) request;
		HttpServletResponse hsp = (HttpServletResponse) response;
		HttpSession session = hsr.getSession();
		Integer errorCount = (Integer) session
				.getAttribute(CAPTCHA_ERROR_COUNT_KEY);
		if (errorCount != null) {
			errorCount++;
		} else {
			errorCount = 1;
		}
		session.setAttribute(CAPTCHA_ERROR_COUNT_KEY, errorCount);
		User user = userShiroService.updateLoginFailure(username);
		if (errorCount > 3 || (user != null && user.isCaptchaRequired())) {
			// 加入需要验证码的session
			addCaptchaSession(hsr, hsp);
		}*/
		return super.onLoginFailure(token, e, request, response);
	}

	@Override
	protected void issueSuccessRedirect(ServletRequest req, ServletResponse resp)
			throws Exception {
	/*	HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String successUrl = request.getParameter(FALLBACK_URL_PARAM);
		if (StringUtils.isBlank(successUrl)) {
			if (request.getRequestURI().startsWith(
					request.getContextPath() + backUrl)) {
				// 后台直接返回首页
				successUrl = getBackSuccessUrl();
				// 清除SavedRequest
				WebUtils.getAndClearSavedRequest(request);
				WebUtils.issueRedirect(request, response, successUrl, null,
						true);
				return;
			} else {
				successUrl = getSuccessUrl();
			}
		}
		WebUtils.redirectToSavedRequest(request, response, successUrl);*/
	}

	@Override
	protected boolean isLoginRequest(ServletRequest req, ServletResponse resp) {
		return pathsMatch(getLoginUrl(), req)
				|| pathsMatch(Constants.BACK_LOGIN_URL, req);
	}

	protected void removeCaptchaSession(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.removeAttribute(CAPTCHA_REQUIRED_KEY);
			session.removeAttribute(CAPTCHA_ERROR_COUNT_KEY);
		}
	}

	protected void addCaptchaSession(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.setAttribute(CAPTCHA_REQUIRED_KEY, true);
	}

	protected boolean isCaptchaSessionRequired(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			return session.getAttribute(CAPTCHA_REQUIRED_KEY) != null;
		}
		return false;
	}

}


text:
/*@ngInject*/
export function FreeEmailDirective () {
  return {
    require: 'ngModel',
    link: function (
      scope: angular.IScope,
      element: angular.IAugmentedJQuery,
      attrs: angular.IAttributes,
      ngModel: angular.INgModelController
    ) {

      function setAsFreeEmail (bool: boolean): void {
        ngModel.$setValidity('freeEmail', bool);
      }

      ngModel.$parsers.push(function (value: string): string {
        if (!value || value.length === 0) return;

        setAsFreeEmail(false);

        let re = new RegExp('(gmail|yahoo|hotmail|live|outlook)', 'i');
        let match = re.test(value);

        if (!match) {
          setAsFreeEmail(true);
        } else {
          setAsFreeEmail(false);
        }

        return value;
      });
    }
  };
}


text:
module Turbot
  module Helpers
    DEFAULT_HOST = 'http://turbot.opencorporates.com'

    extend self

    # Returns the base URL of the Turbot server.
    #
    # @return [String] the base URL of the Turbot server
    def host
      ENV['TURBOT_HOST'] || DEFAULT_HOST
    end

    def error(message)
      prefix = ' !    '
      $stderr.puts(prefix + message.split("\n").join("\n#{prefix}"))
      exit(1)
    end

    def styled_error(error, message = 'Turbot client internal error.')
      $stderr.puts(format_error(error, message))
    end

    def format_error(error, message = 'Turbot client internal error.')
      formatted_error = []
      formatted_error << " !    #{message}"
      formatted_error << ' !    Report a bug at: https://github.com/openc/turbot-client/issues/new'
      formatted_error << ''
      formatted_error << "    Error:       #{error.message} (#{error.class})"
      formatted_error << "    Backtrace:   #{error.backtrace.first}"
      error.backtrace[1..-1].each do |line|
        formatted_error << "                 #{line}"
      end
      if error.backtrace.length > 1
        formatted_error << ''
      end
      command = ARGV.map do |arg|
        if arg.include?(' ')
          arg = %{"#{arg}"}
        else
          arg
        end
      end.join(' ')
      formatted_error << "    Command:     turbot #{command}"
      unless host == DEFAULT_HOST
        formatted_error << "    Host:        #{host}"
      end
      formatted_error << "    Version:     #{Turbot::DEBUG_VERSION}"
      formatted_error << "\n"
      formatted_error.join("\n")
    end
  end
end


text:
package io.gmi.capsule.runner;

public class ApplicationStartEvent {
}


text:
package com.amazonaws.services.migrationhub.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ResourceAttributeType {

    IPV4_ADDRESS("IPV4_ADDRESS"),
    IPV6_ADDRESS("IPV6_ADDRESS"),
    MAC_ADDRESS("MAC_ADDRESS"),
    FQDN("FQDN"),
    VM_MANAGER_ID("VM_MANAGER_ID"),
    VM_MANAGED_OBJECT_REFERENCE("VM_MANAGED_OBJECT_REFERENCE"),
    VM_NAME("VM_NAME"),
    VM_PATH("VM_PATH"),
    BIOS_ID("BIOS_ID"),
    MOTHERBOARD_SERIAL_NUMBER("MOTHERBOARD_SERIAL_NUMBER");

    private String value;

    private ResourceAttributeType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ResourceAttributeType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ResourceAttributeType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ResourceAttributeType enumEntry : ResourceAttributeType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
from .. import Provider as ColorProvider

class Provider(ColorProvider):
    """Implement color provider for ``en_US`` locale."""

    pass


text:
Mongoose is easy to use, powerful, embeddable web server.
   * [Mailing list](http://groups.google.com/group/mongoose-users)
   * [Downloads](http://cesanta.com/mongoose.shtml) and
   [Documentation](http://cesanta.com/docs.shtml)
    * [How to use Lua Server Pages](http://cesanta.com/docs/Lua.shtml)
    * [How to create basic website with Mongoose](http://cesanta.com/docs/BasicWebsite.shtml)
    * [How to create PHP website with Mongoose](http://cesanta.com/docs/PhpWebsite.shtml)
    * [Embedding Guide](http://cesanta.com/docs/Embed.shtml)

# Features

- Works on Windows, Mac, UNIX/Linux, iPhone, Android eCos, QNX and many other platforms
- CGI, SSI, SSL, Digest auth, Websocket, WEbDAV, Resumed download, URL rewrite, file blacklist, Custom error pages, Virtual hosts, IP-based ACL, Windows service
- Lua Server Pages (PHP-like scripting in [Lua](http://lua.org) ), see [dirscan.lp](https://github.com/cesanta/mongoose/blob/master/examples/lua/dirscan.lp)
- Simple and clean
  [embedding API](https://github.com/cesanta/mongoose/blob/master/mongoose.h).
  The source is in single
  [mongoose.c](https://github.com/cesanta/mongoose/blob/master/mongoose.c) file
  to make embedding easy
- Extremely lightweight, has a core of under 40kB and tiny runtime footprint
- Asyncronouns, non-blocking core supporting single- or multi-threaded usage
- HTTP client functionality
- On the market since 2004, stable, mature and tested,
  has several man-years invested in continuous improvement and refinement
- Professional support and consultancy available from
[Cesanta Software](http://cesanta.com), developer of Mongoose

# Screenshots

Download, double-click to start, run browser -- that's all!

![shot1](http://cesanta.com/images/tut_sharing/tut1.png)
![shot2](http://cesanta.com/images/tut_sharing/tut2.png)

![shot3](http://cesanta.com/images/tut_sharing/tut3.png)
![shot4](http://cesanta.com/images/tut_sharing/tut4.png)

# Acknowledgements

Mongoose made better thanks to the contribution of following people:

Arnout Vandecappelle, Benoît Amiaux, Boris Pek, Cody Hanson, Colin Leitner,
Daniel Oaks, Eric Bakan, Erik Oomen, Filipp Kovalev, Ger Hobbelt,
Hendrik Polczynski, Igor Okulist, Jay, Joe Mucchiello, John Safranek,
José Miguel Gonçalves, Shueng Chuan, Katerina Blinova, Konstantin Sorokin,
Marin Atanasov, Matt Healy, Mitch Hendrickson, Nigel Stewart, Pavel Khlebovich,
Sebastian Reinhard, Stefan Doehla, abadc0de, nullable.type,
T.Barmann, D.Hughes, J.C.Sloan, R.Romeo, L.E.Spencer, S.Kotay, R.M.Shorter,
W.Mar, J.Wilander, Santa from Memphis, S.Davies, C.Beck,
O.M.Vilhunen, C.Radik, G.Woodcock, M.Szczepkowski,
Eternal Lands Dev Team, T.Tollet, C.Tangerino, G.Karsai, A.Bourgett,
C.Blakemore, D.Fonaryov, T.Andrle, O.IJsselmuiden, R.Womack, M.Tomlinson,
A.Slåttå, L.Farrell, J.D.P.Ballestero, V.Albaev, B.Harker, T.Scheffel, H.Klein,
R.Merit, T.Bennett, H.Solis, A.Zincenko, M.S., S.Krul, K.Cooke, S.McCallum,
F.Morenius, and 10 others.

# Licensing

Mongoose is released under
[GNU GPL v.2](http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
Businesses have an option to get non-restrictive, royalty-free commercial
license and professional support from
[Cesanta Software](http://cesanta.com).

[Frozen JSON parser](https://github.com/cesanta/frozen),
[Super Light Regular Expression library](https://github.com/cesanta/slre),
[Super Light DNS Resolver](https://github.com/cesanta/sldr)
are other projects by Cesanta Software, developed with the same philosophy
of functionality and simplicity.