text:
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_PBCORE_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Export/Export_PBCore.h"
#include "MediaInfo/File__Analyse_Automatic.h"
#include <ctime>
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//---------------------------------------------------------------------------
extern MediaInfo_Config Config;
//---------------------------------------------------------------------------

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
Ztring PBCore_MediaType(MediaInfo_Internal &MI)
{
         if (MI.Count_Get(Stream_Video))
        return __T("Video");
    else if (MI.Count_Get(Stream_Audio))
        return __T("Sound");
    else if (MI.Count_Get(Stream_Image))
        return __T("Static Image");
    else if (MI.Count_Get(Stream_Text))
        return __T("Text");
    else
        return Ztring();
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
Export_PBCore::Export_PBCore ()
{
}

//---------------------------------------------------------------------------
Export_PBCore::~Export_PBCore ()
{
}

//***************************************************************************
// Input
//***************************************************************************

//---------------------------------------------------------------------------
void PBCore_Transform(Ztring &ToReturn, MediaInfo_Internal &MI, stream_t StreamKind, size_t StreamPos)
{
    //Menu: only if TimeCode
    if (StreamKind==Stream_Menu && MI.Get(Stream_Menu, StreamPos, Menu_Format)!=__T("TimeCode"))
        return;

    //essenceTrackType
    Ztring essenceTrackType;
    switch (StreamKind)
    {
        case Stream_Video:
                            essenceTrackType=__T("Video");
                            break;
        case Stream_Audio:
                            essenceTrackType=__T("Audio");
                            break;
        case Stream_Text:
                            {
                            Ztring Format=MI.Get(Stream_Text, StreamPos, Text_Format);
                            if (Format==__T("EIA-608") || Format==__T("EIA-708"))
                                essenceTrackType=__T("CC");
                            else
                                essenceTrackType=__T("Text");
                            }
                            break;
        case Stream_Menu:
                            if (MI.Get(Stream_Menu, StreamPos, Menu_Format)==__T("TimeCode"))
                            {
                                essenceTrackType=__T("TimeCode");
                                break;
                            }
                            else
                                return; //Not supported
        default:            return; //Not supported
    }

    ToReturn+=__T("\t\t<pbcoreEssenceTrack>\n");

    ToReturn+=__T("\t\t\t<essenceTrackType>")+essenceTrackType+__T("</essenceTrackType>\n");

    //essenceTrackIdentifier
    if (!MI.Get(StreamKind, StreamPos, __T("ID")).empty())
    {
        ToReturn+=__T("\t\t\t<essenceTrackIdentifier>")+MI.Get(StreamKind, StreamPos, __T("ID"))+__T("</essenceTrackIdentifier>\n");
        ToReturn+=__T("\t\t\t<essenceTrackIdentifierSource>ID (Mediainfo)</essenceTrackIdentifierSource>\n");
    }
    else if (!MI.Get(StreamKind, StreamPos, __T("UniqueID")).empty())
    {
        ToReturn+=__T("\t\t\t<essenceTrackIdentifier>")+MI.Get(StreamKind, StreamPos, __T("UniqueID"))+__T("</essenceTrackIdentifier>\n");
        ToReturn+=__T("\t\t\t<essenceTrackIdentifierSource>UniqueID (Mediainfo)</essenceTrackIdentifierSource>\n");
    }
    else if (!MI.Get(StreamKind, StreamPos, __T("StreamKindID")).empty())
    {
        ToReturn+=__T("\t\t\t<essenceTrackIdentifier>")+MI.Get(StreamKind, StreamPos, __T("StreamKindID"))+__T("</essenceTrackIdentifier>\n");
        ToReturn+=__T("\t\t\t<essenceTrackIdentifierSource>StreamKindID (Mediainfo)</essenceTrackIdentifierSource>\n");
    }

    //essenceTrackStandard
    if (StreamKind==Stream_Video && !MI.Get(Stream_Video, StreamPos, Video_Standard).empty())
        ToReturn+=__T("\t\t\t<essenceTrackStandard>")+MI.Get(Stream_Video, StreamPos, Video_Standard)+__T("</essenceTrackStandard>\n");

    //essenceTrackEncoding
    if (!MI.Get(StreamKind, StreamPos, __T("Format")).empty())
    {
        ToReturn+=__T("\t\t\t<essenceTrackEncoding>");
        ToReturn+=MI.Get(StreamKind, StreamPos, __T("Format"));
        if (!MI.Get(StreamKind, StreamPos, __T("Format_Profile")).empty()) ToReturn+=__T(' ')+MI.Get(StreamKind, StreamPos, __T("Format_Profile"));
        if (!MI.Get(StreamKind, StreamPos, __T("CodecID")).empty()) ToReturn+=__T(" (")+MI.Get(StreamKind, StreamPos, __T("CodecID"))+__T(')');
        ToReturn+=__T("</essenceTrackEncoding>\n");
    }

    //essenceTrackDataRate
    if (!MI.Get(StreamKind, StreamPos, __T("BitRate")).empty())
    {
        ToReturn+=__T("\t\t\t<essenceTrackDataRate>");
        ToReturn+=MI.Get(StreamKind, StreamPos, __T("BitRate"));
        if (!MI.Get(StreamKind, StreamPos, __T("BitRate_Mode")).empty())
            ToReturn+=__T(' ')+MI.Get(StreamKind, StreamPos, __T("BitRate_Mode"));
        ToReturn+=__T("</essenceTrackDataRate>\n");
    }

    //essenceTrackFrameRate
    if (StreamKind==Stream_Video && !MI.Get(Stream_Video, StreamPos, Video_FrameRate).empty())
    {
        ToReturn+=__T("\t\t\t<essenceTrackFrameRate>");
        ToReturn+=MI.Get(Stream_Video, StreamPos, Video_FrameRate);
        if (!MI.Get(Stream_Video, StreamPos, Video_FrameRate_Mode).empty())
            ToReturn+=__T(' ')+MI.Get(Stream_Video, StreamPos, Video_FrameRate_Mode);
        ToReturn+=__T("</essenceTrackFrameRate>\n");
    }

    //essenceTrackSamplingRate
    if (StreamKind==Stream_Audio && !MI.Get(Stream_Audio, StreamPos, Audio_SamplingRate).empty())
        ToReturn+=__T("\t\t\t<essenceTrackSamplingRate>")+MI.Get(Stream_Audio, StreamPos, Audio_SamplingRate)+__T("</essenceTrackSamplingRate>\n");

    //essenceTrackBitDepth
    if (!MI.Get(StreamKind, StreamPos, __T("BitDepth")).empty())
        ToReturn+=__T("\t\t\t<essenceTrackBitDepth version=\"PBCoreXSD_Ver_1.2_D1\">")+MI.Get(StreamKind, StreamPos, __T("BitDepth"))+__T("</essenceTrackBitDepth>\n");

    //essenceTrackFrameSize
    if (StreamKind==Stream_Video && !MI.Get(Stream_Video, StreamPos, Video_Width).empty())
        ToReturn+=__T("\t\t\t<essenceTrackFrameSize>")+MI.Get(Stream_Video, StreamPos, Video_Width)+__T('x')+MI.Get(Stream_Video, StreamPos, Video_Height)+__T("</essenceTrackFrameSize>\n");

    //essenceTrackAspectRatio
    if (StreamKind==Stream_Video && !MI.Get(Stream_Video, StreamPos, Video_DisplayAspectRatio).empty())
        ToReturn+=__T("\t\t\t<essenceTrackAspectRatio>")+MI.Get(Stream_Video, StreamPos, Video_DisplayAspectRatio)+__T("</essenceTrackAspectRatio>\n");

    //essenceTrackDuration
    if (!MI.Get(StreamKind, StreamPos, __T("Duration")).empty())
        ToReturn+=__T("\t\t\t<essenceTrackDuration>")+MI.Get(StreamKind, StreamPos, __T("Duration"))+__T("</essenceTrackDuration>\n");

    //essenceTrackLanguage
    if (!MI.Get(StreamKind, StreamPos, __T("Language")).empty())
        ToReturn+=__T("\t\t\t<essenceTrackLanguage>")+MediaInfoLib::Config.Iso639_2_Get(MI.Get(StreamKind, StreamPos, __T("Language")))+__T("</essenceTrackLanguage>\n");

    //essenceTrackAnnotation - all fields (except *_String*) separated by |
    Ztring Temp;
    for (size_t Pos=0; Pos<MI.Count_Get(StreamKind, StreamPos); Pos++)
        if (MI.Get(StreamKind, StreamPos, Pos, Info_Name).find(__T("String"))==std::string::npos && !MI.Get(StreamKind, StreamPos, Pos).empty())
            Temp+=MI.Get(StreamKind, StreamPos, Pos, Info_Name)+__T(": ")+MI.Get(StreamKind, StreamPos, Pos)+__T('|');
    if (!Temp.empty())
    {
        Temp.resize(Temp.size()-1);
        ToReturn+=__T("\t\t\t<essenceTrackAnnotation>"); ToReturn+=Temp; ToReturn+=__T("</essenceTrackAnnotation>\n");
    }

    ToReturn+=__T("\t\t</pbcoreEssenceTrack>\n");
}

//---------------------------------------------------------------------------
Ztring Export_PBCore::Transform(MediaInfo_Internal &MI)
{
    //Current date/time is ISO format
    time_t Time=time(NULL);
    Ztring TimeS; TimeS.Date_From_Seconds_1970((int32u)Time);
    TimeS.FindAndReplace(__T("UTC "), __T(""));
    TimeS.FindAndReplace(__T(" "), __T("T"));
    TimeS+=__T('Z');

    Ztring ToReturn;
    ToReturn+=__T("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    ToReturn+=__T("<PBCoreDescriptionDocument xsi:schemaLocation=\"http://www.pbcore.org/PBCore/PBCoreNamespace.html http://www.pbcore.org/PBCore/PBCoreXSD_Ver_1-2-1.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.pbcore.org/PBCore/PBCoreNamespace.html\">\n");
    ToReturn+=__T("\t<!-- Generated at ")+TimeS+__T(" by ")+MediaInfoLib::Config.Info_Version_Get()+__T(" -->\n");
    ToReturn+=__T("\t<!-- Warning: MediaInfo outputs only pbcoreInstantiation, other mandatory PBCore data is junk -->\n");
    ToReturn+=__T("\t<pbcoreIdentifier>\n");
    ToReturn+=__T("\t\t<identifier>***</identifier>\n");
    ToReturn+=__T("\t\t<identifierSource>***</identifierSource>\n");
    ToReturn+=__T("\t</pbcoreIdentifier>\n");
    ToReturn+=__T("\t<pbcoreTitle>\n");
    ToReturn+=__T("\t\t<title>***</title>\n");
    ToReturn+=__T("\t</pbcoreTitle>\n");
    ToReturn+=__T("\t<pbcoreDescription>\n");
    ToReturn+=__T("\t\t<description>***</description>\n");
    ToReturn+=__T("\t\t<descriptionType>***</descriptionType>\n");
    ToReturn+=__T("\t</pbcoreDescription>\n");
    ToReturn+=__T("\t<pbcoreInstantiation>\n");

    //pbcoreFormatID
    ToReturn+=__T("\t\t<pbcoreFormatID>\n");
        //formatIdentifier
        ToReturn+=__T("\t\t\t<formatIdentifier>")+MI.Get(Stream_General, 0, General_FileName)+__T("</formatIdentifier>\n");
        //formatIdentifierSource
        ToReturn+=__T("\t\t\t<formatIdentifierSource version=\"PBCoreXSD_Ver_1.2_D1\">File Name</formatIdentifierSource>\n");
    ToReturn+=__T("\t\t</pbcoreFormatID>\n");

    //formatDigital
    if (!MI.Get(Stream_General, 0, General_InternetMediaType).empty())
    {
        ToReturn+=__T("\t\t<formatDigital>");
        ToReturn+=MI.Get(Stream_General, 0, General_InternetMediaType);
        ToReturn+=__T("</formatDigital>\n");
    }
    else
    {
        //TODO: how to implement formats without Media Type?
        ToReturn+=__T("\t\t<formatDigital>");
        if (MI.Count_Get(Stream_Video))
            ToReturn+=__T("video/x-");
        else if (MI.Count_Get(Stream_Image))
            ToReturn+=__T("image/x-");
        else if (MI.Count_Get(Stream_Audio))
            ToReturn+=__T("audio/x-");
        else
            ToReturn+=__T("application/x-");
        ToReturn+=Ztring(MI.Get(Stream_General, 0, __T("Format"))).MakeLowerCase();
        ToReturn+=__T("</formatDigital>\n");
    }

    //formatLocation
    ToReturn+=__T("\t\t<formatLocation>")+MI.Get(Stream_General, 0, General_CompleteName)+__T("</formatLocation>\n");

    //dateCreated
    if (!MI.Get(Stream_General, 0, General_Encoded_Date).empty())
    {
        Ztring dateCreated=MI.Get(Stream_General, 0, General_Recorded_Date);
        dateCreated.FindAndReplace(__T("UTC"), __T("-"));
        dateCreated.FindAndReplace(__T(" "), __T("T"));
        dateCreated+=__T('Z');
        ToReturn+=__T("\t\t<dateCreated>")+dateCreated+__T("</dateCreated>\n");
    }

    //dateIssued
    if (!MI.Get(Stream_General, 0, General_Recorded_Date).empty())
    {
        Ztring dateIssued=MI.Get(Stream_General, 0, General_Recorded_Date);
        dateIssued.FindAndReplace(__T("UTC"), __T("-"));
        dateIssued.FindAndReplace(__T(" "), __T("T"));
        dateIssued+=__T('Z');
        ToReturn+=__T("\t\t<dateIssued>")+dateIssued+__T("</dateIssued>\n");
    }

    //formatMediaType
    if (!PBCore_MediaType(MI).empty())
        ToReturn+=__T("\t\t<formatMediaType version=\"PBCoreXSD_Ver_1.2_D1\">")+PBCore_MediaType(MI)+__T("</formatMediaType>\n");
    else
        ToReturn+=__T("\t\t<formatMediaType version=\"PBCoreXSD_Ver_1.2_D1\">application/octet-stream</formatMediaType>\n");

    //formatGenerations
    ToReturn+=__T("\t\t<formatGenerations version=\"PBCoreXSD_Ver_1.2_D1\" />\n");

    //formatFileSize
    if (!MI.Get(Stream_General, 0, General_FileSize).empty())
        ToReturn+=__T("\t\t<formatFileSize>")+MI.Get(Stream_General, 0, General_FileSize)+__T("</formatFileSize>\n");

    //formatTimeStart
    if (!MI.Get(Stream_Video, 0, Video_Delay_Original_String3).empty())
        ToReturn+=__T("\t\t<formatTimeStart>")+MI.Get(Stream_Video, 0, Video_Delay_Original_String3)+__T("</formatTimeStart>\n");
    else if (!MI.Get(Stream_Video, 0, Video_Delay_String3).empty())
        ToReturn+=__T("\t\t<formatTimeStart>")+MI.Get(Stream_Video, 0, Video_Delay_String3)+__T("</formatTimeStart>\n");

    //formatDuration
    if (!MI.Get(Stream_General, 0, General_Duration_String3).empty())
        ToReturn+=__T("\t\t<formatDuration>")+MI.Get(Stream_General, 0, General_Duration_String3)+__T("</formatDuration>\n");

    //formatDataRate
    if (!MI.Get(Stream_General, 0, General_OverallBitRate).empty())
    {
        ToReturn+=__T("\t\t<formatDataRate>");
        ToReturn+=MI.Get(Stream_General, 0, General_OverallBitRate);
        if (!MI.Get(Stream_General, 0, General_OverallBitRate_Mode).empty())
            ToReturn+=__T(' ')+MI.Get(Stream_General, 0, General_OverallBitRate_Mode);
        ToReturn+=__T("</formatDataRate>\n");
    }

    //formatTracks
    ToReturn+=__T("\t\t<formatTracks>")+Ztring::ToZtring(MI.Count_Get(Stream_Video)+MI.Count_Get(Stream_Audio)+MI.Count_Get(Stream_Image)+MI.Count_Get(Stream_Text))+__T("</formatTracks>\n");

    //Streams
    for (size_t StreamKind=Stream_General+1; StreamKind<Stream_Max; StreamKind++)
        for (size_t StreamPos=0; StreamPos<MI.Count_Get((stream_t)StreamKind); StreamPos++)
            PBCore_Transform(ToReturn, MI, (stream_t)StreamKind, StreamPos);

    ToReturn+=__T("\t</pbcoreInstantiation>\n");
    ToReturn+=__T("</PBCoreDescriptionDocument>\n");

    //Carriage return
    ToReturn.FindAndReplace(__T("\n"), EOL, 0, Ztring_Recursive);

    return ToReturn;
}

//***************************************************************************
//
//***************************************************************************

} //NameSpace

