text:
package gologgly

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"runtime"
	"strconv"
	"time"
)

type entryRoot struct {
	Timestamp time.Time `json:"timestamp"`
	Message   string    `json:"message"`
	Tags      []string  `json:"tags"`
	File      entryFile `json:"file"`
	Request   entryUser `json:"request,omitempty"`
}
type entryUser struct {
	Host  string `json:"host,omitempty"`
	Agent string `json:"user_agent,omitempty"`
}
type entryFile struct {
	Name   string `json:"name"`
	Line   int    `json:"line"`
	Path   string `json:"path"`
	Memory string `json:"memory_address"`
}

// Creates a log entry on Loggly using the specified input within the input map and setting the specified tags,
// specified message, file name, file line number, memory address, time, user agent, and user ip address/host.
func Log(input string, tags []string, message string, rw http.ResponseWriter, req *http.Request) (err error) {

	// Get the error time right away so that it's as accurate as possible.
	timestamp := time.Now()

	// Initialize a new entry.
	var entry entryRoot

	// Lookup the file line, file name, and memory address of where Loggly was called.
	pc, file, line, ok := runtime.Caller(1)
	if !ok {
		file = "???.go"
		line = -1
	}

	// Remove the directory from the file name.
	short := file
	path := ""
	for i := len(file) - 1; i > 0; i-- {
		if file[i] == '/' {
			short = file[i+1:]
			path = file[:i+1]
			break
		}
	}
	file = short

	// Assemble output.
	entry.Message = message
	entry.Timestamp = timestamp
	entry.Tags = tags
	entry.Request.Host = req.RemoteAddr
	entry.Request.Agent = req.UserAgent()
	entry.File.Name = file
	entry.File.Path = path
	entry.File.Line = line
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "0x%x", pc)
	entry.File.Memory = buf.String()

	// Construct the body of the request.
	entry_json, err := json.Marshal(entry)
	if err != nil {
		return err
	}
	body := bytes.NewReader(entry_json)

	// Retrieve the input's url from the globally defined input map.
	url := "https://logs-01.loggly.com/inputs/" + loggly[input]

	// Append tags to the input's url.
	first_run := true
	for _, value := range tags {
		if first_run {
			url += "/tag/" + value
			first_run = false
		} else {
			url += "," + value
		}
	}

	// Initialize a http.Client.
	client := http.Client{}

	// Construct the request.
	request, err := http.NewRequest("POST", url, body)
	if err != nil {
		return err
	}
	request.Header.Add("Content-Type", "application/json")

	// Send log message to Loggly.
	response, err := client.Do(request)
	if err != nil {
		return err
	}

	// Handle response.
	if !(response.StatusCode == 201 || response.StatusCode == 200) {
		return errors.New("Loggly log did not send: '" + string(entry_json) + "'" + " Loggly HTTP response was code: " + strconv.Itoa(response.StatusCode))
	}

	// Success!
	return nil
}


text:
package com.tq.requisition.presentation.serviceContract.hptMgt;

import com.tq.requisition.presentation.dto.hpt.PersonAndHPTDto;
import com.tq.requisition.presentation.dto.rmHousehold.FamilyItemDto;

/**
 * 购房券和人员的服务契约
 * @author Bless
 * @time 2015-03-16 15:25
 *
 */
public interface IHPTMgtFmlItemServiceContract {

	/**
	 * 新增购房券信息
	 * @param dto
	 * 		待新增的购房券信息
	 * @return
	 * 		json
	 */
	String add(PersonAndHPTDto personAndHPTDto);

	/**
	 * 增加家庭成员
	 * @param dto
	 * @return
	 */
	String add(FamilyItemDto dto);
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
cern.jet.stat (Colt 1.2.0 - API Specification)
</TITLE>

<META NAME="keywords" CONTENT="cern.jet.stat package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

cern.jet.stat

Classes

Descriptive

Gamma

Probability


text:
package com.google.android.exoplayer2.trackselection;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import android.net.Uri;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.chunk.MediaChunk;
import com.google.android.exoplayer2.testutil.FakeClock;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.util.MimeTypes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.RobolectricTestRunner;

/** Unit test for {@link AdaptiveTrackSelection}. */
@RunWith(RobolectricTestRunner.class)
public final class AdaptiveTrackSelectionTest {

  @Mock private BandwidthMeter mockBandwidthMeter;
  private FakeClock fakeClock;

  private AdaptiveTrackSelection adaptiveTrackSelection;

  @Before
  public void setUp() {
    initMocks(this);
    fakeClock = new FakeClock(0);
  }

  @Test
  public void testFactoryUsesInitiallyProvidedBandwidthMeter() {
    BandwidthMeter initialBandwidthMeter = mock(BandwidthMeter.class);
    BandwidthMeter injectedBandwidthMeter = mock(BandwidthMeter.class);
    Format format = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    AdaptiveTrackSelection adaptiveTrackSelection =
        new AdaptiveTrackSelection.Factory(initialBandwidthMeter)
            .createTrackSelection(new TrackGroup(format), injectedBandwidthMeter, /* tracks= */ 0);
    adaptiveTrackSelection.updateSelectedTrack(
        /* playbackPositionUs= */ 0,
        /* bufferedDurationUs= */ 0,
        /* availableDurationUs= */ C.TIME_UNSET);

    verify(initialBandwidthMeter, atLeastOnce()).getBitrateEstimate();
    verifyZeroInteractions(injectedBandwidthMeter);
  }

  @Test
  public void testSelectInitialIndexUseMaxInitialBitrateIfNoBandwidthEstimate() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L);
    adaptiveTrackSelection = adaptiveTrackSelection(trackGroup);