#endif


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Thyroid preparations are medications used to treat thyroid gland disorders.</value>
		<pattern_crowdsource> [[Thyroid preparations|C0279175]] are [[medications|C0013227]] used to treat [[thyroid gland disorders|C0040128]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Thyroid preparations</surface-form>
				<RDF-ID>C0279175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medications</surface-form>
				<RDF-ID>C0013227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid gland disorders</surface-form>
				<RDF-ID>C0040128</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0279175 ISA C0013227</triple>
			<triple>C0013227 TREATS C0040128</triple>
			<triple>C0279175 TREATS C0040128</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- Levothyroxine (Synthroid, Levothroid)  - Liothyronine (Cytomel)  - Liotrix (Thyrolar, Euthroid)  - Other thyroid medication   Note: This list may not be all-inclusive.</value>
		<pattern_crowdsource> - [[Levothyroxine|C0040165]] ([[Synthroid|C0728762]], Levothroid)  - [[Liothyronine|C0041014]] ([[Cytomel|C0010826]])  - [[Liotrix|C0936106]] ([[Thyrolar|C0145867]], Euthroid)  - Other thyroid medication   Note: This list may not be all-inclusive.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Levothyroxine</surface-form>
				<RDF-ID>C0040165</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Synthroid</surface-form>
				<RDF-ID>C0728762</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Levothroid</surface-form>
				<RDF-ID>C0721345</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Liothyronine</surface-form>
				<RDF-ID>C0041014</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Cytomel</surface-form>
				<RDF-ID>C0010826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Liotrix</surface-form>
				<RDF-ID>C0936106</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Thyrolar</surface-form>
				<RDF-ID>C0145867</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Euthroid</surface-form>
				<RDF-ID>C0306141</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid medication</surface-form>
				<RDF-ID>C0279175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Note</surface-form>
				<RDF-ID>C1317574</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>list</surface-form>
				<RDF-ID>C0745732</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>inclusive</surface-form>
				<RDF-ID>C0332257</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0728762 ISA C0040165</triple>
			<triple>C0010826 ISA C0041014</triple>
			<triple>C0145867 ISA C0936106</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Determine the following information:  - Patient's age, weight, and condition  - The name of the product (ingredients and strengths if known)  - Time it was swallowed  - The amount swallowed  - If the medication was prescribed for the person</value>
		<pattern_crowdsource> Determine the following information:  - Patient's age, weight, and condition  - The name of the product (ingredients and strengths if known)  - Time it was swallowed  - The amount swallowed  - If the [[medication|C0013227]] was prescribed for the [[person|C0027361]]		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>following</surface-form>
				<RDF-ID>C0332282</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>information</surface-form>
				<RDF-ID>C1533716</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Patient's</surface-form>
				<RDF-ID>C0030705</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>age</surface-form>
				<RDF-ID>C0001779</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>weight</surface-form>
				<RDF-ID>C0043100</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>condition</surface-form>
				<RDF-ID>C0348080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>name</surface-form>
				<RDF-ID>C0027365</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>product</surface-form>
				<RDF-ID>C1514468</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>ingredients</surface-form>
				<RDF-ID>C1550600</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>strengths</surface-form>
				<RDF-ID>C0808080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Time</surface-form>
				<RDF-ID>C0040223</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>amount</surface-form>
				<RDF-ID>C1265611</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medication</surface-form>
				<RDF-ID>C0013227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>person</surface-form>
				<RDF-ID>C0027361</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0013227 TREATS C0027361</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Patients who receive quick treatment make a good recovery.</value>
		<pattern_crowdsource> [[Patients|C0030705]] who receive quick [[treatment|C0087111]] make a good recovery.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Patients</surface-form>
				<RDF-ID>C0030705</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>quick</surface-form>
				<RDF-ID>C0439831</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>treatment</surface-form>
				<RDF-ID>C0087111</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>good</surface-form>
				<RDF-ID>C0205170</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>recovery</surface-form>
				<RDF-ID>C0237820</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0087111 ADMINISTERED_TO C0030705</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Heart-related complications may lead to death.</value>
		<pattern_crowdsource> [[Heart-related complications|C0161816]] may lead to [[death|C0011065]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>related</surface-form>
				<RDF-ID>C1522149</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Heart-related complications</surface-form>
				<RDF-ID>C0161816</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>death</surface-form>
				<RDF-ID>C0011065</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0161816 CAUSES C0011065</triple>
		</triples>
	</Sentence>

</Document>

redpajama_set_name: RedPajamaGithub


text:
namespace Shadow {

namespace Vision {

template <DeviceType D, typename T>
void SSDNormalize(const T* in_data, int outer_num, int channel, int inner_num,
                  float eps, T* val_data, T* out_data, Context* context);

}  // namespace Vision

}  // namespace Shadow

namespace Shadow {

class SSDNormalizeKernel : public Kernel {
 public:
  virtual void Run(const std::shared_ptr<Blob>& input,
                   const std::shared_ptr<Blob>& scale,
                   std::shared_ptr<Blob>& output, Workspace* ws,
                   bool across_spatial, bool channel_shared, float eps) = 0;
};

template <DeviceType D>
class SSDNormalizeKernelDefault : public SSDNormalizeKernel {
 public:
  void Run(const std::shared_ptr<Blob>& input,
           const std::shared_ptr<Blob>& scale, std::shared_ptr<Blob>& output,
           Workspace* ws, bool across_spatial, bool channel_shared,
           float eps) override {
    const auto* in_data = input->data<float>();
    auto* out_data = output->mutable_data<float>();

    int batch = input->shape(0), channel = input->shape(1),
        spatial_dim = input->count(2);
    int count = input->count(), num = input->num();

    Blas::Square<D, float>(count, in_data, 0, out_data, 0, ws->Ctx().get());

    if (across_spatial) {
      for (int b = 0; b < batch; ++b) {
        int offset = b * num;
        float sum = 0;
        Blas::BlasSasum<D, float>(num, out_data, offset, &sum, ws->Ctx().get());
        Blas::Mul<D, float>(num, in_data, offset, 1.f / std::sqrt(sum + eps),
                            out_data, offset, ws->Ctx().get());
      }
    } else {
      ws->GrowTempBuffer(batch * spatial_dim * sizeof(float));

      auto scalar = ws->CreateTempBlob({batch, spatial_dim}, DataType::kF32);

      Vision::SSDNormalize<D, float>(in_data, batch, channel, spatial_dim, eps,
                                     scalar->mutable_data<float>(), out_data,
                                     ws->Ctx().get());
    }

    if (scale != nullptr) {
      if (channel_shared) {
        CHECK_EQ(scale->count(), 1);
        float scale_data = 1;
        scale->get_data<float>(&scale_data, 1);
        Blas::BlasSscal<D, float>(count, scale_data, out_data, 0,
                                  ws->Ctx().get());
      } else {
        Vision::Scale<D, float>(out_data, count, scale->data<float>(), channel,
                                spatial_dim, out_data, ws->Ctx().get());
      }
    }
  }

  DeviceType device_type() const override { return D; }

  std::string kernel_type() const override { return "Default"; }
};

}  // namespace Shadow

#endif  // SHADOW_OPERATORS_KERNELS_SSD_NORMALIZE_HPP_


text:
package export

import (
	"fmt"
	"math"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/prometheus/prometheus/model/labels"
	"github.com/prometheus/prometheus/model/textparse"
	"github.com/prometheus/prometheus/model/value"
	"github.com/prometheus/prometheus/storage"
	"github.com/prometheus/prometheus/tsdb/record"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/testing/protocmp"
	"google.golang.org/protobuf/types/known/anypb"

	timestamp_pb "github.com/golang/protobuf/ptypes/timestamp"
	distribution_pb "google.golang.org/genproto/googleapis/api/distribution"
	metric_pb "google.golang.org/genproto/googleapis/api/metric"
	monitoredres_pb "google.golang.org/genproto/googleapis/api/monitoredres"
	monitoring_pb "google.golang.org/genproto/googleapis/monitoring/v3"
)

type seriesMap map[storage.SeriesRef]labels.Labels
type metricMetadataMap map[string]MetricMetadata

func testMetadataFunc(metadata metricMetadataMap) MetadataFunc {
	return func(metric string) (MetricMetadata, bool) {
		md, ok := metadata[metric]
		md.Metric = metric
		return md, ok
	}
}

func wrapAsAny(any proto.Message) *anypb.Any {
	result, err := anypb.New(any)
	if err != nil {
		panic(err)
	}
	return result
}

func TestSampleBuilder(t *testing.T) {
	externalLabels := labels.FromMap(map[string]string{
		"project_id": "example-project",
		"location":   "europe",
		"cluster":    "foo-cluster",
	})

	cases := []struct {
		doc        string
		metadata   MetadataFunc
		series     seriesMap
		samples    [][]record.RefSample
		exemplars  []map[storage.SeriesRef]record.RefExemplar
		matchers   Matchers
		wantSeries []*monitoring_pb.TimeSeries
		wantFail   bool
	}{
		{
			doc: "convert gauge",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeGauge, Help: "metric1 help text"},
			}),
			series: seriesMap{
				123: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{{Ref: 123, T: 3000, V: 0.6}},
				{{Ref: 123, T: 4000, V: math.Inf(1)}},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/gauge",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 3},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{0.6},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/gauge",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{math.Inf(1)},
						},
					}},
				},
			},
		}, {
			doc: "convert untyped",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeUnknown, Help: "metric1 help text"},
			}),
			series: seriesMap{
				123: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{{Ref: 123, T: 3000, V: 0.6}},
				{{Ref: 123, T: 4000, V: 100}},
			},
			//
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/unknown",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 3},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{0.6},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/unknown",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{100},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/unknown:counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 3},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{99.4},
						},
					}},
				},
			},
		}, {
			doc: "convert counter (Prometheus format metadata key)",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1_total": {Type: textparse.MetricTypeCounter, Help: "metric1 help text"},
			}),
			series: seriesMap{
				123: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_total", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{{Ref: 123, T: 2000, V: 5.5}},
				{{Ref: 123, T: 3000, V: 8}},
				{{Ref: 123, T: 4000, V: 9}},
				{{Ref: 123, T: 5000, V: 7}},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// First sample skipped to initialize reset handling.
				// Subsequent samples are relative to the initial sample in value and timestamp.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 2},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 3},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{2.5},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 2},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{3.5},
						},
					}},
				},
				// Reset in the Prometheus series. Start timestamp is set to 1ms
				// before end timestamp.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 4, Nanos: 999000000},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 5},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{7},
						},
					}},
				},
			},
		}, {
			doc: "convert counter - skip duplicates (OpenMetrics format metadata key)",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeCounter, Help: "metric1 help text"},
			}),
			series: seriesMap{
				123: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_total", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{
					{Ref: 123, T: 2000, V: 5.5},
					{Ref: 123, T: 2000, V: 5.5}, // duplicate
				}, {
					{Ref: 123, T: 4000, V: 9},
				}, {
					{Ref: 123, T: 5000, V: 7},
					{Ref: 123, T: 5000, V: 7}, // duplicate
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// First sample skipped to initialize reset handling.
				// Second sample was a duplicate of the reset value, should be dropped.
				// Subsequent samples are relative to the initial sample in value and timestamp.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"location":   "europe",
							"project_id": "example-project",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 2},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{3.5},
						},
					}},
				},
				// Reset in the Prometheus series. Start timestamp is set to 1ms
				// before end timestamp.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"location":   "europe",
							"project_id": "example-project",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 4, Nanos: 999000000},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 5},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{7},
						},
					}},
				},
				// subsequent duplicates still get through.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"location":   "europe",
							"project_id": "example-project",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 4, Nanos: 999000000},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 5},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{7},
						},
					}},
				},
			},
		}, {
			doc: "convert counter - skip on previous timestamp",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1_total": {Type: textparse.MetricTypeCounter, Help: "metric1 help text"},
			}),
			series: seriesMap{
				123: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_total", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{{Ref: 123, T: 2000, V: 5.5}},
				{{Ref: 123, T: 1000, V: 5.5}}, // drop old timestamp.
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// First sample skipped to initialize reset handling.
				// Second sample occured before first, panic.
			},
		}, {
			doc: "convert summary",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeSummary, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "quantile", "0.5"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "quantile", "0.9"),
			},
			samples: [][]record.RefSample{
				{
					{Ref: 1, T: 2000, V: 1},
					{Ref: 2, T: 2000, V: 2},
				}, {
					{Ref: 1, T: 3000, V: 21},
					{Ref: 3, T: 3000, V: 3},
				}, {
					{Ref: 3, T: 4000, V: 4},
					{Ref: 4, T: 4000, V: 4},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/summary",
						Labels: map[string]string{"quantile": "0.5"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{2},
						},
					}},
				},
				// first metric1_count and metric1_sum dropped by reset handling.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_sum/summary:counter",
						Labels: map[string]string{},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 2},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 3},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{20},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_count/summary",
						Labels: map[string]string{},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 3},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{1},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/summary",
						Labels: map[string]string{"quantile": "0.9"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{4},
						},
					}},
				},
			},
		}, {
			doc: "convert summary - skip counter duplicates",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeSummary, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "quantile", "0.5"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "quantile", "0.9"),
			},
			samples: [][]record.RefSample{
				{
					{Ref: 1, T: 2000, V: 1},
					{Ref: 2, T: 2000, V: 2},
				}, {
					{Ref: 3, T: 3000, V: 3},
					{Ref: 3, T: 3000, V: 3}, // duplicate
				}, {
					{Ref: 3, T: 4000, V: 4},
					{Ref: 4, T: 4000, V: 4},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"location":   "europe",
							"project_id": "example-project",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/summary",
						Labels: map[string]string{"quantile": "0.5"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{2},
						},
					}},
				},
				// first metric1_count dropped by reset handling.
				// duplicate of initial reset sample.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"location":   "europe",
							"project_id": "example-project",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_count/summary",
						Labels: map[string]string{},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 3},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{1},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"location":   "europe",
							"project_id": "example-project",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/summary",
						Labels: map[string]string{"quantile": "0.9"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 4},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{4},
						},
					}},
				},
			},
		}, {
			doc: "convert histogram",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1":         {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
				"metric1_a_count": {Type: textparse.MetricTypeGauge, Help: "metric1_a_count help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "0.1"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "0.5"),
				5: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "1"),
				6: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "2.5"),
				7: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "+Inf"),
				// Add another series that only deviates by having an extra label. We must properly detect a new histogram.
				// This is a discouraged but possible case of metric labeling.
				8:  labels.FromStrings("job", "job1", "instance", "instance1", "a", "b", "__name__", "metric1_sum"),
				9:  labels.FromStrings("job", "job1", "instance", "instance1", "a", "b", "__name__", "metric1_count"),
				10: labels.FromStrings("job", "job1", "instance", "instance1", "a", "b", "__name__", "metric1_bucket", "le", "2.5"),
				11: labels.FromStrings("job", "job1", "instance", "instance1", "a", "b", "__name__", "metric1_bucket", "le", "+Inf"),
				// An incomplete histogram.
				12: labels.FromStrings("job", "job1", "instance", "instance1", "a", "c", "__name__", "metric1_sum"),
				13: labels.FromStrings("job", "job1", "instance", "instance1", "a", "c", "__name__", "metric1_count"),
				// Metric with prefix and suffix matching the previous histograms but actually a distinct metric.
				14: labels.FromStrings("job", "job1", "instance", "instance1", "a", "b", "__name__", "metric1_a_count"),
			},
			samples: [][]record.RefSample{
				// First sample set, should be skipped by reset handling.
				// The buckets must be in ascending order for an individual histogram but otherwise
				// no order or grouping constraints apply for series of a given histogram metric.
				{
					{Ref: 8, T: 1000, V: 100},  // hist2, sum
					{Ref: 1, T: 1000, V: 55.1}, // hist1, sum
					{Ref: 3, T: 1000, V: 2},    // hist1, 0.1
					{Ref: 4, T: 1000, V: 5},    // hist1, 0.5
					{Ref: 5, T: 1000, V: 6},    // hist1, 1
					{Ref: 6, T: 1000, V: 8},    // hist1, 2.5
					{Ref: 7, T: 1000, V: 10},   // hist1, inf
					{Ref: 9, T: 1000, V: 10},   // hist2, count
					{Ref: 2, T: 1000, V: 10},   // hist1, count
					{Ref: 10, T: 1000, V: 10},  // hist2, 2.5
					{Ref: 11, T: 1000, V: 10},  // hist2, inf
					{Ref: 12, T: 1000, V: 10},  // hist3, sum
					{Ref: 13, T: 1000, V: 10},  // hist3, count
				},
				// Second sample set should actually be emitted.
				{
					// Second samples for histograms should produce a distribution.
					{Ref: 3, T: 2000, V: 4},     // hist1, 0.1
					{Ref: 2, T: 2000, V: 21},    // hist1, count
					{Ref: 1, T: 2000, V: 123.4}, // hist1, sum
					{Ref: 4, T: 2000, V: 9},     // hist1, 0.5
					{Ref: 5, T: 2000, V: 11},    // hist1, 1
					{Ref: 6, T: 2000, V: 15},    // hist1, 2.5
					{Ref: 7, T: 2000, V: 21},    // hist1, inf
					{Ref: 10, T: 2000, V: 10},   // hist2, 2.5
					{Ref: 11, T: 2000, V: 13},   // hist2, inf
					{Ref: 9, T: 2000, V: 12},    // hist2, count – less than inf, ignored
					{Ref: 8, T: 2000, V: 115},   // hist2, sum
					// Incomplete histogram should not produce a sample.
					{Ref: 12, T: 2000, V: 10}, // hist3, sum
					{Ref: 13, T: 2000, V: 10}, // hist3, count
					// Different metric with prefix common with previous histograms must be detected
					// as the gauge it is.
					{Ref: 14, T: 1000, V: 3},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// 0: skipped by reset handling.
				{ // 1
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/histogram",
						Labels: map[string]string{},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DISTRIBUTION,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 1},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DistributionValue{
								DistributionValue: &distribution_pb.Distribution{
									Count:                 11,
									Mean:                  6.20909090909091,
									SumOfSquaredDeviation: 270.301590909091,
									BucketOptions: &distribution_pb.Distribution_BucketOptions{
										Options: &distribution_pb.Distribution_BucketOptions_ExplicitBuckets{
											ExplicitBuckets: &distribution_pb.Distribution_BucketOptions_Explicit{
												Bounds: []float64{0.1, 0.5, 1, 2.5},
											},
										},
									},
									BucketCounts: []int64{2, 2, 1, 2, 4},
								},
							},
						},
					}},
				},
				// 2: skipped by reset handling
				{ // 3
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/histogram",
						Labels: map[string]string{"a": "b"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DISTRIBUTION,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 1},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DistributionValue{
								DistributionValue: &distribution_pb.Distribution{
									Count:                 3,
									Mean:                  5,
									SumOfSquaredDeviation: 18.75,
									BucketOptions: &distribution_pb.Distribution_BucketOptions{
										Options: &distribution_pb.Distribution_BucketOptions_ExplicitBuckets{
											ExplicitBuckets: &distribution_pb.Distribution_BucketOptions_Explicit{
												Bounds: []float64{2.5},
											},
										},
									},
									BucketCounts: []int64{0, 3},
								},
							},
						},
					}},
				},
				{ // 4
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_a_count/gauge",
						Labels: map[string]string{"a": "b"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 1},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{3},
						},
					}},
				},
			},
		}, {
			doc: "histogram with 0 buckets is ignored",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
			},
			samples: [][]record.RefSample{
				// Add two samples for each series as the first ones are discarded for reset
				// handling regardless of the zero bucket count.
				{
					{Ref: 1, T: 1000, V: 5},
					{Ref: 2, T: 1000, V: 2},
				}, {
					{Ref: 1, T: 2000, V: 5},
					{Ref: 2, T: 2000, V: 2},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// skipped by reset handling.
				// skipped due to zero buckets.
			},
		}, {
			doc: "histogram with only Inf buckets is ignored",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "+Inf"),
			},
			samples: [][]record.RefSample{
				// Add two samples for each series as the first ones are discarded for reset
				// handling regardless of the zero bucket bounds count.
				{
					{Ref: 1, T: 1000, V: 5},
					{Ref: 2, T: 1000, V: 2},
					{Ref: 3, T: 1000, V: 2},
				}, {
					{Ref: 1, T: 2000, V: 5},
					{Ref: 2, T: 2000, V: 2},
					{Ref: 3, T: 2000, V: 2},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// skipped by reset handling.
				// skipped due to zero buckets.
			},
		}, {
			doc: "histogram NaN sum",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "1"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "+Inf"),
			},
			samples: [][]record.RefSample{
				{
					{Ref: 1, T: 1000, V: math.Float64frombits(value.NormalNaN)},
					{Ref: 2, T: 1000, V: 2},
					{Ref: 3, T: 1000, V: 1},
					{Ref: 4, T: 1000, V: 2},
				}, {
					{Ref: 1, T: 2000, V: math.Float64frombits(value.NormalNaN)},
					{Ref: 2, T: 2000, V: 3},
					{Ref: 3, T: 2000, V: 2},
					{Ref: 4, T: 2000, V: 3},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type: "prometheus.googleapis.com/metric1/histogram",
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DISTRIBUTION,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 1},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DistributionValue{
								DistributionValue: &distribution_pb.Distribution{
									Count:                 1,
									Mean:                  0,
									SumOfSquaredDeviation: 0.25,
									BucketOptions: &distribution_pb.Distribution_BucketOptions{
										Options: &distribution_pb.Distribution_BucketOptions_ExplicitBuckets{
											ExplicitBuckets: &distribution_pb.Distribution_BucketOptions_Explicit{
												Bounds: []float64{1},
											},
										},
									},
									BucketCounts: []int64{1, 0},
								},
							},
						},
					}},
				},
			},
		}, {
			doc: "histogram NaN count",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "1"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "+Inf"),
			},
			samples: [][]record.RefSample{
				{
					{Ref: 1, T: 1000, V: 10},
					{Ref: 2, T: 1000, V: math.Float64frombits(value.NormalNaN)},
					{Ref: 3, T: 1000, V: 1},
					{Ref: 4, T: 1000, V: 2},
				}, {
					{Ref: 1, T: 2000, V: 10},
					{Ref: 2, T: 2000, V: math.Float64frombits(value.NormalNaN)},
					{Ref: 3, T: 2000, V: 2},
					{Ref: 4, T: 2000, V: 12},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type: "prometheus.googleapis.com/metric1/histogram",
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DISTRIBUTION,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 1},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DistributionValue{
								DistributionValue: &distribution_pb.Distribution{
									Count:                 10,
									Mean:                  0,
									SumOfSquaredDeviation: 9.25,
									BucketOptions: &distribution_pb.Distribution_BucketOptions{
										Options: &distribution_pb.Distribution_BucketOptions_ExplicitBuckets{
											ExplicitBuckets: &distribution_pb.Distribution_BucketOptions_Explicit{
												Bounds: []float64{1},
											},
										},
									},
									BucketCounts: []int64{1, 9},
								},
							},
						},
					}},
				},
			},
		}, {
			doc:      "no metric metadata",
			metadata: testMetadataFunc(metricMetadataMap{}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{{Ref: 1, T: 1000, V: 1}},
			},
			wantSeries: []*monitoring_pb.TimeSeries{},
		}, {
			doc: "filter with matchers",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeGauge, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "k1", "v1"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1", "k1", "v2"),
				3: labels.FromStrings("job", "job2", "instance", "instance1", "__name__", "metric1", "k1", "v3"),
				4: labels.FromStrings("job", "job2", "instance", "instance1", "__name__", "metric1", "k1", "v4"),
			},
			samples: [][]record.RefSample{{
				{Ref: 1, T: 1000, V: 1},
				{Ref: 1, T: 2000, V: 2},
				{Ref: 2, T: 1000, V: 1},
				{Ref: 3, T: 1000, V: 1},
				{Ref: 4, T: 1000, V: 1},
			}},
			// Series must pass either of the matchers
			matchers: Matchers{
				labels.Selector{
					labels.MustNewMatcher(labels.MatchEqual, "k1", "v1"),
				},
				labels.Selector{
					labels.MustNewMatcher(labels.MatchRegexp, "job", ".+2"),
					labels.MustNewMatcher(labels.MatchNotEqual, "k1", "v3"),
				},
			},
			// If the metadata is nil we expect the series to be converted to a gauge as
			// metadata-less series are produced by rules and any processing result of type gauge.
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/gauge",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 1},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{1},
						},
					}},
				}, {
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/gauge",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{2},
						},
					}},
				},
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job2",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/gauge",
						Labels: map[string]string{"k1": "v4"},
					},
					MetricKind: metric_pb.MetricDescriptor_GAUGE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							EndTime: &timestamp_pb.Timestamp{Seconds: 1},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{1},
						},
					}},
				},
			},
		}, {
			doc: "histogram is not in-order",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1": {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "+Inf"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "1"),
				5: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "0.5"),
				6: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "0.1"),
			},
			samples: [][]record.RefSample{
				{
					{Ref: 3, T: 1000, V: 10}, // +Inf
					{Ref: 4, T: 1000, V: 5},  // 1
					{Ref: 6, T: 1000, V: 0},  // 0.1
					{Ref: 5, T: 1000, V: 0},  // 0.5
					{Ref: 1, T: 1000, V: 10}, // count
					{Ref: 2, T: 1000, V: 3},  // sum
				}, {
					{Ref: 3, T: 2000, V: 13}, //+Inf
					{Ref: 4, T: 2000, V: 7},  // 1
					{Ref: 6, T: 2000, V: 0},  // 0.1
					{Ref: 5, T: 2000, V: 1},  // 0.5
					{Ref: 1, T: 2000, V: 13}, // count
					{Ref: 2, T: 2000, V: 12}, // sum
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type: "prometheus.googleapis.com/metric1/histogram",
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DISTRIBUTION,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 1},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DistributionValue{
								DistributionValue: &distribution_pb.Distribution{
									Count:                 3,
									Mean:                  1,
									SumOfSquaredDeviation: 0.5525,
									BucketOptions: &distribution_pb.Distribution_BucketOptions{
										Options: &distribution_pb.Distribution_BucketOptions_ExplicitBuckets{
											ExplicitBuckets: &distribution_pb.Distribution_BucketOptions_Explicit{
												Bounds: []float64{0.1, 0.5, 1},
											},
										},
									},
									BucketCounts: []int64{0, 1, 1, 1},
								},
							},
						},
					}},
				},
			},
		},
		{
			doc: "convert histogram with exemplars",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1":         {Type: textparse.MetricTypeHistogram, Help: "metric1 help text"},
				"metric1_a_count": {Type: textparse.MetricTypeGauge, Help: "metric1_a_count help text"},
			}),
			series: seriesMap{
				1: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_sum"),
				2: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_count"),
				3: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "0.1"),
				4: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "0.5"),
				5: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "1"),
				6: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "2.5"),
				7: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_bucket", "le", "+Inf"),
			},
			samples: [][]record.RefSample{
				// First sample set, should be skipped by reset handling.
				// The buckets must be in ascending order for an individual histogram but otherwise
				// no order or grouping constraints apply for series of a given histogram metric.
				{
					{Ref: 1, T: 1000, V: 55.1}, // hist1, sum
					{Ref: 3, T: 1000, V: 2},    // hist1, 0.1
					{Ref: 4, T: 1000, V: 5},    // hist1, 0.5
					{Ref: 5, T: 1000, V: 6},    // hist1, 1
					{Ref: 6, T: 1000, V: 8},    // hist1, 2.5
					{Ref: 7, T: 1000, V: 10},   // hist1, inf
					{Ref: 2, T: 1000, V: 10},   // hist1, count
				},
				// Second sample set should actually be emitted.
				{
					// Second samples for histograms should produce a distribution.
					{Ref: 3, T: 2000, V: 4},     // hist1, 0.1
					{Ref: 2, T: 2000, V: 21},    // hist1, count
					{Ref: 1, T: 2000, V: 123.4}, // hist1, sum
					{Ref: 4, T: 2000, V: 9},     // hist1, 0.5
					{Ref: 5, T: 2000, V: 11},    // hist1, 1
					{Ref: 6, T: 2000, V: 15},    // hist1, 2.5
					{Ref: 7, T: 2000, V: 21},    // hist1, inf
				},
			},
			exemplars: []map[storage.SeriesRef]record.RefExemplar{
				// first sample set is skipped by reset handling
				{},
				{
					// project_id, trace_id, and span_id should be in the span context
					// random should be in the dropped labels
					3: {Ref: 3, T: 1500, V: .099, Labels: labels.New(
						labels.Label{Name: "project_id", Value: "1"},
						labels.Label{Name: "trace_id", Value: "2"},
						labels.Label{Name: "span_id", Value: "3"},
						labels.Label{Name: "random", Value: "4"},
					)},
					// project_id and trace_id should both be in dropped labels
					// since we have no span_id to make a full span context
					4: {Ref: 4, T: 1500, V: .4, Labels: labels.New(
						labels.Label{Name: "project_id", Value: "1"},
						labels.Label{Name: "trace_id", Value: "2"},
					)},
					5: {Ref: 7, T: 1500, V: 2},
					7: {Ref: 5, T: 1500, V: .99},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// 0: skipped by reset handling.
				{ // 1
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1/histogram",
						Labels: map[string]string{},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DISTRIBUTION,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 1},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 2},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DistributionValue{
								DistributionValue: &distribution_pb.Distribution{
									Count:                 11,
									Mean:                  6.20909090909091,
									SumOfSquaredDeviation: 270.301590909091,
									BucketOptions: &distribution_pb.Distribution_BucketOptions{
										Options: &distribution_pb.Distribution_BucketOptions_ExplicitBuckets{
											ExplicitBuckets: &distribution_pb.Distribution_BucketOptions_Explicit{
												Bounds: []float64{0.1, 0.5, 1, 2.5},
											},
										},
									},
									BucketCounts: []int64{2, 2, 1, 2, 4},
									Exemplars: []*distribution_pb.Distribution_Exemplar{
										{
											Value:     .099,
											Timestamp: &timestamp_pb.Timestamp{Seconds: 1, Nanos: 500000000},
											Attachments: []*anypb.Any{
												wrapAsAny(&monitoring_pb.SpanContext{
													SpanName: "projects/1/traces/2/spans/3",
												}),
												wrapAsAny(&monitoring_pb.DroppedLabels{
													Label: map[string]string{"random": "4"},
												}),
											},
										},
										{
											Value:     .4,
											Timestamp: &timestamp_pb.Timestamp{Seconds: 1, Nanos: 500000000},
											Attachments: []*anypb.Any{
												wrapAsAny(&monitoring_pb.DroppedLabels{
													Label: map[string]string{"trace_id": "2", "project_id": "1"},
												}),
											},
										},
										{
											Value:     .99,
											Timestamp: &timestamp_pb.Timestamp{Seconds: 1, Nanos: 500000000},
										},
										{
											Value:     2,
											Timestamp: &timestamp_pb.Timestamp{Seconds: 1, Nanos: 500000000},
										},
									},
								},
							},
						},
					}},
				},
			},
		},
		{
			doc: "convert counter with exemplars (exemplars should be dropped)",
			metadata: testMetadataFunc(metricMetadataMap{
				"metric1_total": {Type: textparse.MetricTypeCounter, Help: "metric1 help text"},
			}),
			series: seriesMap{
				123: labels.FromStrings("job", "job1", "instance", "instance1", "__name__", "metric1_total", "k1", "v1"),
			},
			samples: [][]record.RefSample{
				{{Ref: 123, T: 2000, V: 5.5}},
				{{Ref: 123, T: 3000, V: 8}},
			},
			exemplars: []map[storage.SeriesRef]record.RefExemplar{
				// first sample set is skipped by reset handling
				{},
				{
					// project_id, trace_id, and span_id should be in the span context
					// random should be in the dropped labels
					123: {Ref: 123, T: 2500, V: 7},
				},
			},
			wantSeries: []*monitoring_pb.TimeSeries{
				// First sample skipped to initialize reset handling.
				// Subsequent samples are relative to the initial sample in value and timestamp.
				{
					Resource: &monitoredres_pb.MonitoredResource{
						Type: "prometheus_target",
						Labels: map[string]string{
							"project_id": "example-project",
							"location":   "europe",
							"cluster":    "foo-cluster",
							"namespace":  "",
							"job":        "job1",
							"instance":   "instance1",
						},
					},
					Metric: &metric_pb.Metric{
						Type:   "prometheus.googleapis.com/metric1_total/counter",
						Labels: map[string]string{"k1": "v1"},
					},
					MetricKind: metric_pb.MetricDescriptor_CUMULATIVE,
					ValueType:  metric_pb.MetricDescriptor_DOUBLE,
					Points: []*monitoring_pb.Point{{
						Interval: &monitoring_pb.TimeInterval{
							StartTime: &timestamp_pb.Timestamp{Seconds: 2},
							EndTime:   &timestamp_pb.Timestamp{Seconds: 3},
						},
						Value: &monitoring_pb.TypedValue{
							Value: &monitoring_pb.TypedValue_DoubleValue{2.5},
						},
					}},
				},
			},
		},
	}

	for i, c := range cases {
		t.Run(fmt.Sprintf("%d: %s", i, c.doc), func(t *testing.T) {
			cache := newSeriesCache(nil, nil, MetricTypePrefix, c.matchers)
			// Fake lookup into TSDB.
			cache.getLabelsByRef = func(ref storage.SeriesRef) labels.Labels {
				return c.series[ref]
			}

			// Process entire input sample batch.
			var result []*monitoring_pb.TimeSeries

			for i, batch := range c.samples {
				b := newSampleBuilder(cache)

				for k := 0; len(batch) > 0; k++ {
					var exemplars map[storage.SeriesRef]record.RefExemplar
					if len(c.exemplars) > i {
						exemplars = c.exemplars[i]
					}
					out, tail, err := b.next(c.metadata, externalLabels, batch, exemplars)
					if err == nil && c.wantFail {
						t.Fatal("expected error but got none")
					}
					if err != nil && !c.wantFail {
						t.Fatalf("unexpected error: %s", err)
					}
					if err != nil {
						break
					}
					if len(tail) >= len(batch) {
						t.Fatalf("no sample was consumed")
					}
					for _, s := range out {
						result = append(result, s.proto)
					}
					batch = tail
				}
				b.close()
			}
			if diff := cmp.Diff(c.wantSeries, result, protocmp.Transform(), cmpopts.EquateEmpty()); diff != "" {
				t.Errorf("unexpected result (-want, +got): %v", diff)
			}
		})
	}
}


text:
// **********************************************************************
//
// <copyright>
//
//  BBN Technologies
//  10 Moulton Street
//  Cambridge, MA 02138
//  (617) 873-8000
//
//  Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/GraphicUpdate.java,v $
// $RCSfile: GraphicUpdate.java,v $
// $Revision: 1.3 $
// $Date: 2004/10/14 18:05:55 $
// $Author: dietrick $
//
// **********************************************************************

package com.bbn.openmap.layer.link;

import com.bbn.openmap.omGraphics.OMGraphic;

/**
 * A simple object used by the GestureLinkResponse to associate an
 * action with a particular graphic, either with the graphic's ID for
 * MODIFY-type actions, or with the graphic for UPDATE-type actions.
 */
public class GraphicUpdate implements LinkPropertiesConstants {
    /**
     * A masked integer describing the action for the graphic. See
     * GestureLinkResponse fo the masks.
     */
    public int action = 0;
    /** The graphic's ID. */
    public String id = null;
    /** The graphic, for updates. */
    public OMGraphic graphic = null;

    /** Constructor for modify-type actions. */
    public GraphicUpdate(int graphicAction, String gid) {
        action = graphicAction;
        id = gid;
    }

    /** Constructor for update-type actions. */
    public GraphicUpdate(int graphicAction, OMGraphic omg) {
        action = graphicAction;
        if (omg != null) {
            Object obj = omg.getAppObject();
            if (obj instanceof LinkProperties) {
                id = ((LinkProperties) obj).getProperty(LPC_GRAPHICID);
            }
        }
        graphic = omg;
    }
}