    assertThat(adaptiveTrackSelection.getSelectedFormat()).isEqualTo(format2);
    assertThat(adaptiveTrackSelection.getSelectionReason()).isEqualTo(C.SELECTION_REASON_INITIAL);
  }

  @Test
  public void testSelectInitialIndexUseBandwidthEstimateIfAvailable() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(500L);
    adaptiveTrackSelection = adaptiveTrackSelection(trackGroup);

    assertThat(adaptiveTrackSelection.getSelectedFormat()).isEqualTo(format1);
    assertThat(adaptiveTrackSelection.getSelectionReason()).isEqualTo(C.SELECTION_REASON_INITIAL);
  }

  @Test
  public void testUpdateSelectedTrackDoNotSwitchUpIfNotBufferedEnough() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    // The second measurement onward returns 2000L, which prompts the track selection to switch up
    // if possible.
    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L, 2000L);
    adaptiveTrackSelection =
        adaptiveTrackSelectionWithMinDurationForQualityIncreaseMs(
            trackGroup, /* minDurationForQualityIncreaseMs= */ 10_000);

    adaptiveTrackSelection.updateSelectedTrack(
        /* playbackPositionUs= */ 0,
        /* bufferedDurationUs= */ 9_999_000,
        /* availableDurationUs= */ C.TIME_UNSET);

    // When bandwidth estimation is updated to 2000L, we can switch up to use a higher bitrate
    // format. However, since we only buffered 9_999_000 us, which is smaller than
    // minDurationForQualityIncreaseMs, we should defer switch up.
    assertThat(adaptiveTrackSelection.getSelectedFormat()).isEqualTo(format2);
    assertThat(adaptiveTrackSelection.getSelectionReason()).isEqualTo(C.SELECTION_REASON_INITIAL);
  }

  @Test
  public void testUpdateSelectedTrackSwitchUpIfBufferedEnough() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    // The second measurement onward returns 2000L, which prompts the track selection to switch up
    // if possible.
    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L, 2000L);
    adaptiveTrackSelection =
        adaptiveTrackSelectionWithMinDurationForQualityIncreaseMs(
            trackGroup, /* minDurationForQualityIncreaseMs= */ 10_000);

    adaptiveTrackSelection.updateSelectedTrack(
        /* playbackPositionUs= */ 0,
        /* bufferedDurationUs= */ 10_000_000,
        /* availableDurationUs= */ C.TIME_UNSET);

    // When bandwidth estimation is updated to 2000L, we can switch up to use a higher bitrate
    // format. When we have buffered enough (10_000_000 us, which is equal to
    // minDurationForQualityIncreaseMs), we should switch up now.
    assertThat(adaptiveTrackSelection.getSelectedFormat()).isEqualTo(format3);
    assertThat(adaptiveTrackSelection.getSelectionReason()).isEqualTo(C.SELECTION_REASON_ADAPTIVE);
  }

  @Test
  public void testUpdateSelectedTrackDoNotSwitchDownIfBufferedEnough() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    // The second measurement onward returns 500L, which prompts the track selection to switch down
    // if necessary.
    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L, 500L);
    adaptiveTrackSelection =
        adaptiveTrackSelectionWithMaxDurationForQualityDecreaseMs(
            trackGroup, /* maxDurationForQualityDecreaseMs= */ 25_000);

    adaptiveTrackSelection.updateSelectedTrack(
        /* playbackPositionUs= */ 0,
        /* bufferedDurationUs= */ 25_000_000,
        /* availableDurationUs= */ C.TIME_UNSET);

    // When bandwidth estimation is updated to 500L, we should switch down to use a lower bitrate
    // format. However, since we have enough buffer at higher quality (25_000_000 us, which is equal
    // to maxDurationForQualityDecreaseMs), we should defer switch down.
    assertThat(adaptiveTrackSelection.getSelectedFormat()).isEqualTo(format2);
    assertThat(adaptiveTrackSelection.getSelectionReason()).isEqualTo(C.SELECTION_REASON_INITIAL);
  }

  @Test
  public void testUpdateSelectedTrackSwitchDownIfNotBufferedEnough() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    // The second measurement onward returns 500L, which prompts the track selection to switch down
    // if necessary.
    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L, 500L);
    adaptiveTrackSelection =
        adaptiveTrackSelectionWithMaxDurationForQualityDecreaseMs(
            trackGroup, /* maxDurationForQualityDecreaseMs= */ 25_000);

    adaptiveTrackSelection.updateSelectedTrack(
        /* playbackPositionUs= */ 0,
        /* bufferedDurationUs= */ 24_999_000,
        /* availableDurationUs= */ C.TIME_UNSET);

    // When bandwidth estimation is updated to 500L, we should switch down to use a lower bitrate
    // format. When we don't have enough buffer at higher quality (24_999_000 us is smaller than
    // maxDurationForQualityDecreaseMs), we should switch down now.
    assertThat(adaptiveTrackSelection.getSelectedFormat()).isEqualTo(format1);
    assertThat(adaptiveTrackSelection.getSelectionReason()).isEqualTo(C.SELECTION_REASON_ADAPTIVE);
  }

  @Test
  public void testEvaluateQueueSizeReturnQueueSizeIfBandwidthIsNotImproved() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    FakeMediaChunk chunk1 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 0, /* endTimeUs= */ 10_000_000);
    FakeMediaChunk chunk2 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 10_000_000, /* endTimeUs= */ 20_000_000);
    FakeMediaChunk chunk3 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 20_000_000, /* endTimeUs= */ 30_000_000);
    List<FakeMediaChunk> queue = new ArrayList<>();
    queue.add(chunk1);
    queue.add(chunk2);
    queue.add(chunk3);

    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(500L);
    adaptiveTrackSelection = adaptiveTrackSelection(trackGroup);

    int size = adaptiveTrackSelection.evaluateQueueSize(0, queue);
    assertThat(size).isEqualTo(3);
  }

  @Test
  public void testEvaluateQueueSizeDoNotReevaluateUntilAfterMinTimeBetweenBufferReevaluation() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    FakeMediaChunk chunk1 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 0, /* endTimeUs= */ 10_000_000);
    FakeMediaChunk chunk2 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 10_000_000, /* endTimeUs= */ 20_000_000);
    FakeMediaChunk chunk3 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 20_000_000, /* endTimeUs= */ 30_000_000);
    List<FakeMediaChunk> queue = new ArrayList<>();
    queue.add(chunk1);
    queue.add(chunk2);
    queue.add(chunk3);

    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(500L);
    adaptiveTrackSelection =
        adaptiveTrackSelectionWithMinTimeBetweenBufferReevaluationMs(
            trackGroup,
            /* durationToRetainAfterDiscardMs= */ 15_000,
            /* minTimeBetweenBufferReevaluationMs= */ 2000);

    int initialQueueSize = adaptiveTrackSelection.evaluateQueueSize(0, queue);

    fakeClock.advanceTime(1999);
    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L);

    // When bandwidth estimation is updated, we can discard chunks at the end of the queue now.
    // However, since min duration between buffer reevaluation = 2000, we will not reevaluate
    // queue size if time now is only 1999 ms after last buffer reevaluation.
    int newSize = adaptiveTrackSelection.evaluateQueueSize(0, queue);
    assertThat(newSize).isEqualTo(initialQueueSize);
  }

  @Test
  public void testEvaluateQueueSizeRetainMoreThanMinimumDurationAfterDiscard() {
    Format format1 = videoFormat(/* bitrate= */ 500, /* width= */ 320, /* height= */ 240);
    Format format2 = videoFormat(/* bitrate= */ 1000, /* width= */ 640, /* height= */ 480);
    Format format3 = videoFormat(/* bitrate= */ 2000, /* width= */ 960, /* height= */ 720);
    TrackGroup trackGroup = new TrackGroup(format1, format2, format3);

    FakeMediaChunk chunk1 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 0, /* endTimeUs= */ 10_000_000);
    FakeMediaChunk chunk2 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 10_000_000, /* endTimeUs= */ 20_000_000);
    FakeMediaChunk chunk3 =
        new FakeMediaChunk(format1, /* startTimeUs= */ 20_000_000, /* endTimeUs= */ 30_000_000);
    List<FakeMediaChunk> queue = new ArrayList<>();
    queue.add(chunk1);
    queue.add(chunk2);
    queue.add(chunk3);

    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(500L);
    adaptiveTrackSelection =
        adaptiveTrackSelectionWithMinTimeBetweenBufferReevaluationMs(
            trackGroup,
            /* durationToRetainAfterDiscardMs= */ 15_000,
            /* minTimeBetweenBufferReevaluationMs= */ 2000);

    int initialQueueSize = adaptiveTrackSelection.evaluateQueueSize(0, queue);
    assertThat(initialQueueSize).isEqualTo(3);

    fakeClock.advanceTime(2000);
    when(mockBandwidthMeter.getBitrateEstimate()).thenReturn(1000L);

    // When bandwidth estimation is updated and time has advanced enough, we can discard chunks at
    // the end of the queue now.
    // However, since duration to retain after discard = 15 000 ms, we need to retain at least the
    // first 2 chunks
    int newSize = adaptiveTrackSelection.evaluateQueueSize(0, queue);
    assertThat(newSize).isEqualTo(2);
  }

  private AdaptiveTrackSelection adaptiveTrackSelection(TrackGroup trackGroup) {
    return new AdaptiveTrackSelection(
        trackGroup,
        selectedAllTracksInGroup(trackGroup),
        mockBandwidthMeter,
        AdaptiveTrackSelection.DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
        AdaptiveTrackSelection.DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
        AdaptiveTrackSelection.DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
        /* bandwidthFraction= */ 1.0f,
        AdaptiveTrackSelection.DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
        AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
        fakeClock);
  }

  private AdaptiveTrackSelection adaptiveTrackSelectionWithMinDurationForQualityIncreaseMs(
      TrackGroup trackGroup, long minDurationForQualityIncreaseMs) {
    return new AdaptiveTrackSelection(
        trackGroup,
        selectedAllTracksInGroup(trackGroup),
        mockBandwidthMeter,
        minDurationForQualityIncreaseMs,
        AdaptiveTrackSelection.DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
        AdaptiveTrackSelection.DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
        /* bandwidthFraction= */ 1.0f,
        AdaptiveTrackSelection.DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
        AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
        fakeClock);
  }

  private AdaptiveTrackSelection adaptiveTrackSelectionWithMaxDurationForQualityDecreaseMs(
      TrackGroup trackGroup, long maxDurationForQualityDecreaseMs) {
    return new AdaptiveTrackSelection(
        trackGroup,
        selectedAllTracksInGroup(trackGroup),
        mockBandwidthMeter,
        AdaptiveTrackSelection.DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
        maxDurationForQualityDecreaseMs,
        AdaptiveTrackSelection.DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
        /* bandwidthFraction= */ 1.0f,
        AdaptiveTrackSelection.DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
        AdaptiveTrackSelection.DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
        fakeClock);
  }

  private AdaptiveTrackSelection adaptiveTrackSelectionWithMinTimeBetweenBufferReevaluationMs(
      TrackGroup trackGroup,
      long durationToRetainAfterDiscardMs,
      long minTimeBetweenBufferReevaluationMs) {
    return new AdaptiveTrackSelection(
        trackGroup,
        selectedAllTracksInGroup(trackGroup),
        mockBandwidthMeter,
        AdaptiveTrackSelection.DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
        AdaptiveTrackSelection.DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
        durationToRetainAfterDiscardMs,
        /* bandwidthFraction= */ 1.0f,
        AdaptiveTrackSelection.DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
        minTimeBetweenBufferReevaluationMs,
        fakeClock);
  }

  private int[] selectedAllTracksInGroup(TrackGroup trackGroup) {
    int[] listIndices = new int[trackGroup.length];
    for (int i = 0; i < trackGroup.length; i++) {
      listIndices[i] = i;
    }
    return listIndices;
  }

  private static Format videoFormat(int bitrate, int width, int height) {
    return Format.createVideoSampleFormat(
        /* id= */ null,
        /* sampleMimeType= */ MimeTypes.VIDEO_H264,
        /* codecs= */ null,
        /* bitrate= */ bitrate,
        /* maxInputSize= */ Format.NO_VALUE,
        /* width= */ width,
        /* height= */ height,
        /* frameRate= */ Format.NO_VALUE,
        /* initializationData= */ null,
        /* drmInitData= */ null);
  }

  private static final class FakeMediaChunk extends MediaChunk {

    private static final DataSource DATA_SOURCE = new DefaultHttpDataSource("TEST_AGENT", null);

    public FakeMediaChunk(Format trackFormat, long startTimeUs, long endTimeUs) {
      super(
          DATA_SOURCE,
          new DataSpec(Uri.EMPTY),
          trackFormat,
          C.SELECTION_REASON_ADAPTIVE,
          null,
          startTimeUs,
          endTimeUs,
          0);
    }

    @Override
    public void cancelLoad() {
      // Do nothing.
    }

    @Override
    public void load() throws IOException, InterruptedException {
      // Do nothing.
    }

    @Override
    public boolean isLoadCompleted() {
      return true;
    }
  }
}


text:
package com.github.horrorho.inflatabledonkey.requests;

import java.nio.charset.StandardCharsets;
import javax.annotation.concurrent.Immutable;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;

/**
 * Authentication NSDictionary HttpUriRequest factory.
 *
 * @author Ahseya
 */
@Immutable
public final class GetRequestMetaData {

    public static GetRequestMetaData create() {
        return instance;
    }

    private static final GetRequestMetaData instance = new GetRequestMetaData();

    GetRequestMetaData() {
    }