text:
package com.github.os72.protocjar.maven;

import java.io.File;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.github.os72.protocjar.ProtocVersion;

import io.takari.maven.testing.TestResources;
import io.takari.maven.testing.executor.MavenRuntime;
import io.takari.maven.testing.executor.MavenRuntime.MavenRuntimeBuilder;
import io.takari.maven.testing.executor.MavenVersions;
import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;

@RunWith(MavenJUnitTestRunner.class)
@MavenVersions({"3.2.3"})
public class MojoBasicTest
{
	@Rule
	public final TestResources resources = new TestResources();
	public final MavenRuntime maven;

	public MojoBasicTest(MavenRuntimeBuilder mavenBuilder) throws Exception {
		this.maven = mavenBuilder.withCliOptions("-B", "-U", "-e").build();
	}

	@Test
	public void testBasic() throws Exception {
		File basedir = resources.getBasedir("basic-test");
		maven.forProject(basedir)
			.withCliOption("-Dprotobuf.version=" + ProtocVersion.PROTOC_VERSION)
			.withCliOption("-Dprotoc.version=" + ProtocVersion.PROTOC_VERSION)
			.execute("verify")
			.assertErrorFreeLog();
	}

	@Test
	public void testBasic241() throws Exception {
		File basedir = resources.getBasedir("basic-test");
		maven.forProject(basedir)
			.withCliOption("-Dprotobuf.version=2.4.1")
			.withCliOption("-Dprotoc.version=2.4.1")
			.execute("verify")
			.assertErrorFreeLog();
	}
}


text:
using QuantConnect.Brokerages.Oanda.RestV1.DataType.Communications;

namespace QuantConnect.Brokerages.Oanda.RestV1.DataType
{
#pragma warning disable 1591
    /// <summary>
    /// Represents an order on Oanda.
    /// </summary>
    public class Order : Response
    {
        public long id { get; set; }
		public string instrument { get; set; }
		public int units { get; set; }
		public string side { get; set; }
		public string type { get; set; }
        public string time { get; set; }
        public double price { get; set; }
        public double takeProfit { get; set; }
        public double stopLoss { get; set; }
        public string expiry { get; set; }
        public double upperBound { get; set; }
        public double lowerBound { get; set; }
        public int trailingStop { get; set; }
    }
#pragma warning restore 1591
}


text:
package com.icegreen.greenmail.imap;

import com.icegreen.greenmail.server.ProtocolHandler;
import com.icegreen.greenmail.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/**
 * The handler class for IMAP connections.
 *
 * @author Federico Barbieri <scoobie@systemy.it>
 * @author Peter M. Goldstein <farsight@alum.mit.edu>
 */
public class ImapHandler implements ImapConstants, ProtocolHandler {
    protected final Logger log = LoggerFactory.getLogger(getClass());
    private ImapRequestHandler requestHandler = new ImapRequestHandler();
    private ImapSession session;
    private Object closeMonitor = new Object();