    /**
     * Returns a new authentication NSDictionary HttpUriRequest.
     *
     * @param dsPrsID not null
     * @param mmeAuthToken not null
     * @param mediaStreamUrl not null
     * @return Authenticate property list, not null
     */
    public HttpUriRequest from(String dsPrsID, String mmeAuthToken, String mediaStreamUrl) {

        String url = mediaStreamUrl + "/" + dsPrsID + "/streams/getmetadata";
        String authorization = HeadersLegacy.mobilemeAuthToken(dsPrsID, mmeAuthToken);

        HttpPost request = new HttpPost(url);
        request.setHeader(HttpHeaders.USER_AGENT, "iCloud.exe (unknown version) CFNetwork/520.20.9");
        request.setHeader("x-apple-mme-streams-version", "AfCPlf71FDRQ");
        request.setHeader("x-apple-mme-streams-client-token", "1a1f03da91f4a769a5b03b9c5b36667f245c3fbec3b2bcbe624f9f41b9f431e2");
        request.setHeader("x-apple-mme-streams-client-udid", "f5a277cb39ca5b4559b5c72880c4060800000000");
        request.setHeader("x-mme-client-info", "<PC><Windows;6.1(1.0);7601><com.apple.mediastreams.windows/7.5 (com.apple.mediastreams.windows/7.5)>");
        request.setHeader("Authorization", authorization);

        String post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
                + "<plist version=\"1.0\">\n"
                + "<dict/>\n"
                + "</plist>";

        request.setEntity(new StringEntity(post, StandardCharsets.UTF_8));

        return request;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.owasp.appsensor.block.proxy.util (appsensor-parent 2.3.2 API)</title>
<meta name="date" content="2017-04-05">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.owasp.appsensor.block.proxy.util

Classes

ConfigurationContext


text:
#ifndef ALIANALYSISTASKEVENTEXTRACTOR_H
#define ALIANALYSISTASKEVENTEXTRACTOR_H

//###############################################################################################################################################3
class AliEventTree;

/**
 * \class AliAnalysisTaskEventExtractor
 * \brief Analysis task that implements AliEventTree to extract events containing MC particles + associated rec. particles to a tree
 *
 * Usage: Task will by default extract particles + tracks.
 * To adjust event extraction percentage, use task->SetEventPercentage()
 *
 * \author Ruediger Haake <ruediger.haake@cern.ch>, Yale
 * \date Apr 16, 2019
 */
//

class AliAnalysisTaskEventExtractor : public AliAnalysisTaskEmcal {
 public:
  AliAnalysisTaskEventExtractor();
  AliAnalysisTaskEventExtractor(const char *name);
  virtual ~AliAnalysisTaskEventExtractor();
  static AliAnalysisTaskEventExtractor* AddTaskEventExtractor(TString trackArray, TString particleArray, const char* taskNameSuffix);
  void                        UserCreateOutputObjects();
  void                        Terminate(Option_t *option);
  AliEventTree*               GetTree() {return fTree;}

  void                        SetSaveTracks(Bool_t val) {fSaveTracks = val;}
  void                        SetCustomStartupScript(const char* path)            { fCustomStartupScript = path; }
  void                        SetEventPercentage(Double_t val)                    { fEventPercentage  = val; }
  void                        SetRandomSeed(ULong_t val)                          { fRandomSeed  = val; }

 protected:
  void                        ExecOnce();
  Bool_t                      Run();

  // ################## CUTS AND SETTINGS: Should be set during task initialization

  Bool_t                      fSaveTracks;                              ///< save arrays of tracks for each particle
  Double_t                    fEventPercentage;                         ///< percentage (0, 1] which will be extracted
  ULong_t                     fRandomSeed;                              ///< random seed
  TString                     fCustomStartupScript;                     ///< startup script
  // ################## BUFFERS: Variables set during execution time
  AliEventTree*               fTree;
  Int_t                       fMultiplicity;                            ///< Multiplicity (number tracks, also for multiple containers)
  TRandom3*                   fRandomGenerator;                         //!<! Random number generator, used for event + jet efficiency

  // ################## HELPER FUNCTIONS
  Double_t                    GetDistance(Double_t eta1, Double_t eta2, Double_t phi1, Double_t phi2)
  {
    Double_t deltaPhi = TMath::Min(TMath::Abs(phi1-phi2),TMath::TwoPi() - TMath::Abs(phi1-phi2));
    return TMath::Sqrt((eta1-eta2)*(eta1-eta2) + deltaPhi*deltaPhi);
  }
  void                        FillHistogram(const char * key, Double_t x);
  void                        FillHistogram(const char * key, Double_t x, Double_t y);
  void                        FillHistogram(const char * key, Double_t x, Double_t y, Double_t add);
  void                        FillHistogram3D(const char * key, Double_t x, Double_t y, Double_t z, Double_t add = 0);
  template <class T> T*       AddHistogram1D(const char* name = "CustomHistogram", const char* title = "NO_TITLE", const char* options = "", Int_t xBins = 100, Double_t xMin = 0.0, Double_t xMax = 20.0, const char* xTitle = "x axis", const char* yTitle = "y axis");
  template <class T> T*       AddHistogram2D(const char* name = "CustomHistogram", const char* title = "NO_TITLE", const char* options = "", Int_t xBins = 100, Double_t xMin = 0.0, Double_t xMax = 20.0, Int_t yBins = 100, Double_t yMin = 0.0, Double_t yMax = 20.0,  const char* xTitle = "x axis", const char* yTitle = "y axis", const char* zTitle = "z axis");
  template <class T> T*       AddHistogram3D(const char* name = "CustomHistogram", const char* title = "NO_TITLE", const char* options = "", Int_t xBins = 100, Double_t xMin = 0.0, Double_t xMax = 20.0, Int_t yBins = 100, Double_t yMin = 0.0, Double_t yMax = 20.0, Int_t zBins = 100, Double_t zMin = 0.0, Double_t zMax = 20.0, const char* xTitle = "x axis", const char* yTitle = "y axis", const char* zTitle = "z axis");

 private:
  AliAnalysisTaskEventExtractor(const AliAnalysisTaskEventExtractor&);            // not implemented
  AliAnalysisTaskEventExtractor &operator=(const AliAnalysisTaskEventExtractor&); // not implemented

  /// \cond CLASSIMP
  ClassDef(AliAnalysisTaskEventExtractor, 1) // Track extraction task
  /// \endcond
};

//###############################################################################################################################################3
/**
 * \class AliEventTree
 * \brief Class managing creation of a tree containing certain parts of events
 *        The tree is intended to be used for ML tasks
 *
 *
 * \author Ruediger Haake <ruediger.haake@cern.ch>, Yale
 * \date Apr 16, 2019
 */
//
class AliEventTree : public TNamed
{
  public:
    AliEventTree();
    AliEventTree(const char* name);
    void            InitializeTree(Bool_t saveTracks);
    Bool_t          AddEventToTree(Long64_t eventID, std::vector<Double_t> vertex, std::vector<AliVParticle*> particles, std::vector<AliVTrack*> tracks);
    TTree*          GetTreePointer() {return fTree;}
  protected:
    TTree*          fTree;                                //!<! tree structure
    Bool_t          fInitialized;                         ///< init state of tree

    // Buffers that will be added to the tree
    Long64_t        fBuffer_Event_ID;                     //!<! array buffer
    Int_t           fBuffer_Event_Number_Particles;       //!<! array buffer
    Int_t           fBuffer_Event_Number_Tracks;          //!<! array buffer
    Float_t         fBuffer_Event_Vertex_X;               //!<! array buffer
    Float_t         fBuffer_Event_Vertex_Y;               //!<! array buffer
    Float_t         fBuffer_Event_Vertex_Z;               //!<! array buffer

    Float_t*        fBuffer_Particles_Pt;                 //!<! array buffer
    Float_t*        fBuffer_Particles_Eta;                //!<! array buffer
    Float_t*        fBuffer_Particles_Phi;                //!<! array buffer
    Int_t*          fBuffer_Particles_Charge;             //!<! array buffer
    Int_t*          fBuffer_Particles_Label;              //!<! array buffer
    Int_t*          fBuffer_Particles_PdgCode;            //!<! array buffer
    Float_t*        fBuffer_Particles_E;                  //!<! array buffer
    Bool_t*         fBuffer_Particles_IsPrimary;          //!<! array buffer

    Float_t*        fBuffer_Tracks_Pt;                    //!<! array buffer
    Float_t*        fBuffer_Tracks_Eta;                   //!<! array buffer
    Float_t*        fBuffer_Tracks_Phi;                   //!<! array buffer
    Int_t*          fBuffer_Tracks_Charge;                //!<! array buffer
    Int_t*          fBuffer_Tracks_Label;                 //!<! array buffer
    Bool_t*         fBuffer_Tracks_IsGlobal;              //!<! array buffer

    /// \cond CLASSIMP
    ClassDef(AliEventTree, 1) // Event tree class
    /// \endcond
};

#endif


text:
Estas a punto de retar a Sir <?php echo $knight->name;?>.

Las buenas costumbres indican que alguien tiene que salir abofeteado para llevar a cabo un desafio...


text:
export {CrosshairTool} from "./crosshair_tool"
export {CustomJSHover} from "./customjs_hover"
export {HoverTool}     from "./hover_tool"
export {InspectTool}   from "./inspect_tool"


text:
(function(JST) {
  return Object.defineProperty(JST, 'users', {
    value: function() {}
  });
})(this.JST);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ang Port Scan</title>

Ang-port Scan

		Ay nagbibigay ng isang pangunahing port scanner na nagpapakita kung aling mga port ay bukas sa mga site ng target.

		Na-configure ang pag-scan ng port gamit ang  Mga Pagpipilian sa Port Scan
screen </>.

Pop up ang mga item sa menu

Port Scan host

	Ito ay magsisimula ng port scan ng host para sa napiling node.

 Ang
	Port Scan tab magiging display at ipapakita ang progreso ng mga scan.

Na-access sa pamamagitan ng

			Port Scan tab

			Mga site na tab
			I-click ang menu item ng 'Pag-atake / Port Scan host'


text:
<?php

namespace Rocketeer\Services\Tasks;

use Closure;
use Exception;
use KzykHys\Parallel\Parallel;
use LogicException;
use Rocketeer\Connection;
use Rocketeer\Traits\HasHistory;
use Rocketeer\Traits\HasLocator;

/**
 * Handles running an array of tasks sequentially
 * or in parallel.
 *
 * @author Maxime Fabre <ehtnam6@gmail.com>
 */
class TasksQueue
{
    use HasLocator;
    use HasHistory;

    /**
     * @type Parallel
     */
    protected $parallel;

    /**
     * A list of Tasks to execute.
     *
     * @type array
     */
    protected $tasks;

    /**
     * The Remote connection.
     *
     * @type Connection
     */
    protected $remote;

    /**
     * @param Parallel $parallel
     */
    public function setParallel($parallel)
    {
        $this->parallel = $parallel;
    }

    ////////////////////////////////////////////////////////////////////
    ////////////////////////////// SHORTCUTS ///////////////////////////
    ////////////////////////////////////////////////////////////////////

    /**
     * Execute Tasks on the default connection and
     * return their output.
     *
     * @param string|array|Closure $queue
     * @param string|string[]|null $connections
     *
     * @return bool
     */
    public function execute($queue, $connections = null)
    {
        if ($connections) {
            $this->connections->setConnections($connections);
        }

        // Run tasks
        $this->run($queue);
        $history = $this->history->getFlattenedOutput();

        return end($history);
    }

    /**
     * Execute Tasks on various connections.
     *
     * @param string|string[]      $connections
     * @param string|array|Closure $queue
     *
     * @return bool
     */
    public function on($connections, $queue)
    {
        return $this->execute($queue, $connections);
    }

    ////////////////////////////////////////////////////////////////////
    //////////////////////////////// QUEUE /////////////////////////////
    ////////////////////////////////////////////////////////////////////

    /**
     * Run the queue
     * Run an array of Tasks instances on the various
     * connections and stages provided.
     *
     * @param string|array $tasks An array of tasks
     *
     * @throws Exception
     *
     * @return Pipeline
     */
    public function run($tasks)
    {
        $tasks    = (array) $tasks;
        $queue    = $this->builder->buildTasks($tasks);
        $pipeline = $this->buildPipeline($queue);

        // Wrap job in closure pipeline
        foreach ($pipeline as $key => $job) {
            $pipeline[$key] = function () use ($job) {
                return $this->executeJob($job);
            };
        }

        // Run the tasks and store the results
        if ($this->getOption('parallel')) {
            $pipeline = $this->runAsynchronously($pipeline);
        } else {
            $pipeline = $this->runSynchronously($pipeline);
        }

        return $pipeline;
    }

    /**
     * Build a pipeline of jobs for Parallel to execute.
     *
     * @param array $queue
     *
     * @return Pipeline
     */
    public function buildPipeline(array $queue)
    {
        // First we'll build the queue
        $pipeline = new Pipeline();

        // Get the connections to execute the tasks on
        $connections = (array) $this->connections->getConnections();
        foreach ($connections as $connection) {
            $servers = $this->connections->getConnectionCredentials($connection);
            $stages  = $this->getStages($connection);

            // Add job to pipeline
            foreach ($servers as $server => $credentials) {
                foreach ($stages as $stage) {
                    $pipeline[] = new Job([
                        'connection' => $connection,
                        'server'     => $server,
                        'stage'      => $stage,
                        'queue'      => $queue,
                    ]);
                }
            }
        }

        return $pipeline;
    }

    /**
     * Run the queue, taking into account the stage.
     *
     * @param Job $job
     *
     * @return bool
     */
    protected function executeJob(Job $job)
    {
        // Set proper server
        $this->connections->setConnection($job->connection, $job->server);

        foreach ($job->queue as $key => $task) {
            if ($task->usesStages()) {
                $stage = $task->usesStages() ? $job->stage : null;
                $this->connections->setStage($stage);
            }

            // Here we fire the task, save its
            // output and return its status
            $state = $task->fire();
            $this->toOutput($state);

            // If the task didn't finish, display what the error was
            if ($task->wasHalted() || $state === false) {
                $this->command->error('The tasks queue was canceled by task "'.$task->getName().'"');

                return false;
            }
        }

        return true;
    }

    //////////////////////////////////////////////////////////////////////
    ////////////////////////////// RUNNERS ///////////////////////////////
    //////////////////////////////////////////////////////////////////////

    /**
     * Run the pipeline in order.
     * As long as the previous entry didn't fail, continue.
     *
     * @param Pipeline $pipeline
     *
     * @return Pipeline
     */
    protected function runSynchronously(Pipeline $pipeline)
    {
        $results = [];

        /** @type Closure $task */
        foreach ($pipeline as $key => $task) {
            $results[$key] = $task();
            if (!$results[$key]) {
                break;
            }
        }

        // Update Pipeline results
        $pipeline->setResults($results);

        return $pipeline;
    }

    /**
     * Run the pipeline in parallel order.
     *
     * @param Pipeline $pipeline
     *
     * @throws \Exception
     * @return Pipeline
     *
     */
    protected function runAsynchronously(Pipeline $pipeline)
    {
        $this->parallel = $this->parallel ?: new Parallel();

        // Check if supported
        if (!$this->parallel->isSupported()) {
            throw new Exception('Parallel jobs require the PCNTL extension');
        }

        try {
            $this->parallel = $this->parallel ?: new Parallel();
            $results        = $this->parallel->values($pipeline->all());
            $pipeline->setResults($results);
        } catch (LogicException $exception) {
            return $this->runSynchronously($pipeline);
        }

        return $pipeline;
    }

    ////////////////////////////////////////////////////////////////////
    //////////////////////////////// STAGES ////////////////////////////
    ////////////////////////////////////////////////////////////////////

    /**
     * Get the stages of a connection.
     *
     * @param string $connection
     *
     * @return array
     */
    public function getStages($connection)
    {
        $this->connections->setConnection($connection);

        $stage = $this->rocketeer->getOption('stages.default');
        if ($this->hasCommand()) {
            $stage = $this->getOption('stage') ?: $stage;
        }

        // Return all stages if "all"
        if ($stage === 'all' || !$stage) {
            $stage = $this->connections->getStages();
        }

        // Sanitize and filter
        $stages = (array) $stage;
        $stages = array_filter($stages, [$this, 'isValidStage']);

        return $stages ?: [null];
    }

    /**
     * Check if a stage is valid.
     *
     * @param string $stage
     *
     * @return bool
     */
    public function isValidStage($stage)
    {
        return in_array($stage, $this->connections->getStages(), true);
    }
}


text:
(function() {
  'use strict';

  angular.module('dimApp')
    .controller('dimInfuseCtrl', dimInfuseCtrl);

  dimInfuseCtrl.$inject = ['$scope', 'dimStoreService', 'dimItemService', 'ngDialog', 'dimLoadoutService', 'toaster', '$q', '$translate'];

  function dimInfuseCtrl($scope, dimStoreService, dimItemService, ngDialog, dimLoadoutService, toaster, $q, $translate) {
    var vm = this;

    if (_gaq) {
      // Disable sending pageviews on popups for now, over concerns that we'll go over our free GA limits.
      // Send a virtual pageview event, even though this is a popup
      // _gaq('send', 'pageview', { page: '/infuse' });
    }

    angular.extend(vm, {
      getAllItems: true,
      showLockedItems: false,
      target: null,
      exotic: false,
      infused: 0,
      infusable: [],
      transferInProgress: false,

      setSourceItem: function(item) {
        // Set the source and reset the targets
        vm.source = item;
        vm.infused = 0;
        vm.target = null;
        vm.exotic = item.tier === 'Exotic';
        vm.stat = vm.source.primStat.stat;
        vm.wildcardMaterialIcon = item.bucket.sort === 'General' ? '2e026fc67d445e5b2630277aa794b4b1'
          : vm.stat.statIdentifier === 'STAT_DAMAGE' ? 'f2572a4949fb16df87ba9760f713dac3'
          : '972ae2c6ccbf59cde293a2ed50a57a93';
        vm.wildcardMaterialIcon = '/common/destiny_content/icons/' + vm.wildcardMaterialIcon + '.jpg';
        // 2 motes, or 10 armor/weapon materials
        vm.wildcardMaterialCost = item.bucket.sort === 'General' ? 2 : 10;
      },

      selectItem: function(item, e) {
        if (e) {
          e.stopPropagation();
        }
        vm.target = item;
        vm.infused = vm.target.primStat.value;
      },

      // get Items for infusion
      getItems: function() {
        var stores = dimStoreService.getStores();
        var allItems = [];

        // If we want ALL our weapons, including vault's one
        if (!vm.getAllItems) {
          stores = _.filter(stores, function(store) {
            return store.id === vm.source.owner;
          });
        }

        // all stores
        stores.forEach(function(store) {
          // all items in store
          var items = _.filter(store.items, function(item) {
            return item.primStat &&
              item.year !== 1 &&
              (!item.locked || vm.showLockedItems) &&
              item.type === vm.source.type &&
              item.primStat.value > vm.source.primStat.value;
          });

          allItems = allItems.concat(items);
        });

        allItems = _.sortBy(allItems, function(item) {
          return item.primStat.value + ((item.talentGrid.totalXP / item.talentGrid.totalXPRequired) * 0.5);
        });

        vm.infusable = allItems;
        if (allItems.length) {
          vm.selectItem(allItems[allItems.length - 1]);
        } else {
          vm.target = null;
          vm.infused = 0;
        }
      },

      closeDialog: function() {
        $scope.$parent.closeThisDialog();
      },

      transferItems: function() {
        if (vm.target.notransfer) {
          toaster.pop('error', $translate.instant('Infusion.NoTransfer', { target: vm.target.name }));
          return $q.resolve();
        }
        var store = dimStoreService.getStore(vm.source.owner);
        var items = {};
        var key = vm.target.type.toLowerCase();
        items[key] = items[key] || [];
        var itemCopy = angular.copy(vm.target);
        itemCopy.equipped = false;
        items[key].push(itemCopy);
        // Include the source, since we wouldn't want it to get moved out of the way
        items[vm.source.type.toLowerCase()].push(vm.source);

        items.material = [];
        if (vm.target.bucket.sort === 'General') {
          // Mote of Light
          items.material.push({
            id: '0',
            hash: 937555249,
            amount: 2,
            equipped: false
          });
        } else if (vm.stat.statIdentifier === 'STAT_DAMAGE') {
          // Weapon Parts
          items.material.push({
            id: '0',
            hash: 1898539128,
            amount: 10,
            equipped: false
          });
        } else {
          // Armor Materials
          items.material.push({
            id: '0',
            hash: 1542293174,
            amount: 10,
            equipped: false
          });
        }
        if (vm.exotic) {
          // Exotic shard
          items.material.push({
            id: '0',
            hash: 452597397,
            amount: 1,
            equipped: false
          });
        }

        var loadout = {
          classType: -1,
          name: 'Infusion Materials',
          items: items
        };

        vm.transferInProgress = true;
        return dimLoadoutService.applyLoadout(store, loadout).then(function() {
          vm.transferInProgress = false;
        });
      }
    });

    vm.setSourceItem($scope.$parent.ngDialogData);
    vm.getItems();
  }
})();


text:
require 'rails_helper'

RSpec.describe ApplicationRecord do
  it 'is a ActiveRecord::Base' do
    expect(ApplicationRecord.ancestors).to include ActiveRecord::Base
  end
end


text:
/*
**  @file tcDemTileReader.cpp
*/
/*
**  Copyright (c) 2014, GCBLUE PROJECT
**  All rights reserved.
**
**  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
**  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
**  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**
**  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
**     this software without specific prior written permission.
**
**  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
**  NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
**  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
**  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
**  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
**  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef WX_PRECOMP
#include "stdwx.h"
#endif

#include "tcDemTileReader.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

int tcDemTileReader::GetTileWidth(int resolution) const
{
    switch (resolution)
    {
    case HIGH_RES:
        return N_DEMTILE;
        break;
    case MEDIUM_RES:
        return N_DEMTILE/4;
        break;
    case LOW10_RES:
        return N_DEMTILE/10;
        break;
    case LOW_RES:
        return N_DEMTILE/12;
        break;
    default:
        wxASSERT(false);
        return -1;
    }
}

int tcDemTileReader::GetTileHeight(int resolution) const
{
    switch (resolution)
    {
    case HIGH_RES:
        return M_DEMTILE;
        break;
    case MEDIUM_RES:
        return M_DEMTILE/4;
        break;
    case LOW10_RES:
        return M_DEMTILE/10;
        break;
    case LOW_RES:
        return M_DEMTILE/12;
        break;
    default:
        wxASSERT(false);
        return -1;
    }
}

/**
* Sets namestring to path + filename of 10 x 10 dem tile for northwest
* point of (lat_deg, lon_deg). lat_deg and lon_deg must be multiples
* of 10 to get a valid file name
*/
void tcDemTileReader::GetTileName(wxString& nameString, int lat_deg, int lon_deg, int resolution)
{
	wxASSERT(lat_deg % 10 == 0);
	wxASSERT(lon_deg % 10 == 0);

    switch (resolution)
    {
    case HIGH_RES:
	    nameString = demPathHigh.GetBuffer();
        break;
    case MEDIUM_RES:
        nameString = demPathMedium.GetBuffer();
        break;
    case LOW_RES:
        nameString = demPathLow.GetBuffer();
        break;
    case LOW10_RES:
        nameString = demPathLow10.GetBuffer();
        break;
    default:
        wxASSERT(false);
        nameString = "Error";
        return;
        break;
    }

	nameString += wxString::Format("%dx%d.dat", lat_deg, lon_deg);
}

bool tcDemTileReader::IsTileAvailable(int lat, int lon, int resolution)
{
    static std::map<long, bool> nullMap;

    std::map<long, bool>& statusMap = nullMap;

    switch (resolution)
    {
    case HIGH_RES:
	    statusMap = tileStatusHigh;
        break;
    case MEDIUM_RES:
        statusMap = tileStatusMedium;
        break;
    case LOW_RES:
        statusMap = tileStatusLow;
        break;
    case LOW10_RES:
        statusMap = tileStatusLow10;
        break;
    default:
        wxASSERT(false);
        return false;
    }

	std::map<long, bool>::const_iterator mapIter;

	long key = LatLonToKey(lat, lon);

    mapIter = statusMap.find(key);
    if (mapIter == statusMap.end())  // not found
    {
		tcFile demTile;
		LoadDemTile(demTile, lat, lon, resolution);
		statusMap[key] = demTile.IsOpen();
		demTile.Close();
		return statusMap[key];
    }
	else
	{
		return statusMap[key];
	}
}

void tcDemTileReader::KeyToLatLon(long key, int& lat, int& lon)
{
	lon = (key / 256) - 180;
	lat = (key % 256) - 90;
}

long tcDemTileReader::LatLonToKey(int lat, int lon)
{
	return (lat + 90) + 256 * (lon + 180);
}

/**
* Loads 10 x 10 deg DEM tile specified by Northwest corner point
* (lat_deg, lon_deg). If tile does not exist no load takes place.
* @param lat_deg latitude of Northwest corner point in deg
* @param lat_deg should be mult of 10 deg between -80 and 90
* @param lon_deg longitude of Northwest corner point in deg
* @param lon_deg should be mult of 10 deg between -180 and 170
*/
void tcDemTileReader::LoadDemTile(tcFile& tileFile, int lat_deg, int lon_deg, int resolution)
{
	//static int errorCount = 0;

	wxString demTileName;
	GetTileName(demTileName, lat_deg, lon_deg, resolution);

	if (tileFile.Open(demTileName.c_str(), tcFile::modeRead) ==0)
	{
		/*
		if ((errorCount < 10)||(errorCount++ % 100 == 0))
		{
			fprintf(stderr, "Map tile not found: %s\n", demTileName.c_str());
		}
		*/
	}
}

void tcDemTileReader::MarkTileUnavailable(int lat, int lon, int resolution)
{
    static std::map<long, bool> nullMap;

    std::map<long, bool>& statusMap = nullMap;

    switch (resolution)
    {
    case HIGH_RES:
	    statusMap = tileStatusHigh;
        break;
    case MEDIUM_RES:
        statusMap = tileStatusMedium;
        break;
    case LOW_RES:
        statusMap = tileStatusLow;
        break;
    case LOW10_RES:
        statusMap = tileStatusLow10;
        break;
    default:
        wxASSERT(false);
        return;
    }

	long key = LatLonToKey(lat, lon);

	statusMap[key] = false;
}

void tcDemTileReader::ScanTiles()
{
    // high resolution tiles
	int availCount = 0;

	for (int lat = -80; lat <= 90; lat += 10)
	{
		for (int lon = -180; lon <=170; lon += 10)
		{
			availCount += IsTileAvailable(lat, lon, HIGH_RES) ? 1 : 0;
		}
	}

	fprintf(stdout, "%d / %d high res map tiles available\n",
		availCount, 648);

    // medium resolution tiles
	availCount = 0;

	for (int lat = -80; lat <= 90; lat += 10)
	{
		for (int lon = -180; lon <=170; lon += 10)
		{
			availCount += IsTileAvailable(lat, lon, MEDIUM_RES) ? 1 : 0;
		}
	}

	fprintf(stdout, "%d / %d medium res map tiles available\n",
		availCount, 648);

    // low resolution tiles
	availCount = 0;

	for (int lat = -80; lat <= 90; lat += 10)
	{
		for (int lon = -180; lon <=170; lon += 10)
		{
			availCount += IsTileAvailable(lat, lon, LOW_RES) ? 1 : 0;
		}
	}

	fprintf(stdout, "%d / %d low res map tiles available\n",
		availCount, 648);

    // low resolution tiles (10:1 decimation)
	availCount = 0;

	for (int lat = -80; lat <= 90; lat += 10)
	{
		for (int lon = -180; lon <=170; lon += 10)
		{
			availCount += IsTileAvailable(lat, lon, LOW10_RES) ? 1 : 0;
		}
	}

    fprintf(stdout, "%d / %d low res (10:1) map tiles available\n",
		availCount, 648);

}

tcDemTileReader::tcDemTileReader()
{
	demPathHigh = "maps\\tiles\\";
    demPathMedium = "maps\\tiles\\medres\\";
    demPathLow = "maps\\tiles\\lowres\\";
    demPathLow10 = "maps\\tiles\\lowres10\\";

	ScanTiles();
}

tcDemTileReader::~tcDemTileReader()
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-path name="external_files" path="."/>
</paths>


text:
namespace SIM.Pipelines.Reinstall
{
  using Sitecore.Diagnostics.Base;
  using Sitecore.Diagnostics.Base.Annotations;

  #region

  #endregion

  [UsedImplicitly]
  public class DeleteWebsiteFolder : ReinstallProcessor
  {
    #region Methods

    protected override void Process([NotNull] ReinstallArgs args)
    {
      Assert.ArgumentNotNull(args, nameof(args));

      FileSystem.FileSystem.Local.Directory.DeleteIfExists(args.WebRootPath);
    }

    #endregion
  }
}


text:
class AddColumnToProfiles < ActiveRecord::Migration
  def change
    change_table(:profiles) do |t|
		t.integer :user_id
		t.string :first_name
		t.string :last_name
		t.string :job_title
		t.string :phone_number
		t.string :contact_email
		t.text :description
		t.timestamps
	end
  end
end


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151208_115619_create_user_table extends Migration {

	public function up() {

		$this->createTable('{{%user}}', [
			'id' => $this->primaryKey(),
			'username' => $this->string()->notNull(),
			'login' => $this->string()->notNull(),
			'email' => $this->string()->notNull(),
			'auth_key' => $this->string(32),
			'password_hash' => $this->string()->notNull(),
				], 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB');

		$this->createIndex('idx_user_username', '{{%user}}', 'username');
		$this->createIndex('idx_user_login', '{{%user}}', 'login');
		$this->createIndex('idx_user_email', '{{%user}}', 'email');
	}

	public function down() {
		$this->dropTable('{{%user}}');
	}

	/*
	  // Use safeUp/safeDown to run migration code within a transaction
	  public function safeUp()
	  {
	  }

	  public function safeDown()
	  {
	  }
	 */
}


text:
<!DOCTYPE html>

<title>RemoteMessagePort_sendMessage_missarg</title>
<meta charset="utf-8"/>


text:
package org.apache.druid.indexing.firehose;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.inject.Binder;
import com.google.inject.Module;
import org.apache.druid.client.coordinator.CoordinatorClient;
import org.apache.druid.data.input.Firehose;
import org.apache.druid.data.input.FirehoseFactory;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.InputRowParser;
import org.apache.druid.data.input.impl.JSONParseSpec;
import org.apache.druid.data.input.impl.MapInputRowParser;
import org.apache.druid.data.input.impl.TimeAndDimsParseSpec;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.guice.GuiceAnnotationIntrospector;
import org.apache.druid.guice.GuiceInjectableValues;
import org.apache.druid.guice.GuiceInjectors;
import org.apache.druid.indexing.common.RetryPolicyConfig;
import org.apache.druid.indexing.common.RetryPolicyFactory;
import org.apache.druid.indexing.common.SegmentLoaderFactory;
import org.apache.druid.indexing.common.TestUtils;
import org.apache.druid.indexing.common.config.TaskStorageConfig;
import org.apache.druid.indexing.common.task.NoopTask;
import org.apache.druid.indexing.common.task.Task;
import org.apache.druid.indexing.overlord.HeapMemoryTaskStorage;
import org.apache.druid.indexing.overlord.TaskLockbox;
import org.apache.druid.indexing.overlord.TaskStorage;
import org.apache.druid.java.util.common.IOE;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.JodaUtils;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.metadata.IndexerSQLMetadataStorageCoordinator;
import org.apache.druid.query.aggregation.DoubleSumAggregatorFactory;
import org.apache.druid.query.aggregation.LongSumAggregatorFactory;
import org.apache.druid.query.filter.SelectorDimFilter;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.IndexMergerV9;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.column.ColumnHolder;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.loading.LocalDataSegmentPuller;
import org.apache.druid.segment.loading.LocalLoadSpec;
import org.apache.druid.segment.realtime.firehose.CombiningFirehoseFactory;
import org.apache.druid.segment.realtime.plumber.SegmentHandoffNotifierFactory;
import org.apache.druid.segment.transform.ExpressionTransform;
import org.apache.druid.segment.transform.TransformSpec;
import org.apache.druid.server.metrics.NoopServiceEmitter;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.partition.NumberedPartitionChunk;
import org.apache.druid.timeline.partition.NumberedShardSpec;
import org.apache.druid.timeline.partition.PartitionChunk;
import org.apache.druid.timeline.partition.PartitionHolder;
import org.easymock.EasyMock;
import org.joda.time.Interval;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 *
 */
@RunWith(Parameterized.class)
public class IngestSegmentFirehoseFactoryTest
{
  private static final ObjectMapper MAPPER;
  private static final IndexMergerV9 INDEX_MERGER_V9;
  private static final IndexIO INDEX_IO;
  private static final TaskStorage TASK_STORAGE;
  private static final IndexerSQLMetadataStorageCoordinator MDC;
  private static final TaskLockbox TASK_LOCKBOX;
  private static final Task TASK;

  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();

  static {
    TestUtils testUtils = new TestUtils();
    MAPPER = setupInjectablesInObjectMapper(TestHelper.makeJsonMapper());
    INDEX_MERGER_V9 = testUtils.getTestIndexMergerV9();
    INDEX_IO = testUtils.getTestIndexIO();
    TASK_STORAGE = new HeapMemoryTaskStorage(
        new TaskStorageConfig(null)
        {
        }
    );
    MDC = new IndexerSQLMetadataStorageCoordinator(null, null, null)
    {
      private final Set<DataSegment> published = new HashSet<>();

      @Override
      public List<DataSegment> getUsedSegmentsForInterval(String dataSource, Interval interval)
      {
        return ImmutableList.copyOf(SEGMENT_SET);
      }

      @Override
      public List<DataSegment> getUsedSegmentsForIntervals(String dataSource, List<Interval> interval)
      {
        return ImmutableList.copyOf(SEGMENT_SET);
      }

      @Override
      public List<DataSegment> getUnusedSegmentsForInterval(String dataSource, Interval interval)
      {
        return ImmutableList.of();
      }

      @Override
      public Set<DataSegment> announceHistoricalSegments(Set<DataSegment> segments)
      {
        Set<DataSegment> added = new HashSet<>();
        for (final DataSegment segment : segments) {
          if (published.add(segment)) {
            added.add(segment);
          }
        }

        return ImmutableSet.copyOf(added);
      }

      @Override
      public void deleteSegments(Set<DataSegment> segments)
      {
        // do nothing
      }
    };
    TASK_LOCKBOX = new TaskLockbox(TASK_STORAGE, MDC);
    TASK = NoopTask.create();
    TASK_LOCKBOX.add(TASK);
  }

  @Parameterized.Parameters(name = "{0}")
  public static Collection<Object[]> constructorFeeder() throws IOException
  {
    final IndexSpec indexSpec = new IndexSpec();

    final IncrementalIndexSchema schema = new IncrementalIndexSchema.Builder()
        .withMinTimestamp(JodaUtils.MIN_INSTANT)
        .withDimensionsSpec(ROW_PARSER)
        .withMetrics(
            new LongSumAggregatorFactory(METRIC_LONG_NAME, DIM_LONG_NAME),
            new DoubleSumAggregatorFactory(METRIC_FLOAT_NAME, DIM_FLOAT_NAME)
        )
        .build();
    final IncrementalIndex index = new IncrementalIndex.Builder()
        .setIndexSchema(schema)
        .setMaxRowCount(MAX_ROWS * MAX_SHARD_NUMBER)
        .buildOnheap();

    for (Integer i = 0; i < MAX_ROWS; ++i) {
      index.add(ROW_PARSER.parseBatch(buildRow(i.longValue())).get(0));
    }

    if (!PERSIST_DIR.mkdirs() && !PERSIST_DIR.exists()) {
      throw new IOE("Could not create directory at [%s]", PERSIST_DIR.getAbsolutePath());
    }
    INDEX_MERGER_V9.persist(index, PERSIST_DIR, indexSpec, null);

    final CoordinatorClient cc = new CoordinatorClient(null, null)
    {
      @Override
      public List<DataSegment> getDatabaseSegmentDataSourceSegments(String dataSource, List<Interval> intervals)
      {
        return ImmutableList.copyOf(SEGMENT_SET);
      }
    };

    SegmentHandoffNotifierFactory notifierFactory = EasyMock.createNiceMock(SegmentHandoffNotifierFactory.class);
    EasyMock.replay(notifierFactory);

    final SegmentLoaderFactory slf = new SegmentLoaderFactory(null, MAPPER);
    final RetryPolicyFactory retryPolicyFactory = new RetryPolicyFactory(new RetryPolicyConfig());

    Collection<Object[]> values = new ArrayList<>();
    for (InputRowParser parser : Arrays.<InputRowParser>asList(
        ROW_PARSER,
        new MapInputRowParser(
            new JSONParseSpec(
                new TimestampSpec(TIME_COLUMN, "auto", null),
                new DimensionsSpec(
                    DimensionsSpec.getDefaultSchemas(ImmutableList.of()),
                    ImmutableList.of(DIM_FLOAT_NAME, DIM_LONG_NAME),
                    ImmutableList.of()
                ),
                null,
                null
            )
        )
    )) {
      for (List<String> dim_names : Arrays.<List<String>>asList(null, ImmutableList.of(DIM_NAME))) {
        for (List<String> metric_names : Arrays.<List<String>>asList(
            null,
            ImmutableList.of(METRIC_LONG_NAME, METRIC_FLOAT_NAME)
        )) {
          for (Boolean wrapInCombining : Arrays.asList(false, true)) {
            final IngestSegmentFirehoseFactory isfFactory = new IngestSegmentFirehoseFactory(
                TASK.getDataSource(),
                Intervals.ETERNITY,
                null,
                new SelectorDimFilter(DIM_NAME, DIM_VALUE, null),
                dim_names,
                metric_names,
                null,
                INDEX_IO,
                cc,
                slf,
                retryPolicyFactory
            );
            final FirehoseFactory factory = wrapInCombining
                                            ? new CombiningFirehoseFactory(ImmutableList.of(isfFactory))
                                            : isfFactory;
            values.add(
                new Object[]{
                    StringUtils.format(
                        "DimNames[%s]MetricNames[%s]ParserDimNames[%s]WrapInCombining[%s]",
                        dim_names == null ? "null" : "dims",
                        metric_names == null ? "null" : "metrics",
                        parser == ROW_PARSER ? "dims" : "null",
                        wrapInCombining
                    ),
                    factory,
                    parser
                }
            );
          }
        }
      }
    }
    return values;
  }

  public static ObjectMapper setupInjectablesInObjectMapper(ObjectMapper objectMapper)
  {
    objectMapper.registerModule(
        new SimpleModule("testModule").registerSubtypes(LocalLoadSpec.class)
    );

    final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector();
    objectMapper.setAnnotationIntrospectors(
        new AnnotationIntrospectorPair(
            guiceIntrospector,
            objectMapper.getSerializationConfig().getAnnotationIntrospector()
        ),
        new AnnotationIntrospectorPair(
            guiceIntrospector,
            objectMapper.getDeserializationConfig().getAnnotationIntrospector()
        )
    );
    objectMapper.setInjectableValues(
        new GuiceInjectableValues(
            GuiceInjectors.makeStartupInjectorWithModules(
                ImmutableList.of(
                    new Module()
                    {
                      @Override
                      public void configure(Binder binder)
                      {
                        binder.bind(LocalDataSegmentPuller.class);
                      }
                    }
                )
            )
        )
    );
    return objectMapper;
  }

  public IngestSegmentFirehoseFactoryTest(
      String testName,
      FirehoseFactory factory,
      InputRowParser rowParser
  )
  {
    this.factory = factory;

    // Must decorate the parser, since IngestSegmentFirehoseFactory will undecorate it.
    this.rowParser = TransformSpec.NONE.decorate(rowParser);
  }

  private static final Logger log = new Logger(IngestSegmentFirehoseFactoryTest.class);
  private static final String DATA_SOURCE_NAME = "testDataSource";
  private static final String DATA_SOURCE_VERSION = "version";
  private static final Integer BINARY_VERSION = -1;
  private static final String DIM_NAME = "testDimName";
  private static final String DIM_VALUE = "testDimValue";
  private static final String DIM_LONG_NAME = "testDimLongName";
  private static final String DIM_FLOAT_NAME = "testDimFloatName";
  private static final String METRIC_LONG_NAME = "testLongMetric";
  private static final String METRIC_FLOAT_NAME = "testFloatMetric";
  private static final Long METRIC_LONG_VALUE = 1L;
  private static final Float METRIC_FLOAT_VALUE = 1.0f;
  private static final String TIME_COLUMN = "ts";
  private static final Integer MAX_SHARD_NUMBER = 10;
  private static final Integer MAX_ROWS = 10;
  private static final File TMP_DIR = Files.createTempDir();
  private static final File PERSIST_DIR = Paths.get(TMP_DIR.getAbsolutePath(), "indexTestMerger").toFile();
  private static final List<DataSegment> SEGMENT_SET = new ArrayList<>(MAX_SHARD_NUMBER);

  private final FirehoseFactory<InputRowParser> factory;
  private final InputRowParser rowParser;
  private File tempDir;

  private static final InputRowParser<Map<String, Object>> ROW_PARSER = new MapInputRowParser(
      new TimeAndDimsParseSpec(
          new TimestampSpec(TIME_COLUMN, "auto", null),
          new DimensionsSpec(
              DimensionsSpec.getDefaultSchemas(ImmutableList.of(DIM_NAME)),
              ImmutableList.of(DIM_FLOAT_NAME, DIM_LONG_NAME),
              ImmutableList.of()
          )
      )
  );

  private static Map<String, Object> buildRow(Long ts)
  {
    return ImmutableMap.of(
        TIME_COLUMN, ts,
        DIM_NAME, DIM_VALUE,
        DIM_FLOAT_NAME, METRIC_FLOAT_VALUE,
        DIM_LONG_NAME, METRIC_LONG_VALUE
    );
  }

  private static DataSegment buildSegment(Integer shardNumber)
  {
    Preconditions.checkArgument(shardNumber < MAX_SHARD_NUMBER);
    Preconditions.checkArgument(shardNumber >= 0);
    return new DataSegment(
        DATA_SOURCE_NAME,
        Intervals.ETERNITY,
        DATA_SOURCE_VERSION,
        ImmutableMap.of(
            "type", "local",
            "path", PERSIST_DIR.getAbsolutePath()
        ),
        ImmutableList.of(DIM_NAME),
        ImmutableList.of(METRIC_LONG_NAME, METRIC_FLOAT_NAME),
        new NumberedShardSpec(
            shardNumber,
            MAX_SHARD_NUMBER
        ),
        BINARY_VERSION,
        0L
    );
  }

  @BeforeClass
  public static void setUpStatic()
  {
    for (int i = 0; i < MAX_SHARD_NUMBER; ++i) {
      SEGMENT_SET.add(buildSegment(i));
    }
  }

  @AfterClass
  public static void tearDownStatic()
  {
    recursivelyDelete(TMP_DIR);
  }

  private static void recursivelyDelete(final File dir)
  {
    if (dir != null) {
      if (dir.isDirectory()) {
        final File[] files = dir.listFiles();
        if (files != null) {
          for (File file : files) {
            recursivelyDelete(file);
          }
        }
      } else {
        if (!dir.delete()) {
          log.warn("Could not delete file at [%s]", dir.getAbsolutePath());
        }
      }
    }
  }

  @Before
  public void setup() throws IOException
  {
    tempDir = temporaryFolder.newFolder();
  }

  @After
  public void teardown()
  {
    tempDir.delete();
  }

  @Test
  public void sanityTest()
  {
    if (factory instanceof CombiningFirehoseFactory) {
      // This method tests IngestSegmentFirehoseFactory-specific methods.
      return;
    }
    final IngestSegmentFirehoseFactory isfFactory = (IngestSegmentFirehoseFactory) factory;
    Assert.assertEquals(TASK.getDataSource(), isfFactory.getDataSource());
    if (isfFactory.getDimensions() != null) {
      Assert.assertArrayEquals(new String[]{DIM_NAME}, isfFactory.getDimensions().toArray());
    }
    Assert.assertEquals(Intervals.ETERNITY, isfFactory.getInterval());
    if (isfFactory.getMetrics() != null) {
      Assert.assertEquals(
          ImmutableSet.of(METRIC_LONG_NAME, METRIC_FLOAT_NAME),
          ImmutableSet.copyOf(isfFactory.getMetrics())
      );
    }
  }

  @Test
  public void simpleFirehoseReadingTest() throws IOException
  {
    Assert.assertEquals(MAX_SHARD_NUMBER.longValue(), SEGMENT_SET.size());
    Integer rowcount = 0;
    try (final Firehose firehose = factory.connect(rowParser, TMP_DIR)) {
      while (firehose.hasMore()) {
        InputRow row = firehose.nextRow();
        Assert.assertArrayEquals(new String[]{DIM_NAME}, row.getDimensions().toArray());
        Assert.assertArrayEquals(new String[]{DIM_VALUE}, row.getDimension(DIM_NAME).toArray());
        Assert.assertEquals(METRIC_LONG_VALUE.longValue(), row.getMetric(METRIC_LONG_NAME));
        Assert.assertEquals(
            METRIC_FLOAT_VALUE,
            row.getMetric(METRIC_FLOAT_NAME).floatValue(),
            METRIC_FLOAT_VALUE * 0.0001
        );
        ++rowcount;
      }
    }
    Assert.assertEquals((int) MAX_SHARD_NUMBER * MAX_ROWS, (int) rowcount);
  }

  @Test
  public void testTransformSpec() throws IOException
  {
    Assert.assertEquals(MAX_SHARD_NUMBER.longValue(), SEGMENT_SET.size());
    Integer rowcount = 0;
    final TransformSpec transformSpec = new TransformSpec(
        new SelectorDimFilter(ColumnHolder.TIME_COLUMN_NAME, "1", null),
        ImmutableList.of(
            new ExpressionTransform(METRIC_FLOAT_NAME, METRIC_FLOAT_NAME + " * 10", ExprMacroTable.nil())
        )
    );
    int skipped = 0;
    try (final Firehose firehose =
             factory.connect(transformSpec.decorate(rowParser), TMP_DIR)) {
      while (firehose.hasMore()) {
        InputRow row = firehose.nextRow();
        if (row == null) {
          skipped++;
          continue;
        }
        Assert.assertArrayEquals(new String[]{DIM_NAME}, row.getDimensions().toArray());
        Assert.assertArrayEquals(new String[]{DIM_VALUE}, row.getDimension(DIM_NAME).toArray());
        Assert.assertEquals(METRIC_LONG_VALUE.longValue(), row.getMetric(METRIC_LONG_NAME).longValue());
        Assert.assertEquals(
            METRIC_FLOAT_VALUE * 10,
            row.getMetric(METRIC_FLOAT_NAME).floatValue(),
            METRIC_FLOAT_VALUE * 0.0001
        );
        ++rowcount;
      }
    }
    Assert.assertEquals(90, skipped);
    Assert.assertEquals((int) MAX_ROWS, (int) rowcount);
  }

  @Test
  public void testGetUniqueDimensionsAndMetrics()
  {
    final int numSegmentsPerPartitionChunk = 5;
    final int numPartitionChunksPerTimelineObject = 10;
    final int numSegments = numSegmentsPerPartitionChunk * numPartitionChunksPerTimelineObject;
    final Interval interval = Intervals.of("2017-01-01/2017-01-02");
    final String version = "1";

    final List<TimelineObjectHolder<String, DataSegment>> timelineSegments = new ArrayList<>();
    for (int i = 0; i < numPartitionChunksPerTimelineObject; i++) {
      final List<PartitionChunk<DataSegment>> chunks = new ArrayList<>();
      for (int j = 0; j < numSegmentsPerPartitionChunk; j++) {
        final List<String> dims = IntStream.range(i, i + numSegmentsPerPartitionChunk)
                                           .mapToObj(suffix -> "dim" + suffix)
                                           .collect(Collectors.toList());
        final List<String> metrics = IntStream.range(i, i + numSegmentsPerPartitionChunk)
                                              .mapToObj(suffix -> "met" + suffix)
                                              .collect(Collectors.toList());
        final DataSegment segment = new DataSegment(
            "ds",
            interval,
            version,
            ImmutableMap.of(),
            dims,
            metrics,
            new NumberedShardSpec(numPartitionChunksPerTimelineObject, i),
            1,
            1
        );

        final PartitionChunk<DataSegment> partitionChunk = new NumberedPartitionChunk<>(
            i,
            numPartitionChunksPerTimelineObject,
            segment
        );
        chunks.add(partitionChunk);
      }
      final TimelineObjectHolder<String, DataSegment> timelineHolder = new TimelineObjectHolder<>(
          interval,
          version,
          new PartitionHolder<>(chunks)
      );
      timelineSegments.add(timelineHolder);
    }

    final String[] expectedDims = new String[]{
        "dim9",
        "dim10",
        "dim11",
        "dim12",
        "dim13",
        "dim8",
        "dim7",
        "dim6",
        "dim5",
        "dim4",
        "dim3",
        "dim2",
        "dim1",
        "dim0"
    };
    final String[] expectedMetrics = new String[]{
        "met9",
        "met10",
        "met11",
        "met12",
        "met13",
        "met8",
        "met7",
        "met6",
        "met5",
        "met4",
        "met3",
        "met2",
        "met1",
        "met0"
    };
    Assert.assertEquals(
        Arrays.asList(expectedDims),
        IngestSegmentFirehoseFactory.getUniqueDimensions(timelineSegments, null)
    );
    Assert.assertEquals(
        Arrays.asList(expectedMetrics),
        IngestSegmentFirehoseFactory.getUniqueMetrics(timelineSegments)
    );
  }

  private static ServiceEmitter newMockEmitter()
  {
    return new NoopServiceEmitter();
  }
}


text:
using Effort;
using Pitch;
using Pitch.Models;
using Pitch.Repository;
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.EntityClient;

namespace Pitch.Tests
{
    [TestClass]
    public class AppRepositoryTests
    {
        private AppRepository _repo;

        [TestMethod]
        public void TestAddPlayer()
        {
            _repo.Clear();
            Assert.AreEqual(0, _repo.GetPlayersCount());
            Profile profile = new Profile("Blaise");
            _repo.AddUser(profile);
            Assert.AreEqual(1, _repo.GetPlayersCount());
        }

        [TestMethod]
        public void TestAddSongToPlayer()
        {
            Profile testuser = new Profile("testUser");
            _repo.AddUser(testuser);
            Song song = new Song("song");
            _repo.CreateSong(song);
            _repo.AddSongToUser(testuser.ID, song.ID);
            List<Models.Song> usersSongs = _repo.GetUserSongs(testuser.ID);
            Song savedSong = usersSongs.First<Models.Song>();
            Assert.AreEqual("song", savedSong.title);
        }

        [TestMethod]
        public void TestAddingSongsToPlayer()
        {
            Profile adam = new Profile("adam");
            _repo.AddUser(adam);
            List<int> songIds = new List<int> { 1, 2, 3 };
            _repo.AddSongsToUser(adam.ID, songIds);
            List<Models.Song> adamsSongs = _repo.GetUserSongs(adam.ID);
            Assert.AreEqual(3, adamsSongs.Count());
        }

        [TestMethod]
        public void TestRetrievingId()
        {
            Profile dave = new Profile("Dave");
            _repo.AddUser(dave);
            int profileId = _repo.GetPlayerIdByName("Dave");
            Assert.AreEqual(9, profileId);
            Assert.AreEqual(9, _repo.GetPlayersCount());
            Assert.AreEqual(1, _repo.GetPlayerIdByName("Blaise"));
        }

        [TestMethod]
        public void TestRetrievingSongPlayers()
        {
            _repo.AddSongsToUser(1, new List<int> { 1, 2, 3, 4, 5 });
            _repo.AddSongsToUser(2, new List<int> { 2, 3, 4, 5, 6 });
            _repo.AddSongsToUser(3, new List<int> { 1, 3, 5 });
            List<int> list1 = new List<int> { 1, 3 };
            List<int> list2 = new List<int> { 1, 2 };
            List<int> list3 = new List<int> { 1, 2, 3 };
            List<int> list4 = new List<int> { 1, 2 };
            List<int> list5 = new List<int> { 1, 2, 3 };
            List<int> list6 = new List<int> { 2 };
            CollectionAssert.AreEquivalent(list1, _repo.GetSongPlayers(1));
            CollectionAssert.AreEquivalent(list2, _repo.GetSongPlayers(2));
            CollectionAssert.AreEquivalent(list3, _repo.GetSongPlayers(3));
            CollectionAssert.AreEquivalent(list4, _repo.GetSongPlayers(4));
            CollectionAssert.AreEquivalent(list5, _repo.GetSongPlayers(5));
            CollectionAssert.AreEquivalent(list6, _repo.GetSongPlayers(6));
        }

        [TestMethod]
        public void TestRetrievingInstrumentPlayers()
        {
            _repo.AddInstrumentToUser(1, 1);
            _repo.AddInstrumentToUser(1, 3);
            _repo.AddInstrumentToUser(2, 2);
            _repo.AddInstrumentToUser(2, 3);
            _repo.AddInstrumentToUser(3, 4);
            _repo.AddInstrumentToUser(6, 2);
            _repo.AddInstrumentToUser(6, 3);
            _repo.AddInstrumentToUser(3, 1);
            CollectionAssert.AreEquivalent(new List<int> { 1, 3 }, _repo.GetInstrumentPlayers(1));
            CollectionAssert.AreEquivalent(new List<int> { 2, 6 }, _repo.GetInstrumentPlayers(2));
            CollectionAssert.AreEquivalent(new List<int> { 1, 2, 6 }, _repo.GetInstrumentPlayers(3));
            CollectionAssert.AreEquivalent(new List<int> { 3 }, _repo.GetInstrumentPlayers(4));
        }

        [TestMethod]
        public void TestGettingMatchSetOfPlayersAndInstruments()
        {
            _repo.AddInstrumentToUser(1, 1);
            _repo.AddInstrumentToUser(1, 2);
            _repo.AddInstrumentToUser(1, 3);
            _repo.AddInstrumentToUser(1, 4);
            _repo.AddInstrumentToUser(2, 2);
            _repo.AddInstrumentToUser(2, 3);
            _repo.AddInstrumentToUser(3, 2);
            _repo.AddInstrumentToUser(4, 3);
            _repo.AddInstrumentToUser(5, 4);
            _repo.AddSongsToUser(1, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 });
            _repo.AddSongsToUser(2, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            _repo.AddSongsToUser(2, new List<int> { 11, 12, 13,14, 15, 16, 17, 18, 19, 20 });
            _repo.AddSongsToUser(3, new List<int> { 1, 2, 3, 4, 5, 16, 17, 18, 19, 20 });
            _repo.AddSongsToUser(4, new List<int> { 6, 7, 8, 9, 10, 11, 12, 13, 14, 15});
            CollectionAssert.AreEquivalent(new List<int> { 1 }, _repo.MatchInstrumentPlayersToSongPlayers(_repo.GetInstrumentPlayers(1), _repo.GetSongPlayers(1)));
            CollectionAssert.AreEquivalent(new List<int> { 1, 2, 3 }, _repo.MatchInstrumentPlayersToSongPlayers(_repo.GetInstrumentPlayers(2), _repo.GetSongPlayers(2)));
            CollectionAssert.AreEquivalent(new List<int> { 1, 2, 4 }, _repo.MatchInstrumentPlayersToSongPlayers(_repo.GetInstrumentPlayers(3), _repo.GetSongPlayers(10)));
            CollectionAssert.AreEquivalent(new List<int> { 1 }, _repo.MatchInstrumentPlayersToSongPlayers(_repo.GetInstrumentPlayers(4), _repo.GetSongPlayers(8)));
            CollectionAssert.AreEquivalent(new List<int> { 1, 2 }, _repo.MatchInstrumentPlayersToSongPlayers(_repo.GetInstrumentPlayers(2), _repo.GetSongPlayers(12)));
        }

        [TestMethod]
        public void TestMatchingSetOfInstrumentPlayersToManySongs()
        {
            _repo.AddInstrumentToUser(1, 1);
            _repo.AddInstrumentToUser(1, 2);
            _repo.AddInstrumentToUser(2, 2);
            _repo.AddInstrumentToUser(2, 3);
            _repo.AddInstrumentToUser(3, 1);
            _repo.AddInstrumentToUser(3, 3);
            _repo.AddSongsToUser(1, new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            _repo.AddSongsToUser(2, new List<int> { 1, 2, 3, 4, 5, 6 });
            _repo.AddSongsToUser(3, new List<int> { 4, 5, 6, 7, 8, 9, 10 });
            CollectionAssert.AreEquivalent(new List<int> { 1 }, _repo.GetInstrumentPlayersOfSetOfSongs(1, new List<int> { 1, 2, 3, 4, 5 }));
            CollectionAssert.AreEquivalent(new List<int> { 1, 3 }, _repo.GetInstrumentPlayersOfSetOfSongs(1, new List<int> { 4, 5 }));
            CollectionAssert.AreEquivalent(new List<int> { 1, 2 }, _repo.GetInstrumentPlayersOfSetOfSongs(2, new List<int> { 4, 5, 6 }));
            CollectionAssert.AreEquivalent(new List<int> { 1, 2 }, _repo.GetInstrumentPlayersOfSetOfSongs(2, new List<int> { 1, 4 }));
            CollectionAssert.AreEquivalent(new List<int> { 3 }, _repo.GetInstrumentPlayersOfSetOfSongs(3, new List<int> { 7, 8, 9 }));
        }

        [TestInitialize]
        public void SetUpTest()
        {
            DbConnection connection = Effort.DbConnectionFactory.CreateTransient();
            using(var context = new AppContext(connection))
            {
                context.Database.CreateIfNotExists();
                Profile blaise = new Profile("Blaise");
                Profile adam = new Profile("Adam");
                Profile colby = new Profile("Colby");
                Profile leon = new Profile("Leon");
                Profile jackie = new Profile("Jackie");
                Profile spencer = new Profile("Spencer");
                Profile gerald = new Profile("Gerald");
                Profile alex = new Profile("Alex");
                Instrument piano = new Instrument("Piano");
                Instrument guitar = new Instrument("Guitar");
                Instrument bass = new Instrument("Bass");
                Instrument drums = new Instrument("Drums");
                Song song1 = new Song("Song1");
                Song song2 = new Song("Song2");
                Song song3 = new Song("Song3");
                Song song4 = new Song("Song4");
                Song song5 = new Song("Song5");
                Song song6 = new Song("Song6");
                Song song7 = new Song("Song7");
                Song song8 = new Song("Song8");
                Song song9 = new Song("Song9");
                Song song10 = new Song("Song10");
                Song song11 = new Song("Song11");
                Song song12 = new Song("Song12");
                Song song13 = new Song("Song13");
                Song song14 = new Song("Song14");
                Song song15 = new Song("Song15");
                Song song16 = new Song("Song16");
                Song song17 = new Song("Song17");
                Song song18 = new Song("Song18");
                Song song19 = new Song("Song19");
                Song song20 = new Song("Song20");
                context.Songs.Add(song1);
                context.Songs.Add(song2);
                context.Songs.Add(song3);
                context.Songs.Add(song4);
                context.Songs.Add(song5);
                context.Songs.Add(song6);
                context.Songs.Add(song7);
                context.Songs.Add(song8);
                context.Songs.Add(song9);
                context.Songs.Add(song10);
                context.Songs.Add(song11);
                context.Songs.Add(song12);
                context.Songs.Add(song13);
                context.Songs.Add(song14);
                context.Songs.Add(song15);
                context.Songs.Add(song16);
                context.Songs.Add(song17);
                context.Songs.Add(song18);
                context.Songs.Add(song19);
                context.Songs.Add(song20);
                context.Players.Add(blaise);
                context.Players.Add(colby);
                context.Players.Add(adam);
                context.Players.Add(jackie);
                context.Players.Add(leon);
                context.Players.Add(spencer);
                context.Players.Add(gerald);
                context.Players.Add(alex);
                context.Instruments.Add(piano);
                context.Instruments.Add(guitar);
                context.Instruments.Add(bass);
                context.Instruments.Add(drums);
                context.SaveChanges();
            }
            _repo = new AppRepository(new AppContext(connection));
        }

        [TestCleanup]
        public void ClearRepo()
        {
            _repo.Clear();
        }
    }
}


text:
package net.ymate.platform.validation.impl;

import java.util.Map;

import net.ymate.platform.base.YMP;
import net.ymate.platform.commons.i18n.I18N;
import net.ymate.platform.validation.AbstractValidator;
import net.ymate.platform.validation.IValidateContext;
import net.ymate.platform.validation.ValidationException;

import org.apache.commons.lang.StringUtils;

/**
 *

 * LengthValidator
 *

 *

 * 字符串长度验证;只处理字符串类型数据
 *

 *
 * @author 刘镇(suninformation@163.com)
 * @version 0.0.0
 *

 *

 *          版本号	动作	修改人	修改时间
 *

 *
 *

 *          0.0.0
 *          创建类
 *          刘镇
 *          2013-4-17下午5:17:22
 *

 *

 */
public class LengthValidator extends AbstractValidator {

	public static final String NAME = "length";

	/* (non-Javadoc)
	 * @see net.ymate.platform.validation.IValidator#getName()
	 */
	public String getName() {
		return NAME;
	}

	/* (non-Javadoc)
	 * @see net.ymate.platform.validation.AbstractValidator#onValidate(net.ymate.platform.validation.IValidateContext)
	 */
	@Override
	protected String onValidate(IValidateContext context) {
		if (doParamsLengthCheck(context, 1)) {
			if (isString(context.getFieldValue().getClass())) {
				String _value = (String) context.getFieldValue();
				if (StringUtils.isNotBlank(_value)) {
					Map<String, String> _params = getParamMaps(context);
					boolean _hasMin = _params.containsKey("min");
					boolean _hasMax = _params.containsKey("max");
					int _min = 0;
					int _max = 0;
					if (_hasMin) {
						_min = Integer.parseInt(_params.get("min"));
						if (_min <=0) {
							_hasMin = false;
						}
					}
					if (_hasMax) {
						_max = Integer.parseInt(_params.get("max"));
						if (_max <= 0 || (_hasMin && _max < _min)) {
							_hasMax = false;
						}
					}
					if (!_hasMin && !_hasMax) {
						throw new IllegalArgumentException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.validation.validator_parameter_invalid"));
					}
					if (_hasMax) {
						if (_value.length() <= _max) {
							if (_hasMin) {
								if (_value.length() >= _min) {
									return VALIDATE_SUCCESS;
								}
							} else {
								return VALIDATE_SUCCESS;
							}
						}
					} else if (_hasMin) {
						if (_value.length() >= _min) {
							return VALIDATE_SUCCESS;
						}
					}
					return doMessageResult(context, getResultMessageI18nStr(context, _hasMin, _hasMax, _min, _max), _min + "", _max + "");
				}
			} else {
				throw new ValidationException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.validation.unsupport_non_string_cond_op"));
			}
		} else {
			throw new IllegalArgumentException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.validation.validator_parameter_invalid"));
		}
		return onValidateNull(context);
	}

	/* (non-Javadoc)
	 * @see net.ymate.platform.validation.AbstractValidator#onValidateArray(net.ymate.platform.validation.IValidateContext, java.lang.Class)
	 */
	@Override
	protected String onValidateArray(IValidateContext context, Class<?> arrayClassType) {
		throw new ValidationException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.validation.unsupport_non_string_cond_op"));
	}

	/**
	 * @param context 验证器上下文对象
	 * @return 获取回应消息字符串,非i18n环境请设置为null
	 */
	protected String getResultMessageI18nStr(IValidateContext context, boolean hasMin, boolean hasMax, int min, int max) {
		String _returnValue = "ymp.validation.length";
		if (hasMax && hasMin) {
			return _returnValue;
		} else if (hasMin) {
			return _returnValue + "_min";
		}
		return _returnValue + "_max";
	}

}


text:
package de.qaware.chronix.timeseries;

import de.qaware.chronix.dts.Pair;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

import static de.qaware.chronix.iterators.Iterators.takeAll;
import static de.qaware.chronix.iterators.Iterators.unaryGenerator;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

/**
 * Basic unit test for the TimeSeriesUtil.
 */
public class TimeSeriesUtilTest {

    @Test
    public void testCleanse() {

        List<Pair<Double, Double>> ts = new ArrayList<>();

        ts.add(Pair.pairOf(null, 0.0));
        ts.add(Pair.pairOf(null, 1.0));
        ts.add(Pair.pairOf(null, 2.0));  // keep last of these

        ts.add(Pair.pairOf(0.0, 2.0));
        ts.add(Pair.pairOf(0.0, 2.0));
        ts.add(Pair.pairOf(0.0, 2.0));   // skip these

        ts.add(Pair.pairOf(1.0, null));
        ts.add(Pair.pairOf(1.0, null));
        ts.add(Pair.pairOf(1.0, null));  // keep last of these

        ts.add(Pair.pairOf(2.0, 10.0));  // keep first of these
        ts.add(Pair.pairOf(3.0, 10.0));
        ts.add(Pair.pairOf(4.0, 10.0));

        // call cleanse
        Iterator<Pair<Double, Double>> result = TimeSeriesUtil.cleanse(ts.iterator());

        // unpack result
        List<Pair<Double, Double>> resultAsList = takeAll(result);

        assertThat(resultAsList.size(), is(3));
        assertThat(resultAsList.get(0), is(Pair.pairOf(null, 2.0)));
        assertThat(resultAsList.get(1), is(Pair.pairOf(1.0, null)));
        assertThat(resultAsList.get(2), is(Pair.pairOf(2.0, 10.0)));
    }

    @Test
    public void testMerge() {

        List<Pair<Double, Double>> ts1 = new ArrayList<>();
        ts1.add(Pair.pairOf(0.0, 0.0));
        ts1.add(Pair.pairOf(1.0, 10.0));
        ts1.add(Pair.pairOf(2.0, 20.0));

        List<Pair<Double, Double>> ts2 = new ArrayList<>();
        ts2.add(Pair.pairOf(0.5, 5.0));
        ts2.add(Pair.pairOf(1.5, 15.0));
        ts2.add(Pair.pairOf(2.5, 25.0));

        // put the iterators to be merged in a list
        Iterable<Iterator<Pair<Double, Double>>> input = Arrays.asList(ts1.iterator(), ts2.iterator());

        // call merge to return lists
        Iterator<Pair<Double, List<Double>>> result1 = TimeSeriesUtil.merge(input);

        // unpack the result
        List<Pair<Double, List<Double>>> resultAsList = takeAll(result1);

        assertThat(resultAsList.size(), is(6));
        assertThat(resultAsList.get(0), is(Pair.pairOf(0.0, asList(0.0, null))));
        assertThat(resultAsList.get(1), is(Pair.pairOf(0.5, asList(0.0, 5.0))));
        assertThat(resultAsList.get(2), is(Pair.pairOf(1.0, asList(10.0, 5.0))));
        assertThat(resultAsList.get(3), is(Pair.pairOf(1.5, asList(10.0, 15.0))));
        assertThat(resultAsList.get(4), is(Pair.pairOf(2.0, asList(20.0, 15.0))));
        assertThat(resultAsList.get(5), is(Pair.pairOf(2.5, asList(20.0, 25.0))));

        // rewind input
        input = Arrays.asList(ts1.iterator(), ts2.iterator());

        // call merge with operator to return doubles
        Iterator<Pair<Double, Double>> result2 = TimeSeriesUtil.merge(input, (x, y) -> x + y);

        // unpack the result
        List<Pair<Double, Double>> resultAsList2 = takeAll(result2);

        assertThat(resultAsList2.size(), is(6));
        assertThat(resultAsList2.get(0), is(Pair.pairOf(0.0, 0.0)));
        assertThat(resultAsList2.get(1), is(Pair.pairOf(0.5, 5.0)));
        assertThat(resultAsList2.get(2), is(Pair.pairOf(1.0, 15.0)));
        assertThat(resultAsList2.get(3), is(Pair.pairOf(1.5, 25.0)));
        assertThat(resultAsList2.get(4), is(Pair.pairOf(2.0, 35.0)));
        assertThat(resultAsList2.get(5), is(Pair.pairOf(2.5, 45.0)));
    }

    @Test
    public void testCompact() {

        Function<List<Double>, Double> avg = xs -> {
            double result = 0.0;
            for (Double x : xs) {
                result += x;
            }
            return result / xs.size();
        };

        List<Pair<Double, Double>> ts1 = new ArrayList<>();

        ts1.add(Pair.pairOf(-1.0, 12.0));
        ts1.add(Pair.pairOf(-1.1, 14.0));
        ts1.add(Pair.pairOf(-1.2, 16.0));   // to be skipped

        ts1.add(Pair.pairOf(0.0, 0.0));
        ts1.add(Pair.pairOf(0.1, 10.0));
        ts1.add(Pair.pairOf(0.2, 20.0));   // (0.0, 10.0)

        ts1.add(Pair.pairOf(1.0, 10.0));
        ts1.add(Pair.pairOf(1.1, 12.0));
        ts1.add(Pair.pairOf(1.2, 14.0));    // (1.0, 12.0)

        Iterator<Double> integers = unaryGenerator(0.0, x -> x + 1.0);

        // compact ts to integer timestamps
        Iterator<Pair<Double, Double>> result = TimeSeriesUtil.compact(ts1.iterator(), integers, avg);

        // unpack to List
        List<Pair<Double, Double>> resultAsList = takeAll(result);
        assertThat(resultAsList.size(), is(2));
        assertThat(resultAsList.get(0), is(Pair.pairOf(0.0, 10.0)));
        assertThat(resultAsList.get(1), is(Pair.pairOf(1.0, 12.0)));

        // test empty input
        ts1 = new ArrayList<>();
        integers = unaryGenerator(0.0, x -> x + 1.0);

        result = TimeSeriesUtil.compact(ts1.iterator(), integers, avg);

        // unpack to List
        resultAsList = takeAll(result);
        assertThat(resultAsList.size(), is(0));
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('autorespond', '0013_auto_20171011_0258'),
    ]

    operations = [
        migrations.AddField(
            model_name='excludeduser',
            name='email_notifications',
            field=models.CharField(default=b'DE', help_text=b"Use 'always' or 'never' to override the email notification setting for this user.", max_length=2, choices=[(b'DE', b'default'), (b'AL', b'always'), (b'NE', b'never')]),
        ),
    ]


text: module.exports = require('./baz.litcoffee')(5)


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<ldml>
	<identity>
		<version number="$Revision: 6546 $"/>
		<generation date="$Date: 2012-02-07 12:32:35 -0600 (Tue, 07 Feb 2012) $"/>
		<language type="es"/>
		<territory type="UY"/>
	</identity>
	<numbers>
		<symbols numberSystem="latn">
			<decimal>,</decimal>
			<group>.</group>
		</symbols>
		<currencyFormats numberSystem="latn">
			<currencyFormatLength>
				<currencyFormat>
					<pattern>¤ #,##0.00;(¤ #,##0.00)</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
		<currencies>
			<currency type="UYU">
				<symbol>$</symbol>
			</currency>
		</currencies>
	</numbers>
</ldml>