    /**
     * The TCP/IP socket over which the IMAP interaction
     * is occurring
     */
    private Socket socket;

    private ImapResponse response;

    UserManager userManager;
    private ImapHostManager imapHost;

    public ImapHandler(UserManager userManager, ImapHostManager imapHost, Socket socket) {
        this.userManager = userManager;
        this.imapHost = imapHost;
        this.socket = socket;
    }

    public void forceConnectionClose(final String message) {
        response.byeResponse(message);
        close();
    }

    @Override
    public void run() {
        try {
            // Closed automatically when socket is closed via #close()
            InputStream ins = new BufferedInputStream(socket.getInputStream(), 512);
            OutputStream outs = new BufferedOutputStream(socket.getOutputStream(), 1024);

            response = new ImapResponse(outs);

            // Write welcome message
            String responseBuffer = VERSION +" Server GreenMail ready";
            response.okResponse(null, responseBuffer);

            session = new ImapSessionImpl(imapHost,
                    userManager,
                    this,
                    socket.getInetAddress().getHostAddress());

            while (requestHandler.handleRequest(ins, outs, session)) {
                // Loop ...
            }

        } catch (Exception e) {
            // Ignore if closed is invoked
            if (null != socket && !socket.isClosed()) {
                log.error("Can not handle IMAP connection", e);
                throw new IllegalStateException("Can not handle IMAP connection", e);
            }
        } finally {
           close();
        }
    }

    /**
     * Resets the handler data to a basic state.
     */
    @Override
    public void close() {
        // Use monitor to avoid race between external close and handler thread run()
        synchronized (closeMonitor) {
            // Close and clear streams, sockets etc.
            if (socket != null) {
                try {
                    // Terminates thread blocking on socket read
                    // and automatically closed depending streams
                    socket.close();
                } catch (IOException e) {
                    log.warn("Can not close socket", e);
                } finally {
                    socket = null;
                }
            }

            // Clear user data
            session = null;
            response = null;
        }
    }
}


text:
package org.yatech.jedis.utils.lua.ast;

/**
 * Created by Yinon Avraham on 11/09/2015.
 */
public class LuaAstStringValue extends LuaAstValue<String> {

    public LuaAstStringValue(String value) {
        super(value);
    }

    @Override
    public void accept(LuaAstVisitor visitor) {
        visitor.visit(this);
    }

}


text:
<?php

	require_once("includes/general.php");
	require_once("classes/FileSystems/FileFactory.php");
	require_once("classes/FileSystems/LocalFileImpl.php");

	$data = array();
	verifyAccess($mcFileManagerConfig);
	$path = getRequestParam("path");

	if ($path == "")
		renderPage("blank.tpl.php", $data);

	if ($path == "_mc_root_path_") {
		$data['subdirs'] = count(array_keys($mcFileManagerConfig["filesystem.rootpaths"]));
		$data["type"] = "root";
		$data['readable'] = "readable";
		$data['writable'] = "not_writable";
		$data['filename'] = "/";

		renderPage("preview.tpl.php", $data);
	}

	$rootpath = getRequestParam("rootpath", toUnixPath(getRealPath($mcFileManagerConfig, 'filesystem.rootpath')));
	$redirect = getRequestParam("redirect");
	$fileFactory =& new FileFactory($mcFileManagerConfig, $rootpath);
	$targetFile =& $fileFactory->getFile($path);
	$config = $targetFile->getConfig();

	// Setup first filter
	$fileFilterA =& new BasicFileFilter();
	$fileFilterA->setIncludeFilePattern($config['filesystem.include_file_pattern']);
	$fileFilterA->setExcludeFilePattern($config['filesystem.exclude_file_pattern']);
	$fileFilterA->setIncludeExtensions($config['filesystem.extensions']);

	// Setup second filter
	$fileFilterB =& new BasicFileFilter();
	$fileFilterB->setIncludeFilePattern($config['download.include_file_pattern']);
	$fileFilterB->setExcludeFilePattern($config['download.exclude_file_pattern']);
	$fileFilterB->setIncludeExtensions($config['download.extensions']);

	$data['download'] = ($fileFilterA->accept($targetFile) && $fileFilterB->accept($targetFile));

	addFileEventListeners($fileFactory);

	$file =& $fileFactory->getFile($path);
	if (!$file->exists())
		renderPage("blank.tpl.php", $data);

	$data['path'] = $file->getAbsolutePath();
	$data['filename'] = basename(getUserFriendlyPath($file->getAbsolutePath()));
	if ($data['filename'] == "")
		$data['filename'] = "/";
	$data['filesize'] = getSizeStr($file->length());
	$fileType = getFileType($file->getAbsolutePath());
	$data['icon'] = $fileType['icon'];
	$data['type'] = $fileType['type'];
	$data['preview'] = $fileType['preview'];
	$data['previewurl'] = "";
	$data['modificationdate'] = date($config['filesystem.datefmt'], $file->lastModified());
	$data['creationdate'] = date($config['filesystem.datefmt'], $file->creationDate());
	$data['readable'] = ($file->canRead() && checkBool($config["filesystem.readable"]) ? "readable" : "not_readable");
	$data['writable'] = ($file->canWrite() && checkBool($config["filesystem.writable"]) ? "writable" : "not_writable");
	$data['type'] = $file->isDirectory() ? "dir" : "file";
	$data['description'] = $fileType['type'];

	// Count files and dirs
	if ($file->isDirectory()) {
		// Get filtered files
		$fileFilter =& new BasicFileFilter();
		$fileFilter->setIncludeDirectoryPattern($config['filesystem.include_directory_pattern']);
		$fileFilter->setExcludeDirectoryPattern($config['filesystem.exclude_directory_pattern']);
		$fileFilter->setIncludeFilePattern($config['filesystem.include_file_pattern']);
		$fileFilter->setExcludeFilePattern($config['filesystem.exclude_file_pattern']);
		$files = $file->listFilesFiltered($fileFilter);

		//$files = $file->listFiles();

		$fileCount = 0;
		$dirCount = 0;
		$sizeSum = 0;

		foreach ($files as $file) {
			if ($file->isFile())
				$fileCount++;
			else
				$dirCount++;

			$sizeSum += $file->length();
		}

		$data['files'] = $fileCount;
		$data['subdirs'] = $dirCount;
		$data['filessize'] = getSizeStr($sizeSum);
	} else {
		$path = $file->getAbsolutePath();
		$wwwroot = removeTrailingSlash(toUnixPath(getWWWRoot($config)));
		$urlprefix = removeTrailingSlash(toUnixPath($config['preview.urlprefix']));
		$urlsuffix = toUnixPath($config['preview.urlsuffix']);

		$pos = strpos($path, $wwwroot);
		if ($pos !== false && $pos == 0)
			$data['previewurl'] = $urlprefix . substr($path, strlen($wwwroot)) . $urlsuffix;
	}

	// Redirect
	if ($redirect == "true") {
		header('location: ' . $data['previewurl']);
		die;
	}

	// Render output
	renderPage("preview.tpl.php", $data);
?>


text:
import {collections as iter} from './iterator';

export module collections {
    export interface Iterable<T> {
        // Returns an iterator over a set of elements of type T.
        iterator() : iter.Iterator<T>;
    }
}


text:
///
/// \file AliFemtoAvgSepCalculator.h
///

#pragma once

#ifndef ALIFEMTOAVGSEPCALCULATOR_H_
#define ALIFEMTOAVGSEPCALCULATOR_H_

#include "AliFemtoV0.h"
#include "AliFemtoThreeVector.h"

/// \class AliFemtoAvgSepCalculator
/// \brief A helper class for calculating the average separation of track and
///        v0 particles.
///
/// This class is designed to be the common location of algorithms which
/// calculate the average separation between two particles. This currently
/// works with AliFemtoTracks and AliFemtoV0s.
///
/// The goal of this class is to provide a single location that various track
/// cuts may use to accurately calculate the average separation of two tracks
/// in the TPC. Previous to this, each cut had its own implementation in its
/// Pass method; when a bug was found, every class had to be checked and fixed.
/// This class minimizes code repetition, and provides a one-stop-shop for
/// anybody interested in understanding the algorithm.
///
/// The current use-case is to generate a 'calculator' object from the two
/// particles, then calling one of the 'passes' methods (i.e.
/// track_v0_passes(...)) with minimum average separation to see if this pair
/// passes the cut. This may change, as having a single object with the minimum
///
///
class AliFemtoAvgSepCalculator {
public:

  /**
   * Static method used to determine if a vector was actually set or just
   * created using default values (-10000.).
   */
  static bool vector_is_set(const AliFemtoThreeVector &v) {
    return v.x() > -9999.0 && v.y() > -9999.0 && v.z() > -9999.0;
  }

  /**
   * Construct out of two tracks
   *
   * This is the simplest case, where each track has one set of TPC points.
   */
  AliFemtoAvgSepCalculator(const AliFemtoTrack*, const AliFemtoTrack*);

  /**
   * Construct from track and V0
   *
   * This keeps a sigle list of track points and two lists (pos+neg) of V0
   * points
   */
  AliFemtoAvgSepCalculator(const AliFemtoTrack*, const AliFemtoV0*);

  /**
   * Construct from two V0s
   *
   * This keeps 4 vectors of track points for pos+neg daugthers of both V0
   * particles
   */
  AliFemtoAvgSepCalculator(const AliFemtoV0*, const AliFemtoV0*);

  /**
   * Calculates the separation between each point in the two vectors and
   * returns the average value.
   *
   * If the two vectors are different sizes, it stops after the shorter is
   * exhausted.
   */
  static float CalcAvgSep(const std::vector<AliFemtoThreeVector>& coll_0,
                          const std::vector<AliFemtoThreeVector>& coll_1);

  bool track_track_passes(const float avg_sep_pos);
  bool track_v0_passes(const float avg_sep_pos, const float avg_sep_neg);
  bool v0_v0_passes(const float avsep_pospos,
                    const float avsep_posneg,
                    const float avsep_negpos,
                    const float avsep_negneg);

  /*
   * Collection of average separations - currently not used
   */
  // union {
  //   float avg_sep;
  //   struct {
  //     float avg_sep_pos;
  //     float avg_sep_neg;
  //   };
  //   struct {
  //     float avg_sep_pospos;
  //     float avg_sep_posneg;
  //     float avg_sep_negpos;
  //     float avg_sep_negneg;
  //   };
  // } min;

  typedef std::vector<std::vector<AliFemtoThreeVector> > PointCollection_t;

protected:

  /// Collection of vectors
  PointCollection_t t1;
  PointCollection_t t2;

  static void push_vector(const AliFemtoThreeVector &v,
                          std::vector<AliFemtoThreeVector> &storage,
                          bool& save)
  {
    if (vector_is_set(v)) {
      storage.push_back(v);
    } else {
      save = false;
    }
  };
};

inline
AliFemtoAvgSepCalculator::AliFemtoAvgSepCalculator(const AliFemtoTrack *track_1,
                                                   const AliFemtoTrack *track_2):
  t1(1),
  t2(1)
{
  bool save_1 = true,
       save_2 = true;

  for (int i = 0; i < 8 && (save_1 || save_2); ++i) {
    if (save_1) {
      push_vector(track_1->NominalTpcPoint(i), t1[0], save_1);
    }
    if (save_2) {
      push_vector(track_2->NominalTpcPoint(i), t2[0], save_2);
    }
  }
}

inline
AliFemtoAvgSepCalculator::AliFemtoAvgSepCalculator(const AliFemtoTrack *track,
                                                   const AliFemtoV0 *v0):
  t1(1),
  t2(2)
{
  bool save_track = true,
       save_v0_pos = true,
       save_v0_neg = true;

  for (int i = 0; i < 8 && (save_track || save_v0_pos || save_v0_neg); ++i) {
    if (save_track) {
      push_vector(track->NominalTpcPoint(i), t1[0], save_track);
    }
    if (save_v0_pos) {
      push_vector(v0->NominalTpcPointPos(i), t2[0], save_v0_pos);
    }
    if (save_v0_neg) {
      push_vector(v0->NominalTpcPointNeg(i), t2[1], save_v0_pos);
    }
  }
}

inline
AliFemtoAvgSepCalculator::AliFemtoAvgSepCalculator(const AliFemtoV0 *v0_1,
                                                   const AliFemtoV0 *v0_2):
  t1(2),
  t2(2)
{
  bool save_v0_1_pos = true,
       save_v0_1_neg = true,
       save_v0_2_pos = true,
       save_v0_2_neg = true;

  for (int i = 0; i < 8; ++i) {
    if (save_v0_1_pos) {
      push_vector(v0_1->NominalTpcPointPos(i), t1[0], save_v0_1_pos);
    }
    if (save_v0_1_neg) {
      push_vector(v0_1->NominalTpcPointNeg(i), t1[1], save_v0_1_neg);
    }
    if (save_v0_2_pos) {
      push_vector(v0_2->NominalTpcPointPos(i), t2[0], save_v0_2_pos);
    }
    if (save_v0_2_neg) {
      push_vector(v0_2->NominalTpcPointNeg(i), t2[1], save_v0_2_neg);
    }
  }
}

inline float
AliFemtoAvgSepCalculator
  ::CalcAvgSep(const std::vector<AliFemtoThreeVector>& coll_0,
               const std::vector<AliFemtoThreeVector>& coll_1)
{
  const UInt_t size = TMath::Min(coll_0.size(), coll_1.size());
  float avg_sep = 0.0;
  for (UInt_t i = 0; i < size; ++i) {
    avg_sep += (coll_0[i] - coll_1[i]).Mag();
  }
  return avg_sep / size;
}

inline bool
AliFemtoAvgSepCalculator::track_track_passes(const float avg_sep)
{
  return CalcAvgSep(t1[0], t2[0]) >= avg_sep;
}

inline bool
AliFemtoAvgSepCalculator::track_v0_passes(const float avg_sep_pos,
                                          const float avg_sep_neg)
{
  return CalcAvgSep(t1[0], t2[0]) >= avg_sep_pos
      && CalcAvgSep(t1[0], t2[1]) >= avg_sep_neg;
}

inline bool
AliFemtoAvgSepCalculator::v0_v0_passes(const float avsep_pospos,
                                       const float avsep_posneg,
                                       const float avsep_negpos,
                                       const float avsep_negneg)
{
  return CalcAvgSep(t1[0], t2[0]) >= avsep_pospos
      && CalcAvgSep(t1[0], t2[1]) >= avsep_posneg
      && CalcAvgSep(t1[1], t2[0]) >= avsep_negpos
      && CalcAvgSep(t1[1], t2[1]) >= avsep_negneg;
}

#endif


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

//using Core.Math.Intervals;

namespace HolisticWare.Ph4ct3x.DiagnosticTests.Motorical
{
    ///
    /// Approximation for 1RM (1 repetitio/rep maximum, one repetition max) AKA Max Load
    ///
    ///
    ///
    ///
    ///
    /// TODO: Func<> delegate + Dictionary
    public partial class MaxLoadApproximation
    {
        ///
        ///
        /// <param name="mass">Mass (weight)</param>
        /// <param name="number_of_repetitions">Number of repetitions</param>
        /// <returns></returns>
        public double CalculateBrzycki_BrianMac
                                    (
                                        double mass,
                                        ulong number_of_repetitions
                                    )
        {
            // original:    Weight ÷ ( 1.0278 - ( 0.0278 × Number of repetitions ) )
            double max_load = mass / (1.0278 - (0.0278 * number_of_repetitions));

            return max_load;
        }

        public
            double
                CalculateBrzycki_SportScience
                                    (
                                        double mass,
                                        ulong number_of_repetitions
                                    )
        {
            double max_load = mass * (36.0 / (37.0 - number_of_repetitions));

            return max_load;
        }

        public
            double
                CalculateBaechle_BrianMac
                                    (
                                        double mass,
                                        ulong number_of_repetitions
                                    )
        {
            // original: Weight × ( 1 + ( 0.033 × Number of repetitions ) )
            double max_load = mass * (1 + (0.033 * number_of_repetitions));

            return max_load;
        }

        public
            double
                CalculateEpley_BrianMac
                                    (
                                        double mass,
                                        ulong number_of_repetitions
                                    )
        {
            double max_load = mass * (1 + double_0_033_AKA_1_over_30_Epley * number_of_repetitions);

            return max_load;
        }

    }
}